Stackless Python

May 7, 2008

From stackless python’s website -
Stackless Python is an enhanced version of the Python programming language. It allows programmers to reap the benefits of thread-based programming without the performance and complexity problems associated with conventional threads. The microthreads that Stackless adds to Python are a cheap and lightweight convenience which can if used properly, give the following benefits:

    Improved program structure.
    More readable code.
    Increased programmer productivity.

Go give it a try! :-)


Anti-aliased fonts in emacs

February 25, 2008

The blocky fonts in emacs is not something any of us would care about (it’s the code that matters), but if (emacs == religion) for you, it’s worth making some effort for the sake of ur eyes. Actually i happened to see emacs in one my fren’s mac, which has anti-aliasing enabled. So wanted to have in my linux too..

Standard procedures are here. For ubuntu, the easier way. The good thing is, emacs started to show unicode characters (Nepali too) after this hack.

emacs.png


Day of the week

February 25, 2008

Well, you can always use mktime() or localtime(), but also conside this elegant code by Tomohiki Sakamoto. I don’t think any shorter is possible.. ;)


/* 0=sunday */
int dayofweek(int y, int m, int d){
int t[] = {0,3,2,5,0,3,5,1,4,6,2,4};
y -= m < 3;
return (y + y/4 - y/100 + y/400 + t[m-1] + d) % 7;
}


C++ assertions

February 20, 2008

A very simple feature of C++ called assertions can be used can in applications that want to safeguard itself from unwanted side-affects such as for e.g., reading/writing values beyond its boundary. Any condition that wants to be checked can be used in assert. The syntax of assert() is:
assert (some_conditional_expression);
for e.g., assert( 1 != 1) [will fail*]
assert( sizeof(int) != sizeof(int) ) [this one too]

The codes below are just a toys, BEWARE! heh.. ~:-D.

Assertions in C++ can be used by a simple statement called ‘assert (some criteria)’. Here’s a quick example.

#include “iostream”
#include “assert.h”

const int Z = 3;
//prime numbers
int prime[Z] = {2, 3, 5};

int main( )
{
int idx = 5;

assert(idx < Z); //will not go past this line because idx is greater than Z
//on my machine it nicely dumps core file*
//Before trying this example, you could disable coredumps if you are using unix-like OS
assert(idx = 0);

//2. comment out the topmost assert statement and see what happens below.
//this is a classic problem in testing where you check for reading/writing beyond the size of an array.
for (int i=0; i < idx; i++)
{
std::cout << &primes[i] < ” << primes[i] << ‘\n’; //if one follows #2, it’ll print garbage value past ’5′ (the third value in prime[])
// this garbage could be any value that resides next to your prime[]arrays
// memory address and usually _it’s_undefinable_)
}

return 0;
}

One type of assertion-like mechanism used in pre-medievel C++ versions was something like this:

int boundary_23_error_func()
{
return 23; //23, then has to be documented somewhere for devs to be able to make some
//sense out of it and notify the upcalls about it in a meaningful way
//(e.g., a graphics program, a GUI or a webserver etcetera…)
}

int main( )
{

…….

if (idx > Z)
{
return some_boundary_error_code; // or, return boundary_23_error_func();
}

…..
}

I don’t think there’s anything wrong with using this kind of error handling code but when there are many thousand LOC, it quickly becomes a mess and using assert(some_bool_expression) anywhere you feel there should be a error condition check, is _much_^2 easier. Beware, though that it’s not a holy grail of error recovery. You don’t want system to fail just because it coredumped! Meaning, it should not be used in critical infrastructure that requires guaranteed uptime like maybe spaceships modules, aircraft etcetera.

* – on my machine it dumps core. core of a particular process in Unix-like OS contains that process’ memory image before it (abruptly) finishes execution. For more detail refer to core(5).


Scheme song

February 11, 2008

I found this while perusing through the world wide web… Should be familiar to anyone involved with lisp/scheme

I’ve tried to keep the formatting arguably at the expense of readability, If this is hard to read, head over to the place where I found it: http://www.hack.org/mc/texts/scheme-song.scm

