Never been to DZone Snippets before?

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

« Newer Snippets
Older Snippets »
Showing 1-10 of 16 total  RSS 

QIF to CSV conversion script in Ruby

// Converts QIF files to CSV files

#!/usr/bin/env ruby

require 'rubygems'
require 'fileutils'

if ARGV.size < 1
        puts "Usage: #{$0} file.qif"
        exit
end

input = File.new(ARGV[0])
output = [File.basename(ARGV[0]).split('.')[0..-2], 'csv'].join('.')
output = File.new(output, 'w+')
output.write("date,amount,description,transaction id, address\n")

entries = input.read.split("^\n")
entries.compact
for entry in entries
        e = entry.match(/D(.*)\nT-?(.*)\nP(.*)\nN(.*)\nA(.*)\n/).to_a[1..-1]
        e[1] = e[1].to_f rescue nil
        e[-1] = "\"#{e[-1]}\""
        output.write("#{e.join(',')}\n")
end

Convert an integer to IP string

Convert an integer to IP. I don't think you can do this with IPAddr, but I could be wrong

Edit, the original didn't work for low ranges.

And I was wrong about the IPAddr thing. I should have google'd better.

IPAddr.new(16909060, Socket::AF_INET).to_s

UTF-8 Converter //JavaScript Object




Converts a sequence of ANSI characters to UTF-8 and vice-versa.

[UPDATED CODE AND HELP CAN BE FOUND HERE]



//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/geral/utf-8 [v1.0]

UTF8 = {
	encode: function(s){
		for(var c, i = -1, l = (s = s.split("")).length, o = String.fromCharCode; ++i < l;
			s[i] = (c = s[i].charCodeAt(0)) >= 127 ? o(0xc0 | (c >>> 6)) + o(0x80 | (c & 0x3f)) : s[i]
		);
		return s.join("");
	},
	decode: function(s){
		for(var a, b, i = -1, l = (s = s.split("")).length, o = String.fromCharCode, c = "charCodeAt"; ++i < l;
			((a = s[i][c](0)) & 0x80) &&
			(s[i] = (a & 0xfc) == 0xc0 && ((b = s[i + 1][c](0)) & 0xc0) == 0x80 ?
			o(((a & 0x03) << 6) + (b & 0x3f)) : o(128), s[++i] = "")
		);
		return s.join("");
	}
};


Example

var s = "aáéíóúe";
document.write(
	('UTF8.encode("' + s + '") = ').bold(), UTF8.encode(s), "<br />",
	('UTF8.decode(UTF8.encode("' + s + '"))) = ').bold(), UTF8.decode(UTF8.encode(s))
);

Convert Java date to GMT

This function converts a local date to GMT. This version corrects the bug common to this type of conversion where the date is incorrectly converted when the time is close to the DST crossover.

private static Date cvtToGmt( Date date )
{
   TimeZone tz = TimeZone.getDefault();
   Date ret = new Date( date.getTime() - tz.getRawOffset() );

   // if we are now in DST, back off by the delta.  Note that we are checking the GMT date, this is the KEY.
   if ( tz.inDaylightTime( ret ))
   {
      Date dstDate = new Date( ret.getTime() - tz.getDSTSavings() );

      // check to make sure we have not crossed back into standard time
      // this happens when we are on the cusp of DST (7pm the day before the change for PDT)
      if ( tz.inDaylightTime( dstDate ))
      {
         ret = dstDate;
      }
   }

   return ret;
}

Custom base conversion (to and from)

Handy to store large numbers in a shorter notation. Doesn't work with negative numbers (for negative numbers you need to store an additional byte to indicate a positive or negative value, pass the absolute value).

	private static final short BASE_40_RADIX = 40;
	private static final short BASE_40_BASE = 48;
	private static final String BASE_40_ZERO = "0";

	public static long fromBase40(char[] cs) {
		return fromBase(cs, BASE_40_BASE, BASE_40_RADIX);
	}

	public static char[] toBase40(final long i) {
		return toBase(i, BASE_40_BASE, BASE_40_RADIX, BASE_40_ZERO);
	}

	private static final short BASE_75_RADIX = 75;
	private static final short BASE_75_BASE = 48;
	private static final String BASE_75_ZERO = "0";

	public static long fromBase75(char[] cs) {
		return fromBase(cs, BASE_75_BASE, BASE_75_RADIX);
	}

	public static char[] toBase75(final long i) {
		return toBase(i, BASE_75_BASE, BASE_75_RADIX, BASE_75_ZERO);
	}

	private static final short BASE_90_RADIX = 90;
	private static final short BASE_90_BASE = 33;
	private static final String BASE_90_ZERO = "!";

	public static long fromBase90(char[] cs) {
		return fromBase(cs, BASE_90_BASE, BASE_90_RADIX);
	}

	public static char[] toBase90(final long i) {
		return toBase(i, BASE_90_BASE, BASE_90_RADIX, BASE_90_ZERO);
	}

	private static char[] toBase(final long i, final short base, final short radix, String nullCharacter) {
		long value = i;

		if (value == 0) {
			return nullCharacter.toCharArray();
		}

		String result = "";
		while (value > 0) {
			long mod = value % radix;
			value -= mod;
			if (value > 0) value /= radix;
			result = (char)(mod + base) + result;
		}

		return result.toCharArray();
	}

	private static long fromBase(char[] cs, final short base, final short radix) {
		long value = 0;
		for (int i = cs.length - 1; i >= 0; i--) {
			int digit = ((int)cs[i]) - base;
			if (digit < 0 || digit >= radix) {
				throw new IllegalArgumentException("Invalid Base" + radix + " character: " + cs[i]);
			}
			long digitBase = (long)Math.pow(radix, (cs.length - 1) - i);
			value = (digit * digitBase) + value;
		}

		return value;
	}


