3/29/11

bytearray error (an integer is required)

If you see this error: "TypeError: an integer is required" when you use bytearray, it means you can't use string for bytearray anymore.

Bytearray was introduced in python 3.0, it was back-ported to 2.6, in Python 2.6 and 3.0, you can use string:
#in 2.6 or 3.0

>>> a = bytearray()
>>> a.extend("hello")
>>> a
bytearray(b'hello')

But in Python 3.2, it won't work anymore, you have to use list of integers:

>>> a = bytearray()
>>> a.extend("hello")
Traceback (most recent call last):
File "", line 1, in
TypeError: an integer is required
>>> a.extend(b'hello') #this is OK
#if you have to use a string, use str.encode()
>>> a.extend("hello".encode()) # or list(map(ord,"hello")) or [ord(e) for e in "hello"]

3/28/11

Command line IDN punycode convertor

If you need a command line punycode converter for IDN (internationalized domain name), just write a small Perl program using Net-LibIDN(cpan).

On Fedora, do a "yum install perl-Net-LibIDN" to install Net-LibIDN.

To encode:
$cat en-puny.pl
#!/bin/env perl
use Net::LibIDN ':all';
print idn_to_ascii($ARGV[0],'utf-8') . "\n";

To decode:
$cat de-puny.pl
#!/bin/env perl
use Net::LibIDN ':all';
print idn_to_unicode($ARGV[0],'utf-8') . "\n";

Examples:
$./en-puny.pl 你我.中国
xn--6qqp96b.xn--fiqs8s

./de-puny.pl xn--6qqp96b.xn--fiqs8s
你我.中国

$./en-puny.pl ˆ.net
xn--wqa.net

To get punycode without "xn--" prefix, replace idn_to_ascii with idn_punycode_encode, and replace idn_to_unicode with idn_punycode_decode.