Friday, September 21, 2012

How to format/highlight code/commands in mails

I hate to see mails which are not formatted, do not use monospaced font for code/command/logs. What is the point of writing a mail, without proper formatting, spell check, emphasis, punctuation!? I will leave the spell-check and punctuation for now. As a programmer, let me rant on the fonts and colors! ;-)

Monospace it!

How difficult is it to change the font of code snippets and commands, or logs to monospaced font!? I used to think, maybe its quite a bit of work, but... NO! Its really simple, I started using a simple macro with Outlook and Word, to change selected text to monospace (and I like Courier New) its really easy, I wont go into the details, there are lots of blogs and MS articles explaining how. Here is the code in VB:

Sub Change2MonoSpace()
' Macro - For MS WOrd
    Selection.Font.Name = "Courier New"
    Selection.Font.Size = 10
End Sub

Sub OLChange2Mono()
' Macro - For MS Outlook
    Dim objOL As Application
    Dim objDoc As Object
    Dim objSel As Object
    Set objOL = Application
    Set objDoc = objOL.ActiveInspector.WordEditor
    Set objSel = objDoc.Windows(1).Selection
    objSel.Font.Name = "Courier New"
    objSel.Font.Size = 10
End Sub


vim: TOhtml of the C classic.
Colorize

For code snippets, just making it monospaced, isn't sufficient IMO, its better to syntax highlight it, like your editor does. Again, this isn't difficult, I can think of more than one way to do it, which one is easy/simple - is a matter of personal taste.

1 - with PuTTY
    PuTTY has an option in Windows->Selection, "Paste to clipboard in RTF and plain text", enabling this, the selection, when pasted in MS Word or Outlook retains the colors.
 
2 - Vim
    Vim does too many things, and one of which is, the ex-mode command, :TOhtml, with which, a window appears, which has the HTML format of the current file/buffer - this can be saved, and later opened in IE to copy (the syntax highlight and background is as seen in the editor, the color scheme can be changed before conversion to suit needs)

3 - A special editor
    ScITE - Scintilla text editor has a copy option, to copy in RTF (but the highlight is only for supported languages, adding a new one is not simple, requires change in the code not like vim - i.e, users cant write a config/syntax-file)

4 - A utility
    Andre Simon's page has 2 awesome utilities:
    Highlight - syntax highlight source files
    Ansifilter - to colorize the console dumps which contain ANSI escape sequences

In these days where plain text mails are seldom used, the rich-text/HTML mails that we send/receive, can, and should be made to look much more beautiful!

Do not fear learning - fear only forgetting!

This might sound stupid, like, why would anyone fear learning!? But from my observation, once an engineer has been in the industry for long, there is some reluctance to change, changing to new language, or to a new platform, or even to change to a new company.  The reason seems to be fear, at least in part! The fear to cope up with change, and the fear to learn! When it comes to software, which is changing so rapidly, if we are not learning new things every now and then, for sure we will be left behind!

My fear is, on the contrary, about forgetting!, There are so many things which I had learnt as a fresh grad, as a fresher in my first company... but without constant use, all those seems to have faded from memory! :-(. The only way, is to constantly refresh things I've learnt.  At some point, I thought, how nice it would be, if my memory was like a fast access disk - low latency, huge store!  but then, even a fast SDD (using DRAM), requires a periodic memory refresh cycle to retain the charge!!  :-)
So, refresh is the only defense!

Thursday, September 20, 2012

Why is command line cool!? :)

As a developer, I love command-line!, instead of a few clicks here and there on a GUI, I would rather pipe, filter, combine and make new shortcuts to do things quickly and efficiently.
libcli generated CLI sample
While in college, once I got used to the Unix shells, doing anything on Windows shell was a pain!, mainly because of the lack of auto-completion! It was even more painful, when I started using Java on windows (without any funky IDEs). First of all, I hate CamelCase, and since that is default in Java, running
javac SomeLongFileName.java
and then
java SomeLongFile...
over and over, in the edit-compile cycle, made me create my first shell! :). I called it ACSH (Auto Command Completion Shell) :), all it did was to find the file names in current directory (DIRENT..), and then do the completion based on the first few characters, finally, on Enter, use system() :). Simple, but worked well, some of my friends also used it.

