Saturday, December 29, 2007

Consul The Educated Monkey

Consul, the Educated Monkey.

                  1
                12  4
              11  24  9
            10  22  36  16
           9  20  33  48  25
         8  18  30  44  60  36
       7  16  27  40  55  72  49
     6  14  24  36  50  66  84  64
   5  12  21  32  45  60  77  96   81
  4 10  18  28  40  54  70  88  108   100
 3 8  15  24  35  48  63  80  99   120   121
2 6 12  20  30  42  56  72  90  110   132   144
  • Input: n
  • Output: combination(n+1, 2) numbers in an (equilateral) triangle

For example, when n = 12, generate combination(13, 2) = 13!/(2!11!) = 78 numbers.

n = 1, combination(2,2) = 1.

1

n = 2, combination(3,2) = 3.

 1
2 4

n = 3, combination(4,2) = 6.

  1
 3 4
2 6 9

n = 4, combination(5,2) = 10.

   1
  4 4
 3 8  9
2 6 12 16

See the pattern?

    1^2
   4    2^2
 3   4*2   3^2
2 3*2   4*3   4^2

Rotating the triangle counter clockwise might reveal something:

1^2   2^2   3^3   4^2
   4*1   4*2   4*3
      3*1   3*2
         2*1

In general, for input n,

1^2   2^2 ..................................... n^2
   n*1       n*2 ....................... n*(n-1)
      (n-1)*1   (n-1)*2 ... (n-1)*(n-1-1)
             .....................
                      2

Let's implement it in Haskell, an obscure language.

module Main where

First, declare a module.

import qualified System.IO as Sys
import qualified IO

Then, import stuff needed.

main :: IO ()
main = do
    IO.hSetBuffering IO.stdout IO.NoBuffering
    Sys.putStr "Enter n (>=1): "
    num <- Sys.getLine
    let n :: Integer
        n = read num
    print' $ consul n (*)

main function definition. It disables stdout buffering so that the prompt is displayed immediately without waiting for the buffer to be flushed (probably flushed when new line is printed). Then it reads an integer from user and prints the triangle.

consul :: (Integral a) => a -> (a -> a -> a) -> [[a]]
consul n func = (map reverse . diagonals) $ consul' n func

consul just calls consul' then applies diagonals to the output. Then, it applies reverse on each element of the output.

consul' :: Integral a => a -> (a -> a -> a) -> [[a]]
consul' n func = [map (^2) [1..n]]
    ++ [zipWith func (repeat x) [1..x-1] | x <- [n,n-1..2]]

consul' constructs the upside down triangle described above. The triangle is expressed as a list of list of integers.

[[1^2,   2^2, ....................................., n^2]
   , [n*1,       n*2, ......................., n*(n-1)]
      , [(n-1)*1,   (n-1)*2, ..., (n-1)*(n-1-1)]
             , .....................
                      , [2]]

diagonals :: [[a]] -> [[a]]
diagonals [[]] = [[]]
diagonals ([]:ls) = diagonals ls
diagonals ((x:xs):ls) = [x] : zipWith (:) xs (diagonals ls)

diagonals takes elements along the diagonal (NE to SW). Essentially, it rotates the upside triangle clockwise and flips. Since the output triangle is flipped, reverse should be applied for each element list to re-flip the triangle.

print' :: (Show a) => [[a]] -> IO ()
print' [] = return ()
print' (l:ls) = do
    putStrLn $ replicate (length ls) ' ' ++ show l
    print' ls

print' prints the list of list of integers as a triangle by appending spaces in front of each row.

Thursday, December 27, 2007

Literate Haskell with Pandoc (Markdown)

This is Hello.lhs. It uses Markdown.

First, declare module name:

module Main where

Second, define main function:

main :: IO ()

main is of type IO ().

main = do
    putStrLn "Hello, World!"

That's the entire hello world in Haskell. To compile this,

ghc Hello.lhs

To convert this into HTML,

sed -e 's/^> /    /' Hello.lhs | pandoc

KTHXBYE.

Thursday, December 20, 2007

Wednesday, November 28, 2007

Holy Shmoly, C++ smokes Haskell away!!

From a blog, Haskell smokes Python and Ruby away!

My machine: SysInfo: Linux 2.6.22-ARCH | Pentium III (Coppermine) 797.426 MHz | Bogomips: 1596.4 | Mem: 368/504M [||||||||||] | Diskspace: 9.41G Free: 2.94G | Procs: 57 | Uptime: 39 mins | Load: 0.30 0.38 0.27 | Vpenis: 27.7 cm | Screen: nVidia Corporation NV5M64 [RIVA TNT2 Model 64/Model 64 Pro] (rev 15) @ 1280x1024 (24 bpp) | eth0: In: 1.70M Out: 0.47M

C++ version:

#include <iostream>
template <unsigned N> unsigned fib() { return fib<N-1>() + fib<N-2>(); }
template <> unsigned fib<0>() { return 0; }
template <> unsigned fib<1>() { return 1; }
template <unsigned N>
void eval() {
    std::cout<<"n="<<N<<" => "<<fib<N>()<<std::endl;
    eval<N-1>();
}
template <> void eval<0>() { std::cout<<"n=0 => 0"<<std::endl; }
int main() { eval<36>(); }

Initial test:

$ time (g++ fib.cpp && ./a.out) #computation done during compilation
real    0m2.832s
user    0m2.656s
sys     0m0.157s

This includes parsing, calculating fibonacci numbers, and output to console.

Now, onto Haskell:

$ ghc --make Fib.hs
$ time ./Fib
real    0m31.343s
user    0m28.068s
sys     0m0.167s

Compilation time isn't included. But wow.. 31 seconds. Haskell program was like this:

module Main where
import Text.Printf
import Control.Monad

fib :: Int -> Int
fib 0 = 0
fib 1 = 1
fib n = fib (n-1) + fib (n-2)

main = forM_ [0..35] $ \i ->
    printf "n=%d => %d\n" i (fib i)

I'm not sure if it's a proper way to do. I don't know about forM_. And printf might be also expensive.

Anyways testing with optimization flag:

$ ghc --make -O3 Fib.hs
$ time ./Fib
real    0m2.566s
user    0m2.530s
sys     0m0.007s

