<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DZone Snippets: parse code</title>
    <link>http://snippets.dzone.com/posts</link>
    <pubDate>Fri, 25 Jul 2008 00:38:38 GMT</pubDate>
    <description>DZone Snippets: parse code</description>
    <item>
      <title>ARGV Parser</title>
      <link>http://snippets.dzone.com/posts/show/5099</link>
      <description>This function parse ARGV and return a string.&lt;br /&gt;See exemples for more informations :&lt;br /&gt;&lt;br /&gt;// Go : http://blackh.badfile.net/wordz/&lt;br /&gt;&lt;br /&gt;Function :&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;  def options(param)&lt;br /&gt;  &lt;br /&gt;	i = 0&lt;br /&gt;		ARGV.each  { |valeur|&lt;br /&gt;		&lt;br /&gt;    		if (valeur == '-' + param.to_s)&lt;br /&gt;				return ARGV[i+1]&lt;br /&gt;			elseif (valeur != '-' + param.to_s)&lt;br /&gt;				return false&lt;br /&gt;			end&lt;br /&gt;		i += 1&lt;br /&gt;		}&lt;br /&gt;		&lt;br /&gt;   end&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Usage :&lt;br /&gt;&lt;br /&gt;// cmd&gt; ruby test.rb -o foo&lt;br /&gt;&lt;code&gt;&lt;br /&gt;&lt;br /&gt;	out =  self.options('o')&lt;br /&gt;&lt;br /&gt;	if (out != false and out.empty? == false)&lt;br /&gt;                   puts out # print -&gt; foo&lt;br /&gt;	end&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Sun, 03 Feb 2008 20:24:59 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/5099</guid>
      <author>Black_H (Black_H)</author>
    </item>
    <item>
      <title>Regex-based parsing technique</title>
      <link>http://snippets.dzone.com/posts/show/4852</link>
      <description>&lt;code&gt;&lt;br /&gt;&lt;br /&gt;#!/usr/local/bin/ruby -w&lt;br /&gt;&lt;br /&gt;# Regular expressions and strings with embedded objects&lt;br /&gt;# From: http://t-a-w.blogspot.com/2007/06/regular-expressions-and-strings-with.html&lt;br /&gt;# Author: Tomasz W&#281;grzanowski&lt;br /&gt;# License: &lt;br /&gt;# Creative Commons License, http://creativecommons.org/licenses/by-sa/3.0/&lt;br /&gt;# GNU Free Documentation License, http://en.wikipedia.org/wiki/GNU_Free_Documentation_License&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;def hash_or_die(kw)&lt;br /&gt;  Hash.new{|ht,k| raise "Unknown key: #{k}"}.merge(kw)&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;def parse(data)&lt;br /&gt;  esc = hash_or_die "\\" =&gt; "A", "\"" =&gt; "B", "n" =&gt; "C", "'" =&gt; "D"&lt;br /&gt;  rev_esc = hash_or_die "A" =&gt; "\\", 'B' =&gt; "\"", "C" =&gt; "n", "D" =&gt; "'"&lt;br /&gt;  data = data.gsub(/\\(.)/) {"\x00" + esc[$1]}&lt;br /&gt;  strs = []&lt;br /&gt;  data = data.gsub(/('[^']*')/) { # '&lt;br /&gt;    strs &lt;&lt; $1&lt;br /&gt;    "\x01&lt;#{strs.size-1}&gt;"&lt;br /&gt;  }&lt;br /&gt;  records = []&lt;br /&gt;  data.scan(/\((.*?)\)/) {&lt;br /&gt;    records &lt;&lt; $1.split(/,/).map{|field|&lt;br /&gt;      field.gsub(/\x01&lt;(\d+)&gt;/) {&lt;br /&gt;        strs[$1.to_i]}.gsub(/\x00(.)/){ rev_esc[$1]&lt;br /&gt;      }&lt;br /&gt;    }&lt;br /&gt;  }&lt;br /&gt;  records&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;def sql_str_unquote(str)&lt;br /&gt;  str =~ /\A'(.*)'\Z/ or raise "SQL string format is wrong: #{str}"&lt;br /&gt;  $1.gsub(/\\(.)/) {$1}&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;=begin&lt;br /&gt;&lt;br /&gt;page_fn = Dir["plwiki-*-page.sql"].sort[-1]&lt;br /&gt;externallinks_fn = Dir["plwiki-*-externallinks.sql"].sort[-1]&lt;br /&gt;&lt;br /&gt;pages = {}&lt;br /&gt;&lt;br /&gt;File.open(page_fn).each{|line|&lt;br /&gt;  next unless line =~ /\AINSERT INTO `page` VALUES (.*)\Z/&lt;br /&gt;  parse($1).each{|id,ns,title,*stuff|&lt;br /&gt;    next unless ns == "0"&lt;br /&gt;    title = sql_str_unquote(title)&lt;br /&gt;    pages[id] = title&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;File.open(externallinks_fn).each{|line|&lt;br /&gt;  next unless line =~ /\AINSERT INTO `externallinks` VALUES (.*)\Z/&lt;br /&gt;  parse($1).each{|from,to,index|&lt;br /&gt;    title = pages[from]&lt;br /&gt;    next unless title&lt;br /&gt;    to = sql_str_unquote(to)&lt;br /&gt;    next unless to =~ /\Ahttp:\/\//&lt;br /&gt;    puts "#{title}\t#{to}"&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;=end&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;sql_dump = &lt;&lt;-EOS&lt;br /&gt;&lt;br /&gt;INSERT INTO `page` VALUES (1,0,'Astronomia','',1800,0,0,0.600461925007833,'20070601091320',8076762,8584,0), (2,0,'AWK','',329,0,0,0.487812640599732,'20070530195555',8058046,4265,0), (4,0,'Alergologia','',108,0,0,0.580574716050713,'20070520093413',7912844,292,0), ...&lt;br /&gt;INSERT INTO `page` VALUES (14880,0,'D&#378;wignica_linotorowa','',26,0,0,0.597327036408081,'20060814072401',4282357,727,0), (14881,0,'Urz&#261;dzenia_transportowe','',91,0,0,0.176666489966834,'20070527090143',2976610,1041,0), ...&lt;br /&gt;&lt;br /&gt;EOS&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;pages = {}&lt;br /&gt;&lt;br /&gt;sql_dump.each{|line|&lt;br /&gt;  next unless line =~ /\AINSERT INTO `page` VALUES (.*)\Z/&lt;br /&gt;  parse($1).each{|id,ns,title,*stuff|&lt;br /&gt;    next unless ns == "0"&lt;br /&gt;    title = sql_str_unquote(title)&lt;br /&gt;    pages[id] = title&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;p pages&lt;br /&gt;&lt;br /&gt;=begin&lt;br /&gt;&lt;br /&gt;sql_dump.each{|line|&lt;br /&gt;  next unless line =~ /\AINSERT INTO `externallinks` VALUES (.*)\Z/&lt;br /&gt;  parse($1).each{|from,to,index|&lt;br /&gt;    title = pages[from]&lt;br /&gt;    next unless title&lt;br /&gt;    to = sql_str_unquote(to)&lt;br /&gt;    next unless to =~ /\Ahttp:\/\//&lt;br /&gt;    puts "#{title}\t#{to}"&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;=end&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;#-----------------&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;require 'pp'&lt;br /&gt;&lt;br /&gt;lisp_code = '(a (b c) (d (e) f g) (((h))))'&lt;br /&gt;nodes = []&lt;br /&gt;&lt;br /&gt;lisp_code.gsub!(/([a-z]+)/) {&lt;br /&gt;  nodes &lt;&lt; [:atom, $1]&lt;br /&gt;  "&lt;#{nodes.size-1}&gt;"&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;#p nodes&lt;br /&gt;&lt;br /&gt;lisp_code.gsub!(/\s/,"")&lt;br /&gt;#puts lisp_code&lt;br /&gt;&lt;br /&gt;true while lisp_code.gsub!(/\(((?:&lt;\d+&gt;)*)\)/) {&lt;br /&gt;  #p nodes&lt;br /&gt;  nodes &lt;&lt; [:app, *$1.scan(/&lt;(\d+)&gt;/).map{|x,| nodes[x.to_i]}]&lt;br /&gt;  "&lt;#{nodes.size-1}&gt;"&lt;br /&gt;}&lt;br /&gt;lisp_code =~ /&lt;(\d+)&gt;/&lt;br /&gt;&lt;br /&gt;#puts&lt;br /&gt;#p nodes&lt;br /&gt;#puts&lt;br /&gt;&lt;br /&gt;pp nodes[$1.to_i]&lt;br /&gt;&lt;br /&gt;# Output:&lt;br /&gt;#  [:app,&lt;br /&gt;#  [:atom, "a"],&lt;br /&gt;#  [:app, [:atom, "b"], [:atom, "c"]],&lt;br /&gt;#  [:app, [:atom, "d"], [:app, [:atom, "e"]], [:atom, "f"], [:atom, "g"]],&lt;br /&gt;#  [:app, [:app, [:app, [:atom, "h"]]]]]&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;#------------------&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;math_code = '(2 + 2 * 2) / ((2 + 2) * 2)'&lt;br /&gt;nodes = []&lt;br /&gt;&lt;br /&gt;math_code.gsub!(/(\d+)/) {&lt;br /&gt;  nodes &lt;&lt; $1.to_i&lt;br /&gt;  "&lt;#{nodes.size-1}&gt;"&lt;br /&gt;}&lt;br /&gt;math_code.gsub!(/\s/,"")&lt;br /&gt;&lt;br /&gt;until math_code =~ /\A&lt;(\d+)&gt;\Z/&lt;br /&gt;  next if math_code.gsub!(/\((&lt;\d+&gt;)\)/) { $1 }&lt;br /&gt;  next if math_code.gsub!(/&lt;(\d+)&gt;([\*\/])&lt;(\d+)&gt;/) {&lt;br /&gt;    nodes &lt;&lt; [$2, nodes[$1.to_i], nodes[$3.to_i]]&lt;br /&gt;    "&lt;#{nodes.size-1}&gt;"&lt;br /&gt;  }&lt;br /&gt;  next if math_code.gsub!(/&lt;(\d+)&gt;([\+\-])&lt;(\d+)&gt;/) {&lt;br /&gt;    nodes &lt;&lt; [$2, nodes[$1.to_i], nodes[$3.to_i]]&lt;br /&gt;    "&lt;#{nodes.size-1}&gt;"&lt;br /&gt;  }&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;pp nodes[$1.to_i]&lt;br /&gt;&lt;br /&gt;# Output:&lt;br /&gt;# ["/", ["+", 2, ["*", 2, 2]], ["*", ["+", 2, 2], 2]]&lt;br /&gt;&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;</description>
      <pubDate>Thu, 06 Dec 2007 15:43:11 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/4852</guid>
      <author>ntk ()</author>
    </item>
    <item>
      <title>xml parsing using content handler</title>
      <link>http://snippets.dzone.com/posts/show/4719</link>
      <description>// description of your code here&lt;br /&gt;given an xml:&lt;br /&gt;&lt;code&gt;&lt;br /&gt;&lt;request&gt;&lt;br /&gt;	&lt;action&gt;managePermissions&lt;/action&gt;&lt;br /&gt;	&lt;xml&gt;&lt;br /&gt;		&lt;permission type='chm:allow-roles'&gt;&lt;br /&gt;			&lt;role&gt;role1&lt;/role&gt;&lt;br /&gt;			&lt;role&gt;role2&lt;/role&gt;&lt;br /&gt;			&lt;role&gt;role3&lt;/role&gt;&lt;br /&gt;		&lt;/permission&gt;&lt;br /&gt;		&lt;permission type='chm:deny-roles'&gt;&lt;br /&gt;			&lt;role&gt;roleA&lt;/role&gt;&lt;br /&gt;			&lt;role&gt;roleB&lt;/role&gt;&lt;br /&gt;		&lt;/permission&gt;&lt;br /&gt;	&lt;/xml&gt;&lt;br /&gt;	&lt;parameters&gt;&lt;br /&gt;		&lt;uuid&gt;xyz&lt;/uuid&gt;&lt;br /&gt;	&lt;/parameters&gt;&lt;br /&gt;&lt;/request&gt;&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;will parse into permission map&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;static Map&lt;String, List&lt;String&gt;&gt; getPermissionMap(String xml){&lt;br /&gt;    final Map&lt;String, List&lt;String&gt;&gt; permissionMap = new HashMap&lt;String, List&lt;String&gt;&gt;();&lt;br /&gt;    &lt;br /&gt;    //handler will produce a permission map based on xml&lt;br /&gt;    ContentHandler allowDenyXmlHandler = new DefaultHandler() {&lt;br /&gt;      private String permissionType;&lt;br /&gt;      private List&lt;String&gt; roleList = new ArrayList&lt;String&gt;();&lt;br /&gt;      private Stack&lt;String&gt; nodes = new Stack&lt;String&gt;();&lt;br /&gt;      private StringBuilder roleBuffer = new StringBuilder();&lt;br /&gt;      &lt;br /&gt;      /**&lt;br /&gt;       * Get type of permission that is defined in type attribute&lt;br /&gt;       */&lt;br /&gt;      public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {&lt;br /&gt;        nodes.push(qName.trim());&lt;br /&gt;        //get type of permission&lt;br /&gt;        if(nodes.peek().equals(PERMISSION)){&lt;br /&gt;          permissionType = attributes.getValue(PERMISSION_TYPE);&lt;br /&gt;        }&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;      /**&lt;br /&gt;       * Get role data for specified role&lt;br /&gt;       */&lt;br /&gt;      public void characters(char ch[], int start, int length) throws SAXException {&lt;br /&gt;        if(nodes.peek().equals(ROLE)){&lt;br /&gt;          roleBuffer.append(ch, start, length);  &lt;br /&gt;        }&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;      /**&lt;br /&gt;       * Populate role list if role end tag, or populate permission map if permission end tag&lt;br /&gt;       */&lt;br /&gt;      public void endElement(String uri, String localName, String qName) throws SAXException {&lt;br /&gt;        String nodeName = nodes.pop();&lt;br /&gt;        if(nodeName.equals(ROLE)){&lt;br /&gt;          roleList.add(roleBuffer.toString());&lt;br /&gt;          roleBuffer.setLength(0);  &lt;br /&gt;        }else if(nodeName.equals(PERMISSION)){&lt;br /&gt;          List&lt;String&gt; tempList = new ArrayList&lt;String&gt;();&lt;br /&gt;          tempList.addAll(roleList);&lt;br /&gt;          permissionMap.put(permissionType, tempList);&lt;br /&gt;          roleList.clear();&lt;br /&gt;        }&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;      public void endDocument() throws SAXException {&lt;br /&gt;        // sanity check&lt;br /&gt;        if (nodes.size() &gt; 0) logger.error("Node stack is not empty !!!");&lt;br /&gt;      }&lt;br /&gt;    };&lt;br /&gt;    &lt;br /&gt;    try {&lt;br /&gt;      SAXParser parser = null;&lt;br /&gt;      // get SAXParser&lt;br /&gt;      synchronized (XMLParserHelper.saxParserFactory) {&lt;br /&gt;        parser = XMLParserHelper.saxParserFactory.newSAXParser();&lt;br /&gt;      }&lt;br /&gt;      // Set custom content handler&lt;br /&gt;      parser.getXMLReader().setContentHandler(allowDenyXmlHandler);&lt;br /&gt;      // parse xml&lt;br /&gt;      parser.getXMLReader().parse(new InputSource(new StringReader(xml)));&lt;br /&gt;&lt;br /&gt;    } catch (Exception e) {&lt;br /&gt;      logger.error("[DLA00002] Unable to process permissions from XML {" + xml + "}", e);&lt;br /&gt;    }&lt;br /&gt;    &lt;br /&gt;    return permissionMap;&lt;br /&gt;  }&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Tue, 30 Oct 2007 18:04:26 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/4719</guid>
      <author>mwaschkowski (Mark Waschkowski)</author>
    </item>
    <item>
      <title>Parse Exim log file with SpamAssassin score</title>
      <link>http://snippets.dzone.com/posts/show/4590</link>
      <description>&lt;code&gt;&lt;br /&gt;grep '\[Spam score: [1-9]' /var/log/exim/main.log | awk '{print $3}' | xargs -t -i grep {} /var/log/exim/main.log &gt; /var/log/exim/spam_score.log&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;grep 'reporter\.pl' /var/log/exim/main.log | awk '{print $3}' | xargs -t -i grep {} /var/log/exim/main.log &gt; /var/log/exim/spam_reporter.pl.log&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Sat, 29 Sep 2007 08:50:51 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/4590</guid>
      <author>Wallace (Wallace)</author>
    </item>
    <item>
      <title>simple backup PHP application (php files + mysql db)</title>
      <link>http://snippets.dzone.com/posts/show/4539</link>
      <description>// backup a folder contains all .php files and it's mysql database. a backup.ini file is required for storing mysql root login and what folder to be backed up.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;#!/bin/sh&lt;br /&gt;&lt;br /&gt;########################################&lt;br /&gt;# simple sctipt for daily / hourly backup of PHP app + Mysql DB&lt;br /&gt;# Copyleft (c) Sayid Munawar. chenull@yahoo.com&lt;br /&gt;# LICENSE: anyone can copy / modify / distribute. whatever lah&lt;br /&gt;#&lt;br /&gt;# example of workhours backup (8 am - 5 pm. Mon - Fri)&lt;br /&gt;# 0 8-17 * * 1-5 /home/backup/backup.sh&lt;br /&gt;#&lt;br /&gt;# example of simple dayly backup ( 6 pm. Mon - Fri)&lt;br /&gt;# 0 18 * * 1-5 /home/backup/backup.sh&lt;br /&gt;########################################&lt;br /&gt;&lt;br /&gt;########################################&lt;br /&gt;# example of backup.ini. REMOVE ALL leading '#'s&lt;br /&gt;# file must be chmod 600&lt;br /&gt;#[main]&lt;br /&gt;#target = /home/backup/storage&lt;br /&gt;#mysql_user = root   ; root can connect to any db&lt;br /&gt;#mysql_pass = secret ; mysql root password&lt;br /&gt;#&lt;br /&gt;#[hukum]&lt;br /&gt;#path = /home/hukum&lt;br /&gt;#mysql_db = hukum&lt;br /&gt;#&lt;br /&gt;#[phpmyadmin]&lt;br /&gt;#path = /home/phpmyadmin&lt;br /&gt;#mysql_db = test&lt;br /&gt;########################################&lt;br /&gt;&lt;br /&gt;PATH=$PATH:/usr/bin:/bin:/usr/local/bin&lt;br /&gt;&lt;br /&gt;inifile=`dirname $0`/backup.ini&lt;br /&gt;&lt;br /&gt;test ! -r $inifile &amp;&amp; echo "ERROR! backup.ini not found nor readable" &amp;&amp; exit 1&lt;br /&gt;&lt;br /&gt;#test apakah backup.ini bisa dibaca orang lain&lt;br /&gt;echo -n `stat -c '%a' $inifile` | grep -q '[0-7]00' &gt;/dev/null 2&gt;&amp;1&lt;br /&gt;test $? -gt 0 &amp;&amp; echo "ERROR! $inifile can be read by others" &amp;&amp; exit 2&lt;br /&gt;#test `stat -c '%U' $inifile` != 'root' &amp;&amp; echo "ERROR! $inifile ownernya bukan root" &amp;&amp; exit 3&lt;br /&gt;&lt;br /&gt;# function to parse ini file (backup.ini)&lt;br /&gt;#&lt;br /&gt;# $1 -&gt; file.ini&lt;br /&gt;# $2 -&gt; section&lt;br /&gt;_parse_ini () {&lt;br /&gt;    if [ -z "$1" ] || [ -z "$2" ]; then return 0; fi&lt;br /&gt;    eval `cat $1 | \&lt;br /&gt;       sed -e 's/[[:space:]]*\=[[:space:]]*/=/g' \&lt;br /&gt;           -e 's/;.*$//' \&lt;br /&gt;           -e 's/[[:space:]]*$//' \&lt;br /&gt;           -e 's/^[[:space:]]*//' \&lt;br /&gt;           -e "s/^\(.*\)=\([^\"']*\)$/\1=\"\2\"/" | \&lt;br /&gt;       sed -n -e "/^\[$2\]/,/^\s*\[/{/^[^;].*\=.*/p;}"`&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;_parse_ini $inifile main&lt;br /&gt;&lt;br /&gt;# coba konek &lt;br /&gt;mysql -u $mysql_user  -p${mysql_pass} -e '' &gt; /dev/null 2&gt;&amp;1&lt;br /&gt;test $? -gt 0 &amp;&amp; echo "ERROR! Failed to connect to mysql" &amp;&amp; exit 4&lt;br /&gt;&lt;br /&gt;# bikin target kalo blum ada&lt;br /&gt;test ! -d $target &amp;&amp; mkdir -p $target&lt;br /&gt;&lt;br /&gt;hari=`date +%A`&lt;br /&gt;jam=`date +%H`&lt;br /&gt;&lt;br /&gt;# get pwd&lt;br /&gt;cwd=`pwd`&lt;br /&gt;&lt;br /&gt;# looping&lt;br /&gt;for section in `cat $inifile | grep '^\[' | grep -v main | sed 's/\[//' | sed 's/\]//'`; do&lt;br /&gt;  outdir=$target/$section/$hari/$jam&lt;br /&gt;  echo Backing up ${section} to $outdir...&lt;br /&gt;  # parse .ini&lt;br /&gt;  _parse_ini $inifile $section&lt;br /&gt;  # cek dulu&lt;br /&gt;  test ! -d $path &amp;&amp; echo "Warning: $path not found.  Backup process of $section skipped" &amp;&amp; echo &amp;&amp; continue&lt;br /&gt;  mysql -u $mysql_user  -p${mysql_pass} -e '' $mysql_db &gt; /dev/null 2&gt;&amp;1&lt;br /&gt;  test $? -gt 0 &amp;&amp; echo "Warning: Database $mysql_db not found.  Backup process of $section skipped" &amp;&amp; echo &amp;&amp; continue&lt;br /&gt;&lt;br /&gt;  test ! -d $outdir &amp;&amp; mkdir -p $outdir&lt;br /&gt;  cd $path&lt;br /&gt;  tar -czpf $outdir/$section.tar.gz .&lt;br /&gt;  cd $cwd&lt;br /&gt;  mysqldump -Q -u $mysql_user -p${mysql_pass} $mysql_db | gzip &gt; $outdir/${mysql_db}.sql.gz&lt;br /&gt;  ln -fs $outdir/$section.tar.gz $target/$section/latest.tar.gz&lt;br /&gt;  ln -fs $outdir/${mysql_db}.sql.gz $target/$section/latest.sql.gz&lt;br /&gt;done&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Fri, 14 Sep 2007 00:15:12 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/4539</guid>
      <author>chenull (Sayid Munawar)</author>
    </item>
    <item>
      <title>CSV parsing regex</title>
      <link>http://snippets.dzone.com/posts/show/4430</link>
      <description>The regular expression is taken from Raimond Brookman, &lt;a href="http://blogs.infosupport.com/raimondb/archive/2005/04/27/199.aspx"&gt;Regex fun with CSV&lt;/a&gt;.&lt;br /&gt;For a good general CSV overview see &lt;a href="http://www.creativyst.com/Doc/Articles/CSV/CSV01.htm"&gt;The Comma Separated Value (CSV) File Format&lt;/a&gt;.&lt;br /&gt;A complete Ruby CSV parsing library is &lt;a href="http://fastercsv.rubyforge.org"&gt;FasterCSV&lt;/a&gt; (sudo gem install fastercsv).&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;&lt;br /&gt;csv_data = &lt;&lt;-EOS&lt;br /&gt;&lt;br /&gt;fname,lname,age,salary&lt;br /&gt;nancy,davolio,33,$30000&lt;br /&gt;erin,borakova,28,$25250&lt;br /&gt;tony,raphael,35,$28700&lt;br /&gt;&lt;br /&gt;"Date","Pupil","Grade"&lt;br /&gt;"25 May","Bloggs, Fred","C"&lt;br /&gt;"25 May","Doe, Jane","B"&lt;br /&gt;"15 July","Bloggs, Fred","D"&lt;br /&gt;&lt;br /&gt;123456789,"Carr, Lisa",100000.00&lt;br /&gt;444556666,"Barr, Clark",87000.00&lt;br /&gt;777227878,"Parr, Jack",123000.00&lt;br /&gt;998877665,"Charr, Lee",123000.00&lt;br /&gt;&lt;br /&gt;Conference room 1, "John,  &lt;br /&gt;Please bring the M. Mathers file for review  &lt;br /&gt;-J.L.&lt;br /&gt;"&lt;br /&gt;10/18/2002,...&lt;br /&gt;&lt;br /&gt;John,Doe,120 jefferson st.,Riverside, NJ, 08075&lt;br /&gt;Jack,McGinnis,220 hobo Av.,Phila, PA,09119&lt;br /&gt;"John ""Da Man""",Repici,120 Jefferson St.,Riverside, NJ,08075&lt;br /&gt;Stephen,Tyler,"7452 Terrace ""At the Plaza"" road",SomeTown,SD, 91234&lt;br /&gt;,Blankman,,SomeTown, SD, 00298&lt;br /&gt;"Joan ""the bone"", Anne",Jet,"9th, at Terrace plc",Desert City,CO,00123&lt;br /&gt;&lt;br /&gt;XXXX,D,3-May-02,83.01,83.58,71.13,78.04,9645300&lt;br /&gt;XXXX,D,2-May-02,82.47,85.76,82.05,83.84,7210000,&lt;br /&gt;XXXX,D,1-May-02,86.80,90.83,81.74,85.50,14253300&lt;br /&gt;&lt;br /&gt;"1997",car model,E350&lt;br /&gt;1997,car model,E350,"  Super luxurious truck    "&lt;br /&gt;1997,car model,E350,"Go get one now&lt;br /&gt;they are going fast"&lt;br /&gt;1997,car model,E350,"Super ""luxurious"" truck"&lt;br /&gt;1997,car model,E350,"Super, luxurious truck"&lt;br /&gt;&lt;br /&gt;1997,car model,E350,"ac, abs, moon",3000.00&lt;br /&gt;1999, car model,"Venture ""Extended Edition""",,4900.00,&lt;br /&gt;1996, car model,Old Car,"BEYOND REPAIR!&lt;br /&gt;air, moon roof, loaded",4799.00&lt;br /&gt;&lt;br /&gt;This,is,a test,CSV, file," from ""http://lorance.freeshell.org/csv/test.csv""."&lt;br /&gt;It contains,"quoted text",and,numbers 1234,5678&lt;br /&gt;It also has,"quoted text with an embedded quote""&lt;- right there"&lt;br /&gt;Then there are a few,,blank fields like these here -&gt;,,,&lt;br /&gt;A quoted blank field,"",&lt;- there.&lt;br /&gt;A quoted blank field with newline,"\n",&lt;- there.&lt;br /&gt;This next one causes an error if newline handling is turned off.&lt;br /&gt;"There is a newline here -&gt;&lt;br /&gt;&lt;- and it should be processed correctly."&lt;br /&gt;ABCD&lt;br /&gt;"And here,,, is an""Error - no"&lt;br /&gt;"And here,,, is an"Error - yes&lt;br /&gt;"And here,,, is an",Error - no&lt;br /&gt;&lt;br /&gt;1,2,3&lt;br /&gt;ab,"c,d","e""f", "g"",""","h&lt;br /&gt;jk",kl&lt;br /&gt;&lt;br /&gt;"aaa","bbb","ccc"&lt;br /&gt;zzz,yyy,xxx&lt;br /&gt;"aaa","b&lt;br /&gt;bb","ccc"&lt;br /&gt;zzz,yyy,xxx&lt;br /&gt;&lt;br /&gt;"aaa","b""bb","ccc"&lt;br /&gt;&lt;br /&gt;EOS&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;csv_data.split(/(,|\r\n|\n|\r)(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))/m).each do |csv|&lt;br /&gt;#csv_data.split(/[,\n\r]+(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))/m).each do |csv|&lt;br /&gt;&lt;br /&gt;   next if csv.empty?&lt;br /&gt;&lt;br /&gt;   csv = csv.strip&lt;br /&gt;&lt;br /&gt;   if csv =~ /\A(".*[^"]|[^"].*")\z/m then     # examples: csv =&gt; "ab\nc"def  or  abc"de\nf"&lt;br /&gt;       puts&lt;br /&gt;       puts "Error:" &lt;br /&gt;       p csv &lt;br /&gt;       puts csv[/\A./mu], csv[/.\z/mu] &lt;br /&gt;       #puts csv[0..0], csv[-1..-1] &lt;br /&gt;       puts&lt;br /&gt;       next&lt;br /&gt;   end&lt;br /&gt;&lt;br /&gt;   if csv =~ /\A".*"\z/m then csv.gsub!(/\A"(.*)"\z/m, '\1') end  # remove double-quotes at string beginning &amp; end&lt;br /&gt;   if csv =~ /""/m then csv.gsub!(/""/m, '"') end                 # remove a double-quote from double double-quotes&lt;br /&gt;&lt;br /&gt;   p csv&lt;br /&gt;&lt;br /&gt;end&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;</description>
      <pubDate>Sat, 18 Aug 2007 17:17:23 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/4430</guid>
      <author>ntk ()</author>
    </item>
    <item>
      <title>Fix for camping multipart parsing issue.</title>
      <link>http://snippets.dzone.com/posts/show/4356</link>
      <description>// description of your code here&lt;br /&gt;I wrote a nice description of this issue, but snippets ate it.  &lt;br /&gt;&lt;br /&gt;In short, this parses complicated form names into nice hashes, i.e. name[asd][asd] for multipart forms.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;module Camping&lt;br /&gt;module Base&lt;br /&gt; def initialize(r, e, m) #:nodoc:&lt;br /&gt;      e = H[e.to_hash]&lt;br /&gt;      @status, @method, @env, @headers, @root = 200, m.downcase, e,&lt;br /&gt;          {'Content-Type'=&gt;'text/html'}, e.SCRIPT_NAME.sub(/\/$/,'')&lt;br /&gt;      @k = C.kp(e.HTTP_COOKIE)&lt;br /&gt;      qs = C.qs_parse(e.QUERY_STRING)&lt;br /&gt;      @in = r&lt;br /&gt;      todo = []&lt;br /&gt;      if %r|\Amultipart/form-data.*boundary=\"?([^\";,]+)|n.match(e.CONTENT_TYPE)&lt;br /&gt;        b = /(?:\r?\n|\A)#{Regexp::quote("--#$1")}(?:--)?\r$/&lt;br /&gt;        until @in.eof?&lt;br /&gt;          fh=H[]&lt;br /&gt;          for l in @in&lt;br /&gt;            case l&lt;br /&gt;            when Z: break&lt;br /&gt;            when /^Content-Disposition: form-data;/&lt;br /&gt;              fh.u H[*$'.scan(/(?:\s(\w+)="([^"]+)")/).flatten]&lt;br /&gt;            when /^Content-Type: (.+?)(\r$|\Z)/m&lt;br /&gt;              puts "=&gt; fh[type] = #$1"&lt;br /&gt;              fh[:type] = $1&lt;br /&gt;            end&lt;br /&gt;          end&lt;br /&gt;          fn=fh[:name]&lt;br /&gt;          o=if fh[:filename]&lt;br /&gt;            o=fh[:tempfile]=Tempfile.new(:C)&lt;br /&gt;            o.binmode&lt;br /&gt;          else&lt;br /&gt;            fh=""&lt;br /&gt;          end&lt;br /&gt;          while l=@in.read(16384)&lt;br /&gt;            if l=~b&lt;br /&gt;              o&lt;&lt;$`.chomp&lt;br /&gt;              @in.seek(-$'.size,IO::SEEK_CUR)&lt;br /&gt;              break&lt;br /&gt;            end&lt;br /&gt;            o&lt;&lt; l&lt;br /&gt;          end&lt;br /&gt;          if(fn)&lt;br /&gt;            qs.merge!(C.qs_parse(fn + "=1"))&lt;br /&gt;            parts = fn.split(/\[/)&lt;br /&gt;            line = ""&lt;br /&gt;            parts.each do |pp|&lt;br /&gt;              pp = pp.gsub(/\]/,"")&lt;br /&gt;              line += "['#{pp}']"&lt;br /&gt;            end&lt;br /&gt;            #p "line is:"&lt;br /&gt;            #p line&lt;br /&gt;            #p fh&lt;br /&gt;            todo &lt;&lt; ["qs#{line}", fh]&lt;br /&gt;            #eval("qs#{line} = fh")&lt;br /&gt;            #p qs&lt;br /&gt;          end&lt;br /&gt;          fh[:tempfile].rewind if fh.is_a?H&lt;br /&gt;        end&lt;br /&gt;      elsif @method == "post"&lt;br /&gt;        qs.merge!(C.qs_parse(@in.read))&lt;br /&gt;      end&lt;br /&gt;      #post process vars&lt;br /&gt;      todo.each do |n|&lt;br /&gt;        eval("#{n.first} = n.last")&lt;br /&gt;      end&lt;br /&gt;      #p "END QUERY"&lt;br /&gt;      #p qs&lt;br /&gt;      #exit&lt;br /&gt;      @cookies, @input = @k.dup, qs.dup&lt;br /&gt;    end&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;end &lt;br /&gt;end&lt;br /&gt;// insert code here..&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Thu, 26 Jul 2007 01:53:58 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/4356</guid>
      <author>NetherBen (Ben)</author>
    </item>
    <item>
      <title>Making md5sum.exe Work with Paths in Python</title>
      <link>http://snippets.dzone.com/posts/show/4139</link>
      <description>On Windows systems, md5sum.exe is a nice little program to generate MD5 sums. However, whoever created this application forgot to add the ability to recognize paths in the file given to md5sum.exe. For example, say you want to md5 a file called test.txt.&lt;br /&gt;&lt;br /&gt;C:\test&gt;dir&lt;br /&gt; Directory of C:\test&lt;br /&gt;&lt;br /&gt;06/13/2007  03:52 PM    &lt;DIR&gt;          .&lt;br /&gt;06/13/2007  03:52 PM    &lt;DIR&gt;          ..&lt;br /&gt;06/13/2007  03:52 PM                 0 test.txt&lt;br /&gt;               1 File(s)              0 bytes&lt;br /&gt;&lt;br /&gt;C:\test&gt;md5sum test.txt&lt;br /&gt;d41d8cd98f00b204e9800998ecf8427e *test.txt&lt;br /&gt;&lt;br /&gt;Groovy, cool...&lt;br /&gt;&lt;br /&gt;However, if you try the same thing from some other directory (where text.txt does not live) you get the following:&lt;br /&gt;&lt;br /&gt;C:\&gt;md5sum c:/test/test.txt&lt;br /&gt;md5sum: test.txt: No such file or directory&lt;br /&gt;&lt;br /&gt;Sucky, eh?&lt;br /&gt;You could always find a different program to do md5sum. Or, if you don't want to do this, you can spawn a pipe to "cmd", navigate to the correct directory, and then run md5sum.&lt;br /&gt;&lt;br /&gt;Here's the code in python to do just that.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;# define your file name and path&lt;br /&gt;file_name = "afile.txt"&lt;br /&gt;file_path = "c:\\afolder"&lt;br /&gt;&lt;br /&gt;# setup the md5sum command (assuming md5sum.exe location is in PATH)&lt;br /&gt;md5_cmd = "md5sum \"" + file_path "\\" + file_name + "\"\n"&lt;br /&gt;&lt;br /&gt;# open the command shell&lt;br /&gt;fromchild, tochild = popen2.popen4("cmd")&lt;br /&gt;&lt;br /&gt;#push the directory change and md5sum commands to the shell &lt;br /&gt;tochild.write("c:\nchdir " + my_path + "\n" + md5_cmd + "exit\n")&lt;br /&gt;tochild.close()&lt;br /&gt;&lt;br /&gt;#get the output from the shell session&lt;br /&gt;out = fromchild.read()&lt;br /&gt;&lt;br /&gt;#split the output so that we may extract the md5sum&lt;br /&gt;output = string.split(out)&lt;br /&gt;&lt;br /&gt;#grab the md5sum  &lt;br /&gt;md5sum_local = ""&lt;br /&gt;for item in output:&lt;br /&gt;    matchmd5local = re.match("([0-9a-fA-F]{32})",item)&lt;br /&gt;    if matchmd5local:&lt;br /&gt;        md5sum_local = matchmd5local.groups()&lt;br /&gt;        md5sum_local = md5sum_local[0]&lt;br /&gt;&lt;br /&gt;if md5sum_local:&lt;br /&gt;    print_status("MD5: Local checksum = " + md5sum_local + "\n")&lt;br /&gt;else:&lt;br /&gt;    print_status("ERROR: could not obtain local md5sum for " + my_file + "\n")&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Wed, 13 Jun 2007 23:10:02 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/4139</guid>
      <author>minitotoro (Natalie)</author>
    </item>
    <item>
      <title>Ruby CSV to XML Converter</title>
      <link>http://snippets.dzone.com/posts/show/3701</link>
      <description>This code will take an input CSV file and output XML. IT was easy to write, but I haven't found anything out there to do this. The first line of the CSV file should contain the element names.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;#!/usr/bin/ruby&lt;br /&gt;&lt;br /&gt;require 'csv'&lt;br /&gt;&lt;br /&gt;print "CSV file to read: "&lt;br /&gt;input_file = gets.chomp&lt;br /&gt;&lt;br /&gt;print "File to write XML to: "&lt;br /&gt;output_file = gets.chomp&lt;br /&gt;&lt;br /&gt;print "What to call each record: "&lt;br /&gt;record_name = gets.chomp&lt;br /&gt;&lt;br /&gt;csv = CSV::parse(File.open(input_file) {|f| f.read} )&lt;br /&gt;fields = csv.shift&lt;br /&gt;&lt;br /&gt;puts "Writing XML..."&lt;br /&gt;&lt;br /&gt;File.open(output_file, 'w') do |f|&lt;br /&gt;  f.puts '&lt;?xml version="1.0"?&gt;'&lt;br /&gt;  f.puts '&lt;records&gt;'&lt;br /&gt;  csv.each do |record|&lt;br /&gt;    f.puts " &lt;#{record_name}&gt;"&lt;br /&gt;    for i in 0..(fields.length - 1)&lt;br /&gt;      f.puts "  &lt;#{fields[i]}&gt;#{record[i]}&lt;/#{fields[i]}&gt;"&lt;br /&gt;    end&lt;br /&gt;    f.puts " &lt;/#{record_name}&gt;"&lt;br /&gt;  end&lt;br /&gt;  f.puts '&lt;/records&gt;'&lt;br /&gt;end # End file block - close file&lt;br /&gt;&lt;br /&gt;puts "Contents of #{input_file} written as XML to #{output_file}."&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Mon, 19 Mar 2007 19:17:05 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/3701</guid>
      <author>jnorris (Jason Norris)</author>
    </item>
    <item>
      <title>named-fields?</title>
      <link>http://snippets.dzone.com/posts/show/3009</link>
      <description>&lt;code&gt;&lt;br /&gt;	; This can't guarantee that a record is actually a series of&lt;br /&gt;	; named fields; it can only tell if it *isn't*.&lt;br /&gt;	named-fields?: func [rec [block!]] [&lt;br /&gt;		parse rec [some [word! any-type!]]&lt;br /&gt;	]&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Thu, 16 Nov 2006 05:16:23 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/3009</guid>
      <author>gregg.irwin (Gregg Irwin)</author>
    </item>
  </channel>
</rss>