And here are some tests:

	public void testFromBase40() {
		assertEquals(2559999, NumberUtils.fromBase40("WWWW".toCharArray()));
		assertEquals(1117580, NumberUtils.fromBase40("ABCD".toCharArray()));

		assertEquals(0, NumberUtils.fromBase40("0".toCharArray()));
		assertEquals(1, NumberUtils.fromBase40("1".toCharArray()));

		assertEquals(40, NumberUtils.fromBase40("10".toCharArray()));
		assertEquals(80, NumberUtils.fromBase40("20".toCharArray()));

		assertEquals(41, NumberUtils.fromBase40("11".toCharArray()));
		assertEquals(81, NumberUtils.fromBase40("21".toCharArray()));

		assertEquals(81, NumberUtils.fromBase40("0021".toCharArray()));

		assertEquals(3061560805L, NumberUtils.fromBase40("MSTSD5".toCharArray()));
	}

	public void testToBase40() {
		assertEquals("0", new String(NumberUtils.toBase40(0)));
		assertEquals("1", new String(NumberUtils.toBase40(1)));

		assertEquals("10", new String(NumberUtils.toBase40(40)));
		assertEquals("20", new String(NumberUtils.toBase40(80)));

		assertEquals("11", new String(NumberUtils.toBase40(41)));
		assertEquals("21", new String(NumberUtils.toBase40(81)));

		assertEquals("ABCD", new String(NumberUtils.toBase40(1117580)));
		assertEquals("WWWW", new String(NumberUtils.toBase40(2559999)));

		assertEquals("MSTSD5", new String(NumberUtils.toBase40(3061560805L)));

	}

	public void testToBase90() throws Exception {
		assertEquals("#Q&Y.`QY#", new String(NumberUtils.toBase90(10908158098650842L)));
	}

	public void testFromBase90() throws Exception {
		assertEquals(10908158098650842L, NumberUtils.fromBase90("#Q&Y.`QY#".toCharArray()));
	}

Convert an integer to English written form

// Convert an integer to English written form

