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

Recent Snippets

                    If you have three tables, 'posts', 'tags', and a join table 'posts_tags', and you wish to find all posts which are all associated with a number of different tags, you can use this SQL trick:

SELECT p.* FROM posts_tags pt, posts p, tags t WHERE pt.tag_id = AND ( IN ('tag1', 'tag2', 'tag3')) AND GROUP BY HAVING COUNT( = 3;
.. where 3 is the number of tags in total. In Ruby/Rails, if you have an array called 'tags' containing the tags, you could use this code:

@posts = Post.find_by_sql ("SELECT p.* FROM posts_tags pt, posts p, tags t WHERE pt.tag_id = AND ( = '" + tags.uniq.join ('\' OR\'') + "') AND GROUP BY HAVING COUNT( = " + tags.uniq.length.to_s)

This is how Snippets itself works. You can also add a p.user_id check to the HAVING operator to only find posts with certain tags by a certain user.                
                    Tobi posted this as a new URL scheme for Typo.

# allow neat perma urls
map.connect 'articles/:year/:month/:day', :controller  => 'articles', 
     :action => 'find_by_date', 
     :year => /\d{4}/, :day => nil, :month => nil
map.connect 'articles/:year/:month/:day/:title', :controller  => 'articles', 
     :action => 'permalink', :year => /\d{4}/
                    Run as root:

#Software suspend
echo 4 > /proc/acpi/sleep

#umount and mount all devices
umount -a -r
mount -a
                    Looking up the length of an array on each iteration of a loop is slow and inefficient (if the length of the array isn't changing).

If it's OK to iterate from back to front:
for ( var i=myArray.length-1; i>=0; --i ){

If you need to go from front to back:
for ( var i=0, len=myArray.length; i<len; ++i ){
Math.randomMax = function(maxVal,asFloat){
	var val = Math.random()*maxVal;
	return asFloat?val:Math.round(val);

For a random integer between 0 and 10 (inclusive), simply:
var theNumber = Math.randomMax( 10 );

For a random float value between 0 and 10, pass a truth value to the second parameter:
var theNumber = Math.randomMax( 10, true );
/usr/sbin/ioreg -p IODeviceTree -n battery -w 0 | grep IOBatteryInfo

ioreg -l -w0 | grep -i IOBatteryInfo
@params[:tags].map do |tag|
	Tag.find_by_name (tag) rescue nil
                    When you don't want an application to apply to a certain action.. say AJAX or RSS/xml output..

layout 'application', :except => :create_with_ajax
Person.find_by_user_name_and_password(user_name, password)
<%= select('user', 'sites', Site.find_all.collect  {|site|}) %>