Thursday, December 30, 2010

VIM

Vim Text Editor

Pros:
  • On every platform
  • 100% keyboard driven
  • Text surgery
  • powerful editing
  • Local and remote
  • Highly configurable
  • Extendable with plugins
  • Mac-friendly
  • Great Documentation
  • Long-terms skills
Cons:
  • Undesirable defaults
  • Clunky scripting Language
  • Destructive tasks are too easy
  • Inconsistent regular expressions
Started in 1976 then 1991 and now it is called VIMproved (VIM)

Main modes of VI editor
  1. Normal
  2. Insert
  3. Visual
  4. Replace
  5. Command-line
Upper case commands are super sized versions of the lower case commands

i - Inserts text starting from the cursor
I - Inserts text starting from the beginning of the line.
w - moves forward one word
3w - moves forward 3 words
b - moves backware one word
W - moves contiguous code as one word and move forward to the next meaningful word
dd - deletes the line where the cursor is located
dw - deletes the word
d2w - delete two words
G - goes to the end of the file
gg - goes to the start of the file
:w - write file (save)
:w! - write without confirmation
:q! - quit vim
:wq! - write and quit
:e filename - opens a file to edit
code folding command starts with a z
 
cw - change word
3cw - change three words
:h - help:bd - buffer delete

yy - yank line (copy)
Y - yank line (copy)
p - paste below cursor
P - paste above cursor
a - append text after cursor
6l - Forward six letters
2j - Down two lines
fN - Jump forward to the first 'N'
3fN - Jump forward to third 'N'
n- Next 

u - undo
Ctrl+R - redo

vim -N abcd.py (-N compatible with the latest version only)

Vim comes with 500 different syntax highlights.

:syntax enable
:set syntax=apache

:set hidden
:set syntax=python
:set syntax=cpp

:w !sudo tee %

:set incsearch
:set hlsearch


Search and replace

:%s/search/replace/gc

  % search the current buffer
  g - search for all occurance
  c - ask for confirmation on each match

e.g :%s/2.\2\.8/2.2.9/gc - this will replace all 2.2.8 occurances to 2.2.9 and will confirmation all occurances.

:set number
12G - go to line 12

:cd path
:pwd
:e . - to find out the files in the directory


V - visual mode

:b name - Switch to buffer (try TAB and arrows as well)
:bp - Previous buffer

:set autochdir - Automatically use the current file's directory as the working directory


Check out the vim-rooter plugin.

:set wildmode=list:longest - Activate TAB auto-completion for file paths.

Directory listing.

i - thin, long, wide or tree listings
s - sort on name, time or file size
r - Reverse sort order
gh - Hide or unhide dot files
- Open the file or directory
x - View file with associated application
d - Make directory
D - delete the file or directory
R - Rename the directory or file
- <-- Go up a directory


Window Management

Ctrl+w s - split window horizontally
Ctrl+w v - split vertically
Ctrl+w j - Move focus down
Ctrl+w k - Move focus up
Ctrl+w h - Move focus left
Ctrl+w l - Move focus right

Ctrl+w J - Move buffer up one window
Ctrl+w K - Move buffer down one window
Ctrl+w H - Move buffer left one window
Ctrl+w L - Move buffer right one window

Ctrl+w c - Close window
Ctrl+w o - Close all but current
Ctrl+w w - Cycle focus
Ctrl+w p - Focus previous window

Friday, October 15, 2010

Puzzle

Came along an interesting puzzle so wanted to share.

Write a function that adds two numbers.  You should not use + or any arithmetic operators.

Lets have two number which are fairly large and try to add those two numbers but try a different approach.

987+789 = 1776

Lets just think backwards

   987
+ 789
--------
   666

Carry : 1110.  This is calculated when the first carry is the first digit and the last carry is the last.

Add 1110 and 666 which gives you the ultimate result.

Now lets implement it in source (I am using python)

>>> def sum_without_arithmetic(a,b):
...     if b==0: 
...         return a
...     sum = a^b
...     carry = (a&b)<<1
...     return sum_without_arithmetic(sum, carry)
...
>>> sum_without_arithmetic(987,789)
1776

Thursday, October 14, 2010

More Interview Questions

Networking:

Explain what happens, step by step, after you type a URL into a browser.  Use as much details as possible.

1. Browser contacts the DNS server to find the IP address of the URL.
2. DNS server returns the IP address of the site.
3. Browser opens a TCP connection to the web server at port 80.
4. Browser fetches the html code of the page requested.
5. Browser renders the HTML in the display window.
6. Browser terminates the connection when window is closed.


Database:

1. What are different types of join?  Please explain how they differ and why certain types are better in certain conditions.

JOIN is used to combine the results of two tables.  To perform a join, each of the tables must have at least one field which will be used to find matching records from the other table.  The join type defines which records will go into the result set.


1. INNER JOIN:

