Saturday, February 09, 2008

Programming Challenges

Today, I had a chat with ali on different online programming challenges as IOPC is going on write now and ali has taken part in it. I was remembering my glorious days when I won a jacket in bitwise.

I am just going to enlist a few programming challenges. Obviously, the list is not exhaustive.

1) ACM ICPC : I believe it is one of the most prestigious programming challenges. It is an IBM sponsored annual event.

2) Top Coder : This too is one of the most prestigious programming challenges. General belief is that the emphasis is more on programming rather than algorithms.

3) IOCCC : Well, here one can find the weirdest C programs. Most of the time it will seem that the winning entry programs won't even compile. However, they do but it is difficult ( rather next to impossible ) to find out what they would do by merely reading the code. My favorite program is here. And yeah, it DOES compile and run.

4) Bitwise : One of the most prestigious INDIAN programming challenges. I used the word "Indian" because it is held by Indian Institute of Technology, Kharagpur. The challenge however is open internationally. It is really a pity to see that since the inception of the event, only once an Indian team could grab the first prize. Ameya Karkare ( aka crack-kare ) and Navneet Lohiwal ( aka lollu ) from Indian Institute of technology Bombay (my alma-matter :-) ) played with handle "AK47", undoubtedly shooting down all competing teams.

5) OPC : Held annually by Chennai Mathematical Institute. One of the toughest programming challenge I have ever faced.

6) CodeCraft : Held annually by International Institute of Information Technology, Hyderabad as part of their technology festival Felicity.

7) IOPC : Hosted by IIT Kanpur as part of its technology festival techkriti.

Friday, January 11, 2008

Pune Innovation 2008 : Ideas in Practice


Website: http://www.innovations-pune.com/
Government : www.dsir.gov.in [Click TePP]

1. Do the innovation. It should be unique. It can be simple and obvious too. Think Beyond Imagination.
2. Find out a pricing model / revenue model. Strategy/People.
3. Do the market analysis. Compare with other products. Pros/Cons of your and others products.
4. What are the pin points of your product?
5. Take care of customers and their expectations. Think as if you are one of them. User experience.
6. Think not only for early bird advantage but in long terms. Think Fast. Vision.
7. Do the Risks/Liabilities.
8. How do you do marketing? Promote. Om Shanti Om.
9. Always have the exit plan ready. (Just like in sysadgiri where you should always have the backup plan ready.)
10. Blank. (You have to fill this by yourself.)
 
Vaibhav.

ps: What your Dreams really mean!

My AJAX Notes.



My AJAX Notes.


Vaibhav.




Tuesday, September 25, 2007

Kool Linux Sites

http://www.slax.org/

: Get the Software

http://linuxhardware.org/ : Find about Hardware

http://www.linuxdevices.com/ : The Device part

http://tldp.org/LDP/sag/html/ : Do sysad

http://www.winehq.org/site/about : Want to plat games

http://newdata.box.sk/bx/hacker/ : Do something.

Vaibhav.

"When you guys actually learn something, come to me
and say, 'We learned something! We learned something!' and I'll
show you some cool stuff."

Wednesday, September 19, 2007

Tiddlywiki

http://www.tiddlywiki.com/

To set up:

wget http://www.tiddlywiki.com/empty.html
firefox file:///`pwd`/empty.html

Done.
<snip>
The easiest way to learn about TiddlyWiki is to use it! Try clicking
on various links and see what happens - you cannot damage
tiddlywiki.com or your browser.
</snip>

Thursday, July 26, 2007

VIM Tip

Convert any file to html file using vim from command prompt :
vim -c ":runtime! syntax/2html.vim | :wq | :q " <FILENAME>
File Created: <FILENAME>.html

Example:
vim -c ":runtime! syntax/2html.vim | :wq | :q " a.c

will create a file "a.c.html"

Friday, May 11, 2007

[Perl] Script to check stock

Script to check the stock and their graph :D
Uses finance.yahoo.com to get the graphs.

