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

Snippets

  • submit to reddit

Recent Snippets

                    By Shane Allen.

RewriteEngine On
RewriteCond %{HTTP_X_MOZ} ^prefetch$
RewriteRule ^.*$ - [F]
                
                    Suppose you have a bunch of files where you need to make the same substitution. This oneliner will make the substitution and keep the old version in backups. This is particularly handy for configuration files.

perl -p -i.bak -e 's:oldtext:newtext:g' *.conf
                 
                    Version 2.. it had issues with zombie / defunct processes on Linux. This is significantly more stable, and I'm currently serving 300,000+ requests a day on something based off of this:

#!/usr/bin/perl

# Basic pre-forking HTTP daemon - version 2
# By Peter Cooper - http://www.petercooper.co.uk/
#
# Inspiration and various rehashed snippetsof code from the Perl 
# cfdaemon engine - http://perl-cfd.sourceforge.net/
#
# You can switch out HTTP::Daemon and make it a pre-forking daemonized 
# 'anything' if you wish..

use HTTP::Daemon;
use HTTP::Status;
use CGI;
use POSIX;

my $totalChildren = 15;				# Number of listening children to keep alive
my $childLifetime = 10;			# Let each child serve up to this many requests
my $logFile = "/tmp/daemon.log";	# Log requests and errors to this file
my %children;							# Store pids of children
my $children = 0;						# Store number of currently active children

&daemonize;								# Daemonize the parent

my $d = HTTP::Daemon->new( LocalPort => 1981, LocalAddr => '127.0.0.1', Reuse => 1, Timeout => 180 ) || die "Cannot create socket: $!\n";

warn ("master is ", $d->url);

&spawnChildren;
&keepTicking;
exit;


# spawnChildren - initial process to spawn the right number of children

sub spawnChildren {
	for (1..$totalChildren) {
		&newChild();
	}
}


# keepTicking - a never ending loop for the parent process which just monitors
# dying children and generates new ones

sub keepTicking {
	while ( 1 ) {
		sleep;
	  	for (my $i = $children; $i < $totalChildren; $i++ ) {
		  &newChild();
		}
	};
}


# newChild - a forked child process that actually does some work

sub newChild {
	my $pid;
	my $sigset = POSIX::SigSet->new(SIGINT);				# Delay any interruptions!
   sigprocmask(SIG_BLOCK, $sigset) or die "Can't block SIGINT for fork: $!";
   die "Cannot fork child: $!\n" unless defined ($pid = fork);
	if ($pid) {
		$children{$pid} = 1;										# Report a child is using this pid
		$children++;												# Increase the child count
		warn "forked new child, we now have $children children";
		return;														# Head back to wait around
	}
	
	my $i;
	while ($i < $childLifetime) {				# Loop for $childLifetime requests
		$i++;
		my $c = $d->accept or last;							# Accept a request, or if timed out.. die early
		$c->autoflush(1);
		logMessage ("connect:". $c->peerhost . "\n");	# We've accepted a connection!
     	my $r = $c->get_request(1) or last;					# Get the request. If it fails, die early

		# Insert your own logic code here. The request is in $r
		# What we do here is check if the method is not GET, if so.. send back a 403.

		my $url = $r->url;
		$url =~ s/^\///g;

     	if ($r->method ne 'GET') { 
			$c->send_error(RC_FORBIDDEN); 
			logMessage ($c->peerhost . " made weird request\n"); 
			redo;
		}
		
		my $response = HTTP::Response->new(200);			# Put together a response
		logMessage ($c->peerhost . " " . $d->url . $url . "\n");	
		$response->content("<html><body>The daemon works! This child has served $i requests.</body></html>");
#				$response->content("document.write('OK $i<br \/>');");
		$response->header("Content-Type" => "text/html");
		$c->send_response($response);							# Send back a basic response
		
		logMessage ("disconnect:" . $c->peerhost . " - ct[$i]\n");		# Log the end of the request
      $c->close;
	}
	
	warn "child terminated after $i requests";
	exit;
}