Result set will contain only those data where the criteria match.

2. OUTER JOIN:

Outer join will always contain the results of INNER JOIN, however it can contain some records that have no matching record in other table.  OUTER JOINs are divided into following subtypes

2.1 LEFT OUTER JOIN or simply LEFT JOIN:

The result set will contain all the records from the left table.  If no matching records were found in the right table, then its fields will contain NULL values.

2.2 RIGHT OUTER JOIN or simply RIGHT JOIN:

Opposite of the LEFT JOIN.  It will contain all the records from the right table, and missing fields from the left table will contain NULL.

If we have two tables A and B, then we can say that statement A LEFT JOIN B is equivalent to statement B RIGHT JOIN A.

2.3 FULL OUTER JOIN

FULL OUTER JOIN combines the results of LEFT and RIGHT joins.  All records from both the tables will be part of the result set, whether matching records exists in other table or not.  If no matching record was found, then the corresponding result fields will have a NULL value.

C++

Compare and contrast Hash Table vs. STL map.

Hash Table:

In a hash table, a value is stored by applying hash function on a key.  Thus, values are not stored in a hash table in sorted order.  Additionally, since hash tables use the key to find the index that will store the value, an insert/lookup can be done in amortised O(1) time (assuming a few collisions in a hash table).  One must also handle potential collisions in a hash table.

STL Map

In STL Map, insertion of key/value pair is in sorted order of key.  It uses a treee to store values, which is why an O(log n) insert/lookup is required.  There is also no need to handle collisions.  An STL map works well for things like:
  • find min element
  • find max element
  • print elements in a sorted order
  • find the exact element or if the element is not found, find the next smallest number.
Implementation of a Hash Table

  1. A good hash function is required (e.g. operation % prime number) to ensure that the hash values are uni-formally distributed.
  2. A collision resolving method is also needed: chaining (good for dense table entries), probing (good for sparse table entries), etc.
  3. Implement methods to dynamically increase or decrease the hash table size on a given criterion.  For example, when the [number of elements] by [table size] ratio is greater than the fixed threshold, increase the hash table size by creating a new hash table and transfer the entries from the old table to the new table by computing the index using new hash function.
What can be used instead of a hash table, if the number of inputs is small?

You can use an STL map.  Although this takes O(log n) time, since the number of inputs is small, this time is negligible.

Wednesday, May 5, 2010

C++ style puzzles

Some interesting puzzles that can be asked in an interview.

1. Given a vector v, what is the difference between the lines marked A and B?

void f(vector& v) {
v[0]; // A
v.at(0); // B
}

If v is not empty then there is no difference between lines A and B. If v is empty, then line B is
guaranteed to throw a std::out_of_range exception, but there's no telling what line A might do.
There are two ways to access contained elements within a vector. The first, vector::at, is required to perform bounds-checking to ensure that the vector actually contains the requested element. It doesn't make sense to ask for, say, the 100th element in a vector that contains only 10 elements at the moment, and if you try to do such a thing, at will protest by throwing a std::out_of_range hissy fit (also known as an exception).

Saturday, January 30, 2010

dil to bacha hai ji -- ISHKIYA guitar chords

I have been learning to play guitar for some years now.

Here is my attempt to decode the chords of a new song.

“Dil toh bacha hai ji” from the movie Ishqiya is a good

slow song. Reminds me of the old Rajkapoor movie songs.

Rahat Fateh Ali Khan’s voice has made this song even

better.

Now, to play this song on guitar you show know to play the

Bar Chords.

Strumming pattern: |DD - DD -|DD – DD -|

F#m

Aisi ulji nazar unse hatt ti nahi

Bm

Daant se reshmi dor katt ti nahi

F#m
Umar kab ki baras ke safaid ho gayi

Bm
Kaari badari jawani ki chatt ti nahi

F#m        Bm

Walla ye dhadkan bhadne lagi hai

F#m        Bm
Chehre ki rangat udne lagi hai

F#m        Bm
Darr lagta hai tanha sone mein ji
F#m         Bm        C#m

Dil to bachcha hai ji

F#m        Bm        C#m
Dil to bachcha hai ji

F#m        Bm        C#m
Thoda kaccha hai ji

F#m        Bm        C#m
Haan dil to baccha hai ji

F#m
Aisi ulji nazar unse hatt ti nahi

Bm

Daant se reshmi dor katt ti nahi

F#m

Umar kab ki baras ke safaid ho gayi

Bm

Kaari badari jawani ki chatt ti nahi

F#m        Bm        C#m
Ra ra ra .. x 2

F#m        F#
Kisko pataa tha pehlu mein rakha

Bm
Dil aisa baaji bhi hoga

F#m        F#
Hum to hamesha samajhte the koi

Bm
Hum jaisa haaji hi hoga

F#m        Bm
Hai zor karein, kitna shor karein

