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
mysqldump -v --quick --single-transaction --all-databases -uroot > file.sql
mysqldump -v --quick --single-transaction --all-databases -h -udb1939 -pPASSWORD > mt_all.sql
# Snagged from
for old in `find app/views -name *.rhtml`; do svn mv $old `dirname $old`/`basename $old .rhtml`.html.erb; done
        Requires the Tinder gem, and PHP on the server running MediaWiki must be compiled with --enable-sockets. The computer running the bot will also have to be open to the web - it can't be behind a firewall.

First, add this code to your MediaWiki LocalSettings.php, replacing the IP address with the IP of the server/computer running the bot, and the port to whatever you want to use (probably something above 40,000, but it's up to you):
$wgRC2UDPAddress = '';
$wgRC2UDPPort = '41895';
$wgRC2UDPPrefix = "";

Now, you can run the bot! This is extremely hackish, because the retarded collective-mailing-list-coding system of the MediaWiki repos has somehow managed to code IRC color codes directly into their exported strings (at least with MediaWiki 1.2alpha, which is what I'm running right now).
You'll need to replace the new tinder definition with your subdomain on Campfire, the username and password with ones for the bot account you've created on your campfire room, and the room name with the room you want the updates to be sent to.
require 'rubygems'
require 'tinder'
require 'socket'
puts 'Dependencies loaded...'

campfire = 'subdomain'
campfire.login '', 'password'
exit unless room = campfire.find_room_by_name('Case Sensitive Room Name')
puts 'Campfire logged in...'

server =
exit unless server.bind('', 41895)
puts 'Socket listening...'

loop do
  msg = server.recv(2048).gsub(/\003[\d]{0,2}/,'').chomp
  print "sending to room: #{msg.inspect}..."
  exit unless room.speak msg.to_s
  puts ' sent!'
        This is a script that builds a <a href="">Radiant CMS</a> site with several third-party extensions I use a lot. This just saves me time from having to look up the setup commands each time. YMMV

I call this power_radiant and stick it in /usr/local/bin.

Update: this has been fixed to work with latest Radiant code (since svn path as changed and freeze:edge task no longer works). You will need Git to be installed on your machine for this to work.

radiant --database sqlite3 $1
cd $1
echo "
  adapter: sqlite3
  database: db/production.sqlite3
  adapter: sqlite3
  database: db/test.sqlite3
" > config/database.yml
svn export vendor/extensions/shards
svn export svn:// vendor/extensions/wym_editor_filter
svn export vendor/extensions/page_attachments
#rake radiant:freeze:edge # stopped working in latest gem
git clone git:// /tmp/radiant
cp -r /tmp/radiant/radiant vendor/radiant
rake production db:bootstrap
rake production db:migrate:extensions
rake production radiant:extensions:wym_editor_filter:install
rake production radiant:extensions:page_attachments:update

To run: 
power_radiant my_site
        // takes an array of values and a value to match, and outputs formatted <option>s with the <option> matching $match selected
// must be manually wrapped in <select></select to allow for maximum flexibility

function selectHelper($values, $match)
  $keys = array_keys($values);
  $i = 0;
  foreach($values as $option)
    $selected = null;
    if($match == $keys[$i])
      $selected = " selected";
    echo "	<option value=\"".$keys[$i]."\"$selected>".$option."</option>\n";

//sample usage:
$values = array(
  "lb" => "Pounds",
  "ea" => "Each",
  "oz" => "Ounces");
  selectHelper($values, $product->unit);
Jill Tomich01/23/08
9 replies

DZone to Launch a New Program – Refcardz

Refcardz is a series of high-quality quick reference cards on developer-related topics. We are gathering authors from some of the best computer book publishers to create content that is more than just tables and code as seen in most reference cards available.

        <a href=""></a>    
        Turbo Pascal and conio.h allowed immediate character reading, without wainting for enter. Following code does the same under unix terminals:

#include <stdio.h>
#include <termios.h>

char getch(void) {
        char buf = 0;
        struct termios old = {0};
        if (tcgetattr(0, &old) < 0)
        old.c_lflag &= ~ICANON;
        old.c_lflag &= ~ECHO;
        old.c_cc[VMIN] = 1;
        old.c_cc[VTIME] = 0;
        if (tcsetattr(0, TCSANOW, &old) < 0)
                perror("tcsetattr ICANON");
        if (read(0, &buf, 1) < 0)
                perror ("read()");
        old.c_lflag |= ICANON;
        old.c_lflag |= ECHO;
        if (tcsetattr(0, TCSADRAIN, &old) < 0)
                perror ("tcsetattr ~ICANON");
        return (buf);

int main() {
        char key;
        printf("Press 'x' to exit...\n");
        while((key=getch()) && (key != 'x'))
                printf ("you pressed %c\n", key);
        Function to generate descriptive errors (line number, function name, etc).

#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <string.h>

#ifdef __OPTIMIZE__
#define __OPT__ 1
#define __OPT__ 0

#ifdef __OPTIMIZE_SIZE__
#define __OPT_SIZE__ 1
#define __OPT_SIZE__ 0

#define err_print(args...) __err_print(__FILE__, __FUNCTION__, __LINE__, __DATE__ " " __TIME__, __VERSION__, __OPT__, __OPT_SIZE__, ##args)
void __err_print(char *file, char *function, int line, char *date, char *version, int opt, int opt_size, char *txt, ...)
        va_list argp;

        puts("** ERROR! **");
        printf("File:                 \t %s\n",file);
        printf("Function:             \t %s\n",function);
        printf("Line:                 \t %d\n",line);
        printf("Compilation date:     \t %s\n",date);
        printf("Compilator version:   \t %s\n",version);
        printf("Optimization:         \t %s\n",opt==1 ? "Yes" : "No");
        printf("Size optimization:    \t %s\n",opt_size==1 ? "Yes" : "No");

        if (txt == NULL)
        va_start(argp, txt);
        vprintf(txt, argp);

void other_function() {
        err_print("other %s (%d+%d=%d)", "description",2,2,5);

int main() {
        err_print("test %d", 2);
        return 0;
	// if, redirect to
	if (strtolower(substr($_SERVER['HTTP_HOST'], 0, 3)) == "www") {
		header("Location:" . $_SERVER['REQUEST_URI']);
	// Full path to current URL (including query string)
	//echo "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        // description of your code here

>> "%.2f" % 45.4324234321421
=> "45.43"

>> "[%s]" % "Hey you dirty old ruby, put me in brackets. NOW!"
=> "[Hey you dirty old ruby, put me in brackets. NOW!]"

For more complex substitutions, pass the arguments as an array:
>> "[%s] And a number:%.1f" % ["Hey you dirty old ruby, put me in brackets. NOW!",43.4323]
=> "[Hey you dirty old ruby, put me in brackets. NOW!] And a number:43.4"
        # 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))

def wep_key(text)

        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? # => false 2.hours.from_now # => true

module BeforeAndAfter

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

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

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
/* Javascript functions */
function JSfunc()
	/* Making transliteration! */
	this.strTranslit = function(el)
		new_el = document.getElementById('out');
		A = new Array();
		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; }
var oJS = new JSfunc();

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

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)
        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..
    $md5_hash = md5(rand(0,9999)); 
    $security_code = substr($md5_hash, 25, 5); 
    $_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); 
    imageline($image, 0, $height/2, $width, $height/2, $grey); 
    imageline($image, $width/2, 0, $width/2, $height, $grey); 
    header("Content-Type: image/jpeg"); 
<form name="form1" method="post" action="form.php">
<div align="center">
<input name="Submit" type="submit" value="back"></div>
<div align="center">

$imag = $_POST['number'];
$user = md5($imag);
//echo "$imag  =  =  = $key<br>";
echo ("Verification success");
echo "You have entered wrong verification code!!<br> 
		Please go back and enter proper value.";}
<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>
<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>
        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 :

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);

    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('','')) {
	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 ()

(defun flymake-scala-init ()
  (let* ((text-of-first-line (buffer-substring-no-properties (point-min) (min 20 (point-max)))))
      (remove-hook 'after-save-hook 'flymake-after-save-hook t)
      (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."
  (indent-line-to (max 0 (scala-calculate-indentation))))

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

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

(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."
    (goto-char rstart)
    (let ((open-count 0)
	  (close-count 0)
      (while (and (< (point) rend)
		  (progn (setq opoint (point))
			 (re-search-forward "\\s)\\|\\s(" rend t)))
	(if (= opoint (point))
	    (forward-char 1)

            ;; 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)