Posted by Shriram Krishnamurthi to comp.lang.scheme on January 17,
1996, for Scheme’s twentieth birthday:

                           ((I m a g i n e)
                         (shriram@cs.rice.edu)
                   (((Imagine there's no FORTRAN)
                       (It's easy if you try)
               (No SML below us) (Above us only Y)
              (Imagine all              the people)
             (Living for                their Chez))
          ((Imagine there's          no memory leaks)
                                 (It isn't hard to do)
                                  (Nothing to malloc(3)
                                        or free(3) for)
                                   (And no (void *) too)
                                 (Imagine all the people)
                                  (Living in parentheses))
                               ((You may say I'm a Schemer)
                                 (But I'm not the only one)
                             (I hope someday you'll join us)
                                   (And the world will be as
                            (lambda (f) (lambda (x) (f x)))))
                              ((Imagine those   continuations)
                             (I wonder              if you can)
                       (No need for              C or pointers)
                   (A brotherhood                        of Dan)
                    (Imagine all                      the people)
                    (GCing all                          the world))
               ((You may say                          I'm a Schemer)
              (But I'm not                              the only one)
         (I hope someday                                you'll join us)
        (And the world                                        will be as
    (lambda (f)                                     (lambda (x) (f x)))))))

'shriram

Enjoy
Prasanna Gautam


FreeBSD docos

February 9, 2008

Some really cool “must read” documentation on FreeBSD – the freebsd handbook and Greg Lehey’s "The Complete FreeBSD" and online version is also available.


Database in C++? Use a wrapper

January 27, 2008

Often the database itself provides an API for its access in C/C++. But it often consists of using confusing callback functions (callbacks are fun though) and the process differs from database to database. Solution? Use a wrapper..

This wrapper seems particularly interesting.. http://www.alhem.net/project/mysql/index.html

Download the wrapper source code, compile and install.

# make
# make install

Using the database using this wrapper is as easy as:

#include <mysql/mysql.h>
#include <libmysqlwrapped.h>

int main(){
StderrLog log;
Database db(“localhost”, “dbuser”, “dbpasswd”, “mydb”, &log);
if (!db.Connected()){
printf(“Database not connected – exiting\n”);
exit(-1);
}
Query q(db);
q.get_result(“select * from player”);
while (q.fetch_row()){
long num = q.getval();
std::string name = q.getstr();
printf(“#%ld: %s\n”, num, name.c_str());
}
q.free_result();
}

Good thing is, the same code can also be used for SQLite (my fav) and ODBC too (although with different wrapper and minor modifications). Another advantage is, the wrapper is cross platform, works on both win & *nix.


Print items [Assembly]

January 25, 2008

 A very simple Assembly code to print items in a list. Hopefully the comments will explain it better. :-)

#FILE: print_it.s
#PURPOSE: This program copies the value in data_items to %eax and prints it off one by one in a loop.
#VARIABLES: The registers have the following uses:
#
# %edi – Holds the index of the data item being examined
# %eax – Current data item
#
# The following memory locations are used:
#
# data_items – contains the item data. A 0 is used
# to terminate the data

#data section. holds all important variables.
.section .data
data_items:
.long 67,3,34,-255,45,75,54,34,44,33,22,11,66,0 #values ending with a ’0′.
printer:
.ascii “Current value of EAX is %d \n” # this format string which expands later on. Think about printf’s in C.

#text section. this is the actual code itself.
.section .text
.globl _start
_start: #every executable piece of code has _start

movl $0, %edi # move 0 into the index register (i.e., we want position 0)
movl data_items(, %edi, 4), %eax # data_items + index_register_edi_position * 4.
# (value of index_register_edi_position increments from 0 towards inifinty, see below inside start_loop)
# This is a mode of addressing memory. “4″ is needed
# because it means 4-byte wide (my machine is 32-bit x86)
# and this value must be a multiple of 1,2,4,8,16 …otherwise memory mis-alignment issues will occur.
pushl %eax #push %eax into the stack
pushl $printer #push $printer (our format-string) into the stack
call printf #call printf function (this is dynamically linked to C library at run-time)

start_loop: # think of GOTO like syntax. :-) easy heh?
cmpl $0, %eax #compare 0 with the value in %eax. to check if we hit the end of the tunnel.
je loop_exit #if they are equal, jump to loop_exit [think GOTO again]
incl %edi #increment %edi counter #or else, increment %edi by 1
movl data_items(, %edi, 4), %eax #see above.

pushl %eax #see above
pushl $printer #see above
call printf #print the format-string, see above

popl %eax #pop the contents off the stack
popl %eax #pop the contents off the stack
jmp start_loop #this is the way loops are implemented in Assembly.

loop_exit:
movl $1, %eax; #the value 1 in Linux Systems Programmer’s Manual refers to the exit system call.
# system calls are a way for programmers to call kernel and request service from it.
# In this particular instance, we need to halt the program using exit.
int $0×80; # break out and let kernel do what it does.

Assemble -

$ as print_it.s -o print_it.o

Link -

$ ld print_it.o -o print_it -lc -dynamic-linker /lib/ld-linux.so.2

Execute -

$ ./print_it </blockquote>

Put all nicely in a Makefile -

all:
as print_it.s -o print_it.o;
ld print_it.o -o print_it -lc -dynamic-linker /lib/ld-linux.so.2;
run:
./print_it;

Run the Makefile -

$ make;

Run the code -

$ make run

Note: the “-lc” means to use C library (libc.so on Gnu/Linux systems) so that we can use
printf and exit function call in our code.
The option “-dynamic-linker /lib/ld-linux.so.2″ allows the program to be linked to libraries.
This builds the executable so that before executing, the OS will load the
program /lib/ld-linux.so.2 to load in external libraries and link them with
the program.

Enjoy the facade of ASM. :-) [BTW, FYI, the executable binary is ~2k]


Implementation dilemma

January 22, 2008

Lot of people ask me what language would I chose for implementing software. The question here is not related to language. I have learnt that one should not focus merely on the language (C++ vs. Python). Each of these language has their own role and when implemented rightly can yield a useful abstraction called “software”.

I would like to emphasise that the gory feature of abstractions in C++ vs. that of Python is REALLY uncalled for and should not really be a hinder between you and your target application. What I mean by this is that, say you are in a team of 8 team person developing the next big business suite application. If 7 people are comfortable using Java, and can develop a prototype within 2 weeks, would you invest your time teaching them C++ (Only 1 person is proficient in C++)? Probably the answer is NO and in that case, your team would happily chose Java as the implementation language and move on with it.

Now, think of the same scenario but the target application being that of embedded device and not a business application. Would you still use Java given the fact that 7/8 people are comfortable with Java? Nope. The reason is because of the target environment and the constraints that the app should have to abide by. Since it’s an embedded device, the team would have to develop a stripped down executable, something that can fit within limited amount of memory and cannot have full fledged virtual machine (Python, Java are a big nada). Would even have to get some Assembly going!

So, all these rants are basically pointing to the same fact. Why not use Java? or C++ or Haskell? They got this, that. NO! They are all just a language that promotes your thought down to some form of abstraction so that machine can understand and execute it. Hence, the next time before you ask someone, what language to you/team use, it’s very important that you consider the constraints and the target environment that your app will be running in. Remember, whatever language you use for yourself of your team, at least consider the two factors; Constraints and the target environment. Whaddaya say? :-)


ABI madness

January 18, 2008

I was reading about the ELF (Executable Linkable Format) specification in Linux when I had a severe urge to learn about the concept of ABI. So, here I present some info about ABI which hopefully will explains things better.

An easy escape: It is suppose to mean the same to binary as what API means for source specification [ hoping that you understand what API is ].

More detail: Basically say you have a binary blob A somewhere in your system that B depends on for functionality. If A is modified, then B could break. To prevent this, both A and B conform to a common set of standard called Application Binary Interface or ABI in short.

There are varying cases of ABI specifications. It can range anything from an entire OS ABI to CPU ABI to Programming Language ABI. The basic premise remains the same [ i.e., they are set of standard specifications, that implementers should confirm to; be it a CPU instruction sets or a compiler specification ].


Follow

Get every new post delivered to your Inbox.