DZone 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
  • submit to reddit
        # pad the plaintext to 64 characters, then get an MD5 digest
# 128 bits, duh.

require 'digest/md5'

def pad(text)
   v = text * (1 + (64 / text.length))
   v[0,64]
end

def wep_key(text)
   Digest::MD5.hexdigest(pad(text))
end


    
        The mixin below allows comparison between two Time objects using the more intuitive and natural-sounding before? and after? methods.

Some examples (using Rails' ActiveSupport Time extensions or (preferred) the 'units' gem):

2.minutes.ago.after? Time.now # => false

Time.now.before? 2.hours.from_now # => true

module BeforeAndAfter

  LEFT_SIDE_LATER  = 1
  RIGHT_SIDE_LATER = -1
  
  def before?(input_time)
    (self <=> input_time) == RIGHT_SIDE_LATER
  end
  
  def after?(input_time)
    (self <=> input_time) == LEFT_SIDE_LATER
  end
end

Time.send :include , BeforeAndAfter
    
        // Transliteration (or Translit for short).
// Converts Russian characters into Latin on-the-fly.
// Save the code as UTF-8.

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Translit</title>
<script type="text/javascript">
/* Javascript functions */
function JSfunc()
{
	/* Making transliteration! */
	this.strTranslit = function(el)
	{
		new_el = document.getElementById('out');
		A = new Array();
		A["Ё"]="YO";A["Й"]="I";A["Ц"]="TS";A["У"]="U";A["К"]="K";A["Е"]="E";A["Н"]="N";A["Г"]="G";A["Ш"]="SH";A["Щ"]="SCH";A["З"]="Z";A["Х"]="H";A["Ъ"]="'";
		A["ё"]="yo";A["й"]="i";A["ц"]="ts";A["у"]="u";A["к"]="k";A["е"]="e";A["н"]="n";A["г"]="g";A["ш"]="sh";A["щ"]="sch";A["з"]="z";A["х"]="h";A["ъ"]="'";
		A["Ф"]="F";A["Ы"]="I";A["В"]="V";A["А"]="A";A["П"]="P";A["Р"]="R";A["О"]="O";A["Л"]="L";A["Д"]="D";A["Ж"]="ZH";A["Э"]="E";
		A["ф"]="f";A["ы"]="i";A["в"]="v";A["а"]="a";A["п"]="p";A["р"]="r";A["о"]="o";A["л"]="l";A["д"]="d";A["ж"]="zh";A["э"]="e";
		A["Я"]="YA";A["Ч"]="CH";A["С"]="S";A["М"]="M";A["И"]="I";A["Т"]="T";A["Ь"]="'";A["Б"]="B";A["Ю"]="YU";
		A["я"]="ya";A["ч"]="ch";A["с"]="s";A["м"]="m";A["и"]="i";A["т"]="t";A["ь"]="'";A["б"]="b";A["ю"]="yu";
		new_el.value = el.value.replace(/([\u0410-\u0451])/g,
			function (str,p1,offset,s) {
				if (A[str] != 'undefined'){return A[str];}
			}
		);
	}
	/* Normalizes a string, eÑŽ => eyu */
	this.strNormalize = function(el)
	{
		if (!el) { return; }
		this.strTranslit(el);
	}
}
var oJS = new JSfunc();
</script>
</head>
<body>

<p>введите текст:</p>
<textarea onkeyup="oJS.strNormalize(this)" style="height:10em;width:100%" id="in"></textarea>
<p>результат:</p>
<textarea style="height:10em;width:100%" id="out"></textarea>

</body>
</html>
    
        
SELECT DISTINCT field_name, COUNT(*) AS num FROM table_name GROUP BY field_name ORDER BY num DESC
    
        Convert a utf string to iso, used this when generating a pdf with pdf-writer in Rails, all my text is UTF8 but pdf-writer does not support this.

#add this to environment.rb
#call to_iso on any UTF8 string to get a ISO string back
#example : "Cédez le passage aux français".to_iso

class String
  require 'iconv' #this line is not needed in rails !
  def to_iso
    Iconv.conv('ISO-8859-1', 'utf-8', self)
  end
end
    
        generate random alphanumeric string 'size' characters long

size = 8; (1..size).map{([*('a'..'z')]+[*('A'..'Z')]+[*(1..9)].map{|n|n.to_s}).instance_eval{self[rand(self.size)]}}.join
    
        // description of your code here

// insert code here..
//Cap_Image.php
<?php
    session_start();    	
    $md5_hash = md5(rand(0,9999)); 
    $security_code = substr($md5_hash, 25, 5); 
    $enc=md5($security_code);
    $_SESSION['count'] = $enc;
    $secure = $_SESSION['count'];
    //     echo "--------------------------$secure<br>";

    $width = 100;
    $height = 40; 
    
    $image = ImageCreate($width, $height);  
    $white = ImageColorAllocate($image, 255, 255, 255);
    $black = ImageColorAllocate($image, 0, 100, 0);
    $grey = ImageColorAllocate($image, 204, 204, 204);
     
    ImageFill($image, 0, 0, $grey); 
    //Add randomly generated string in white to the image
    ImageString($image, 10, 30, 10, $security_code, $black); 
    ImageRectangle($image,0,16,$width-1,$height-1,$grey); 
    imageline($image, 0, $height/2, $width, $height/2, $grey); 
    imageline($image, $width/2, 0, $width/2, $height, $grey); 
	
    header("Content-Type: image/jpeg"); 
    ImageJpeg($image);
    ImageDestroy($image);
    ImageDestroy($image);
    ?>
//validate.php
<form name="form1" method="post" action="form.php">
<div align="center">
<input name="Submit" type="submit" value="back"></div>
</form>
<div align="center">
<?php
@session_start();
$key=$_SESSION['count'];

$imag = $_POST['number'];
$user = md5($imag);
//echo "$imag  =  =  = $key<br>";
//echo("$user");
if($user==$key)			
{
echo ("Verification success");
}
else{
echo "You have entered wrong verification code!!<br> 
		Please go back and enter proper value.";}
?>
</div>
//form.php
<?php
session_start();
?>
<form name="form1" method="post" action="validate.php">
<table border="1" width="380" align="center" cellspacing="2" cellpadding="0" bgcolor="#A4EEFF"><TR><TD>
<table bgcolor="" align="center">
<tr> <td align="center" colspan="2"><img src="Cap_Img.php"><br><br>
<input type="button" value="Refresh Image" onClick="window.location.href=window.location.href"></td></tr>
<tr>
<td align="center"> Please enter the string shown in the image.</td><tr>
<td align="center"><input name="number" type="text"></td><tr>
<td align="center">
<input name="Submit" type="submit" value="Submit"></td> </tr>
</table>
</TD></TR></table>
</form>
    
        Sometimes it is necessary to verify that a given page really contains a specific link. This is usually done when checking for a reciprocal link in link exchange scripts and so on.

Several things need to be considered in this situation :

    * Only actual links count. A plain-text URL should not be accepted.
    * Links inside HTML comments (<!– … –>) are are no good.
    * Nofollow’ed links are out as well.

Here’s a PHP function that satisfies these requirements :
(http://w-shadow.com/blog/2007/09/25/checking-if-page-contains-a-link-in-php/)

function contains_link($page_url, $link_url) {
    /* Get the page at page_url */
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $page_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

    curl_setopt($ch, CURLOPT_USERAGENT, 
    'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)');

    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    curl_setopt($ch, CURLOPT_TIMEOUT, 60);
    curl_setopt($ch, CURLOPT_FAILONERROR, true);

    $html = curl_exec($ch);
    curl_close($ch);

    if(!$html) return false; 

    /* Remove HTML comments and their contents */ 
    $html = preg_replace('/<!--.*-->/i', '', $html);

    /* Extract all links */
    $regexp='/(<a[\s]+[^>]*href\s*=\s*[\"\']?)([^\'\" >]+)([\'\"]+[^<>]*>)/i';
    if (!preg_match_all($regexp, $html, $matches, PREG_SET_ORDER)) {
	    return false; /* No links on page */
    };

    /* Check each link */
    foreach($matches as $match){
	    /* Skip links that contain rel=nofollow */	
	    if(preg_match('/rel\s*=\s*[\'\"]?nofollow[\'\"]?/i', $match[0])) continue;
	    /* If URL = backlink_url, we've found the backlink */
	    if ($match[2]==$link_url) return true;
    }

    return false;
}

/* Usage example */

if (contains_link('http://w-shadow.com/','http://w-shadow.com/blog/')) {
	echo 'Reciprocal link found.';
} else {
	echo 'Reciprocal link not found.';
};
    
        // description of your code here

(require 'scala-mode)
(require 'compile)
(require 'flymake)
(require 'font-lock)

(defvar scala-build-commad nil)
(make-variable-buffer-local 'scala-build-command)

(add-hook 'scala-mode-hook
          (lambda ()
	    (flymake-mode-on)
	    ))

(defun flymake-scala-init ()
  (let* ((text-of-first-line (buffer-substring-no-properties (point-min) (min 20 (point-max)))))
    (progn
      (remove-hook 'after-save-hook 'flymake-after-save-hook t)
      (save-buffer)
      (add-hook 'after-save-hook 'flymake-after-save-hook nil t)
      (if (string-match "^//script" text-of-first-line)
	  (list "fsc" (list "-Xscript" "MainScript" "-d" "c:/tmp" buffer-file-name))
	(or scala-build-command (list "fsc" (list "-d" "c:/tmp" buffer-file-name))))
      )))

(push '(".+\\.scala$" flymake-scala-init) flymake-allowed-file-name-masks)
(push '("^\\(.*\\):\\([0-9]+\\): error: \\(.*\\)$" 1 2 nil 3) flymake-err-line-patterns)

(set (make-local-variable 'indent-line-function) 'scala-indent-line)

(defun scala-indent-line ()
  "Indent current line of Scala code."
  (interactive)
  (indent-line-to (max 0 (scala-calculate-indentation))))

(defun scala-calculate-indentation ()
  "Return the column to which the current line should be indented."
  (save-excursion
    (scala-maybe-skip-leading-close-delim)
    (let ((pos (point)))
      (beginning-of-line)
      (if (not (search-backward-regexp "[^\n\t\r ]" 1 0))
	  0
	(progn
	  (scala-maybe-skip-leading-close-delim)
	  (+ (current-indentation) (* 2 (scala-count-scope-depth (point) pos))))))))

(defun scala-maybe-skip-leading-close-delim ()
  (beginning-of-line)
  (forward-to-indentation 0)
  (if (looking-at "\\s)")
      (forward-char)
    (beginning-of-line)))

(defun scala-face-at-point (pos)
  "Return face descriptor for char at point."
  (plist-get (text-properties-at pos) 'face))

(defun scala-count-scope-depth (rstart rend)
  "Return difference between open and close scope delimeters."
  (save-excursion
    (goto-char rstart)
    (let ((open-count 0)
	  (close-count 0)
	  opoint)
      (while (and (< (point) rend)
		  (progn (setq opoint (point))
			 (re-search-forward "\\s)\\|\\s(" rend t)))
	(if (= opoint (point))
	    (forward-char 1)
	  (cond

            ;; Use font-lock-mode to ignore strings and comments
	   ((scala-face-at-point (- (point) 1))) 

	   ((looking-back "\\s)")
	    (incf close-count))
	   ((looking-back "\\s(")
	    (incf open-count))
	   )))
      (- open-count close-count))))


(provide 'scala-extensions)

    
        
for i in 1..100
  print "Now at #{i}. Restart? "
  retry if gets =~ /^y/i
end
    
        Changes the widths of form elements so they fit into smaller columns created using the <a href="http://code.google.com/p/blueprintcss/">Blueprint CSS framework</a>.

div.span-1 input.text, div.span-1 input.title { width:  30px; }
div.span-2 input.text, div.span-2 input.title { width:  50px; }
div.span-3 input.text, div.span-3 input.title { width:  90px; }
div.span-4 input.text, div.span-4 input.title { width: 130px; }
div.span-5 input.text, div.span-5 input.title { width: 170px; }
div.span-6 input.text, div.span-6 input.title { width: 210px; }
div.span-7 input.text, div.span-7 input.title { width: 250px; }
div.span-8 input.text, div.span-8 input.title { width: 290px; }

div.span-1 select { width:  30px; }
div.span-2 select { width:  50px; }
div.span-3 select { width:  90px; }
div.span-4 select { width: 130px; }
div.span-5 select { width: 170px; }

div.span-1  textarea { width:  30px; height:  25px; }
div.span-2  textarea { width:  50px; height:  50px; }
div.span-3  textarea { width:  90px; height:  75px; }
div.span-4  textarea { width: 130px; height: 100px; }
div.span-5  textarea { width: 170px; height: 125px; }
div.span-6  textarea { width: 210px; height: 150px; }
div.span-7  textarea { width: 250px; height: 175px; }
div.span-8  textarea { width: 290px; height: 200px; }
div.span-9  textarea { width: 330px; height: 225px; }
div.span-10 textarea { width: 370px; height: 250px; }
    
        // A tiny Ruby web server.

#!/usr/bin/env ruby

require "webrick"

s=WEBrick::HTTPServer.new(
        :BindAddress => "localhost",
        :Port => 8080,
        :DocumentRoot => File.dirname($0)+"/"+"www/"
)

trap("INT") { s.shutdown }

s.start
    
        // i can't get this to work.  This seems to be the problem portion of the code.

//import random
# choose from a list
adam = random.choice([1,2])
print adam
input('press enter to continue');
if adam = 1:
    print 'you loose'
raw_input('press enter to exit')
if adam = 2:
    print 'you WIN!!'
raw_input('press enter to exit')
    
        In some test cases I need all my fixtures to be loaded.  To make this easier, add the following to test/test_helper.rb:

class Test::Unit::TestCase
  def self.all_fixtures
    Dir[File.dirname(__FILE__) + "/fixtures/*.yml"].each do |f|
      fixtures File.basename(f, '.yml')
    end
  end

  ..
end

and in your tests use it as follows:

class FooTest < Test::Unit::TestCase
  all_fixtures

  ..
end

Happy testing!    
        // ggarciaa at gmail dot com (04-July-2007 01:57)
// I needed to empty a directory, but keeping it
// so I slightly modified the contribution from
// stefano at takys dot it (28-Dec-2005 11:57)
// A short but powerfull recursive function
// that works also if the dirs contain hidden files
//
// $dir = the target directory
// $DeleteMe = if true delete also $dir, if false leave it alone
//
// SureRemoveDir('EmptyMe', false);
// SureRemoveDir('RemoveMe', true);

<?php
function SureRemoveDir($dir, $DeleteMe) {
    if(!$dh = @opendir($dir)) return;
    while (false !== ($obj = readdir($dh))) {
        if($obj=='.' || $obj=='..') continue;
        if (!@unlink($dir.'/'.$obj)) SureRemoveDir($dir.'/'.$obj, true);
    }

    closedir($dh);
    if ($DeleteMe){
        @rmdir($dir);
    }
}
?>
    
        
class String
  def is_numeric?
    Float self rescue false
  end
end
    
        More lovely alias commands... this time to kill/restart Rail's script/server from any Terminal session or login on your box... (as long as your the same user).

alias dierails='ps -a|grep "/usr/local/bin/ruby script/server"|grep -v "grep /usr"|cut -d " " -f1|xargs -n 1 kill -KILL $1'
alias resetrails='ps -a|grep "/usr/local/bin/ruby script/server"|grep -v "grep /usr"|cut -d " " -f1|xargs -n 1 kill -HUP $1'
    
        This lil Ruby-OSA script will allow you to import your "Flagged Items" in NetNewsWire as Web Archive Items in Yojimbo. Thus allowing you to save RSS articles for off-line viewing/storage.

#!/usr/local/bin/ruby
['rubygems', 'rbosa'].each {|lib| require lib}
nnw = OSA.app('NetNewsWire')
yojimbo = OSA.app('Yojimbo')

nnw.subscriptions.find { |s| s if s.display_name == 'Flagged Items' }.headlines.each do |article|
  unless yojimbo.web_archive_items.map { |f| f.source_url }.include?(article.url)
    archived = yojimbo.make(OSA::Yojimbo::WebArchiveItem, 
                            article.url, 
                            :name => article.title)
    # Adjust this for slower/faster bandwidth connections (or your feeling lucky, punk)
    sleep(5)
    # Uncomment below to remove the flagged items upon successfully archiving
    # if archived.name == 'untitled' && archived.source_url.empty?
    #   puts "!!! #{article.title} does not look to be imported !!!"
    # else
    #   article.delete
    # end
  end
end
    
        // It's not necessarily the cleanest, but it got the job done on an internal transfer we were doing. Your mileage may vary by quite a bit. 

def convert_from_twiki_to_mediawiki(old_page_text)
  new_page_text = ""
  
  # shifting the tables over
  while (true)
    if (old_page_text.index(/\n\|/).nil?)
      new_page_text += old_page_text
      break
    end
        
    # table extraction
    table_index = old_page_text.index("\n|")
    first_chunk = old_page_text.slice!(0..table_index)
    table_chunk = ""
    old_page_text.each_line do |line|
      if line[0..0] == '|'
        table_chunk += line
      else
        break
      end
    end
    old_page_text.slice!(table_chunk)
    
    # table conversion
    table_chunk.gsub!(/\|/, "||")
    table_chunk.gsub!(/\|\|\s*$/, "\n|-")
    table_chunk.gsub!(/^\|\|/, "|")
    table_chunk.gsub!(/\|-\s*\Z/, "|}")
    table_chunk.gsub!(/\A\|/, "{|class=\"wikitable sortable\"\n|")
    
    # process new table looking for headings
    new_table_chunk = ""
    table_chunk.each_line do |line|
      if line.match(/\*\s.*\s\*/)
        line.gsub!(/\|\|/, "!!")
        line.gsub!(/^\|/, "!")
        line.gsub!("*", '')
      end
      
      new_table_chunk += line
    end
    
    new_page_text += first_chunk + new_table_chunk
  end
  
  # bold
  new_page_text.gsub!(/(^|[\s\(])\*([^ ].*?[^ ])\*([\s\)\.\,\:\;\!\?]|$)/, "\\1'''\\2'''\\3")
  # italic bold
  new_page_text.gsub!(/(^|[\s\(])\_\_([^ ].*?[^ ])\_\_([\s\)\.\,\:\;\!\?]|$)/, "\\1''<b>\\2<\/b>''\\3") 
  # italic
  new_page_text.gsub!(/(^|[\s\(])\_([^ ].*?[^ ])\_([\s\)\.\,\:\;\!\?]|$)/, "\\1''\\2''\\3")
  # monospaced bold
  new_page_text.gsub!(/(^|[\s\(])==([^ ].*?[^ ])==([\s\)\.\,\:\;\!\?]|$)/, "\\1'''<tt>\\2<\/tt>'''\\3")
  # monospaced
  new_page_text.gsub!(/(^|[\s\(])=([^ ].*?[^ ])=([\s\)\.\,\:\;\!\?]|$)/, "\\1<tt>\\2<\/tt>\\3")
  # H6
  new_page_text.gsub!(/(^|[\n\r])---\+\+\+\+\+\+([^\n\r]*)/, "\\1======\\2 ======")
  # H5
  new_page_text.gsub!(/(^|[\n\r])---\+\+\+\+\+([^\n\r]*)/, "\\1=====\\2 =====")
  # H4
  new_page_text.gsub!(/(^|[\n\r])---\+\+\+\+([^\n\r]*)/, "\\1====\\2 ====")
  # H3
  new_page_text.gsub!(/(^|[\n\r])---\+\+\+([^\n\r]*)/, "\\1===\\2 ===")
  # H2
  new_page_text.gsub!(/(^|[\n\r])---\+\+([^\n\r]*)/, "\\1==\\2 ==")
  # H1
  new_page_text.gsub!(/(^|[\n\r])---\+([^\n\r]*)/, "\\1=\\2 =")
  # external link
  new_page_text.gsub!(/\[\[(https?\:.*?)\]\[(.*?)\]\]/, "\[\\1 \\2\]")
  # internal link [[WikiWord][WikiWord]]
  new_page_text.gsub!(/\[\[([^\]]*)\]\]/, "\[\[\\1\|\\1\]\]")
  # internal lnk [[WikiWord][label]]
  new_page_text.gsub!(/\[\[([^\]]*)\]\[(.*?)\]\]/, "\[\[\\1\|\\2\]\]")
  # level 1 bullet
  new_page_text.gsub!(/(^|[\n\r])[ ]{3}\* /, "\\1*")
  # level 2 bullet
  new_page_text.gsub!(/(^|[\n\r])[ ]{6}\* /, "\\1**")
  # level 3 bullet
  new_page_text.gsub!(/(^|[\n\r])[ ]{9}\* /, "\\1***")
  # level 4 bullet
  new_page_text.gsub!(/(^|[\n\r])[ ]{12}\* /, "\\1****")
  # level 5 bullet
  new_page_text.gsub!(/(^|[\n\r])[ ]{15}\* /, "\\1*****")
  # level 6 bullet
  new_page_text.gsub!(/(^|[\n\r])[ ]{18}\* /, "\\1******")
  # level 7 bullet
  new_page_text.gsub!(/(^|[\n\r])[ ]{21}\* /, "\\1*******")
  # level 8 bullet
  new_page_text.gsub!(/(^|[\n\r])[ ]{24}\* /, "\\1********")
  # level 9 bullet
  new_page_text.gsub!(/(^|[\n\r])[ ]{27}\* /, "\\1*********")
  # level 10 bullet
  new_page_text.gsub!(/(^|[\n\r])[ ]{30}\* /, "\\1**********")
  # level 1 bullet
  new_page_text.gsub!(/(^|[\n\r])[ ]{3}[0-9]\.? /, "\\1#")
  # level 2 bullet
  new_page_text.gsub!(/(^|[\n\r])[ ]{6}[0-9]\.? /, "\\1##")
  # level 3 bullet
  new_page_text.gsub!(/(^|[\n\r])[ ]{9}[0-9]\.? /, "\\1###")
  # level 4 bullet
  new_page_text.gsub!(/(^|[\n\r])[ ]{12}[0-9]\.? /, "\\1####")
  # level 5 bullet
  new_page_text.gsub!(/(^|[\n\r])[ ]{15}[0-9]\.? /, "\\1#####")
  # level 6 bullet
  new_page_text.gsub!(/(^|[\n\r])[ ]{18}[0-9]\.? /, "\\1######")
  # level 7 bullet
  new_page_text.gsub!(/(^|[\n\r])[ ]{21}[0-9]\.? /, "\\1#######")
  # level 8 bullet
  new_page_text.gsub!(/(^|[\n\r])[ ]{24}[0-9]\.? /, "\\1########")
  # level 9 bullet
  new_page_text.gsub!(/(^|[\n\r])[ ]{27}[0-9]\.? /, "\\1#########")
  # level 10 bullet
  new_page_text.gsub!(/(^|[\n\r])[ ]{30}[0-9]\.? /, "\\1##########")
    
  
  new_page_text
end
    
        Get PHP parsing errors on command line. Useful for those extreme cases where you can't get them to print to the browser.

find . -name \*.php \! -exec php -l {} \;