public class IntToEnglish {
    static String[] to_19 = { "zero",  "one",   "two",  "three", "four",   "five",   "six",
        "seven", "eight", "nine", "ten",   "eleven", "twelve", "thirteen",
        "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
    static String[] tens  = { "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
    static String[] denom = { "",
        "thousand",     "million",         "billion",       "trillion",       "quadrillion",
        "quintillion",  "sextillion",      "septillion",    "octillion",      "nonillion",
        "decillion",    "undecillion",     "duodecillion",  "tredecillion",   "quattuordecillion",
        "sexdecillion", "septendecillion", "octodecillion", "novemdecillion", "vigintillion" };

    public static void main(String[] argv) throws Exception {
        int tstValue = Integer.parseInt(argv[0]);
        IntToEnglish itoe = new IntToEnglish();
        System.out.println(itoe.english_number(tstValue));
        /* for (int i = 0; i < 2147483647; i++) {
            System.out.println(itoe.english_number(i));
        } */
    }
    // convert a value < 100 to English.
    private String convert_nn(int val) throws Exception {
        if (val < 20)
            return to_19[val];
        for (int v = 0; v < tens.length; v++) {
            String dcap = tens[v];
            int dval = 20 + 10 * v;
            if (dval + 10 > val) {
                if ((val % 10) != 0)
                    return dcap + "-" + to_19[val % 10];
                return dcap;
            }        
        }
        throw new Exception("Should never get here, less than 100 failure");
    }
    // convert a value < 1000 to english, special cased because it is the level that kicks 
    // off the < 100 special case.  The rest are more general.  This also allows you to
    // get strings in the form of "forty-five hundred" if called directly.
    private String convert_nnn(int val) throws Exception {
        String word = "";
        int rem = val / 100;
        int mod = val % 100;
        if (rem > 0) {
            word = to_19[rem] + " hundred";
            if (mod > 0) {
                word = word + " ";
            }
        }
        if (mod > 0) {
            word = word + convert_nn(mod);
        }
        return word;
    }
    public String english_number(int val) throws Exception {
        if (val < 100) {
            return convert_nn(val);
        }
        if (val < 1000) {
            return convert_nnn(val);
        }
        for (int v = 0; v < denom.length; v++) {
            int didx = v - 1;
            int dval = new Double(Math.pow(1000, v)).intValue();
            if (dval > val) {
                int mod = new Double(Math.pow(1000, didx)).intValue();
                int l = val / mod;
                int r = val - (l * mod);
                String ret = convert_nnn(l) + " " + denom[didx];
                if (r > 0) {
                    ret = ret + ", " + english_number(r);
                }
                return ret;
            }
        }
        throw new Exception("Should never get here, bottomed out in english_number");
    }
}

html table to wiki converter

import HTMLParser, re, sys
class html2wiki(HTMLParser.HTMLParser):
	def __init__(self):
		HTMLParser.HTMLParser.__init__(self)
		self.wiki = ''	  # The Wiki text
		self.wikirow = ''   # The current Wiki row of table being constructed from HTML
		self.inTD = 0	  # Used to track if we are inside or outside a <TD>...</TD> tag.
		self.inTR = 0	  # Used to track if we are inside or outside a <TR>...</TR> tag.
		self.re_multiplespaces = re.compile('\s+')  # regular expression used to remove spaces in excess
		self.rowCount = 0  # output row counter.
		self.rowspan = ''
		self.colspan = ''
		self.linebreak = '<br>'
		self.data = ''
		self.prop = ''
		
	def handle_starttag(self, tag, attrs):
		if tag == 'table': self.start_table()
		elif   tag == 'tr': self.start_tr()
		elif tag == 'td': self.start_td(attrs)
		
	def handle_endtag(self, tag):
		if tag == 'table': self.end_table();
		elif   tag == 'tr': self.end_tr()
		elif tag == 'td': self.end_td()
		
	def start_table(self):
		self.wiki += '{| border=1' + self.linebreak
		self.wiki += '|-' + self.linebreak
		
	def end_table(self):
		self.wiki += '|}' + self.linebreak
	
	def start_tr(self):
		if self.inTR: self.end_tr()  # <TR> implies </TR>
		self.inTR = 1
		
	def end_tr(self):
		if self.inTD: self.end_td()  # </TR> implies </TD>
		self.inTR = 0			
		if len(self.wikirow) > 0:
			self.wiki += self.wikirow
			self.wiki += '|-' + self.linebreak
			self.wikirow = ''
		self.rowCount += 1

	def start_td(self, attrs):
		if not self.inTR: self.start_tr() # <TD> implies <TR>
		self.data = ''
		self.prop = ''
		self.rowspan = ''
		self.colspan = ''
		for key, value in attrs:
			if key == 'rowspan':
				self.rowspan = value
			elif key == 'colspan':
				self.colspan = value			
		self.inTD = 1
		
	def end_td(self):
		if self.inTD:				
			self.wikirow += '| ' + self.prop + self.re_multiplespaces.sub(' ',self.data.replace('\t',' ').replace(self.linebreak,'').replace('\r','').replace('"','""'))+ self.linebreak;
			self.data = ''
			self.inTD = 0

	def handle_data(self, data):
		if self.inTD:
			if data.strip() != '':				
				self.prop = ''
				if self.rowspan != '':
					self.prop = ' rowspan = '+self.rowspan 
				if self.colspan != '':
					self.prop += ' colspan = '+self.colspan
				if self.prop:
					self.prop += ' | '
				self.data += data

if __name__ == '__main__':				
	parser = html2wiki()
	if len(sys.argv) == 2:
		in_file = open(sys.argv[1],"r")
		text = in_file.read()
		parser.feed(text)
		in_file.close()
		print parser.wiki
	else:
		print 'Argument - filename required'

MIDI Note number and frequency

Summary of MIDI Note Numbers
MIDI Note to Frequency

I can use them with my midi snippet.
# from http://logic-users.org/forums/L-OT/295
# Each note's frequency is 2^(1/12) times of the previous note.

freq = 440 * 2^((n-69)/12)
n = 69 + 12*log(freq/440)/log(2)

# Doe, ray, me, fa, sol, la, tee, doe
>>> play([(i, 100) for i in [60, 62, 64,65, 67, 69, 71,72]])

Find conversion words

is-conv-word?: func [word][
	all [
		("to-" =  copy/part to-string word 3)
		(not error? try [
			datatype! = type? get to-word join copy (at to-string word 4) "!"
		])
	]
]
conversion-words: does [
	lib/ser/keep-if first system/words :is-conv-word?
]
print mold conversion-words

Convert a number to its closest fraction

Sometimes, I need to find a ratio approximation of a number.
Like 640 / 480 (vga) or similar number. I learn about farey
series a few years ago (1994).
The idea is actually quite simple.
>>> farey(math.pi,100)
(22, 7)

Get the implementation here.
« Newer Snippets
Older Snippets »
Showing 1-10 of 16 total  RSS