INPUT : stock.conf : contains stock symbol (one per line ) for each company.
You can find the symbols on http://finance.yahoo.com/lookup, if you don't know.

OUTPUT: Generates a html page that contains the information and graph for the given companies in stock.conf.

Requires: lynx
Usages: Put stocks.cgi and stock.conf in your cgi-bin directory. Open in firefox. Refresh to get latest info.
Note: you can also run the script from shell prompt and then redirect the output to a html file , then open this file in firefox :D But you need to run it every time you want the latest info.
# perl stock.cgi > mystocks.html
# firefox mystocks.html

Here are the files:

----- stocks.cgi ---
#!/usr/bin/perl -w
use strict;
use CGI qw(:standard);
#Written by Vaibhav Gupta
################ Variables ######################
my $stockfile = "stock.conf";
my $tab_width = 3;
################################################

sub generatestockhtml () {
my @allfile = `cat $stockfile `;
my $toprint = "<table frame=box><tr>\n";
my $count=0;

foreach my $line (@allfile) {
chomp $line;
my ($firstchar) = ($line =~ /(.)/ );
my $stock=`lynx -source " http://finance.yahoo.com/d/quotes.csv?s=$line&amp;f=l1d1t1c6ohgn&e=.csv"` ;
my ($lasttrade,$lasttradedate,$lasttradetime,$change,$open,$dayhigh,$daylow,$name) = split(/,/,$stock);
#Not Printing lasttradetime
$toprint .="<td>
<b>$name</b> Trade Date = $lasttradedate <br>
Current: <font color=green>$lasttrade</font> Change:<font color=red> $change</font> <br>
Open: <font color=green>$open</font> High: <font color=green>$dayhigh</font> Low: <font color=green>$daylow</font>
<a href=\" http://ichart.yahoo.com/v?s=$line\">
<img src=\"http://chart.yahoo.com/c/0b/$firstchar/$line.gif\">
</a> <br>
<a href=\"http://finance.yahoo.com/q?s=$line&d=b\"> More Info</a>
</td>
\n";
$count++;
if($count % $tab_width == 0) {
$toprint .= "</tr><tr>";
}
}
$toprint .= "</tr></table>";
print $toprint;
}


print header("text/html"),
start_html("Vaibhav Gupta's Stock Page");
my $cur = CGI->new() ;
&generatestockhtml();
print end_html;

--- stock.conf --
goog
yhoo
msft
amzn
emc

Thursday, April 19, 2007

Trapping signals (^C and ^Z) in Bash

#!/bin/bash
#Script written by Vaibhav Gupta
#Trapping HUP TERM INT and ^Z in shell.

echo "Process ID = $$";
stty susp "" #Trapping CTRL-Z
trap 'echo "Trapping CTRL-C, TERM and HUP";' HUP TERM INT
echo

echo "Sleeping for some time"
for i in `seq 1 20`; do
    sleep 1
    echo -n "."
done
echo
stty susp "^Z"


Koool bash Functions


http://www.novell.com/coolsolutions/tools/18639.html

Tuesday, April 17, 2007

Script to exchange ssh keys

 1 #!/usr/bin/perl