At that point, I didn't know about command modes, or, structuring the commands in a tree like hierarchy. Only after encountering the IOS (note the case - not iOS!) parser did I get more ideas on command line. But then I had lost my ACSH source (since Yahoo Geocities closed down, and I didn't take a backup! :-(, I might still have it somewhere on old Floppies or disks, I don't have time to find it!), while discussing the IOS command line capability with a friend, I created a bare-bones implementation using a Trie, worked well  long time after, when I started working on a module, which had a simulator and dumb CLI, I could not bear to use it! I enhanced my Trie based CLI to create a library, with some capabilities of IOS parser and a few bash like features, and plugged it in. I continue to maintain it, and keep adding new features, whenever I get some idea about how-to-make-command-line-more-usable :)

Many people think command line is dead!, and funky GUIs are the way to go! that isn't true!, just think - why did MS create the PowerShell in 2006 !?

CLI is cool because it get things done, quick! and it can be re-combined, re-configured, aliased, with use, you can be faster ...

Sunday, August 26, 2012

Don't like shortcuts? :-O

source: hostingreviews.com (used with permission)
Picture this:
You are going on Old airport road - towards Marathahalli, to reach, say Whitefield, or outer ring-road, and there is a huge jam for more
than a kilometer, and then, you see a road to the left, which joins to
the ring road, no clog, clean way... would you take it? My guess - certainly!
Or
Say you are in a queue, could be for a movie ticket or train ticket :) and
due to some distraction nobody is observing you, and you can jump the line,
would you jump? Well... Maybe! :)

The point here is, when confronted with a shortcut, in real life , we usually pick the
shortcut. For obvious reasons, it saves precious time.
What surprises me is,in the world of software (or the tools which we use day-to-day),
almost all of them provide some or the other way of creating/configuring shortcuts,
but people hardly use them!, why?
Don't they want to save time? is it really so difficult to learn to create/configure
those shortcuts ? or, its just plain old "Oh!... don't make me think!" ?

Wednesday, April 04, 2012

Putting an extra [s]mile! :)

I brought my new car , and when I went to the showroom (with my family), I had such a nice time, and so many unexpected events - maybe they are common these days, but they were new to me [at least!] (because this is the first car I'm buying, not the first I'm driving thou).

The puja ceremony was organized (as communicated by the sales person), and as soon as I completed the paperwork, the pujari was ready, on time, after all the usual stuff, he handed over the keys to me, and said "you can start the car now" ! :-O (cosmopolitan!), he even said "good luck, and happy-n-safe driving" when I put the dakshina! :). Then, the sales guy took a photo of us, and gave it to us, framed, so quick!, with (now, this is the best part, which I like..) a pack of Chocolates! :-D Yum!. I squashed the lemons which were placed under all the tyres, they popped confetti, and I drove away... it all seemed so good!

It might have hardly cost anything [compared to the price of the car!] to the showroom guys, but it definitely makes a difference!

Programming = math? Nah!

Now, if I think back, I feel I was so dumb while in PU II!, I didn't know which stream I should pick, what should I do going further, nothing was clear to me, nor did I bother. But, one was clear, I always thought, engineering = lot-of-math, and I never liked math!, I was more of a art
guy.
art /noun/ : The expression or application of human creative skill and imagination, typically in a visual form such as painting or sculpture
I loved to make clay/thermocol/paper models, caricature, water paintings...
But Math! yuck!. Biology always seemed interesting to me (maybe because I could draw all those plants/trees/organisms easily!), so I thought, why not MBBS ? But my parents gave me this advice (not force!, just advice), that "we can support your MBBS, but think, do you want to study till you're 30+ ?, if you cant manage to get a MD seat on merit, lakhs have to be spent for a seat!" This made me think hard, and I took Engineering, and since I didn't even like Electronics, I took Information Science (Computers seemed fun, as I had learnt/did some fun stuff in school ... 6-8 years before! Duh!)
When I joined my first company, one of my teammate happened to be my classmate, and he was schocked to see me there - as a programmer (well, lets glorify the title a bit, as a software engineer! :) )
But then, when I think of it, I haven't been that bad!, the reason seems straight forward, if you see the most blogs, or books on programming, they are not called science of programming or math of
programming, the most popular one is of course:
The art of computer programming (but this one, is full of math, and I haven't read it ! :-)). Recently, when I visited my old book on Regular expressions, I came across the phrase "Far from being some stuffy science, writing regular expressions is closer to an art", and I love regexes!
Had programming been anything closer to pure science, I would not have been here, doing it day in, day out, with passion :)

Sunday, January 23, 2011

Ruminations on 'ld', ELF and entry point to a C program

Q. Can a C program start at a function other than main()?

To answer this question in depth, one needs to know the C
run-time environment, i.e, at least the basic difference between a
  • Hosted environment (where all C standard libraries are available, program starts at main()). E.g. GNU/Linux, Windows.
  • Freestanding environment (no libraries available, how to start/load is up to the environment). E.g. Embedded systems.
(for this discussion, lets consider only GNU/Linux and the GCC compiler tools)

Now, when we do a
$ gcc <file>.c