F#m        Bm
Bewaja baatein pe ainwe gaur karein

Bm
Dilsa koi kameena nahi

F#m        Bm
Koi to rokey, koi to tokey

F#m        Bm
Iss umar mein ab khaogey dhokhe

F#m        Bm
Darr lagta hai ishq karne mein ji

F#m        Bm        C#m
Dil toh bachcha hai ji

F#m        Bm        C#m
Dil toh bachcha hai ji

F#m         Bm         C#m

Thoda kaccha hai ji

F#m          Bm         C#m

Haan dil to baccha hai ji

F#m         F#

Aisi udhaasi baithi hai dil pe

Bm

Hassne se ghabra rahe hain

F#m         F#

Saari jawani katra ke kaati

Bm

Piri mein takra gaye hain

F#m         Bm

Dil dhadakta hai to aise lagta hai who

F#m         Bm
Aa raha hai yahin dekhta hi na woh

F#m         Bm

Prem ki maarein kataar re

F#m         Bm

Taubah ye lamhe katt te nahi kyun

F#m         Bm

Aankhein se meri hatt te nahi kyun

F#m         Bm

Darr lagta hai mujhse kehne mein ji

F#m         Bm         C#m

Dil toh bachcha hai ji

F#m         Bm         C#m

Dil toh bachcha hai ji

F#m         Bm         C#m

Thoda kaccha hai ji

F#m         Bm         C#m

Haan dil toh baccha hai ji

Saturday, August 22, 2009

how to download songs for free...!!!!

Everybody is looking for bollywood songs and they want to play in their cars / ipods and nobody wants to pay for the mp3s or CDs. The only reason is if somebody can get it for free why can't I? Well a lot of people discuss how to download songs from the Internet and there is no single source on the internet that will give you all the songs starting from oldies to the latest songs. I believe lot of people know about the new songs....so that is available but oldies fans like me have a hard time finding songs that they can download and play in their ipods and cars.

So as always I dedicate this post to all the fellow oldies fans and obviously the new ones....... I will show you how you can download songs...any songs...

1. Use Firefox only. This works only in firefox
2. Go to Tools-->Add ons--> Get Add ons --> Browse all add ons...
3. This will take you to all the add ons available.
4. Search for downloadhelper.
5. First result you will get is downloadvideohelper.
6. Download that and install it and restart firefox.

You are almost done.....

1. Go to your favorite songs site and start playing your favorite songs and you will see the downloadvideohelper icon revolving.
2. Click the icon and you will see all the songs that are playing....click one of them and it will ask you to save ....and there you go.....You are all set.....

Let me know if you have any questions.......

Friday, August 21, 2009

Python Interview questions

List of questions on the interview....

1. What is list comprehension?
2. what is better += or .join()?
3. Do you know what is ISAPI filters?
4. How do you do unit testing?
5. What are you good with? Object oriented or subject oriented?
6. What is your favorite programming language? C++ or Python or anything else?
7. What is your favorite design pattern?
8. Explain singleton design pattern.
9. What version of Python do you use? 2.4/2.6/3.0?
10.Have you used any of the python frameworks? Django?
11. Are you are back end developer or a front end too?
12. When and why did you use Inno setup?
13. Explain difference between public, private and protected in C++
14. How many million pois we have in our db?
15. What is the percentage of C++ coding v/s Python coding in the last two years..?
16. Do you use Navteq maps for the map data?
17.

Tuesday, July 21, 2009

Hindi translation of common english words



I am trying to imporve my hindi vocabulary and was trying to find out transloation of words that we use in our day to day life.

I found a blog that served my purpose....This is not my creation...just a bookmark of somebody else's work... I like to appreciate others work by posting their article on mine and giving them credit ...Here you go and hope you like it...


CRICKET : Gol guttam lakad battam de danadan pratiyogita

CRICKET TEST MATCH : Pakad dandu, maar mandu, de danaadan pratiyogita

TABLE TENNIS : Lakdi ke phalak shetra pe le takaatak de takaatak

LAWN TENNIS : Harit Ghaas par le tada tad, de tada tad

LIGHT BULB : Vidyut Prakashak Kanch golak

TIE : Kanth Langoti

MATCH BOX : Ragdampatti Agni Utpaadan Peti

TRAFFIC SIGNAL : Aavat Jaavat Suchak Jhandaa

TEA : Dugdh Jal Mishrit Sharkara Yukt Parvatiya(pahaadi) Booti

TRAIN : Sahasra Chakra Louh Path Gaamini

ALL ROUTE PASS : Yatr Tatr Sarvatr Gaman Aagya Patr

RAILWAY SIGNAL : Loh Path Gamini Suchak Yantra

RAILWAY SIGNAL : Agni Rath Aava Gaman Soochak Pattika

RAILWAY SIGNAL : Louh path gaamini aawagaman suchak yantra

RAILWAY STATION : Bhabhka Adda