2 use Expect;
3 #USAGE: ssh-key-exchange.pl <IP> <USERNAME> <PASSWORD>
4
5 my $ip = $ARGV[0];
6 my $login = $ARGV[ 1];
7 my $password = $ARGV[2 ];
8 my $private_key='/root/.ssh/id_rsa ';
9 my $public_key='/root/.ssh/id_rsa.pub ';
10 my $authorisedkeyfile='/root/.ssh/authorized_keys ';
11 my $timeout = 10;
12 my $aft = new Expect;
13
14 #Generate the public and private key on the local m/c A
15 if(!(( -e $public_key ) &&( -e $private_key ))) {
16 print "Generating the Public and Private Key:\n ";
17 @result=`ssh-keygen -t rsa -f /root/.ssh/id_rsa -P "" `;
18 #print @result;
19 }
20 #Copy the file to m/c B
21 print "Copying Public Key from A to B.\n ";
22 $aft->spawn("scp $public_key $login\@$ip:/tmp/");
23 $aft->expect($timeout,[ qr'\? $' , sub { my $fh=shift; $fh->send("yes\n"); exp_continue; } ],
24 [ 'Password: $',sub { my $fh=shift;$fh->send("$password \n");exp_continue;} ],
25 # '-re','\# $'
26 );
27 $aft->do_soft_close();
28
29
30 #Add Keys to authorised keys in B
31 print " Adding Keys to authorised key in B with IP=$ip,[ $login $password ] \n";
32 my $aft = new Expect;
33 $aft->log_file("/tmp/expect_log" ,"w");
34 $aft->spawn( "ssh $login\@$ip") or die "Cannot ssh to the machine \n";
35 $aft->expect($timeout,[ qr'\? $', sub { my $fh=shift;$fh ->send("yes\n"); exp_continue; } ],
36 [ 'Password: $',sub { my $fh=shift;$fh->send("$password\n ");exp_continue;} ],
37 '-re', '\# $'
38 );
39 $aft ->send("touch $authorisedkeyfile\n");
40 $aft->expect($timeout,'-re' ,'\# $');
41 $aft->send( "cat /tmp/id_rsa.pub >> $authorisedkeyfile\n");
42 $aft->expect($timeout,'-re', '\# $');
43 $aft->send(" exit\n");
44 $aft->do_soft_close();
45

Monday, November 27, 2006

My New Homepage.


Check my new homepage at  http://vaibhav.gupta.googlepages.com/
You can download all the scripts from the given page.
My stumble page http://vaibhav.stumbleupon.com/


Vaibhav.
 

Friday, November 24, 2006

[perl] Create dir and links for a given dir.

#!/usr/bin/perl
#written by vaibhav gupta
#Creates a new directory for a given directory and creates links for files.
$dir = $ARGV[0];
&usages unless $dir ;
&copy;
sub usages {
        print "Usages: <Dirname> \n";
        exit;
}
sub copy {
        @result = `find $dir -type d`;
        $dirname = `echo "$dir"  | rev | cut -d"/" -f 1 | rev`;
        chomp $dirname;
        $desination = "$dirname";
        foreach $d(@result) {
                chomp $d;
                ($a,$b) = split(/$dirname/,$d);
                print "Creating $desination$b\n";
#               print "[$a -- $b]";
                @res = `mkdir -p $desination$b`;
                print @res;
        }
        @result = `find $dir -type f `;
        foreach $d(@result) {
                chomp $d;
                ($a,$b) = split(/$dirname/,$d);
                print "Copying $d\n";
                @res = `ln -s  $d $desination$b`;
                print @res;
        }
}

[perl] Popup window

#!/usr/bin/perl
# written by vaibhav gupta
use Gtk2 '-init';
$x=100;$y=100; #default Cordinates
$blue = 0xffff ;
$label = "Hello there";
$label = $ARGV[0] if $ARGV[0];
$delay = 5 ;
$delay = $ARGV[1] if $ARGV[1];
$x = $ARGV[2] if $ARGV[2];
$y = $ARGV[3] if $ARGV[3];
$blue = $ARGV[4] if $ARGV[4] ;

sub usages {
        print "\n $ARGV[0] <label> <delay> <x> <y> <color>\n";
}

$window = Gtk2::Window->new("popup");
$window->set_title("Hello");
$window->signal_connect( destroy => sub {Gtk2->main_quit}) ;
$label = Gtk2::Label->new($label);
$label->modify_fg('normal',Gtk2::Gdk::Color->new(0,0,$blue) );
$window->add($label);
$window->move($x,$y);
#$window->resize(300,30);
$window->show_all();
Glib::Idle->add( sub { Gtk2->main_quit; 0 } );
#$window->begin_move_drag(0,100,100,1);
Gtk2->main;
print `sleep $delay`;