it goes through all the stages of compilation and linking to yield an executable (in ELF format) in that process, the default entry-points to the program is defined and that will be main() (crt0.o/crt1.o etc which GNU linker [ld] links).

If we want to establish a separate entry point, we have to use the linker option (to ld), and that is -e. And, if we have to mimic a total freestanding implementation, we will need lot of functions to try out this simple exercise, instead, lets use the stdio from libc, and change the entry point to
start().

$ cat tmp.c
#include <stdio.h>

int start()
{
printf ("Hello World.\n");
exit(0);
}

Note: we use exit instead of return. We cant return, because we wont link with the C run-time which has the handlers. Here, we need stdio.h (libc) for both exit() and printf().

Lets compile it:
$ gcc -c tmp.c

we got tmp.o, to link this and get a.out, we need the path to the run-time dynamic linker (which is the path to ld-linux), on my RHEL, it happens to be:
/lib64/ld-linux-x86-64.so.2
(since I have a 64-bit AMD, if you want to find out, just run gcc -v on any program and see the link stage output)

Note: ld is the GNU linker, ld-linux is the dynamic linker (or loader) which the kernel first loads, and is responsible for loading the actual executable and all the required dynamic libraries.

Link:
$ ld -dynamic-linker /lib64/ld-linux-x86-64.so.2 -e start tmp.o -lc

Here, -lc is to link libc, once this runs, we get a.out, and we're done. We can examine a.out using ldd.

$ ldd a.out
libc.so.6 => /lib64/tls/libc.so.6 (0x000000328b700000)
/lib64/ld-linux-x86-64.so.2 (0x000000328b300000)

If we don't use the -dynamic-linker option to ld, it picks default (/lib/ld64.so.1 for me)



At this point, we are done with our agenda of changing the entry point, but lets go a but deeper on ld-linux - the dynamic linker (part of OS) which actually loads the executable.
Why did we have to give the path to ld-linux in the link step ? That's because, the dynamic-linker is a separate binary, and maybe for modularity reasons, is not within in the kernel, when we give the path to dynamic-linker to ld, it will be added into a section called .interp in the ELF headers. When the ELF binary is run, the loader looks for the path to ld-linux in the .interp section, first loads it, and then hands over the program to ld-linux (we can see the ELF headers with the objdump or readelf utilities).
Click to enlarge

This is similar to shebang lines in script executables, i.e, if the first line of a shell (bash) script is:
#!/bin/bash
call it hello.sh, chmod +x and execute it, the loader does something similar to:
/bin/bash hello.sh
i.e, load the shell and hand over the script to it. We can as well try this on any dynamic executable (which are dependent on shared libraries)

$ /lib64/ld-linux-x86-64.so.2 /bin/echo hello
hello


References:

Wednesday, September 08, 2010

[Book review] The Art of Unix Programming

Long time I wrote about a book here.
The Art of Unix Programming by Eric Steve Raymond
well, I honestly like such books on philosophy of Unix, the right way
of doing things on Unix etc ... :)
you may still feel that the review on Amazon where someone said ESR `paints
a 1 sided picture` is right. But there are numerous things which cannot be found
in any other place.
We have "Unix design patterns", "conventions for Unix command line options" etc
The "Rules" of Unix are very neatly explained.
And for the light relief, we have "Rootless root" :), which is also available on
ESR's website, my favorite is the one on GUI :-D LOL!

And I love the cover page image - of the Zen master teaching to the novice :)

And what else ? ... am I forgetting something!?, ... let me read it again! :)

Friday, July 16, 2010

AUTOLOAD in C

Recently, I attended a Perl training on Advanced Perl
(actually, I attended just to kill time, and most of the
subject matter being covered there was known to me :) )
and when learning perl modules, I came across AUTOLOAD

In brief, AUTOLOAD is like a default in a module, when one
tries to invoke a function which is not implemented in the
module, perl calls the function with name AUTOLOAD
passing the function name.
Having AUTOLOAD gives rise to interesting uses - atleast in
Perl. One can handle multiple calls in AUTOLOAD giving the
impression that there are lot of functions defined in the
library - especially useful when method names are like
get_a() get_b() get_c() etc.

I was trying to implement this in C, and its pretty
straight forward. All we need is a dynamic library and a
a default handler - which we shall call catch_all()
The only difference here would be, the responsibility
to call catch_all() will be with the invoker of the lib
(maybe this can be hidden behind neat APIs)

Lets create a library with a function and a catch_all

/* sotest.c */
#include
#include

