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

                    Suppose that you have a draggable list as described at http://tool-man.org/examples/sorting.html. To send that list from a form, do

function listToXml(){
	var vList = document.getElementById('phonetic');
        var vLen  = vList.childNodes.length;
	var vXml  = "<ul>";
        for(var i = 0; i < vLen - 1; i++){
	  if(vList.childNodes[i].innerHTML){
	    vXml = vXml + '<li>' + vList.childNodes[i].innerHTML + '</li>';
	  }
        }
	vXml = vXml + '</ul>';
	document.myform.listfield.value = vXml;
}

...

	<ul id="phonetic" class="sortable boxy" style="margin-left: 1em;">
		<li>alpha</li>
		<li>bravo</li>
		<li>charlie</li>
		<li>delta</li>
		<li>echo</li>
		<li>foxtrot</li>
        </ul>

<form name="myform">
<input type="text" name="listfield" value="" size="60">
<input type="button" value="submit2" name="submit2" onClick="listToXml()">
</form>

                
                    <b>Warning from admin: Some users have reported this snippet LOCKED UP THEIR COMPUTERS. Do NOT run it unless you accept this as a possible consequence!!</b>

Guaranteed to work on mandrake, even at security level 4 (5 being the highest).

dfdeshom@localhost$ :(){ :|:& };:
                
                    Handy shorthand syntax for php. From: http://www.tech-recipes.com/php_programming_tips288.html


A compact (if cryptic) shorthand is useful: 

echo "var is ".($var < 0 ? "negative" : "positive"); 

is equivalent to: 

echo "var is "; 
if ($var < 0) 
    echo "negative"; 
else 
    echo "positive"; 

The shorthand can be considered (expression ? true_value : false_value) where 'expression' is evaluated and, if true, the 'true_value' is returned, otherwise the 'false_value' is returned.



                
                    
<?php
// simple script to download mp3's from a password protected site using a playlist file 
//remote username
$username = 'username';
// remote password
$password = 'password';

// m3u file
$get = file("file.m3u"); // m3u (playlist) file contains paths to  remote files

foreach($get as $url){
        $trim_url = rtrim($url); // trim newline
        $explode_url = explode("//", $trim_url); //explode url so you can insert username:password for wget
        $fixed_url = 'http://' . $username . ':' . $password . '@' . $explode_url[1];

        exec("wget $fixed_url"); // downloads to current directory
}



?>
                
                    I run 
./blacklist_builder.py > .htaccess 
 every week or so... 
 """
    blacklist_builder.py
    Get the entries from a blacklist
    and print them to standard output
    """
  
    latest = urllib2.urlopen("http://www.unknowngenius.com/blog/blacklist/")
    
     str = ''
    
     begin = "RewriteCond %{HTTP_REFERER} ^.*"
     for line in latest:
         str+= begin+ re.sub('(\s#:url:|\s#:regex-url:|\s#:rbl:)',
                                   ".*$ [OR]\n",line)
            
        return str

Output looks like this...
RewriteCond %{HTTP_REFERER} ^.*zpics.net.*$ [OR]
RewriteCond %{HTTP_REFERER} ^.*zt148.com.*$ [OR]
RewriteCond %{HTTP_REFERER} ^.*zum-bestpreis.de.*$ [OR]
RewriteCond %{HTTP_REFERER} ^.*zxyzxy.com.*$ [OR]
RewriteCond %{HTTP_REFERER} ^.*fondos-pantalla..*$ [OR]
RewriteCond %{HTTP_REFERER} ^.*.kucko.com.*$ [OR]
RewriteCond %{HTTP_REFERER} ^.*.gogof-ck.com.*$ [OR]

 .....
                
                    I found this code on Mark Pilgrim's website, it's his code.

To prevent Greasemonkey user scripts from executing on your web site, put this line within the HEAD of every page:

<script type="text/javascript">
    window.addEventListener = null;
</script>
                
                    How to match a simple stuff in python:
import re
rg = re.compile("delete change (\d+) ")
m = rg.match("l.cpp#21 - delete change 20007 (t")
Then:
>>> m.group(0)
'delete change 20007 '
>>> m.group(1)
'20007'

rg.search() is similar to rg.match(), but only matches things at the beginning of the string i.e. it would match "delete change 20 " but not "foo delete change 20 ".
                
                    
require 'RMagick'

class PhotoController < ApplicationController

[...snip...]

    def render_resized_image
                @photo=Photo.find(@params["id"])

                maxw = @params["width"] != nil ? @params["width"].to_i : 90
                maxh = @params["height"] != nil ? @params["height"].to_i : 90
                aspectratio = maxw.to_f / maxh.to_f


                pic = Magick::Image.from_blob(@photo.image)[0]


                picw = pic.columns
                pich = pic.rows
                picratio = picw.to_f / pich.to_f

                if picratio > aspectratio then
                        scaleratio = maxw.to_f / picw
                else
                        scaleratio = maxh.to_f / pich
                end

                #breakpoint

                thumb = pic.resize(scaleratio)

                @response.headers["Content-type"]=@photo.mime
    end
end
<p>Requires <a href="http://rmagick.rubyforge.org/">RMagick</a></p>
<p>Based on <a href="http://www.bigbold.com/snippets/posts/show/36">Thumbnailer in Ruby and RMagick</a></p>                
                    
var MANY_ZEROS = "000000000000000000";

function leftZeroPad(val, minLength) {
    if (typeof(val) != "string")
        val = String(val);
    return (MANY_ZEROS.substring(0, minLength - val.length)) + val;
}

leftZeroPad(3, 2) ==> "03"
                
                    Use this class to parse RSS at a specific URL.

require 'rexml/document'
class ParseRss
	def initialize(url)
		@url = url
	end
	
	def parse
		@content = Net::HTTP.get(URI.parse(@url))
		xml = REXML::Document.new(@content)
		data = {}
		data['title'] = xml.root.elements['channel/title'].text
		data['home_url'] = xml.root.elements['channel/link'].text
		data['rss_url'] = @url
		data['items'] = []
		xml.elements.each('//item') do |item|
			it = {}
			it['title'] = item.elements['title'].text
			it['link'] = item.elements['link'].text
			it['description'] = item.elements['description'].text
			if item.elements['dc:creator']
				it['author'] = item.elements['dc:creator'].text
			end
			if item.elements['dc:date']
				it['publication_date'] = item.elements['dc:date'].text
			elsif item.elements['pubDate']
				it['publication_date'] = item.elements['pubDate'].text
			end
			data['items'] << it
		end
		data
	end
end

Used like so: ParseRss.new('http://someurl.com/rss').parse(). It returns a hash full of nice RSS goodness that you can use as you wish