Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 11-20 of 36 total

Find and replace

This will search all files recursively for SEARCH_STRING and replace all occurrences of SEARCH_STRING with REPLACE_STRING throughout each unique file found. It also creates a backup of each modified file so that FILE is backed-up as FILE~ (with a tilde).

grep -R --files-with-matches 'SEARCH_STRING' . | sort | uniq | xargs perl -pi~ -e 's/SEARCH_STRING/REPLACE_STRING/'

yubnub.py

#!/usr/bin/env python

__author__="Andrew Pennebaker (andrew.pennebaker@gmail.com)"
__date__="9 Dec 2006 - 10 Dec 2006"
__copyright__="Copyright 2006 Andrew Pennebaker"
__license__="GPL"
__version__="0.0.1"
__credits__="Based on Yubnub for Windows (http://www.opbarnes.com/blog/Programming/OPB/Utilities/yubnub.html)"
__URL__="http://snippets.dzone.com/posts/show/3120"

from html2txt import html2txt

import webbrowser
from urllib import urlopen
import re

import sys
from getopt import getopt

PARSER="http://yubnub.org/parser/parse?command="

BROWSER_MODE="BROWSER"
PLAIN_MODE="PLAIN"

def space2plus(s):
	return "+".join(s.split())

def yubnub(command=""):
	global PARSER

	return PARSER+space2plus(command)

def yubnubBrowser(command):
	return webbrowser.open(yubnub(command))

def cleanHTML(html):
	h=html2txt()
	h.feed(html)
	h.close()

	return h.output()

def yubnubPlain(command, clean=True):
	command=yubnub(command)

	try:
		url=urlopen(command)
		lines=url.readlines()
		url.close()

		lines="".join(lines)

		if clean:
			return cleanHTML(lines)

		return lines

	except IOError, e:
		return "Error connecting to "+command

def usage():
	print "Usage: "+sys.argv[0]+" [options] <command>"
	print "-b --browser"
	print "\n--plain (default)"
	print "\t-c --clean (default)"
	print "\t-d --dirty"
	print "\n--parser <parser> (experimental)"
	print "\n-h --help"

	sys.exit()

def main():
	global PARSER

	global BROWSER_MODE
	global PLAIN_MODE

	mode=PLAIN_MODE
	parser=PARSER
	clean=True

	systemArgs=sys.argv[1:]
	optlist, args=[], []
	try:
		optlist, args=getopt(systemArgs, "bhcd", ["browser", "plain", "clean", "dirty", "parser=", "help"])
	except:
		usage()

	for option, value in optlist:
		if option=="-h" or option=="--help":
			usage()

		elif option=="-b" or option=="--browser":
			mode=BROWSER_MODE
		elif option=="--plain":
			mode=PLAIN_MODE
		elif option=="-c" or option=="--clean":
			clean=True
		elif option=="-d" or option=="--dirty":
			clean=False
		elif option=="--parser":
			parser=value

	command=" ".join(args)

	if mode==BROWSER_MODE:
		yubnubBrowser(command)
	elif mode==PLAIN_MODE:
		for line in yubnubPlain(command, clean):
			sys.stdout.write(line)
		print ""

if __name__=="__main__":
	main()

