Sunday, 20 April 2008

bash fun vol. 2

Forget previous post. Bash has functions: goj@abulafia ~ $ tail ~/.bashrc
function apply() {
cmd=$1
shift
for x in $*; do $cmd $x; done
}

function go() {
$@
cd ${!#}
}

Much better now. :)

Monday, 14 April 2008

bash fun

Quote by Terrence Parr:
My Motto: "Why program by hand in five days what you can spend five years of your life automating?"


We do a lot of actions that make a directory interesting for us and then we want to cd intro that directory. Consider:

hg init my_repo; cd my_repo
mkdir -p a/b/c/d; cd a/b/c/d
mv my_file /tmp; cd /tmp


Boring, repetitive and not DRY.

Lesson 1: You can do something like this:
mkdir -p a/b/c/d; cd !$

Better, but not good enough for me. I'd like to type
go hg init my_repo
go mkdir -p a/b/c/d
go mv my_file /tmp


So we need to create a short bash script, don't we?

How do we get last argument of the script (we'll need that). Provided that $1 is the first argument, $2 - second and $# - argument count and $@ all arguments as an array... yes, you guessed it. It's ${!#}

How nice and intuitive. Try those: $$# ${$#} ${${#}} $@[$#].

So do we have all that we need?
goj@abulafia tmp $ cat go
#!/bin/bash
$@
cd ${!#}


goj@abulafia tmp $ ./go echo ~
/home/goj
goj@abulafia tmp $


Epic FAIL. ./go script is executed in child shell. When it terminates it's parent's CWD is unaffected. We have to source it:

goj@abulafia tmp $ . ./go echo ~
/home/goj
goj@abulafia ~ $


But this syntax sucks. Luckily, alias is our friend:

goj@abulafia tmp $ echo 'alias go=". go-source-me"' >> ~/.bashrc
goj@abulafia tmp $ mv go ~/bin/go-source-me


You have to have ~/bin in your PATH.

goj@abulafia tmp $ go echo ~
/home/goj
goj@abulafia ~ $


Ta-dam!

Wednesday, 2 April 2008

April Fool's day

As last year, I managed to make my year's forum unreadable for April Fool's day. Awful, pink theme from last year was yesterday joined by truly horrible spelling and flipped avatars. :>

Here are the results:

Here is a little HOWTO. It may be useful for something practical, or for next year. Basically, you have to use mod_ext_filter see the sed example.

Polish spelling mistakes are different to English ones. They are (mostly) caused by fact, that there are (for historical & (maybe) other slavic languages "compatibility" reasons (is legacy a proper word?)) few sounds that have the two spellings, like ź-rz and u-ó, h-ch. It makes it very easy to inject typos to polish text.

We are talking about HTML pages. You cannot break html, eg <a chref="..."> would be BAD. So we don't touch anything inside html tags, comments and entities. This makes it hard to use regexps. If I were to write this joke's filter program once again I would use flex. But I wrote a short and slow (2,2 seconds to process a page - unacceptable) automata-based python script, and then (when it turned out how bad it performs) added lighting-fast (0,01 s/page) C-code generation to it. Generating code for automata is very easy.

code is here

Code generation itself is a bit over-engineered, too. I shouldn't have cared about beautiful indentation & proper newlines. I should have used GNU indent instead.

Apache configuration:
ExtFilterDefine ortozawal mode=output intype=text/html cmd="/usr/local/bin/ortozawal"
ExtFilterDefine ungzip-filter mode=output intype=text/html cmd="/bin/gunzip -"
ExtFilterDefine gzipme-filter mode=output intype=text/html cmd="/bin/gzip"
ExtFilterDefine flip-image mode=output cmd="/usr/bin/convert - -flip -"

<Location "/forum">
SetOutputFilter ungzip-filter;ortozawal;gzipme-filter
</Location>

<Location "/forum/images">
SetOutputFilter flip-image
</Location>

gunzip-filter-gzip is a filthy trick. You can probably avoid it by proper filter configuration. If you know how, please drop me a comment.

Saturday, 1 March 2008

small, pythonic lisp

Grab it here.

It's < 256 LOC toy lisp. Nothing super-fancy. If you don't count unit tests and Guido's mm.py it's even < 128 LOC.

It's quite pythonic. When you write eval in LISP it's just a big cond. It translates directly to if/elif/elif/... which doesn't look good. I used dict of functions instead, which looks better in my eyes. Uses as many Python features as possible. Python functions, python lists. etc.

Talking about Python and lisp lists:

class slist(object):
class iterator(object):
def __init__(self, lst):
self.lst = lst
def next(self):
if self.lst:
result = self.lst.car
self.lst = self.lst.cdr
return result
else: raise StopIteration

def __iter__(self):
return slist.iterator(self)

def __init__(self, a, b=None):
self.car = a
self.cdr = b

def __str__(self):
return '(%s)' % ' '.join(str(elem) for elem in self)

list_123 = slist(1, slist(2, slist(3)))
a, b, c = list_123

Yes, this is just a linked list, not a true scheme cons, since it doesn't support improper lists, I posted it just to show how Python iterators are neat.

Friday, 29 February 2008

Lap year's WTF

Well, we all know phpBB is evil. Html code it generates makes you sick. It's a great example of spaghetti design antipattern. And it's written in PHP.

Today (it's 29th February) many phpBB by Przemo forums have blown. It's because of lap year and their "whose birthday is it" function.

Warning. Clicking link below may even make you vomit.
I'm ugly, think again

Yes, they didn't use standard date("L"), yes they did their own calculations (using sqrt?!?), and yes, they f*ck*d it badly. Awful switch full of magic numbers (hello, PHP is a junk, but it has loops and arrays) is just a minor ugliness.

Saturday, 9 February 2008

int *(*(*(*b)())[10])();

I've just read Terence Parr's post titled "How To Read C Declarations". The quoted "Golden Rule" makes reading declarations really easy even for a drunk ape, but it's one of the kind I dislike. It gives you some "magical" steps to follow (here are the same rules stated more verbosely in an awful, BASIC-ish GOTO-step-N manner) with no explanation why this way, no another.

Here is the missing explanation:

Declaration reflects how you use declared expression (how you get the value of it), so in int tab[]; tab is an array (you index it) of integers. int (*tab)[]; is a pointer to an array (you dereference it, then index). int *(tab[]); is an array of pointers — you have to index it, then dereference.

How about int *tab[]? You have to know operator precedence

It's not that hard as in looks like. In our case the rule of thumb is: "Postfix binds stronger than prefix.", so you read int *tab[] as array of pointers. "Postfix binds stronger than prefix" is the reason why you look right, then left, in "Golden rule".

Easy, isn't it? Now you know this post's title reads pointer to the function returning pointer to an array of pointers to functions returning pointers to integers. 10 is redundant in this case. (It's no 5 from here, I'm so lazy...).

Of course you'll find out that the Golden rule is an obvious result of sentences above. It's convinient to read declarations that way, but IMO it's very bad to actually think about declarations only in terms of now jump out of the parenthesis.

Friday, 1 February 2008

Vim stuff

Vim is great, but quite hard to master. My experience is that there usually is a lot of "how did you do that?" when working with another vimmer. There goes a random list of some useful commands I taught (or learned) recently:

^rX in command and insert mode.
Puts the content of X register. Typical use case: select something with * and then :%s/^r//new stuff/g

punctuation: ; and ,
repeats last tTfF motion, like everyone's favourite dot repeats last command

rectangle visual mode
^v or quadruple1 click. Often easier and faster, than macros

macros
q. Everyone know them :help q

^o
Jumps intro normal mode for one command. Typical usecase: editing middle of the line ^oo.

^v any_key in insert and command mode
Puts the Vim representation for that key. Useful for editing .vimrc

J in normal mode
joins current line and next line

^a ^x in normal mode
increment/decrement a number

& and \1, \2...
in to part of substitution

"*
X11 clipboard

^p ^n and ^xlot_of_keys like ^xf
completions

autocmds in your .vimrc
see .vimrc examples below

not a command: Wombat
My text is brilliant
My vim is pure.
I saw a Wombat.
Of that I'm sure.
[...]

You're beautiful. You're beautiful.
You're beautiful, it's true.




Some macros from my .vimrc that I found very useful:

" done with current line
inoremap <c-cr> <c-o&ht;o

"XML, HTML, JSP
autocmd FileType xml,html,xhtml,jsp,htmldjango inoremap <C-b> <Esc>"tciw<<C-o>"tp><CR></<C-o>"tp><Esc>O
autocmd FileType xml,html,xhtml,jsp,htmldjango inoremap <C-a> <Esc>"tciw<></><Esc>"tPF>"tPla
autocmd FileType xml,html,xhtml,jsp,htmldjango inoremap <C-s> <ESC>"tciw</><ESC>h"tPa<Space><Space><Left>


Side note: python syntaxfile file (at least in vim 7.0 in my SuSE) seems to be a little outdated:
autocmd FileType python syn keyword Constant True False None
autocmd FileType python syn keyword Keyword with


Meta tip:
type :help one_or_two_random_keys from time to time. prefix with i_ for insert mode stuff.


1 - yes. QUAD-ruple. Click, click, click, click. Four clicks in a row %-| . Open Office does have quadruple click too. Who uses mouse, anyway...