void name1 ()
{
printf ("\n SOTEST: called %s\n", __FUNCTION__);
}
/* this is our AUTOLOAD method, which takes 1 param - name */
void catch_all (char *name)
{
/* If someone tried to call method hello() in this module */
if (0 == strcmp(name, "hello")) {
printf ("\n SOTEST: called hello()\n");
} else
printf ("\n SOTEST: %s, %s()\n", __FUNCTION__, name);
}

make lib: gcc -c -fPIC sotest.c; gcc -shared -fPIC -o libsotest.so sotest.o

Now for the invoker:

/* callso.c */
#include
#include

int main (int argc, char *argv[])
{
void *handle, (*fp)() = NULL, (*gfp)() = NULL;
char *fname = NULL;

if (argc <>\n", argv[0]);
exit (1);
}
fname = argv[1]; /* The function to be invoked in the lib */

handle = dlopen("./libsotest.so", RTLD_LOCAL | RTLD_LAZY);

fp = dlsym(handle, fname);
if (fp) {
fp(); /* If the named function exists, invoke it */
} else {
gfp = dlsym(handle, "catch_all");
gfp ? gfp(fname): 0; /* call the default handler if not */
}

return 0;
}

compile: gcc -L. callso.c -lsotest -ldl # Assume current dir, set LD_LIBRARY_PATH

Simple !. isn't it ? :)

Thursday, May 25, 2006

[Regex] Mastering ...

Hi all,

I purchased this book "Mastering Regular Expressions", 2nd Ed, by Jeffrey Friedl.
This book treats regex as a language on its own, and explains all the intricacies of crafting a regex, advanced syntaxes, regexes in various languages etc.
After 3-4 chapters, uhf... it's really heavy reading!, since I have lot of work nowadays, just managing to read a page/two per week!

--
Ani

Friday, May 12, 2006

[General - programming] Language features with dual behavior

Hi all,

Recently while writing some Python ane Perl code, I noticed that the features provided by the language are useful in dual roles. Perl is anyway famous for TIMTOWTDI.

Consider comments - multiline comments.

There is no dedicated multiline comment character-sequence in Perl/Python, but the common(and probably official way) is

In Perl:

Use the perl module documentation(pod) lines
E.g.
=head
... some code ...
=cut

In Python:

Use the triple-quote string
E.g.
"""
... code...
"""

Even though C/C++ provides the /* ... */ sequence, they cannot nest, so generally the
preprocessor is used to get rid of huge lines of code with

#if 0
...code...
#endif


Interesting....

[update-2/6/10]
After a short sprint with Lua, I found even Lua has a multiline string ([[ ... ]]) , similar to the triple-quote strings of Python, which can be turned into a comment with a leading --:

--[[
A multi
line

comment
]]

[update: 21-May-2015]
In bash, the null command can be used for multi-line comments!

: ' some
long boring
stuff
'

--
Ani

Monday, April 24, 2006

Tracing in linux

#include
#include

Sunday, April 23, 2006

Friday, April 21, 2006

AJAX

Hi Guys,
I hope most of you have heard about AJAX. Its the new buzzword

Here are some useful Links:
http://adaptivepath.com/publications/essays/archives/000385.php
http://www-128.ibm.com/developerworks/web/library/wa-ajaxintro2/#resources

We recently ajaxed a blog tool and these resources were very useful.

Those who want to try out AJAX , this would be good place to start.

[Only me?] It looks like ...

... I am the only one who is posting!
Are all of u busy or lost interest in Blogging already??

Atleast I know the status of a few who are geographically close to me:
Some are lost in TRANSLATIONs and some are lost in a DATABASE of ACTIVE items! ;)

Hmm...
I dont know Reddy's status, Ratish is very busy

--
Ani

[Book] Advance Linux Programming

Hi all,

ALP is a well known book in the Linux world, as of now I've completed 3/4 of the book, and I did not get bored at any point. It's really interesting, and highlights on so many concepts that I faintly remember reading from Advanced programming in Unix env by stevens and many unknown.

--
Ani

Tuesday, April 18, 2006

[General - Inspiring] The mastermind behind the product we work on

Here is a link which describes the founder of Winphoria (Now the Core Networks Division of Motorola) - Murali

http://www.norwestvc.com/portfolio/p_aravamudan.aspx

He has 17 patents and 25 pending!


--
Ani

Tuesday, April 11, 2006

SQL 99 - CASE

SQL 99 supports
CASE statement within SELECT

like

SELECT col_a, col_b
CASE col_c
WHEN col_c = 1 THEN 'ONE'
WHEN col_c = 2 THEN 'TWO'
ELSE 'OTHER'
END
FROM tbl;

Probably this does an outer join and a Union, not sure, but this is handy and much easier to use than JOINs.

If any of u know the internals of this , u'r welcome to describe it here.

--
Ani