BUTTON : Ast Vyast Vastra Niyantrak

MOSQUITO : Gunjanhaari Manav Rakt Pipasu Jeev

CIGERETTE : Shweta patra mandit dhumra shalakha

Friday, June 19, 2009

Guitar Chords - Kisi ki muskurahton pe......



Cm
Kisiki muskuraahaton pe ho nisaar

Cm-------------------------------A#
Kisika dard mil sake to le udhaar

A#-----------------------------------G#
Kisike waaste ho tere dil mein pyaar

G#---------------------G
Jeena issi ka naam hai

(repeat again)


Cm----------------------------
Maana apni jeb se fakeer hain

A#-------------G#-------------G----Cm
Phir bhi yaaron dil ke hum ameer hai

Cm---------------
Mitte jo pyaar ke liye woh zindagi

A#------------------------------
Jale bahaar ke liye woh zindagi

A#---------------------------------G#
Kisi ko ho na ho hamein to aitbaar

G#----------------------G-
Jeena issi kaa naam hai


stanza 2nd as first only..
Cm
(Rishta dil se dil ke aitbaar ka

Cm---------------------------A#
Zinda hai hameen se naam pyar ka) - x2

A#------------------------------G#
Ke mar ke bhi kisi ko yaad aayenge

G#-------------------------------G
Kisi ke aansuon mein muskuraayenge

Cm-------------------------------
Kahega phool har kali se baar baar

G#-------------------G
Jeena isi ka naam hai

Cm
Kisiki muskuraahaton pe ho nisaar..

Thursday, June 4, 2009

C++ -- STL -- Vector -- Tutorial


Found out some good tutorial about Vectors. I believe most of the novice C++ programmers will know a lot about STL and vectors but this is one in case if somebody needs to brush up.

Vector Tutorial - Part I

Vector Tutorial - Part II

Hope this helps

Friday, May 29, 2009

Share your videos with your friends SEETOO.COM

Everything is getting pretty easy and this is one step into the easiness over sharing the data.

What if you want to share a movie with your friends miles away from where you are located...or possibly the next room or may be next street? You write it over a CD or a flash drive and give it to him which he copies and starts watching....but that is pretty impossible when you are miles away from your friend. And sometimes it really becomes difficult for you to upload it somewhere and then your friend needs to download it and I would consider it painful to do this stuff for just small thing like a video.

So what is the solution to this problem? Well here it is www.seetoo.com

And what does seetoo do? Well it says I am seeing this video, you SEE TOO. So it is a service where you share your video to a bunch of friends or many friends over the internet and you can watch it all together.

Well what if you suggest one of your friend a movie and he/she doesn't have a copy of the DVD or doesn't have it downloaded and you know it is painful to wait for the movie to be downloaded. So what you do is talk to him and tell him "Hey I have the movie and I will broadcast it for you.

It is so easy.

1. Go to www.seetoo.com
2. No login - Best part
3. Select the video you want to share.
4. Start the video.
5. Send an invitation to your friends who want to watch the video.

That's it...!!!! Isn't that too simple? I bet your answer will be yes. Don't believe it. I believe you should give it a try.

www.seetoo.com

let me know if you like it....!!! Enjoy...

My Broadcast Channel

Watch live video from Lifecasting on Justin.tv



Guys this is my broadcast channel. Whenever I think I need to talk to somebody, I turn this on.....

I got the motivation from the below video. See the video and you will know what is it that I am trying to do...


Monday, May 11, 2009

Python Interview Questions and Answers



Hi Everybody,

As always interview questions but this time I was lucky to be interviewed for Python, which I had recent experience on. And the interviewer was great. He told me that he had pretty much fundamental and short questions to ask and he joked about MS interviewees will be joyed with this kind of interview process.

This was basically a python position but this made me feel why people cannot do with other programming language experts for python because a python programmer is really way too different than a C++ or Java programmer. Since I am a C++ programmer with recent experience in Python, I was considered for the position. It was fun going through the interview since it was web conference coding interview.

What I had gone through was the LinuxCBT edition of python which helped me a lot. If I had not referred that I would have done miserably.

I had tried searching for python questions over the internet but was not too lucky since I got only a few of them which made sense. Some of them were asked but restricting to just a couple of them. So I think my questions and answers will really help people to get a good idea on what can be asked for python interviews and also for people who are getting interviewed on python. I really appreciate comments and improvements on the questions and answers.

Hope the information helps.....


1. Name five modules that are included in python by default

2. Name a module that is not included in python by default

3. What is __init__.py used for?

4. When is pass used for?

5. What is a docstring?

6. What is list comprehension?

7. What is map?

8. What is the difference between a tuple and a list?


Ans. This is the most frequently asked question on python.

A tuple is a list that is immutable. A list is mutable i.e. The members can be changed and altered but a tuple is immutable i.e. the members cannot be changed.