How to create a OpenSearch reference for your site (as used by Firefox 2's search box)

Create a file like this one as used for Wikipedia, but that refers to your own site's search:

<?xml version="1.0"?>
<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/">
<ShortName>Wikipedia (English)</ShortName>
<Description>Wikipedia (English)</Description>
<Image height="16" width="16" type="image/x-icon">http://en.wikipedia.org/favicon.ico</Image>
<Url type="text/html" method="get" template="http://en.wikipedia.org/w/index.php?title=Special:Search&amp;search={searchTerms}"/>
<Url type="application/x-suggestions+json" method="GET" template="http://en.wikipedia.org/w/api.php?action=opensearch&amp;search={searchTerms}"/>
</OpenSearchDescription>


Then link to it from your pages like so:

<link rel="search" type="application/opensearchdescription+xml" href="/w/opensearch_desc.php" title="Wikipedia (English)" />

Simple Javascript/XML based search

// Use javascript to search an XML based index.
// Provides simple site search where no server-side
// alternatives are available (for example: on a CD ROM)

// The sample XML:
<?xml version="1.0" encoding="utf-8"?>
<searchable_index>
	<item>John</item>
	<item>Paul</item>
	<item>George</item>
	<item>Ringo</item>
</searchable_index>


// The javascript:
window.onload = loadIndex;

function loadIndex() { // load indexfile
// most current browsers support document.implementation
	if (document.implementation && document.implementation.createDocument) {
		xmlDoc = document.implementation.createDocument("", "", null);
		xmlDoc.load("index.xml");
	}
// MSIE uses ActiveX
	else if (window.ActiveXObject) {
		xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.async = "false";
		xmlDoc.load("index.xml");
	}
}


function searchIndex() { // search the index (duh!)
	if (!xmlDoc) {
		loadIndex();
	}
	// get the search term from a form field with id 'searchme'

	var searchterm = document.getElementById("searchme").value;
	var allitems = xmlDoc.getElementsByTagName("item");
	results = new Array;
	if (searchterm.length < 3) {
		alert("Enter at least three characters");
	} else {
		for (var i=0;i<allitems.length;i++) {
// see if the XML entry matches the search term,
// and (if so) store it in an array
			var name = allitems[i].lastChild.nodeValue;
			var exp = new RegExp(searchterm,"i");
			if ( name.match(exp) != null) {
				results.push(allitems[i]);
			}
		}
// send the results to another function that displays them to the user
	showResults(results, searchterm);
	}
}


// The following is just an example of how you
// could handle the search results
function showResults(results, searchterm) {

	if (results.length > 0) {
// if there are any results, put them in a list inside the "resultshere" div
		var resultshere = document.getElementById("resultshere");
		var header = document.createElement("h5");
		var list = document.createElement("ul");
		var searchedfor = document.createTextNode("You've searched for "+searchterm);
		resultshere.appendChild(header);
		header.appendChild(searchedfor);
		resultshere.appendChild(list);
		for (var i=0;i<results.length;i++) {
			var listitem = document.createElement("li");
			var item = document.createTextNode(results[i].lastChild.nodeValue);
			list.appendChild(listitem);
			listitem.appendChild(item);
		}
	} else {
// else tell the user no matches were found
		var resultshere = document.getElementById("resultshere");
		var para = document.createElement("p");
		var notfound = document.createTextNode("Sorry, I couldn't find anything like "+searchterm +"!");
		resultshere.appendChild(para);
		para.appendChild(notfound);
	}
}


// Here's some s(a|i)mple HTML that should work with the code above:

<html>
<head>
<script type="text/javascript" src="searchindex.js"></script>
</head>
<body>
<form action="">
<input type="text" id="searchme" />
<input type="submit" onclick="searchIndex(); return false;" />
</form>
<div id="resultshere">
</div>
</body>
</html>

use google to search / find code snippet

// with google site search you can check for code snippets here

# google.com
search_term site:http://snippets.dzone.com

full text searching for ri content

From ZenSpider, http://blog.zenspider.com/archives/2006/08/full_text_searc.html:
Check it out. Quick and dirty searching of ri content:

Updated using: http://blog.zenspider.com/archives/2006/08/new_and_improve.html

They added path independence and searching of gems and local installed ri/rdoc. Enjoy!
#!/usr/local/bin/ruby -w

require 'rdoc/ri/ri_paths'
require 'find'
require 'yaml'

search = ARGV.shift

puts "Searching for #{search}"
puts

dirs = RI::Paths::PATH
dirs.each do |dir|
  Dir.chdir dir do
    Find.find('.') do |path|
      next unless test ?f, path
      yaml = File.read path
      if yaml =~ /#{search}/io then
        full_name = $1 if yaml[/full_name: (.*)/]
        puts "** FOUND IN: #{full_name}"
        
        data = YAML.load yaml.gsub(/ \!.*/, '')
        desc = data['comment'].map { |x| x.values }.flatten.join("\n").gsub(/&quot;/, "'").gsub(/&lt;/, "<").gsub(/&gt;/, ">").gsub(/&amp;/, "&")
        puts
        puts desc
        puts
      end
    end
  end
end

Lets you do stuff like:
% ./risearch.rb duplicate
Searching for duplicate
[...]
** FOUND IN: Array#uniq!

Removes duplicate elements from self. Returns nil if no changes are made (that is, no duplicates are found).
   a = [ 'a', 'a', 'b', 'b', 'c' ]
   a.uniq!   #=> ['a', 'b', 'c']
   b = [ 'a', 'b', 'c' ]
   b.uniq!   #=> nil

** FOUND IN: Array#|

Set Union---Returns a new array by joining this array with other_array, removing duplicates.
   [ 'a', 'b', 'c' ] | [ 'c', 'd', 'a' ]
          #=> [ 'a', 'b', 'c', 'd' ]
[...]

Posted by zenspider at August 15, 2006 04:16 PM | Bookmark This
Categories: Rails , Ruby , Toys

indexOf an array element

Finds the first instance of an element ($needle) in an array ($haystack). It works in ascending order (from element 0 to the array's length), can be easily modified to work in reverse if required. Will return either the index of the first occurance of false if hasn't been found.

function indexOf($needle, $haystack) {                // conversion of JavaScripts most awesome
        for ($i=0;$i<count($haystack);$i++) {         // indexOf function.  Searches an array for
                if ($haystack[$i] == $needle) {       // a value and returns the index of the *first*
                        return $i;                    // occurance
                }
        }
        return false;
}

Regex to find html tag(s)

// Used to find begin and end tags within HTML.

(<font[^>]*>)

Grab HTML From Sites and Echo Results

Grabs specified tags from any url on the net and then echos each of the results on a seperate line, you then have the option to remove the tags from the echoed results.

<?php

$config['url']       = "http://www.business-tycoon.com"; // url of html to grab
$config['start_tag'] = "<b>"; // where you want to start grabbing
$config['end_tag']   = "</b>"; // where you want to stop grabbing
$config['show_tags'] = 0; // do you want the tags to be shown when you show the html? 1 = yes, 0 = no

class grabber
{
	var $error = '';
	var $html  = '';
	
	function grabhtml( $url, $start, $end )
	{
		$file = file_get_contents( $url );
		
		if( $file )
		{
			if( preg_match_all( "#$start(.*?)$end#s", $file, $match ) )
			{				
				$this->html = $match;
			}
			else
			{
				$this->error = "Tags cannot be found.";
			}
		}
		else
		{
			$this->error = "Site cannot be found!";
		}
	}
	
	function strip( $html, $show, $start, $end )
	{
		if( !$show )
		{
			$html = str_replace( $start, "", $html );
			$html = str_replace( $end, "", $html );
			
			return $html;
		}
		else
		{
			return $html;
		}
	}
}

$grab = new grabber;
$grab->grabhtml( $config['url'], $config['start_tag'], $config['end_tag'] );

echo $grab->error;

foreach( $grab->html[0] as $html )
{
	echo htmlspecialchars( $grab->strip( $html, $config['show_tags'], $config['start_tag'], $config['end_tag'] ) ) . "<br>";
}

?>

Fast Sequential Search/Replace Engine supporting wildcards, backward search, whole words, etc... //Pascal Class

A quite fast unit to search/replace strings sequentially (while Seeker.Search() do...) in files/strings done mostly with pointers to improve speed. It's able to search backward, count end of lines, check case-sensitiveness, match whole words and handle wildcards (* and ?),

The search method was divided into 4 specialized methods, again to improve speed. The right method is choosed according to the options that were setted (wildcard, search backward, etc...)

This is an old code that doesn't match my current skills, anyway it has some cool techniques that I really enjoyed :)

//
//    TNotesSeeker - classe de buscas do Notes.
//
//    Notes, http://notes.codigolivre.org.br
//    Copyright (C) 2003-2004, Equipe do Notes.
//
//    This program is free software; you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation; either version 2 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program; if not, write to the Free Software
//    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//    **************************************************************
//    Revision #0
//      Version  : 1.0.0
//      Date     : 2003-11-30 22:00:00 GMT -3:00
//      Reviewer : Jonas Raoni Soares Silva
//      Changes  : Criada a classe.
//    **************************************************************
//    Revision #1
//      Version  : 1.0.1
//      Date     : 2004-09-09 03:30:00 GMT -3:00
//      Reviewer : Jonas Raoni Soares Silva
//      Changes  : Acho q acabaram-se os bugs... Será??? :]
//    **************************************************************

(*
@abstract(NotesSeeker - classe de buscas do Notes.)
@author(Jonas Raoni Soares Silva <jonblackjack@bol.com.br>)
@created(30 Nov 2003)
*)

unit NotesSeeker;

interface

uses
  SysUtils, Classes;

type

{
  @code(ENotesSeekerException) -
    Notificar erros na classe TNotesSeeker de forma
    profissional, facilitando a interceptação e/ou log de
    erros
}
  ENotesSeekerException = class ( Exception )
  public
    constructor Create(const Msg: string);
    constructor CreateFmt(const Msg: string; const Args: array of const);
  end;

  {Opões de pesquisa: <BR>
   @code(nsHandleEOL) - se você precisar buscar por quebras de linhas, você precisa setar esta opção.<BR>
   @code(nsCaseSensitive) - diferenciar maiúsculas de minúsculas.<BR>
   @code(nsWholeWords) - retorna apenas palavras inteiras.<BR>
   @code(nsBackward) - busca de traz para frente. <BR>
   @code(nsHandleWildCard) - usa coringas * e ? na pesquisa.}
  TNotesSeekerOption = ( nsHandleEOL, nsCaseSensitive, nsWholeWords, nsBackward, nsHandleWildCard );
  { Set de @link(TNotesSeekerOption).}
  TNotesSeekerOptions = set of TNotesSeekerOption;

  TSearchFunction = function: Boolean of object;

{
  @code(TNotesSeeker) -
    Permite fazer buscas em strings com várias opções
}
  TNotesSeeker = class(TObject)
  private
    Jump, LineJump: Cardinal;
    FList: TList;
  protected
    FMatches, FStartAt, FEOLLen, FSearchLen, FCurCol,
    FCurLine, FMatchLen, FMatchLine, FMatchCol: Cardinal;

    FBufferEnd, FBuffer, FBufferBegin, FBufferBackup,
    FEOL, FSearchBegin, FSearch, FSearchEnd: PChar;

    FOptions: TNotesSeekerOptions;

    FContextRightLenght, FContextLeftLenght: Cardinal;

    FKeepText: Boolean;

    function GetText: string;
    function GetReplacedText: string;
    function GetContext: string;
    function GetSearchStr: string;
    function GetRemainingText: string;
    function GetCurByte: Cardinal;
    function GetEOL: string;

    procedure SetOptions(const Value: TNotesSeekerOptions);
    procedure SetText( const Value: string);
    procedure SetSearchStr(const Value: string);
    procedure SetEOL(const Value: string);

    procedure FreeBuffer;
    procedure FreeEOL;
    procedure FreeSearchStr;

    {Search Engines}
    function SearchForward: Boolean;
    function SearchForwardWithWildCard: Boolean;
    function SearchBackward: Boolean;
    function SearchBackwardWithWildCard: Boolean;

  public
    { Efetua a busca: se o termo procurado for encontrado, retorna true, caso contrário retorna false }
    Search: TSearchFunction;

    { Método construtor }
    constructor Create; virtual;
    { Método destruidor }
    destructor Destroy; override;

    { Armazena o tamanho do "match", quando a opção wildcard estiver desligada esta será igual ao tamanho da própria string procurada }
    property MatchLength: Cardinal read FMatchLen;
    { Quando HandleEOL fizer parte das opções, armazenará a linha onde a string procurada foi encontrada }
    property CurLine: Cardinal read FMatchLine;
    { Armazenará a coluna onde a string procurada foi encontrada, se HandleEOL não estiver nas opções, armazenará a mesma coisa que a propriedade CurByte }
    property CurCol: Cardinal read FMatchCol;
    { Armazena a posição ou byte "absoluto" onde a string foi encontrada }
    property CurByte: Cardinal read GetCurByte;
    { Especifica a posição/byte inicial onde a busca deverá começar }
    property StartAt: Cardinal read FStartAt write FStartAt;
    { Retorna o contexto onde a string procurada foi encontrada }
    property Context: string read GetContext;
    { Especifica a quantidade de caracteres que deverão fazer parte do contexto encontrado ao lado esquerdo da string procurada }
    property ContextLeftLenght: Cardinal read FContextLeftLenght write FContextLeftLenght;
    { Especifica a quantidade de caracteres que deverão fazer parte do contexto encontrado ao lado direito da string procurada }
    property ContextRightLenght: Cardinal read FContextRightLenght write FContextRightLenght;
    { Armazena o número de strings que coincidiram com a busca até o presente momento }
    property Matches: Cardinal read FMatches;
    { Permite alterar a sequência de caracteres que demarcam o fim de uma linha }
    property EOL: string read GetEOL write SetEOL;
    { Armazena as opções atualmente habilitadas para a busca, podendo ser alterada a qualquer momento }
    property Options: TNotesSeekerOptions read FOptions write SetOptions;
    { Termo a ser procurado no texto }
    property SearchStr: string read GetSearchStr write SetSearchStr;
    { Texto onde a busca será efetuada }
    property Text: string read GetText write SetText;
    { Texto restante ao término da busca }
    property RemainingText: string read GetRemainingText;
    { Especifica se a classe deverá manter uma cópia do texto setado inicialmente }
    property KeepText: Boolean read FKeepText write FKeepText;
    { Retorna o texto com os replaces, caso KeepText seja falso, essa propriedade se torna sinônimo da propriedade Text }
    property ReplacedText: string read GetReplacedText;

    { Prepara tudo para uma nova busca }
    procedure StartSearch;
    { Carrega o texto da busca a partir de um arquivo }
    procedure LoadFromFile( const AFilename: string );
    { Carrega o texto da busca a partir de um stream }
    procedure LoadFromStream( const AStream: TStream );
    { Carrega o texto da busca a partir de um buffer }
    procedure LoadFromBuffer( const ABuffer: PChar );
    { Efetua a substituição da string encontrada pela string contida em "S" }
    procedure Replace( const S: String );
    { Modo prático para setar as opções }
    procedure EnableOptions( const CaseSensitive: Boolean = true; const WholeWords: Boolean = false; const HandleEOL: Boolean = true; const HandleWildCard: Boolean = false; const Backward: Boolean = false );

  end;

  { Compara Str1 e Str2 de trás pra frente, se as duas forem iguais retorna true, caso contrário false }
  function StrLRComp( S1, S2: PChar; const S2Begin: PChar ): Boolean;
  { Converte para maiúsculo (ANSI) -> VALEUUUUU TIO RUSSÃO hahaha, o que tem no delphi "aplica a alteração"
    Idéia de manter tabela com tudo maiúsculo arrancada de "QStrings 6.07.424 Copyright (C) 2000, 2003 Andrew Dryazgov [ andrewdr@newmail.ru ]" }
  function AnsiUpCase(Ch: Char): Char;

const
  { Caracteres que definem delimitadores de palavra, usada quando a opção WholeWords está ativa }
  WhiteSpaces: set of Char = [' ',#9,#13,#10,'!','"','#','$','%','&','''','(',')','*','+','-','/',':',';','<','=','>','?','@','[','\',']','^','`','{','|','}','~'];

const
  //fiz algumas alterações hehe, o tiozaum russo devia  começano a ficar cego enqto fazia isso :)
  ToUpperChars: array[0..255] of Char =
    (#$00,#$01,#$02,#$03,#$04,#$05,#$06,#$07,#$08,#$09,#$0A,#$0B,#$0C,#$0D,#$0E,#$0F,
     #$10,#$11,#$12,#$13,#$14,#$15,#$16,#$17,#$18,#$19,#$1A,#$1B,#$1C,#$1D,#$1E,#$1F,
     #$20,#$21,#$22,#$23,#$24,#$25,#$26,#$27,#$28,#$29,#$2A,#$2B,#$2C,#$2D,#$2E,#$2F,
     #$30,#$31,#$32,#$33,#$34,#$35,#$36,#$37,#$38,#$39,#$3A,#$3B,#$3C,#$3D,#$3E,#$3F,
     #$40,#$41,#$42,#$43,#$44,#$45,#$46,#$47,#$48,#$49,#$4A,#$4B,#$4C,#$4D,#$4E,#$4F,
     #$50,#$51,#$52,#$53,#$54,#$55,#$56,#$57,#$58,#$59,#$5A,#$5B,#$5C,#$5D,#$5E,#$5F,
     #$60,#$41,#$42,#$43,#$44,#$45,#$46,#$47,#$48,#$49,#$4A,#$4B,#$4C,#$4D,#$4E,#$4F,
     #$50,#$51,#$52,#$53,#$54,#$55,#$56,#$57,#$58,#$59,#$5A,#$7B,#$7C,#$7D,#$7E,#$7F,
     #$80,#$81,#$82,#$81,#$84,#$85,#$86,#$87,#$88,#$89,#$8A,#$8B,#$8C,#$8D,#$8E,#$8F,
     #$90,#$91,#$92,#$93,#$94,#$95,#$96,#$97,#$98,#$99,#$8A,#$9B,#$8C,#$9D,#$9E,#$9F,
     #$A0,#$A1,#$A1,#$A3,#$A4,#$A5,#$A6,#$A7,#$A8,#$A9,#$AA,#$AB,#$AC,#$AD,#$AE,#$AF,
     #$B0,#$B1,#$B2,#$B2,#$A5,#$B5,#$B6,#$B7,#$A8,#$B9,#$BA,#$BB,#$BC,#$BD,#$BE,#$BF,
     #$C0,#$C1,#$C2,#$C3,#$C4,#$C5,#$C6,#$C7,#$C8,#$C9,#$CA,#$CB,#$CC,#$CD,#$CE,#$CF,
     #$D0,#$D1,#$D2,#$D3,#$D4,#$D5,#$D6,#$D7,#$D8,#$D9,#$DA,#$DB,#$DC,#$DD,#$DE,#$DF,
     #$C0,#$C1,#$C2,#$C3,#$C4,#$C5,#$C6,#$C7,#$C8,#$C9,#$CA,#$CB,#$CC,#$CD,#$CE,#$CF,
     #$D0,#$D1,#$D2,#$D3,#$D4,#$D5,#$D6,#$F7,#$D8,#$D9,#$DA,#$DB,#$DC,#$DD,#$DE,#$9F);

implementation

function StrLRComp( S1, S2: PChar; const S2Begin: PChar ): Boolean;
begin
  while ( S2 <> S2Begin ) and ( S1^ = S2^ ) do begin
    dec( S1 );
    dec( S2 );
  end;
  Result := ( S1^ = S2^ ) and ( S2 = S2Begin );
end;

function AnsiUpCase(Ch: Char): Char;
begin
  Result := ToUpperChars[ ord( ch ) ];
end;


{ class : TNotesSeeker }

{ TNotesSeeker : protected }

function TNotesSeeker.GetText: string;
begin
  if Assigned( FBufferBackup ) then
    Result := StrPas( FBufferBackup )
  else
    Result := ReplacedText;
end;

function TNotesSeeker.GetReplacedText: string;