This doesn't include compilation time. And it beats C++.

Let's run C++ version after compilation. Cheating, I know.

$ g++ fib.cpp
$ time ./a.out
real    0m1.278s
user    0m1.253s
sys     0m0.003s

$ g++ -O3 fib.cpp
$ time ./a.out
real    0m0.023s
user    0m0.007s
sys     0m0.007s

Hehe. lolbye.

Tuesday, September 4, 2007

Romance

Such a cute pie (from http://www-ti.informatik.uni-tuebingen.de/~thiele/):

sh
C="/tmp/c.c"&&E="/tmp/e"&&echo -e "#include <X11/Xlib.h>\n#inclu\
de <unistd.h>\n#define l (int)t\n#define B(v,c) p[(2+l)%8][c]*200*v*v/2\
+p[(1+l)%8][c]*200*(v-v*v+0.5)+p[l%8][c]*200*(v*v/2-v+0.5)\nint s[2]={0\
};main(){Display *d;float t=0,v;float p[8][2]={{1.5,1},{2,0},{3,1},{2,3\
},{1,3},{0,1},{1,0},{1.5,1}};d=XOpenDisplay(0);while(t<100){v=t-l;XWarp\
Pointer(d,0,DefaultRootWindow(d),0,0,0,0,B(v,0),B(v,1));XFlush(d);s[1]=\
100;select(0,0,0,0,&s);t+=0.02;}}\n"> $C&&cc -o $E -L/usr/X11R6/lib -lX\
11 -I/usr/X11R6/include $C&&exec $E

rc files

Some of rc files.

vimrc:

"vimrc
set nocompatible
set bs=2
set tw=0
set cindent
set background=dark
set termencoding=utf-8
setlocal spell spelllang=en_us
filetype plugin on
set grepprg=grep\ -nH\ $*

set nowrap
"set textwidth=0

set backup              " keep a backup file
set backupext=.bak    " extension of backup file is .bak

set expandtab
set shiftwidth=4        " indenting size is 2, default was 8
set softtabstop=4 " num of spaces <tab> counts while editing
set tabstop=4     " num of spaces <tab> counts

" VIM tip #80
" Author: Charles E Campbell
" When editing a file, always jump to the last cursor position (if saved)
au BufReadPost * if line("'\"") > 0 |
  \  if line("'\"") <= line("$") |
  \     exe "norm `\"" |
  \  else |
  \     exe "norm $" |
  \  endif |
  \ endif

set mouse=a

"set nowrapscan
set nowrap

set matchpairs=(:),{:},[:],<:> " Matching pair characters
set showmatch

set showmode
set ruler

if has("autocmd")
       "Updates Last Modified filed for source codes.
       "iab YDATE <C-R>=strftime("%Y-%b-%d %X")<CR>
       "map ,L mz1G/Last Modified:\\s*/e+1<CR>CYDATE<ESC>`z
       "autocmd BufWritePre *.cpp *.h *.java *.c *.cc ks|call LastMod()|'s

       "Deletes trailing spaces
       autocmd BufWrite * %s/\s\+$//e
    autocmd BufNewFile,BufRead *.py,*.c,*.cpp,*.h,*.hpp,*.java,*.lsp,*.as,*.max,*.hs :set nospell
    autocmd BufWrite *.py :retab
    autocmd BufNewFile,BufRead *.max :set syntax=maxima
    autocmd BufNewFile,BufRead *.ny :set syntax=lisp
    autocmd BufNewFile,BufRead *.thtml :set syntax=php
    autocmd BufNewFile,BufRead *.s :set syntax=asmMIPS
    autocmd BufNewFile,BufRead *.as :set syntax=actionscript
    autocmd BufNewFile,BufRead *.txt :set syntax=mkd
    "autocmd BufNewFile,BufRead *.mxml :set syntax=xml
    "autocmd BufNewFile,BufRead *.mxml,*.as compiler fcsh
    "autocmd BufNewFile,BufRead *.mxml,*.as :!bash ~/bin/fcshserv.sh
    autocmd BufNewFile,BufRead *.mxml,*.as :nmap <C-B> :!bash ~/bin/fcshcmp.sh %:p
    autocmd BufNewFile,BufRead *.mxml,*.as :nmap <C-A> :!bash ~/bin/fcshcmp.sh %:p run
endif

set uc=0
set t_kD=^?
map ^H X
map \e[3~ x
set mousehide

set hlsearch
set incsearch

let c_comment_strings=1

" Color for xiterm, rxvt, nxterm, color-xterm :
if has("terminfo")
set t_Co=8
set t_Sf=\e[3%p1%dm
set t_Sb=\e[4%p1%dm
else
set t_Co=8
set t_Sf=\e[3%dm
set t_Sb=\e[4%dm
endif

syntax on

"let g:miniBufExplMapWindowNavVim = 1
"let g:miniBufExplMapWindowNavArrows = 1
"let g:miniBufExplMapCTabSwitchBufs = 1
"let g:miniBufExplModSelTarget = 1

nmap <leader>l :ls!<cr>:buf<space>
nmap <c-k> :set bufhidden=delete<cr>
nmap <leader>] :bn<cr>
nmap <leader>[ :bp<cr>
nmap <c-k><c-k> :bw<cr>

zshrc:

#
# .zshrc is sourced in interactive shells.
# It should contain commands to set up aliases,
# functions, options, key bindings, etc.
#

autoload -U compinit
compinit

#allow tab completion in the middle of a word
setopt COMPLETE_IN_WORD

## keep background processes at full speed
#setopt NOBGNICE
## restart running processes on exit
#setopt HUP

## history
#setopt APPEND_HISTORY
## for sharing history between zsh processes
#setopt INC_APPEND_HISTORY
#setopt SHARE_HISTORY

## never ever beep ever
#setopt NO_BEEP

## automatically decide when to page a list of completions
#LISTMAX=0

## disable mail checking
#MAILCHECK=0

#autoload -U colors
#colors

#export MYGLUTPATH="-I/usr/X11R6/include/ -L/usr/X11R6/lib -lX11 -lXi -lXmu -lglut -lGL -lGLU"

setopt PROMPT_SUBST
export PS1='${PWD}]\$ '

#if [[ -z "$ALREADYSRCED" ]]; then
    export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/opt/java/jre/lib/i386:/opt/java/jre/lib/i386/client:/opt/panda3d/lib:.
    export PATH=$PATH:~/flex/sdk/bin:/opt/maven/bin:/usr/local/bin:/opt/mozilla/bin:/opt/qt/bin:/opt/kde/bin:/opt/e17/bin:/opt/java/bin:~/scripts:~/cproj/bin:~/ProgramFiles/bin:/opt/openoffice2/program:/opt/gnome/bin:/opt/panda3d/bin:/opt/Factor
    export PYTHONPATH=$PYTHONPATH:~/documents/ai/lib/python:/opt/panda3d:/opt/panda3d/lib
#fi
#export ALREADYSRCED="true"

alias chmread='wine ~/.ies4linux/ie6/drive_c/windows/system32/hh.exe'
alias rmjunk='find . \( -name "*.bak" -o -name ".*.bak" -o -name "*.swp" -o -name ".*.swp" -o -name "core" -o -name "a.out" -o -name "l.out" \) -ok rm {} \;'
alias ls="ls -larth --color=always"
export MYGLUTPATH="-I/usr/X11R6/include/ -L/usr/X11R6/lib -lX11 -lXi -lXmu -lglut -lGL -lGLU"
export TERM=xterm-color
#export SDL_AUDIODRIVER=alsa
#export SDL_DSP_NOSELECT='1'
alias blender="blender -w -noaudio -p 10 10 1024 768"
alias glutgcc="g++ -I/usr/X11R6/include/ -L/usr/X11R6/lib -lX11 -lXi -lXmu -lglut -lGL -lGLU"
alias qwt3d="g++ -I/opt/qt/include -L/opt/qt/lib -lqwtplot3d"

#alias g++="g++ -Wextra -pedantic -ansi"
#export DISPLAY=":0"
export SQUEAK_IMAGE="/usr/lib/squeak/squeak.image.gz"

case $TERM in
    xterm*)
      preexec () {
        print -Pn "\e]0;$1\a"
      }
    ;;
esac

alias acroread="GTK_IM_MODULE=xim acroread"
alias remotedesktop="rdesktop -g 1150x900 -a 8 -z"
#alias timidity="timidity -L ~/sfont/timidity -c ~/sfont/timidity/timidity.cfg"
alias timidityserver="timidity -iA -B2,8 -Os -E b 0"
export midikeyboard="64:0 128:0"
alias webcamstreamdump="spcaview -a 1 -f yuv -o dump.avi"
export EDITOR=vim
export XMODIFIERS=@im=SCIM
export GTK_IM_MODULE=scim
export QT_IM_MODULE=scim
export LC_CTYPE=en_US
export XIM_PROGRAM="scim -d"
export LC_ALL="en_US.iso88591"

#alias skype="ALSA_OSS_PCM_DEVICE=\"skype\" aoss skype"
alias spim="rlwrap spim -exception_file /usr/share/spim/exceptions.s"
alias xpdf="xpdf -z width"

alias mp="mplayer -af volnorm -subfont-text-scale 2.5"
alias emacst="emacs --no-windows"
bindkey '^[[3~' delete-char

#export MOZ_DISABLE_PANGO=1
export TEXINPUTS=$HOME/.texmf:$HOME/.texmf/data

conkyrc:

# Conky sample configuration
#
# the list of variables has been removed from this file in favour
# of keeping the documentation more maintainable.
# Check http://conky.sf.net for an up-to-date-list.

# set to yes if you want Conky to be forked in the background
background no

# X font when Xft is disabled, you can pick one with program xfontsel
#font 5x7
#font 6x10
#font 7x13
#font 8x13
#font 9x15
#font *mintsmild.se*
#font -*-*-*-*-*-*-34-*-*-*-*-*-*-*
font -*-terminus-*-*-*-*-14-*-*-*-*-*-*-*

# Use Xft?
use_xft no

# Xft font when Xft is enabled
xftfont Bitstream Vera Sans Mono:size=16

# Text alpha when using Xft
xftalpha 0.3

# Print everything to stdout?
# out_to_console no

# MPD host/port
# mpd_host localhost
# mpd_port 6600
# mpd_password tinker_bell

# Print everything to console?
# out_to_console no

# mail spool
mail_spool $MAIL

# Update interval in seconds
update_interval 2.0

# This is the number of times Conky will update before quitting.
# Set to zero to run forever.
total_run_times 0

# Create own window instead of using desktop (required in nautilus)
own_window yes

# If own_window is yes, you may use type normal, desktop or override
own_window_type desktop

# Use pseudo transparency with own_window?
own_window_transparent yes

# If own_window_transparent is set to no, you can set the background colour here
own_window_colour hotpink
# If own_window is yes, these window manager hints may be used
own_window_hints above,sticky,skip_taskbar,skip_pager

# Use double buffering (reduces flicker, may not work for everyone)
double_buffer yes

# Minimum size of text area
minimum_size 50 5

# Draw shades?
draw_shades no

# Draw outlines?
draw_outline no

# Draw borders around text
draw_borders no

# Draw borders around graphs
draw_graph_borders yes

# Stippled borders?
stippled_borders 8

# border margins
border_margin 1

# border width
border_width 1

# Default colors and also border colors
default_color lightgrey
default_shade_color white
default_outline_color gray

# Text alignment, other possible values are commented
#alignment top_left
#alignment top_right
#alignment bottom_left
#alignment bottom_right
alignment bottom_left

# Gap between borders of screen and text
# same thing as passing -x at command line
gap_x 0
gap_y 0

# Subtract file system buffers from used memory?
no_buffers yes

# set to yes if you want all text to be in uppercase
uppercase no

# number of cpu samples to average
# set to 1 to disable averaging
cpu_avg_samples 2

# number of net samples to average
# set to 1 to disable averaging
net_avg_samples 2

# Force UTF8? note that UTF8 support required XFT
override_utf8_locale no

# Add spaces to keep things from moving about?  This only affects certain objects.
use_spacer yes

# Allow each port monitor to track at most this many connections (if 0 or not set, default is 256)
#max_port_monitor_connections 256

# Maximum number of special things, e.g. fonts, offsets, aligns, etc.
#max_specials 512

# Maximum size of buffer for user text, i.e. below TEXT line.
#max_user_text 16384

# variable is given either in format $variable or in ${variable}. Latter
# allows characters right after the variable and must be used in network
# stuff because of an argument

# stuff after 'TEXT' will be formatted on screen

TEXT
${color yellow}${time %I:%M%P%n%Y-%h-%d%n%a}
${color}Up:${color yellow}$uptime
${color green}${hr}
${color}CPU:${color yellow}${cpubar}
  ${cpu}${color}%
${color green}${hr}
${color}D:${color red}${downspeed eth0}k/s
${color}U:${color red}${upspeed eth0}k/s
${color green}${hr}
${color}FS:${color yellow}${fs_bar}
  ${color yellow}$fs_used
  ${color red}$fs_size
${color}Disk:${color yellow}$diskio
${color green}${hr}
${color}RAM:${color yellow}${membar}
  ${color}$memperc %
  ${color yellow}$mem
  ${color red}$memmax
${color green}${hr}
${color}Swap:${color yellow}${swapbar}
  ${color}$swapperc %
  ${color yellow}$swap
  ${color red}$swapmax

openbox rc.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!-- Do not edit this file, it will be overwritten on install.
        Copy the file to $HOME/.config/openbox/ instead. -->
<openbox_config xmlns="http://openbox.org/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://openbox.org/                 file:///usr/share/openbox/rc.xsd">
  <resistance>
    <strength>100</strength>
    <screen_edge_strength>500</screen_edge_strength>
  </resistance>
  <focus>
    <focusNew>yes</focusNew>
    <followMouse>no</followMouse>
    <focusLast>no</focusLast>
    <focusDelay>0</focusDelay>
    <raiseOnFocus>no</raiseOnFocus>
    <underMouse>no</underMouse>
  </focus>
  <theme>
    <name>MyTheme</name>
    <titlelayout>NLSIMC</titlelayout>
    <keepBorder>yes</keepBorder>
    <animateIconify>no</animateIconify>
    <titleLayout>NLIMC</titleLayout>
    <font place="ActiveWindow">
      <name>Sans</name>
      <size>14</size>
      <weight>Normal</weight>
      <slant>Normal</slant>
    </font>
    <font place="InactiveWindow">
      <name>Sans</name>
      <size>12</size>
      <weight>Normal</weight>
      <slant>Normal</slant>
    </font>
    <font place="MenuHeader">
      <name>Sans</name>
      <size>12</size>
      <weight>Normal</weight>
      <slant>Normal</slant>
    </font>
    <font place="MenuItem">
      <name>Sans</name>
      <size>12</size>
      <weight>Normal</weight>
      <slant>Normal</slant>
    </font>
    <font place="OnScreenDisplay">
      <name>Sans</name>
      <size>12</size>
      <weight>Normal</weight>
      <slant>Normal</slant>
    </font>
  </theme>
  <placement>
    <policy>Smart</policy>
  </placement>
  <desktops>
    <number>1</number>
    <firstdesk>1</firstdesk>
    <names>
      <name>one</name>
      <name>two</name>
      <name>three</name>
      <name>four</name>
    </names>
  </desktops>
  <resize>
    <drawContents>yes</drawContents>
    <popupShow>NonPixel</popupShow>
    <popupPosition>Center</popupPosition>
  </resize>
  <dock>
    <position>TopLeft</position>
    <stacking>Top</stacking>
    <direction>Vertical</direction>
    <floatingX>0</floatingX>
    <floatingY>0</floatingY>
    <autoHide>no</autoHide>
    <hideDelay>300</hideDelay>
    <moveButton>A-Left</moveButton>
    <noStrut>no</noStrut>
    <showDelay>300</showDelay>
  </dock>
  <keyboard>
    <chainQuitKey>C-g</chainQuitKey>
    <keybind key="W-l">
      <action name="Execute">
        <execute>xlock -mode blank</execute>
      </action>
    </keybind>
    <keybind key="W-x">
      <action name="Exit"/>
    </keybind>
    <keybind key="W-r">
      <action name="Restart"/>
    </keybind>
    <keybind key="W-t">
      <action name="Execute">
        <execute>aterm</execute>
      </action>
    </keybind>
    <keybind key="W-d">
      <action name="ToggleShowDesktop"/>
    </keybind>
    <keybind key="A-F10">
      <action name="MaximizeFull"/>
    </keybind>
    <keybind key="A-F5">
      <action name="UnmaximizeFull"/>
    </keybind>
    <keybind key="A-F12">
      <action name="ToggleShade"/>
    </keybind>
    <keybind key="C-A-Left">
      <action name="DesktopLeft">
        <wrap>no</wrap>
      </action>
    </keybind>
    <keybind key="C-A-Right">
      <action name="DesktopRight">
        <wrap>no</wrap>
      </action>
    </keybind>
    <keybind key="C-A-Up">
      <action name="DesktopUp">
        <wrap>no</wrap>
      </action>
    </keybind>
    <keybind key="C-A-Down">
      <action name="DesktopDown">
        <wrap>no</wrap>
      </action>
    </keybind>
    <keybind key="S-A-Left">
      <action name="SendToDesktopLeft">
        <wrap>no</wrap>
      </action>
    </keybind>
    <keybind key="S-A-Right">
      <action name="SendToDesktopRight">
        <wrap>no</wrap>
      </action>
    </keybind>
    <keybind key="S-A-Up">
      <action name="SendToDesktopUp">
        <wrap>no</wrap>
      </action>
    </keybind>
    <keybind key="S-A-Down">
      <action name="SendToDesktopDown">
        <wrap>no</wrap>
      </action>
    </keybind>

    <keybind key="C-A-Tab">
        <action name="ShowMenu">
            <menu>client-list-combined-menu</menu>
        </action>
    </keybind>

    <keybind key="A-F4">
      <action name="Close"/>
    </keybind>
    <keybind key="A-Tab">
        <action name="NextWindow"/>
    </keybind>
    <keybind key="A-S-Tab">
      <action name="PreviousWindow"/>
    </keybind>
    <keybind key="A-F7">
      <action name="Move"/>
    </keybind>
    <keybind key="A-F8">
      <action name="Resize"/>
    </keybind>
    <keybind key="A-F9">
      <action name="Iconify"/>
    </keybind>
    <keybind key="A-space">
      <action name="ShowMenu">
        <menu>client-menu</menu>
      </action>
    </keybind>
  </keyboard>
  <mouse>
    <dragThreshold>3</dragThreshold>
    <doubleClickTime>200</doubleClickTime>
    <context name="Frame">
      <mousebind button="A-Left" action="Drag">
        <action name="Move"/>
      </mousebind>
      <mousebind button="A-Left" action="Click">
        <action name="Raise"/>
      </mousebind>
      <mousebind button="A-Left" action="Press">
        <action name="Focus"/>
      </mousebind>
      <mousebind button="A-Right" action="Drag">
        <action name="Resize"/>
      </mousebind>
      <mousebind button="A-Middle" action="Click">
        <action name="Lower"/>
      </mousebind>
      <mousebind button="A-Middle" action="Press">
        <action name="ShowMenu">
          <menu>client-menu</menu>
        </action>
      </mousebind>
      <mousebind button="A-Up" action="Click">
        <action name="DesktopPrevious"/>
      </mousebind>
      <mousebind button="A-Down" action="Click">
        <action name="DesktopNext"/>
      </mousebind>
      <mousebind button="C-A-Up" action="Click">
        <action name="SendToDesktopPrevious"/>
      </mousebind>
      <mousebind button="C-A-Down" action="Click">
        <action name="SendToDesktopNext"/>
      </mousebind>
    </context>
    <context name="Titlebar">
      <mousebind button="Left" action="Drag">
        <action name="Move"/>
      </mousebind>
      <mousebind button="Left" action="Click">
        <action name="Raise"/>
      </mousebind>
      <mousebind button="Left" action="Press">
        <action name="Focus"/>
      </mousebind>
      <mousebind button="Left" action="DoubleClick">
        <action name="ToggleShade"/>
      </mousebind>
      <mousebind button="Middle" action="Press">
        <action name="Lower"/>
      </mousebind>
      <mousebind button="Up" action="Click">
        <action name="Shade"/>
      </mousebind>
      <mousebind button="Down" action="Click">
        <action name="Unshade"/>
      </mousebind>
      <mousebind button="Right" action="Press">
        <action name="ShowMenu">
          <menu>client-menu</menu>
        </action>
      </mousebind>
    </context>
    <context name="Handle">
      <mousebind button="Left" action="Drag">
        <action name="Move"/>
      </mousebind>
      <mousebind button="Left" action="Click">
        <action name="Raise"/>
      </mousebind>
      <mousebind button="Left" action="Press">
        <action name="Focus"/>
      </mousebind>
      <mousebind button="Middle" action="Press">
        <action name="Lower"/>
      </mousebind>
    </context>
    <context name="BLCorner">
      <mousebind button="Left" action="Drag">
        <action name="Resize"/>
      </mousebind>
      <mousebind button="Left" action="Press">
        <action name="Focus"/>
      </mousebind>
    </context>
    <context name="BRCorner">
      <mousebind button="Left" action="Drag">
        <action name="Resize"/>
      </mousebind>
      <mousebind button="Left" action="Press">
        <action name="Focus"/>
      </mousebind>
    </context>
    <context name="TLCorner">
      <mousebind button="Left" action="Drag">
        <action name="Resize"/>
      </mousebind>
      <mousebind button="Left" action="Press">
        <action name="Focus"/>
      </mousebind>
    </context>
    <context name="TRCorner">
      <mousebind button="Left" action="Drag">
        <action name="Resize"/>
      </mousebind>
      <mousebind button="Left" action="Press">
        <action name="Focus"/>
      </mousebind>
    </context>
    <context name="Client">
      <mousebind button="Left" action="Press">
        <action name="Focus"/>
        <action name="Raise"/>
      </mousebind>
      <mousebind button="Middle" action="Press">
        <action name="Focus"/>
      </mousebind>
      <mousebind button="Right" action="Press">
        <action name="Focus"/>
      </mousebind>
    </context>
    <context name="Icon">
      <mousebind button="Left" action="Press">
        <action name="Focus"/>
      </mousebind>
      <mousebind button="Right" action="Press">
        <action name="ShowMenu">
          <menu>client-menu</menu>
        </action>
      </mousebind>
      <mousebind button="Left" action="Press">
        <action name="ShowMenu">
          <menu>client-menu</menu>
        </action>
      </mousebind>
    </context>
    <context name="AllDesktops">
      <mousebind button="Left" action="Press">
        <action name="Focus"/>
      </mousebind>
      <mousebind button="Left" action="Click">
        <action name="ToggleOmnipresent"/>
      </mousebind>
    </context>
    <context name="Shade">
      <mousebind button="Left" action="Press">
        <action name="Focus"/>
      </mousebind>
      <mousebind button="Left" action="Click">
        <action name="ToggleShade"/>
      </mousebind>
    </context>
    <context name="Iconify">
      <mousebind button="Left" action="Press">
        <action name="Focus"/>
      </mousebind>
      <mousebind button="Left" action="Click">
        <action name="Iconify"/>
      </mousebind>
    </context>
    <context name="Maximize">
      <mousebind button="Left" action="Press">
        <action name="Focus"/>
      </mousebind>
      <mousebind button="Middle" action="Press">
        <action name="Focus"/>
      </mousebind>
      <mousebind button="Right" action="Press">
        <action name="Focus"/>
      </mousebind>
      <mousebind button="Left" action="Click">
        <action name="ToggleMaximizeFull"/>
      </mousebind>
      <mousebind button="Middle" action="Click">
        <action name="ToggleMaximizeVert"/>
      </mousebind>
      <mousebind button="Right" action="Click">
        <action name="ToggleMaximizeHorz"/>
      </mousebind>
    </context>
    <context name="Close">
      <mousebind button="Left" action="Press">
        <action name="Focus"/>
      </mousebind>
      <mousebind button="Left" action="Click">
        <action name="Close"/>
      </mousebind>
    </context>
    <context name="Desktop">
      <mousebind button="Up" action="Press">
        <action name="DesktopPrevious"/>
      </mousebind>
      <mousebind button="Down" action="Press">
        <action name="DesktopNext"/>
      </mousebind>
      <mousebind button="A-Up" action="Press">
        <action name="DesktopPrevious"/>
      </mousebind>
      <mousebind button="A-Down" action="Press">
        <action name="DesktopNext"/>
      </mousebind>
      <mousebind button="Left" action="Press">
        <action name="Focus"/>
        <action name="Raise"/>
      </mousebind>
      <mousebind button="Middle" action="Press">
        <action name="ShowMenu">
          <menu>client-list-menu</menu>
        </action>
      </mousebind>
      <mousebind button="Right" action="Press">
        <action name="ShowMenu">
          <menu>root-menu</menu>
        </action>
      </mousebind>
    </context>
    <context name="MoveResize">
      <mousebind button="Up" action="Press">
        <action name="DesktopPrevious"/>
      </mousebind>
      <mousebind button="Down" action="Press">
        <action name="DesktopNext"/>
      </mousebind>
      <mousebind button="A-Up" action="Press">
        <action name="DesktopPrevious"/>
      </mousebind>
      <mousebind button="A-Down" action="Press">
        <action name="DesktopNext"/>
      </mousebind>
    </context>
  </mouse>
  <menu>
    <!-- You can specify more than one menu file in here and they are all loaded,
       just don't make menu ids clash or, well, it'll be kind of pointless -->
    <!-- default menu file (or custom one in $HOME/.config/openbox/) -->
    <file>menu.xml</file>
  </menu>
</openbox_config>

asoundrc:

# .asoundrc to use skype at the same time as other audio apps like xmms
#
# Successfully tested on an IBM x40 with i810_audio using Linux 2.6.15 and
# Debian unstable with skype 1.2.0.18-API. No sound daemons (asound, esd, etc.)
# running. However, YMMV.
#
# For background, see:
#
# https://bugtrack.alsa-project.org/alsa-bug/view.php?id=1228
# https://bugtrack.alsa-project.org/alsa-bug/view.php?id=1224
#
# Usage:
# 1. cp .asoundrc ~
# 2. ALSA_OSS_PCM_DEVICE="skype" aoss /path/to/skype
#
# (C) 2006-06-03 Lorenzo Colitti - http://www.colitti.com/lorenzo/
# Licensed under the GPLv2 or later

#pcm.skype {
#   type asym
#   playback.pcm "skypeout"
#   capture.pcm "skypein"
#}
#
#pcm.skypein {
#   # Convert from 8-bit unsigned mono (default format set by aoss when
#   # /dev/dsp is opened) to 16-bit signed stereo (expected by dsnoop)
#   #
#   # We can't just use a "plug" plugin because although the open will
#   # succeed, the buffer sizes will be wrong and we'll hear no sound at
#   # all.
#   type route
#   slave {
#      pcm "skypedsnoop"
#      format S16_LE
#   }
#   ttable {
#      0 {0 0.5}
#      1 {0 0.5}
#   }
#}
#
#pcm.skypeout {
#   # Just pass this on to the system dmix
#   type plug
#   slave {
#      pcm "dmix"
#   }
#}
#
#pcm.skypedsnoop {
#   type dsnoop
#   ipc_key 1133
#   slave {
#      # "Magic" buffer values to get skype audio to work
#      # If these are not set, opening /dev/dsp succeeds but no sound
#      # will be heard. According to the alsa developers this is due
#      # to skype abusing the OSS API.
#      pcm "hw:0,0"
#      period_size 256
#      periods 16
#      buffer_size 16384
#   }
#   bindings {
#      0 0
#   }
#}

#pcm.ladspa {
#    type ladspa
#    slave.pcm "plughw:0,0"
#    playback_plugins {
#        dyson_compress_1403 {
#            1
#            label compressor
#            filename  /usr/lib/ladspa/dyson_compress_1403.so
#            output {
#                bindings {
#                    0 0
#                }
#            }
#        }
#    }
#}

pcm.compress {
    type ladspa
    slave.pcm "plughw:0,0";
    path "/usr/lib/ladspa";
    plugins [
        {
            label dysonCompress
            output {
                controls [ 0.0 0.1 1.0 1.0 ]
            }
        }
    ]
}

pcm.pcompress {
    type plug
    slave.pcm "compress";
}

########################################################################3

#for playing
pcm.dmix0 {
    type dmix
    ipc_key 34521
    slave {
        pcm "hw:0,0"
    }
}

#for capturing
pcm.dsnoop0 {
    type dsnoop
    ipc_key 34523
    slave {
        pcm "hw:0,0" #first card defined above
    }
}

#couple capture and play
pcm.asym0 {
    type asym #combines half-duplexors to make a full-duplex device
    playback.pcm "dmix0"
    capture.pcm "dsnoop0"
}
pcm.pasym0 {
    type plug
    slave.pcm "asym0"
}


#######################################################

pcm.duplex {
    type asym
    playback.pcm "dmix"
    capture.pcm "dsnoop"
}
pcm.pduplex {
    type plug
    slave.pcm "duplex"
}

pcm.card1 {
    type hw
    card 1
    device 0
}

#OSS emulation expects dsp0
pcm.dsp0 {
    type plug
    slave.pcm "duplex"
}
ctl.dsp0 {
    type hw
    card 0
}

pcm.dsp1 {
    type plug
    slave.pcm "card1"
}
ctl.dsp1 {
    type hw
    card 1
}

#pcm.!default {
#    type plug
#    slave.pcm "asym0"
#}
#ctl.!default {
#    type hw
#    card 0
#}

latex template (for pandoc):

\documentclass[12pt,letterpaper,notitlepage]{article}
%\usepackage{bookman}
\usepackage[breaklinks=true]{hyperref}
\usepackage{ucs}
\usepackage[utf8x]{inputenc}
\usepackage{graphicx}
\usepackage[top=2cm, bottom=2cm, left=2.3cm, right=2.3cm]{geometry}
\setlength{\parindent}{0pt}
\setlength{\parskip}{6pt plus 2pt minus 1pt}
%\addtolength{\textwidth}{3cm}
% This is needed for code blocks in footnotes:
\usepackage{fancyvrb}
\usepackage{fancyhdr}
\usepackage{lastpage}
\VerbatimFootnotes
\pagestyle{fancy}
%\fancyhf{}
%\lhead{\author}
%\rfoot{\thepage/\pageref{LastPage}}
%\renewcommand{\chaptermark}[1]{\markboth{#1}{}}
%\renewcommand{\sectionmark}[1]{\markright{#1}{}}

Xmodmap:

!Swap Caps_Lock and Control_L
remove Lock = Caps_Lock
remove Control = Control_L
keysym Caps_Lock = Control_L
keysym Control_L = Caps_Lock
add Lock = Caps_Lock
add Control = Control_L

Xdefaults:

!xterm*reverseVideo: true
!xterm*saveLines: 10000
!xterm*scrollBar: true
!xterm*font: -*-aquafont-medium-r-*-*-18-*-*-*-*-*-*-*
!xterm*boldFont: -*-aquafont-bold-r-*-*-18-*-*-*-*-*-*-*
!xterm*faceName

*doubleClickTime: 800

!aterm*font: -misc-fixed-*-*-*-*-20-200-*-*-*-*-*-*
!aterm*boldFont: -misc-fixed-*-*-*-*-20-200-*-*-*-*-*-*
!aterm*font: -*-courier-medium-r-*-*-18-*-*-*-*-*-*-*
!aterm*boldFont: -*-courier-bold-r-*-*-18-*-*-*-*-*-*-*
*saveLines: 10000
!aterm*font: -*-mincho-*-*-*-*-*-*-*-*-*-*-*-*
*font: -*-terminus-*-*-*-*-28-*-*-*-*-*-*-*
*boldFont: -*-terminus-bold-*-*-*-28-*-*-*-*-*-*-*
idle*font: -*-terminus-*-*-*-*-24-*-*-*-*-*-*-*
idle*boldFont: -*-terminus-bold-*-*-*-24-*-*-*-*-*-*-*
!*font: -daewoo-*-*-*-*-*-24-*-*-*-*-*-*-*
!*boldFont: -daewoo-*-*-*-*-*-24-*-*-*-*-*-*-*
!*background:  #000000
!*foreground:  #afafaf
!*color0:      #000000
!*color1:      #9e1828
!*color2:      #bece92
!*color3:      #968a38
!*color4:      #414171
!*color5:      #963c59
!*color6:      #418179
!*color7:      #bebebe
!*color8:      #666666
!*color9:      #cf6171
!*color10:     #c5f779
!*color11:     #fff796
!*color12:     #4186ee
!*color13:     #cf9eee
!*color14:     #71bebe
!*color15:     #ffffff

! Colours
*foreground: #daedea
*background: #000000
! Black
*color0: #000000
*color8: #333333
! Red
*color1: #C60000
*color9: #D83333
! Green
*color2: #15C300
*color10: #A5FF00
! Yellow
*color3: #D9DF1A
*color11: #F5FC19
! Blue
*color4: #4E4ED9
*color12: #4E81E4
! Magenta
*color5: #D447FF
*color13: #F382FF
! Cyan
*color6: #2FB2B7
*color14: #41D6DC
! White
*color7: #eAeAeA
*color15:  #FFFFFF

!XEmacs.Font: -*-terminus-*-*-*-*-24-*-*-*-*-*-*-*
Emacs.geometry: 80x28
Emacs.Background: #000000
Emacs.Foreground: #ffffff

Saturday, September 1, 2007

found: pyglet!

pyglet is just awesome! Although it is alpha, documentation is just amazing!!

Archlinux PKGBUILD (dependency might be wrong):

pkgname=pyglet
pkgver=1.0alpha2
pkgrel=1
pkgdesc="pyglet: a cross-platform windowing and multimedia library for Python."
url="http://www.pyglet.org/index.html"
depends=('avbin' 'python' 'gdk-pixbuf' 'gstreamer0.10' 'openal')
source=(http://pyglet.googlecode.com/files/$pkgname-$pkgver.tar.gz)
arch=('i686')
license=('LGPL')
md5sums=('3009386628db389292036869ad9b91ad')
build() {
    cd $startdir/src/$pkgname-$pkgver
    python setup.py install --root=$startdir/pkg
}

Probably I'll use this instead of pygame.

Monday, August 20, 2007

Windows USB thumb drive scripts

This batch file adds right click context menu for all files. So, you can drag and drop gvim.exe to the batch file and have gvim context menu for all files. If it doesn't work, it'll at least create addcontext.reg file to the folder the executable is located. Go to the folder and double click addcontext.reg

@echo off
setlocal
set app_name=%~n1
set app_abs=%~f1
set app=%app_abs:\=\\%
set command=@="%app% \"%%1\""
set workingdir="%~dp0"
set regname=%workingdir%\addcontext.reg
echo Windows Registry Editor Version 5.00 > %regname%
echo. >> %regname%
echo [HKEY_CURRENT_USER\Software\Classes\*\shell] >> %regname%
echo. >> %regname%
echo [HKEY_CURRENT_USER\Software\Classes\*\shell\%app_name%] >> %regname%
echo. >> %regname%
echo [HKEY_CURRENT_USER\Software\Classes\*\shell\%app_name%\command] >> %regname%
echo %command% >> %regname%
regedit.exe /s %regname%
echo %app_name% context menu installed
endlocal
pause

Run this reg file to remove the context menu:

Windows Registry Editor Version 5.00

[-HKEY_CURRENT_USER\Software\Classes\*\shell]

This reg file adds opencmd context menu to folders that opens cmd.exe on that folder:

Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\Software\Classes\Folder\shell]

[HKEY_CURRENT_USER\Software\Classes\Folder\shell\opencmd]

[HKEY_CURRENT_USER\Software\Classes\Folder\shell\opencmd\command]
@="Cmd.exe /k pushd %L"

Run this reg file to remove opencmd context menu:

Windows Registry Editor Version 5.00

[-HKEY_CURRENT_USER\Software\Classes\Folder\shell]

gtk2hs compiled!!

I tried to install gtk2hs for a couple of days. And finally, it succeeds! Somehow, I had to turn off compiler optimization (-O0). Here is PKGBUILD for Archlinux:

pkgname=gtk2hs
pkgver=0.9.12
pkgrel=1
pkgdesc="A GUI Library for Haskell based on Gtk"
url="http://haskell.org/gtk2hs/"
license=('GPL')
depends=('ghc' 'gtk2' 'libglade' 'librsvg' 'gtkglext' 'cairo' 'gtksourceview')
arch=('i686')
source=($pkgname-$pkgver.tar.gz)
install=gtk2hs.install
md5sums=('32752a42c225f55b0280151f8e19a3ed')
build() {
    cd $startdir/src/$pkgname-$pkgver
    ./configure --prefix=/usr --without-pkgreg --disable-split-objs --with-hcflags=-O0
    make || return 1
    make DESTDIR=$startdir/pkg install
}

This is gtk2hs.install file. Without --force, it fails somehow.

post_install() {
    for pkg in /usr/lib/gtk2hs/*.package.conf; do
        ghc-pkg register "$pkg" -g --force
    done
}

post_upgrade() {
    for pkg in /usr/lib/gtk2hs/*.package.conf; do
        #basename $pkg .package.conf
        tmp="${pkg##*/}"
        ghc-pkg unregister "${tmp%%.*}" && ghc-pkg register "$pkg" -g --force
    done
}

pre_remove() {
    for pkg in /usr/lib/gtk2hs/*.package.conf; do
        tmp="${pkg##*/}"
        ghc-pkg unregister "${tmp%%.*}" -g #2>/dev/null
    done
    rm /usr/lib/gtk2hs/*.o
}

op=$1
shift
$op $*

Now, haskell with gui goodness.

Friday, August 17, 2007

pymv

pymv reads file names listed in an xml file and moves them to a directory. It can also move files not listed in the xml file to the directory.

"""moves files listed in xml file to dst directory."""

import sys, os, shutil, optparse, re
from xml.dom import minidom

def domv(src, dst, simulate=True):
    "mv src dst"
    if (not simulate) and os.path.exists(src):
        try:
            shutil.move(src,dst)
        except IOError, err:
            print err.message
        except OSError, err:
            print err.message

def mkre(s):
    """*.mp3 => ^.*\.mp3$"""
    return '^%s$' % re.escape(s).replace('\*', '.*')

def get_nodes(xmldoc, base, tag, attrib, value, no_attrib, from_attrib):
    """retrieves file names from nodes that looks like:
    <tag attrib="value">filename.txt</tag> => base/filename.txt
    when no_attrib=True, attrib="value" is not tested."""
    elements = xmldoc.getElementsByTagName(tag)

    if (attrib is None) or (value is None): #attribute not given.
        no_attrib = True #don't filter using attribute
        from_attrib = False #don't get filename from attribute

    if no_attrib: #don't want to filter using attribute
        attrib_test = lambda x: True
    else: #want to filter using attribute
        print mkre(value)
        attrib_test = lambda x: re.match(mkre(value), str(x))

    if from_attrib: #get filenames from attrib
        result = []
        for x in elements:
            attribute = x.getAttribute(attrib)
            if attrib_test(attribute):
                result.append(os.path.join(base, attribute))
        return result

    #get filenames from node.data
    return [os.path.join(base, x.firstChild.data)
            for x in elements
            if attrib_test(x.getAttribute(attrib)) and x.hasChildNodes()]

def main(argv=None):
    if argv is None:
        argv = sys.argv

    cliparser = optparse.OptionParser(
            usage='Usage: %prog [options] xml destdir')
    cliparser.add_option('-f', '--flip'
            , action="store_true"
            , help="moves files not listed in xml [default: %default]")
    cliparser.add_option('-b', '--base'
            , help="location of files listed in xml [default: where xml is located]")
    cliparser.add_option('-t', '--tag'
            , help="tag name to be searched for file names [default: %default]")
    cliparser.add_option('-a', '--attrib'
            , help="attributes to match [default: %default]")
    cliparser.add_option('-v', '--attrib-val'
            , help="attribute value to match. * matches everything. *.mp3 matches attrib=\"anything.mp3\" [default: %default]")
    cliparser.add_option('-n', '--no-attrib'
            , action="store_true"
            , help="don't test for attrib when selecting xml node [default: %default]")
    cliparser.add_option('-s', '--simulate'
            , action="store_true"
            , help="simulate. don't actually move files [default: %default]")
    cliparser.add_option('--from-attrib'
            , action="store_true"
            , help="get filename from attribute, not from node.data [default: %default]")

    cliparser.set_defaults(flip=False
            , tag="file"
            , attrib=None
            , attrib_val=None
            , no_attrib=False
            , simulate=False
            , from_attrib=False)

    (options, args) = cliparser.parse_args()

    arg_len = len(args)

    if arg_len < 2:
        cliparser.error("should pass xml, destdir")

    xmlf = os.path.abspath(args[0])
    dst = os.path.abspath(args[1])
    if options.base:
        base = os.path.abspath(options.base)
    else:
        #set to where xmlf is located
        base = os.path.dirname(xmlf)
    tag = options.tag
    attrib = options.attrib
    value = options.attrib_val
    no_attrib = options.no_attrib
    simulate = options.simulate
    from_attrib = options.from_attrib

    xmldoc = minidom.parse(xmlf)

    print 'Searching nodes: <%s %s="%s">' % (tag, attrib, value)
    filenames = get_nodes(xmldoc, base, tag, attrib, value
            , no_attrib, from_attrib)

    if simulate:
        for x in filenames:
            print x

    if not os.path.exists(dst):
        print "%(dst)s doesn't exist. Creating %(dst)s" % {'dst':dst}
        if not simulate:
            os.mkdir(dst)
    elif not os.path.isdir(dst): #dst exists but not directory.
        print """%(dst)s exists. And it's not a directory.
        Make sure %(dst)s is a directory.""" % {'dst':dst}
        sys.exit(1)

    if options.flip:
        for x in os.listdir(base):
            src = os.path.join(base, x)
            if os.path.isfile(src)\
                    and (src not in filenames)\
                    and (not src == xmlf):
                print "moving %(x)s to %(dst)s..." % {'x':x, 'dst':dst}
                domv(src, dst, simulate)
    else:
        for x in filenames:
            print "moving %(x)s to %(dst)s..." % {'x':x, 'dst':dst}
            domv(x, dst, simulate)

if __name__ == "__main__":
    main()