# REAPER - a reaper of dead children/zombies with exit codes to spare

sub REAPER {                            
	my $stiff;
	while (($stiff = waitpid(-1, &WNOHANG)) > 0) {
		warn ("child $stiff terminated -- status $?");
		$children--;
		$children{$stiff};
	}
	$SIG{CHLD} = \&REAPER;
}        

# daemonize - daemonize the parent/control app

sub daemonize {
	my $pid = fork;												# Fork off the main process
	defined ($pid) or die "Cannot start daemon: $!"; 	# If no PID is defined, the daemon failed to start
	print "Parent daemon running.\n" if $pid;				# If we have a PID, the parent daemonized okay
	exit if $pid;													# Return control to the user

   # Now we're a daemonized parent process!

	POSIX::setsid();												# Become a session leader

	close (STDOUT);												# Close file handles to detach from any terminals
	close (STDIN);
	close (STDERR);

	# Set up signals we want to catch. Let's log warnings, fatal errors, and catch hangups and dying children

	$SIG{__WARN__} = sub {
			&logMessage ("NOTE! " . join(" ", @_));
	};
	
	$SIG{__DIE__} = sub { 
		&logMessage ("FATAL! " . join(" ", @_));
		exit;
	};

	$SIG{HUP} = $SIG{INT} = $SIG{TERM} = sub {			# Any sort of death trigger results in instant death of all
	  my $sig = shift;
	  $SIG{$sig} = 'IGNORE';
	  kill 'INT' => keys %children;
	  die "killed by $sig\n";
	  exit;
	};	
	
	$SIG{CHLD} = \&REAPER;
}

# logMessage - append messages to a log file. messy, but it works for now.

sub logMessage {
	my $message = shift;
	(my $sec, my $min, my $hour, my $mday, my $mon, my $year) = gmtime();
	$mon++;
	$mon = sprintf("%0.2d", $mon);
	$mday = sprintf("%0.2d", $mday);
	$hour = sprintf("%0.2d", $hour);
	$min = sprintf("%0.2d", $min);
	$sec = sprintf("%0.2d", $sec);
	$year += 1900;
	my $time = qq{$year/$mon/$mday $hour:$min:$sec};
	open (FH, ">>" . $logFile);
	print FH $time . " - " . $message;
	close (FH);
}
                
                    
ActiveRecord::Base.connection.select_one('select sum(quantity) from table').to_i
arrayofhashes = ActiveRecord::Base.connection.select_all('select * from table')
                
                    
>> for i in [1]
>>   puts i
>> end.any? or puts "empty!"
1
=> true
>> for i in [ ]
>>   puts i
>> end.any? or puts "empty!"
empty!
=> nil

short circuit evaluation is not intutitive? try this.

>> class Array
>>   alias :__empty? :empty?
>>   def empty?
>>     yield if __empty? and block_given?
>>     __empty?
>>   end
>> end
=> nil
>> for i in [1]
>>   puts i
>> end.empty? { puts "empty!" }
1
=> false
>> for i in [ ]
>>   puts i
>> end.empty? { puts "empty!" }
empty!
=> true
                
                    I needed a Ruby Hash class that could extract a random key from the keys that have not been extracted before. Plus that the class should be re-entrant... 

I found baby's class, but it was not working (at least not in Ruby 1.8.x). I made it work (slight changes), and I added the keys_not_used to make it work faster (baby's random would cycle almost forever on large lists). But I would say all credit should go to the original author, who did all the hard work. 