Other significant difference is of the syntax. A list is defined as

list1 = [1,2,5,8,5,3,]
list2 = ["Sachin", "Ramesh", "Tendulkar"]

A tuple is defined in the following way

tup1 = (1,4,2,4,6,7,8)
tup2 = ("Sachin","Ramesh", "Tendulkar")

So the difference is in the type of brackets.


Coding questions

9. Using various python modules convert the list a to generate the output 'one, two, three'

a = ['one', 'two', 'three']

ANSWER:




>>> a = ['one','two','three']
>>> ','.join(a)
'one,two,three'

10. What would the following code yield?

word = 'abcdefghij'
print word[:3] + word[3:]

Ans. This will print the word 'abcdefghij'

11. Optimize these statements as a python programmer

word = 'word'
print word.__len__()


ANSWER:
>>> print 'word'.__len__()
4


12. Write a program to print all the contents of a file


Ans.

try:
  f1=open("filename.txt","r")
except Exception, e:
  print "%s" %e  

print f1.readlines() 
 
ANSWER2:
with open("tmp1.txt", "r") as f:
     f.readlines() 

13. What will be the output of the following code

a = 1
a,b=a+1,a+1
print a
print b

Ans.

2
2

Here in the second line a,b=a+1,a+1 means that a=a+1 and b=a+1 which is 2. But this is the python way of initialization which a python programmer should understand.

14. Given the list below remove the repetition of an element. All the elements should be uniquewords = ['one', 'one', 'two', 'three', 'three', 'two']

ANSWER:

>>> set(uniquewords)
set(['three', 'two', 'one'])

15. Iterate over a list of words and use a dictionary to keep track of the frequency(count) of each word. for example

{'one':2,'two':2,'three':2}

ANSWER:

>>> l = ['one', 'one', 'two', 'three', 'three', 'two', 'one', 'one', 'two']
>>> d = {}
>>> for w in l:
...   d[w] = 1 + d.get(w,0)
...
>>> d
{'three': 2, 'two': 3, 'one': 4}

16.Write the following logic in Python:
If a list of words is empty, then let the user know it's empty, otherwise let the user know it's not empty.


Ans.
a=[]
if len(a):
print"The list is not empty"
else:

print"The list is empty"


17. Demonstrate the use of exception handling in python.
Ans.

a=[1,2,3,4]
try:
print a[5]
except Exception, e # This was important. Just do not say except: and print out something. It is
print e # Important to know what is the error

>>> a=[1,2,3,4]
>>> try:
...   print a[5]
... except Exception, e:
...   print "Error %s" % e
...
Error list index out of range

18. Print the length of each line in the file 'file.txt' not including any whitespaces at the end of the lines.
Ans.
>>> f1 = open("abc.py", 'r')
>>> i=0
>>> for line in iter(f1):
...   print "Length of line %d is %d" % (i, len(line.rstrip()))
...   i+=1
...
Length of line 0 is 11
Length of line 1 is 21


19. Print the sum of digits of numbers starting from 1 to 100

Ans. print sum(range(1,101))

This is way too easy but just who know python. Since I am a C++ Programmer, I started writing a for loop to add up which was way too dumb. Hope you don't make this mistake.

Python is known for it short syntax and easy to use functions.

20. Create a new list that converts the following list of number strings to a list of numbers.
num_strings = ['1','21','53','84','50','66','7','38','9']

Ans.




>>>num_strings = ['1','21','53','84','50','66','7','38','9']
>>>[int(j) for j in num_strings]
[1, 21, 53, 84, 50, 66, 7, 38, 9]

21. Create two new lists one with odd numbers and other with even numbers
num_strings = [1,21,53,84,50,66,7,38,9]

Ans.
>>>num_strings = [1,21,53,84,50,66,7,38,9]
>>>o, e = [], []
>>>[o.append(n) if n % 2 else e.append(n) for n in num_strings]
[None, None, None, None, None, None, None, None, None]
>>>o,e
([1, 21, 53, 7, 9], [84, 50, 66, 38])

>>> num_strings = [1,21,53,84,50,66,7,38,9]
>>> odd, even = filter(lambda x:x%2, num_strings), filter(lambda x: not x%2, num_strings)
>>> print odd,even
[1, 21, 53, 7, 9] [84, 50, 66, 38]


22. Write a program to sort the following intergers in list
nums = [1,5,2,10,3,45,23,1,4,7,9]

nums.sort() # This is the quickest sorting algorithm. This is the best possible way to sort.
print nums

23. Write a for loop that prints all elements of a list and their position in the list.
abc = [4,7,3,2,5,9] 
Ans. 
 
>>>abc = [4,7,3,2,5,9]
>>>for i, v in enumerate(abc):
...   print i,v
... 
0 4
1 7
2 3
3 2
4 5
5 9