[python] Start Python

#!/usr/bin/python
import sys
import os
import __builtin__

def helloworld():
    print "Dare to Challenge http://www.pythonchallenge.com/"
    print "Hello World\n";
    print "This is system Path : "
    print sys.path #this is search Path
    sys.path.append("this/is/test/path");
    print "This is system Path after appending test path "
    print sys.path
    filename = os.environ.get('PYTHONSTARTUP')
    print filename
    if filename and os.path.isfile(filename):
        execfile(filename)
    li = []
    print "Method of list ", dir(li) # list all the method of list
    info(__builtin__, 20) # gives the list of built in function

#Factorial Function Start
def fact(n):
    if n > 1:
        return n * fact(n-1)
        else:
        return 1
def info(object, spacing=10, collapse=1):
    """Print methods and doc strings.

    Takes module, class, list, dictionary, or string."""
    # note
    methodList = [e for e in dir(object) if callable(getattr(object, e))]
    processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: s)
    print "\n".join(["%s %s" %
                     (method.ljust(spacing),
                      processFunc(str(getattr(object, method).__doc__)))
                     for method in methodList])

        
def datatypes():
    str = "This is a string."
    print str
    dict = {"server":"mpilgrim", "database":"this will be deleted"}
    print "Currnt Dictionary: ", dict # NOte that it printed in a sorted way.
    dict["server"] = "CHANGED"
    dict["uid"] = "added"
    dict["Uid"] = "case sensitive"
    dict[2] = "mixed data"
    dict["mixed"] = 123
    del dict["database"]
    print "Now Dictionary   : " , dict
    dict.clear() # To clear all the contents
    list = ["a", "b", "mpilgrim", "removethis", "example","pop"]
    print "Current List   :" , list
    print "Length of List : ", len(list)
    print "list[-1]   :", list[-1] #"li[-n] == li[len(li) - n]"
    print "Slicing    :", list[1:-1]
    print "Pop Element: ", list.pop()
    list.append("append")
    list.extend(["extend1","extend2"]) #note the arg is a list.  Concatenates
    list.insert(2,"inserthere")
    list.remove("removethis");
    list += ["Operators"]
    print "Now List   : ",list
    print "Searching extend1 (first occurence): Found at location ", list.index("extend1")
    print "Found c in list:" , "c" in list
    list = ["1","2"]
    print "List Operator  : ", list * 10
    tuple = ("son","mon","tue","wed","thu","fri","sat") # Ordered, fast, But can not be modified
    print tuple
    (a,b,c,d,e,f,g) = range(7)
    print "rnage d = ", d
    #3.6

#Calling main Functions.
helloworld()
#print fact(500)
#datatypes();
#info(list)



"""  Notes
---------- and-or Trick  ----------

>>> a = "first"
>>> b = "second"
>>> 1 and a or b
'first'
>>> 0 and a or b
'second'
---------- and-or Trick Safely ----------
>>> a = ""
>>> b = "second"
>>> (1 and [a] or [b])[0]
---------- split With No Arguments ----------
>>> s = "this    is\na\ttest"
>>> print s
this   is
a       test
>>> print s.split()
['this', 'is', 'a', 'test']
>>> print " ".join(s.split())
'this is a test'

"""

The Fastest Language

Well,
Though this post is a little digression from what this forum is meant
for. It is really an interesting one because many a times we think

Which language is the fastest?

Considering the same hardware/environments are provided, it will all
depend on how well a compiler/interpreter make use of underlying
hardware/environment to generate native/interpreted code.

In a computer language shootout [Survey]
differrent compiler for different languages tested against their
ability to translate code for Ackermann Function
[Ackermann_function], Fibonacci numbers[Fibonacci_number] and
Tak functions [TAKFunction.html].

I was really happy to see that my favourite compiler gcc rules :-)

-by sbjoshi