Without further ado, here is the new version:
class RandomHash < Hash 

   @keys_used = nil 
  
   def random_key 
      if @keys_used == nil then
         @keys_used = Hash.new 
      else
         @keys_used = Hash.new if @keys_used.size == self.size
      end
      
      if (@keys_used.size == 0) then
         pos = rand(self.size)
         key = self.keys[pos]
      else
         @keys_not_used = Hash.new
     	 self.keys.each{ |key|
         	if (! @keys_used.include?(key)) then
            	    @keys_not_used[key] = 1
         	end
	     }
	     pos = rand(@keys_not_used.size)
	     key = @keys_not_used.keys[pos]
	  end
	  
      @keys_used[key] = 1
      return key 
   end 
end 

# Test code
$sources = Hash.new
$RandomSources = RandomHash.new

begin

   (1..10).each{ |val|
      $sources["#{val}"] = 1
   }
   
   $sources.each { |src|
      puts "Src=#{src}"
      $RandomSources[src] = 1
   }

   RandomKeys = Hash.new
   (0..$sources.length).each{ |index| # one more than all values
      key = $RandomSources.random_key
      print "Extracted #{key} ... It's a"
      if (!RandomKeys.has_key?(key)) then
         puts " NEW key!"
         RandomKeys[key] = 1
      else
         puts "n OLD key!"
      end
   }
end
                
                    
<%
On Error Resume Next

If err.Number <> 0 Then
  Response.Write "Number = " & err.Number & "<p>"
  Response.Write "Description = " & err.Description & "<p>"
  Response.Write "Source = " & err.Source
  err.Clear
End If
%>
                
                    
XML:
<addresses>
  <address>
    <name>Robert Jones</name>	
    <street>Cedar Park Way</street>
    <city>Atlanta</city>
    <postcode>30083</postcode>
  </address>
</addresses>

XSLT:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
     version="1.0">

  <xsl:output method="text"/>

  <xsl:template match="addresses">
    <xsl:apply-templates>
      <xsl:sort select="name"/>
    </xsl:apply-templates>
  </xsl:template>

  <xsl:template match="address">
	<!-- Name -->
	<p ><strong><xsl:value-of select="name"/></strong> </p>

	<!--Address-->
	<xsl:variable name="street" select="street"/>
	<xsl:if test="string($street)">
		<p ><strong>Address<br/></strong>
		<xsl:value-of select="$street" /><br/>
		<xsl:value-of select="postcode"/> <xsl:value-of select="city"/>
		</p>
	</xsl:if>  
  </xsl:template>

</xsl:stylesheet>
                
                    Grep a bunch of jars for a certain package or class or expression:

find /path/to/directory -type f -name '*.jar' -print0 | xargs -n1 -0i sh -c 'jar tf "{}" | grep -q query && echo "{}"'

E.g.

find ~/soft/java/maven-repository -type f -name '*.jar' -print0 | xargs -n1 -0i sh -c 'jar tf "{}" | grep -q org.apache && echo "{}"'
                
                    This BigDecimalFormatter tries to parse the text as BigDecimal for the current locale. It uses the BigDecimal(String) constructor to keep the number of decimals from the text.

public class BigDecimalFormatter extends NumberFormatter {
    public Object stringToValue(String text) throws ParseException {
        if("".equals(text.trim())) {
             return null;
         }
         char ds = getDefaultLocaleDecimalSeparator();

         try {
             String val = text;
             if(ds != '.') {
                 val = val.replace(".", "").replace(ds, '.');
             }
             return new BigDecimal(val);
         } catch(NumberFormatException e) {
             return null;
         }
    }

    public String valueToString(Object value) throws ParseException {
        return super.valueToString(value);
    }

    private char getDefaultLocaleDecimalSeparator() {
          DecimalFormatSymbols symbols = new DecimalFormat("0").getDecimalFormatSymbols();
          char ds = symbols.getDecimalSeparator();
          return ds;
      }

}

public class BigDecimalFormatterFactory extends JFormattedTextField.AbstractFormatterFactory {
    public JFormattedTextField.AbstractFormatter getFormatter(JFormattedTextField tf) {
        return new BigDecimalFormatter();
    }
}

Use it like this:

bigdecimalfield.setFormatterFactory(new BigDecimalFormatterFactory());