24. The following code is supposed to remove numbers less than 5 from list n, but there is a bug. Fix the bug.
n = [1,2,5,10,3,100,9,24]

for e in n:
if e<5: 
    n.remove(e)
print n

Ans. The output here will be

[2,3,5,10,100,9,24] which means the 1st and the 5th elements are removed.

It should be implemented as below.

>>> n = [1,2,5,10,3,100,9,24]
>>> nlist = filter(lambda x: x >= 5, n)
>>> print nlist
[5, 10, 100, 9, 24]


list.remove(element) will remove the element, and shrink the list. If
you are iterating over the same list at that time, and you wanted to
go to next element, the next element may very well be the one after.
Here is what is happening in the problem: The 0th element in the list
is less than 5 and is removed, thus, making the list shorter by one
element. The next iteration in the for loop goes to n[1], but n[0]
now is 2, so the loop skips element 2 and doesn't remove it. Same
thing happens at 100, but it is ok to skip 100 as it is > 5

25. What will be the output of the following
def func(x,*y,**z):
print z

func(1,2,3)

Ans.

Here the output is :

{}

If I print all the variables, namely x, y and z it yeilds me this

1 (2,3) {}

* and ** have special usage in the function argument list. *
implies that the argument is a list and ** implies that the argument
is a dictionary. This allows functions to take arbitrary number of
arguments (like your sum function that took range of numbers from 0
.. 100. Pretty cool, eh?


26. Write a program to swap two numbers.
a = 5
b = 9

def swap(c,d):
return d,c

swap(a,b)

This will print the swapped values of a and b

(9,5)

OR if this does not seem convincing,
a, b = 5, 10

t = a
a=b
b=t

print a,b

>>> a = 5
>>> b = 10
>>> a,b=b,a
>>> a
10
>>> b
5

27. What will be the output of the following code
class C(object):
def__init__(self):
self.x =1

c=C()
print c.x
print c.x
print c.x
print c.x

Ans.

All the outputs will be 1

1
1
1
1

28. What is wrong with the code
func([1,2,3]) # explicitly passing in a list
func()             # using a default empty list

def func(n = []):
#do something with n

print n

Ans. I tried running the code with my addition of printing the value of n in the function and found out the following result

func([1,2,3]) resulted in [1,2,3]
while func() resulted in []

29. What all options will work?
a.

n = 1
print n++

b.

n = 1
print ++n

c.

n = 1
print n+=1

d.

int n = 1
print n = n+1

e.

n =1
n = n+1

From the above options I believe the following will work

b. and e.

There are some problems with a, c and d.

if you try running the code in a , it does not accept n++ but it accepts ++n

n+=1 is not accepted while in d the variable is preceded by an int which is not pythonically correct.

30. In Python function parameters are passed by value or by reference?
Ans. Please refer to this


31.Remove the whitespaces from the string.
s = 'aaa bbb ccc ddd eee'

Ans.

a = string.split(s)
print a
['aaa', 'bbb', 'ccc', 'ddd', 'eee'] # This is the output of print a

print string.join(a)
aaa bbb ccc ddd eee # This is the output of print string.join(a)

32. What does the below mean?
s = a + '[' + b + ':' + c + ']'

33. Optimize the below code

def append_s(words):
new_words=[]
for word in words:
new_words.append(word + 's')
return new_words

for word in append_s(['a','b','c']):
print word

The above code adds a trailing s after each element of the list. Is there a better way one can write the above script?

34. If given the first and last names of bunch of employees how would you store it and what datatype?

Ans. Either a dictionary or just a list with first and last names included in an element.


35.
36.

















Thursday, May 7, 2009

Print all prime number upto a certain Range in C++ and Python

I have tried developing in C++ and Python. I like scripting in python and C++ is my favorite programming language.


#!/usr/bin/env python




#Author : Ronak Patel

#Date : 05/07/2009

#Purpose : Write a script to get all prime numbers upto a certain range.



x = int(raw_input("Enter the range: "))

for i in range(2,x):

isprime = 1

for j in range(2,i):

if(i==j):

continue

elif(i%j==0):

isprime=0

if(isprime):

print "%d\t" % i




The logic is the same but only the syntax is different. Here we have two for loops. The first one starts from 2 and goes till the last number you want. The other loop starts with a 2 and end with the first loop digit. So we make sure all the numbers are verified. Let me explain you in a bit detail.

In the above script, Initially i will be 2 and j will also be 2. It will end up exiting the loop because it satisfies the condition i==j and it will be printed since isprime remains 1. Secondly i will be 2 and j will be 3 which wont satisfy the condition i==j and also i%j==0. So it will move forward with i=3 and j=3 which then shows that it is also a prime number.

Now when i=2 and j=4, it satisfies the condition i%j==0 which means it will not be printed since isprime=0. So this is how this works.

Below is the C++ implementation.


// prime.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include


//using namespace std;

void prime(int a)
{
int isprime;

for(int i=2;i<=a;i++)
{
printf("i in the first loop %d\n", i);
isprime =1;
for(int j =2;j<=i;j++)
{
printf("\tj in the second loop %d\n", j);

if(i==j)
{
continue
;
}
else if (i %j == 0)
isprime = 0;
}
if(isprime)
printf("%d\n",i);
}
getchar(); }
void main()
{
int n;
std::cout<<"Enter range: ";
std::cin >> n;

prime(n);

getchar();

}


Hope this helps. I will try and post Perl script too for this. I believe I did not find more implementations of this particular program. You can find many implementations for odd even programs but not prime ones.


Here goes the perl script for the same purpose


#!/usr/bin/perl -w
#use strict;
#Author : Ronak Patel
#Date : 05/07/2009
#Purpose : Write a script in perl to print all prime numbers

print("Enter the range: ");
my $max = <>;
chomp($max);
$i = 0;
$j =0;
$isprime = 0;


for($i = 2;$i <= $max; $i++) { $isprime=1; for($j = 2; $j <= $i; $j++) { if($i == $j){} # continue; elsif($i%$j==0) { $isprime = 0; } } if($isprime) { print("$i\n"); } }

Tuesday, May 5, 2009

Conver DOCX to DOC for free

How To Convert DOCX to DOC For Free Instantly

Do you want to convert a DOCX file to DOC file? Do you have a DOCX file made from Microsoft Word 2007 and you can't open it in Microsoft Word 2000, XP or 2003? If you want to convert DOCX to DOC without installing MS Word 2007 then read on and you will learn how to convert DOCX to DOC for free.

For your information, .docx is the default file extension of MS Word 2007. They are actually just zipped XML documents. Try to rename it from .docx to .zip and extract the file using Winzip or Winrar and other decompression tools.

One solution to convert .docx documents to .doc file format is to download the free Miscrosoft Office Compatibility pack available here. Of course you need to have a licensed Windows OS to get the download.

I hope this short tutorial was able to help you convert DOCX files to DOC format or open DOCX files in other word processing software and applications.

Hope this helps the ones in need.

Download bollywood songs for free

I have been asked by a lot of people on a site where they could download mp3 format songs to play in their cars or on their computers.

Since I am an avid fan of bollywood music and songs I tried searching and found a bunch of useful websites where you can download songs and burn them on a CD. Well I don't know the legality issues and just recommend these sites.



Bollyextreme

123musiq

j4jumpy

songs.pk

mastimag

Hope you will like it.

Sunday, April 19, 2009

Pal - KK

E
Hum rahe ya na rahe kal
A B
Kal yaad aayenge yeh pal
E
Pal, yeh hain pyaar ke pal
A B
Chal, aa mere sang chal
C#m B A E
Chal, soche kya Chhoti si hai zindagi
C#m B A B
Kal mil jaaye to hogi khushnaseebi

E A B E
Hum rahe ya na rahe, yaad aayenge yeh pal




B C#m B C#m
Shaam ka aanchal odhke aayi
A E
Dekho voh raat suhaani
B C#m B C#m
Aa likh de hum donon milke
A B
Apni yeh prem kahaani

E A B E

Hum rahe ya na rahe, yaad aayenge yeh pal


stanza2
chords similar to previous one...
B C#m B C#m
Aane waali subah jaane
A E
Rang kya laaye deewaani
B C#m B C#m
Meri chaahat ko rakh lena
A B
Jaise koi nishaani

E A B E
Hum rahe ya na rahe, yaad aayenge yeh pal

yaaron - Pal chords

KK
Yaaron
Key: F

Chorus
------

F Bb F Bb
yaaro.N dostee ba.Dee hee ha seen hai ye naa

F Bb F Bb
ho to kyaa phir bolo ye zinda gee hai koee

F F/A Bb F F/A Bb
to ho raazdaa r bega raz teraa ho yaar koee

F F/A F
to ho raaz daar


F Bb F Bb
yaaro.N mohabbat hee to banda gee hai ye naa

F Bb F Bb
ho to kyaa phir bolo ye zinda gee hai koee

F F/A Bb F F/A Bb
to dilbar ho yaar jis ko tujhse ho pyaar koee

F F/A F
to dilbar ho yaar

Verse 1
-------

Dm Am Bb F
teree har ek buraayee pe daa.NTe wo dost

Dm Am Bb F
gam kee ho dhoop to saayaa bane teraa wo dost

Bb Am Gm F
naache bhee wo teree khu shee me.N arE

Chorus
------

F Bb F Bb
yaaro.N dostee ba.Dee hee ha seen hai ye naa

F Bb F Bb
ho to kyaa phir bolo ye zinda gee hai koee

F F/A Bb F F/A Bb
to ho raazdaa r bega raz teraa ho yaar koee

F F/A F
to ho raaz daar

Verse 2
-------

Dm Am Bb F
tan man kare tujhpe fidaa mahboob wo

Dm Am Bb F
palko.N pe jo rakhe tujhe mahboob wo

Bb Am Gm F
jiskee wafaa tere liye ho arE

Chorus
------

F Bb F Bb
yaaro.N mohabbat hee to banda gee hai ye naa

F Bb F Bb
ho to kyaa phir bolo ye zinda gee hai koee

F F/A Bb F F/A Bb
to dilbar ho yaar jis ko tujhse ho pyaar koee

F F/A Bb
to dilbar ho yaar

Dil De Diya hai....Masti Chords



This is one of my favorite songs. I tried playing it and it sounds good. Let me know if you find any problems with it. Thanks for visiting....





----------Cm
Dil de diya hai
A#-------
jaan tumhe denge

Cm------Cm
dil de diya hai
A#-------
jaan tumhe denge
G#-----------------Cm
dagaa nahi karenge sanam

------------A#--( D# also seems good here)
hoooo....rabb di kasam ...
--------------Cm
yaara rabb di kasam
(repeat once mukhra)




Cm-----------------------G#
rukh zindagi ne mod liya kaisa

---------A#----------------Cm
humne socha nahi tha kabhi aisa

Cm-----------------------G#
rukh zindagi ne mod liya kaisa

---------A#----------------Cm
humne socha nahi tha kabhi aisa

Cm-----------G#--
aata nahi yakeen

-------A#-------Cm
kya se kya ho gayaa
Cm-------G#-----A#----------Cm--
kis tarah main tumse bewafaa ho gayaa

Cm-------Cm
insaaf kar do

A#
mujhe maaf kar do

G#--------------Cm
itna hee kar do karam

Cm------Cm
dil de diya hai

A#--
jaan tumhe denge

G#-----------------Cm
dagaa nahi karenge sanam



(following stanzas are also like previous one)

Awaargi mein ban gaya diwaana
Cm-----------------------G#

Maine kyun saadgi ko nahin jaana
---------A#----------------Cm

Awaargi mein ban gaya diwaana
Cm-----------------------G#

Maine kyun saadgi ko nahin jaana
---------A#----------------Cm

Chaahat yahi hai ke, is qadar pyaar doon
Cm-------------------------------G#

Qadmon mein tere main, toh jahaan waar doon
--------A#----------------------------Cm

Chain mera le lo, khushi meri le lo
Cm-----------------------A#

De do mujhe dedo saare gham
---------G#----------------Cm


Dil de diya hai, jaan tumhein denge
Cm-----------------------A#

Daga nahin karenge sanam
---------G#----------------Cm

Mere ashq keh rahe meri kahaani
Cm--------------------------G#

Inhein samjho na tum sirf paani) -2
A#-----------------------------Cm

Ro ro ke aansuon ke daag dhool jaayenge
Cm-------------------------------A#

In mein wafa ke rang, aaj ghool jaayenge
G#-------------------------------Cm

Paas tum rahogi, bhool ab na hogi
Cm---------------------------A#

Karoonga na tumpe sitam
G#----------------------Cm

Dil de diya hai, jaan tumhein denge
Daga nahin karenge sanam
Ho...rab di kasam yaara, rab di kasam
(Dil de diya hai, jaan tumhein denge
Daga nahin karenge sanam) -2

Tuesday, April 14, 2009

New C++ questions....

Surprisingly the number of interview questions posts have increased since I am appearing for a number of interviews..... but surely this helps me and I hope that it will help some other people too.


1. Tell me the fundamentals of OOPS.

--> Encapsulation, Inheritance, Polymorphism. Define them.

Surprisingly I was asked that I missed abstraction. I believe it is a generic term for encapsulation.


2. Implementation of polymorphism in recent projects...

Implemented the Logger class to log all the install scripts as well as other database related scripts.


3. What kind of polymorphism did you implement in the recent projects?

--> Run time polymorphism.


4. Explain operator overloading.


5. What is a virtual funtion?


6. What are memory leaks?


7. What is a function pointer?


8. What is a VPT (Virtual Pointer Table)?


--> The virtual table is actually quite simple, though it’s a little complex to describe in words. First, every class that uses virtual functions (or is derived from a class that uses virtual functions) is given it’s own virtual table. This table is simply a static array that the compiler sets up at compile time. A virtual table contains one entry for each virtual function that can be called by objects of the class. Each entry in this table is simply a function pointer that points to the most-derived function accessible by that class.


9. What is a smart pointer?


-->Smart pointers are objects which store pointers to dynamically allocated (heap) objects. They behave much like built-in C++ pointers except that they automatically delete the object pointed to at the appropriate time. Smart pointers are particularly useful in the face of exceptions as they ensure proper destruction of dynamically allocated objects. They can also be used to keep track of dynamically allocated objects shared by multiple owners.