TechMyWay – New Blog

Posted April 28, 2013 by TechMyWay
Categories: Uncategorized


TechMyWay – New Blog

Much has happened since I graduated and started working. Here is a link to my new blog, which I try my best to keep updated. Follow me up there for future posts πŸ™‚

Git add remote branch

Posted September 27, 2012 by TechMyWay
Categories: Uncategorized


A quick post on git (might help some):

To create a branch: git checkout -b branchName
#this also switches you to the newly created branch

Now to upload it to your remote repository use:
git push origin branchName
# if the branch with that name already doesn’t exist then it would be updated (as tested on GitHub)

A major milestone : 5k views

Posted April 23, 2012 by TechMyWay
Categories: Uncategorized

Tags: ,

To all,

Thanks a lot for your love. My blog has crossed 5000 views. πŸ™‚ πŸ™‚

Threading in Python

Posted April 15, 2012 by TechMyWay
Categories: Python

Tags: , ,

Recently in my effort to learn something new in Python, I thought of having a small introduction to threading in python.

The following modules are related to python that come in default installation in python:

From Python Docs:

Note
The thread module has been renamed to _thread in Python 3.0. The 2to3 tool will automatically adapt imports when converting your sources to 3.0; however, you should consider using the high-level threading module instead.

Thus, it can be assumed that when developing scripts that may use threading, always use theΒ threading module rather than thread.

To save myself some time, it would be better if you can read the basic concepts of threads from wiki itself.

Now, comes the first program.

#!/usr/bin/env python

import time
import thread

def myfunction(string, sleeptime, max_count, *args):

    counter = 0
    ## To manage I/O
    time.sleep(0.2)
    while counter < max_count:
        print "{}. {}".format(counter, string)
        counter += 1
        time.sleep(sleeptime)
        #sleep for a specified amount of time.

if __name__=="__main__":

    print "thread Started : {}".format(thread.start_new_thread(myfunction,("Thread No:1", 2, 10)))
##    thread.exit_thread
##
    ## this can be omitted
    while 1:
        pass

 

In the above script, a new thread is started using the function myfunction. The arguments to the function are passed to the start_new_thread() using a tuple (do remember to make a tuple from the arguments you want to pass). The start_new_thread() returns the thread identifier of the thread started (which has been printed here).
A very usual thing I noticed in threaded programs is the use of time.sleep(), it helps in synchronizing the input output on the terminal. In actual backend scripts, the sleep function would not prove useful (I may be wrong!)

The last example was just for introduction. To jump up the level, let’s calculate the Fibonacci series from a thread.

Code:

#Fibonacci threader

import time, thread, threading

def fib(n):
    a, b = 0, 1
    while a</pre>
&nbsp;

The above script uses bothΒ <a title="Python Docs" href="http://docs.python.org/library/thread.html">thread</a> andΒ <a title="Python Docs" href="http://docs.python.org/library/threading.html">threading</a> module. The thread module is used to create threads and threading module is used to get information on the current running threads in the process.

Here the function fib(n) is actually a <a title="Python Docs" href="http://wiki.python.org/moin/Generators">generator</a> and returning a iterator (returning a <a title="Python Docs" href="http://docs.python.org/release/2.5.2/ref/yield.html">generator iterator</a>). Thus we are able to iterate over the Fibonacci numbers using these generators. After the required number of Fibonacci numbers have been generated, <a title="Python Docs" href="http://docs.python.org/library/thread.html#thread.exit">thread.exit_thread() </a>is called which exits the running thread silently.

After creating the thread the script prints the information of the running threads. (Execute to see)

In the end, I would be showing you the code for the (quite famous) <a title="Wikipedia" href="http://en.wikipedia.org/wiki/Producer-consumer_problem">Consumer-Producer problem</a> which would include the code for using locks.

Code:


#!/usr/bin/env python

import time
import thread

## Implementing consumer-producer problem using threads and locks

product = []

def producer(lock, produce_time, lim, *args):

    pr_val = 0

    while True:

        print "Producing.."
        time.sleep(produce_time)
        print "Produced {}".format(pr_val)

        lock.acquire_lock()
        print "P: Lock ACK"
        product.append(pr_val)
        print "Added product {}".format(pr_val)
        lock.release_lock()
        print "P: Release ACK"

        pr_val += 1

        if pr_val > lim:
            break

def consumer(lock, consume_time, waiting_time, lim, *args):

    con_val = 0
    got_product = False

    while True:

        lock.acquire_lock()
        print "C: Lock ACK"

        try:
            con_val = product.pop()
            print "Retrieved value {}".format(con_val)
            got_product = True
        except IndexError:
            print "No produce!"
            got_product = False

        lock.release_lock()
        print "C: Release ACK"

        if got_product:
            print "Consuming.. {}".format(con_val)
            time.sleep(consume_time)
        else:
            print "Waiting for produce"
            time.sleep(waiting_time)

        if con_val == lim:
            break

if __name__=="__main__":

    lock=thread.allocate_lock()
    max_produce = 3
    thread.start_new_thread(producer,(lock, 1, max_produce))
    thread.start_new_thread(consumer,(lock, 2, 1, max_produce))

    # Required for commandline output
    while 1:
        pass

 

The above code creates a lock to be used by the consumer and producer to acquire the produce-line. Then we define the units to be produced. When the threads are started, the consumer and producer are also told the consume-time and produce-time as arguments (these values are implemented in the program using the time.sleep() function).

The consumer thread starts with acquiring the lock on the produce-line and then taking the product from it. If there is no produce yet, it prints an error message. Else, the produce is picked and the lock released. The consumer then consumes the produce and go backs to the start of the loop.

The producer thread starts by producing an item. Then it acquires the lock on the produce-line and adds the produce to it. Then it releases the lock and starts reproducing.

What I have not covered: The threads can also be created and defined using classes. I could not cover that in this post. A good resource of it can be from IBM and devshed.

Github repository for it : https://github.com/ayushgoel/PythonScripts/tree/master/learning_threading

Also, python (CPython actually) is known to be not very good at threading because of GIL (Global Interpreter Lock) on all the data. Google for more information. πŸ˜›

My little hack on Pidgin

Posted February 16, 2012 by TechMyWay
Categories: Internet

Tags: , , , , ,

I hope you have had the good luck of using one of the best IM-client available named pidgin. You can find a whole lot of posts around telling about why it’s good and all so I am skipping it.

Now, this post is not aimed at dragging you to use pidgin. It’s actually about one good thing I stumbled upon when using it.

Usually when I am chatting with people, I find myself using terms they sometimes don’t know. So, the next usual thing to be done is to ask them to go and google it. (duh!) Now, wouldn’t it be better to just give them a link directly.!

I was thinking of making a plugin myself for this which would keep an eye on what I write and replace it with google links as and when required. But it required time.!

Luckily, I found another plugin by default in Pidgin which does the job for me. I am using Pidgin 2.7.9

  • Go to Tools->Plugins
  • Find a plugin named Text Replacement 2.7.9
  • Enable it by clicking on the little check-box by it’s side
  • Now click on the Configure Plugin just below the whole list of plugins.
  • Fill: You type -> !google
  • Fill: You type -> http://www.google.com/search?q=
  • Un-checkΒ  (remove the tick) Only replace whole words
  • Check (tick it) exact case match
  • Click on Add

Now you have got a kind of Bot which would create links for you.. πŸ™‚

How to use it:

  • When chatting let your query be “techmyway”
  • Type in !googletechmyway
  • Press enter (and the link gets inserted) voila! πŸ™‚

OR (this is what happens in my case)

  • whenever you write “!google” it is automatically replaced with the link

Now here is the catch: the queries can only be single-worded. The space is not recognized in urls. You would have to use %20 instead of space character. Also, remember not to try to replace every space with %20, your whole chat can get messed up.!

Share the info if you like.

Adding to each node the next inorder successor node in a binary tree

Posted February 3, 2012 by TechMyWay
Categories: C

Tags: , , ,

Lately I came to a question which stated that Given a Binary tree where each node has an extra field (node * next), write a function that puts the inorder successor of that node in the next pointer.

This can be petty easily done using the general Inorder traversal algorithm of binary trees, but in the code shown below, as you can see, I am using a global variable (which I don’t think is a good practice). If anyone turns up with a method that doesn’t use a global variable, please share the link.

I have added the necessary comments to my code so that even novices don’t have a problem in understanding it.

(Since wordpress has a bad habit of removing the spaces I put in my code x-( , you can have a better view at this gist )

// Global var to contain the inorder predecessor
node * prev;

void add_inorder(node * nd)
{
// Base case
if (nd == NULL)
return;

// Recursive call for inorder processing
add_inorder(nd->left);

// The current node has a predecessor
if (prev != NULL)
{
// Set the next pointer
prev->next = nd;
prev = nd;
}

// This is the first node in the inorder processing
else
{
prev = nd;
}

// Recursive call for inorder processing
add_inorder(nd->right);
}

void mark_inorder(node * root)
{
/* assuming the structure to be:
typedef struct node{
int val;
struct node * next;
struct node * left;
struct node * right;
} */

// Initialising the global variable
prev = NULL;
// calling the function to add the values to pointers
add_inorder(root);
// Complete the next pointers by adding to the next
// pointer of last node in inorder processing, NULL
prev->next = NULL;
}

K distance nodes in a Binary tree

Posted February 3, 2012 by TechMyWay
Categories: Uncategorized

Tags: , , , , ,

For a Given node of a binary tree, print the K distance nodes.

For the solution, you can also refer to stackoverflow. This also tells that only one ancestor can be at K distance from a given node.

Source code: (written in C)

void K_dist_children(node * nd, int K)
{
// Base case
// The Kth child found
if(K==0)
{
printf("%d\n", nd->val);
return;
}

// K distance node from nd are at
// K-1 distance from children of current node
K_dist_children(nd->left, K-1);
K_dist_children(nd->right, K-1);
}

int K_dist_ancestor(node * cur,Β Β Β  //curent node
node * search, //node being searched
int K)
{
// If the node is found, return back the result
if (cur == search)
{
return K-1;
}

int n1, n2;

// recursively search for the node in the tree
n1 = K_dist_ancestor(cur->left, search, K);
n2 = K_dist_ancestor(cur->right, search, K);

// PS: n1 & n2 can't be non-(-1) at the same time

// if node found in any of the sub trees
if((n1 == -1) && (n2 == -1))
return -1;

// node found in right subtree
if((n1 == -1))
{
// the current node is at distance K
if(n2 == 0)
printf("%d", cur->val);

// return back the distance
return (n2-1);
}

// node found in left subtree
if((n2 == -1))
{
// the current node is at distance K
if(n1 == 0)
printf("%d", cur->val);

// return back the distance
return (n1-1);
}
}

void print_K_distance_nodes(node * root, node * search, int K)
{
// The structure of node is:
// struct node{
// int val;
// node * left;
// node * right;
// }

// Print the ancestor at distance K
K_dist_ancestor(root, search, K);

// Print the children at distance K
K_dist_children(search, K);
}

Python script to bring all files from subfolders to main folder

Posted January 3, 2012 by TechMyWay
Categories: Python, Windows

Tags: , , , , ,

A usual plight with me is bringing all photos I transfer from my phone to one folder. My phone transfer creates a subfolder for each date it has a pic for.

This was till I discovered the module shutil. (No, I knew about it for around _4 months, but I was too lazy to actually write the code πŸ˜› )

This code I have written is meant to be cross-platform. In case of any discrepancies, please do tell.

import shutil
import os

# copy all the files in the subfolders to main folder

# The current working directory
dest_dir = os.getcwd()
# The generator that walks over the folder tree
walker = os.walk(dest_dir)

# the first walk would be the same main directory
# which if processed, is
# redundant
# and raises shutil.Error
# as the file already exists

rem_dirs = walker.next()[1]

for data in walker:
for files in data[2]:
try:
shutil.move(data[0] + os.sep + files, dest_dir)
except shutil.Error:
# still to be on the safe side
continue

# clearing the directories
# from whom we have just removed the files
for dirs in rem_dirs:
shutil.rmtree(dest_dir + os.sep + dirs)


 

Since the code is all documented, I would skip the explanation here.

Please comment, share or like the post. (Good for my writing spirit πŸ™‚ )

Some tricks of Python

Posted December 31, 2011 by TechMyWay
Categories: Python

Tags: , , ,

Zen of Python

First of all, see the Zen of Python πŸ˜‰

>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

List Comprehensions

These are one of the most smart things to happen in python. They build up a list for you pretty simply and in ONE line.

>>> x
[]
>>> for i in range(20):
x.append(10 * i) ## append elements to list b

>>> print x ## use the list
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190]

Now this can be done (pretty easily) by:


>>> print [10 * i for i in range(20)]
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190]

A better example would be


>>> [i**2 for i in xrange(10) if i%2 == 0]
[0, 4, 16, 36, 64]
## this gives a list containing squares of all even numbers in range of [0, 10)
## means including 0 and not including 10

>>> [ord(i) for i in raw_input()]
1wed342k
[49, 119, 101, 100, 51, 52, 50, 107]

Now, a more Memory efficient solution to above exists with generators:


>>> for j in (i**2 for i in xrange(10) if i%2 == 0):
print j

0
4
16
36
64

Generator Expression

The generator expression do not calculate all the values at the same time (like it was happening in list comprehensions). It calculates values as and when required.
A generator expression is very similar to list comprehensions (just a change in brackets [] -> () )

In python 2.7

dict and set comprehensions

are also provided:


>>> {i: chr(i) for i in range(48, 58)}  ## a dict formed
{48: '0', 49: '1', 50: '2', 51: '3', 52: '4', 53: '5', 54: '6', 55: '7', 56: '8', 57: '9'}
>>> {chr(i) for i in range(48, 58)}     ## a set formed
set(['1', '0', '3', '2', '5', '4', '7', '6', '9', '8'])

P.S. the above code snippets have been pasted from IDLE python shell. If similar statements are used in scripts the results are not printed.

zip function:


>>> print zip.__doc__
zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]
Return a list of tuples, where each tuple contains the i-th element
 from each of the argument sequences. The returned list is truncated
 in length to the length of the shortest argument sequence.

The above function can be used to transpose a matrix.!


>>> a = [[1, 2], [4, 3], [5, 6]]
>>> zip(*a)
[(1, 4, 5), (2, 3, 6)]

The (*a) means unpack the list/tuple named a i.e. this operator is valid on both tuples and lists.
It can be used only in function call arguments.
This * is also called the

Splat Operator

πŸ˜€ .
Dictionaries respond differently and have got an extra operator (**)


>>> a = {'a': 1, 'b': 2, 'c': 3}
>>> def splat(*args):
print args

>>> splat(a)
({'a': 1, 'c': 3, 'b': 2},)
>>> splat(*a)
('a', 'c', 'b')
>>> splat(**a)
Traceback (most recent call last):
File "<pyshell#75>", line 1, in <module>
splat(**a)
TypeError: splat() got an unexpected keyword argument 'a'

>>> def splat(a, b, c):
print a, b, c

>>> splat(a)
Traceback (most recent call last):
File "<pyshell#79>", line 1, in <module>
splat(a)
TypeError: splat() takes exactly 3 arguments (1 given)

>>> splat(*a)
a c b
>>> splat(**a)
1 2 3

Ok, this is something I was mistaking from long.
When you have a list named say my_list and you need its index when looping it, you usually do


>>> my_list = [1, 4, 5, 2, 3, 6]
>>> for i in range(len(my_list)):
print i, my_list[i]

0 1
1 4
2 5
3 2
4 3
5 6

Now, this is something they say “unpythonic” (though i like it πŸ˜› ,Β  even if its dirty, at least it works πŸ˜‰ ).

Enumerate

But there is a better way to it:


>>> for index, val in enumerate(my_list):
print index, val

0 1
1 4
2 5
3 2
4 3
5 6

(Ok, now I also agree, it was “unpythonic” πŸ˜€ )

Reversing

Now, remember one thing, every slicable type (list and strings to be precise) can be simply reversed by


>>> a
[1, 4, 5, 2, 3, 6]
>>> a[::-1]
[6, 3, 2, 5, 4, 1]
>>> b = "this will be reversed"
>>> b[::-1]
'desrever eb lliw siht'

Though reversed(sequence) is better πŸ˜›


>>> import timeit
>>> a = timeit.Timer('a[::-1]', 'a = [2, 4, 1, 6]')
>>> a.timeit()
0.7627712499545058
>>> a = timeit.Timer('reversed(a)', 'a = [2, 4, 1, 6]')
>>> a.timeit()
0.5815445977713054

itertools module

And this is for some testing purposes (my favorite module)
These ones are most used by me to generate tests. You can see other functions in the modules.


>>> import itertools as it
>>> print list(it.combinations('asd', 2))         ## all the combinations
[('a', 's'), ('a', 'd'), ('s', 'd')]
>>> print list(it.combinations_with_replacement('asd', 2)) ## combinations + repeated values
[('a', 'a'), ('a', 's'), ('a', 'd'), ('s', 's'), ('s', 'd'), ('d', 'd')]
>>> print list(it.permutations('asd', 2))         ## permutations
[('a', 's'), ('a', 'd'), ('s', 'a'), ('s', 'd'), ('d', 'a'), ('d', 's')]
>>> print list(it.product('asd', 'def'))          ## product of sequences
[('a', 'd'), ('a', 'e'), ('a', 'f'), ('s', 'd'), ('s', 'e'), ('s', 'f'), ('d', 'd'), ('d', 'e'), ('d', 'f')]

P.S. The above functions actually return an iterator (the one with next() function), but tho show the use, I have put out all the values in the form of a list.

 

This was one of my best finds on internet:


>>> import antigravity

Just give it a try πŸ˜‰

 

And at last, something to laugh.. πŸ˜€


>>> from __future__ import braces
SyntaxError: not a chance (<pyshell#106>, line 1)

 

Do remember to comment, like or share the post. πŸ™‚

N – QUEEN Backtracking problem solved

Posted November 9, 2011 by TechMyWay
Categories: C++

Tags: , , ,

This all started when I started doubting my coding and downloaded the code from geeksforgeeks for this N-Queen problem. I told one of my friends that I am gonna read it and understand. Then he told me that the problem is quite easy to code, just see the wiki (actually he and me were interested more in the animation on that page πŸ˜‰

Anyhow the wiki pages : Eight Queen , Backtracking were not of much use as they were not giving good pseudo code. But this here, see it and try to think, what all can I need for the N – Queen problem..

Enough of waiting now, here is the C++ code for the problem I wrote.

#include<iostream>
using namespace std;

/** this is the size of chess board */
#define N 8

/** Given a completed board, this prints it to the stdout */
void print_solution(int state[N][N])
{
int i,j;
for(i=0; i<N; ++i)
{
for(j=0; j<N; ++j)
cout<<state[i][j]<<" ";
cout<<endl;
}
cout<<endl;
}

/** return true if placing a queen on [row][col] is acceptable
else return false */
bool accept(int state[N][N], int row, int col)
{
int i,j;

/* check the column */
for (i=0; i<N; ++i)
{
if (state[row][i])
return false;
}

/* check the row */
for (i=0; i<N; ++i)
{
if (state[i][col])
return false;
}

/* check the upper left diagnol */
for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
{
if (state[i][j])
return false;
}

/* check the lower left diagnol */
for (i = row, j = col; i < N && j >= 0; ++i, --j)
{
if (state[i][j])
return false;
}

/* check the upper right diagnol */
for (i = row, j = col; i >= 0 && j < N; i--, ++j)
{
if (state[i][j])
return false;
}

/* check the lower right diagnol */
for (i = row, j = col; i < N && j < N; ++i, ++j)
{
if (state[i][j])
return false;
}

/* return true if all tests passed */
return true;
}

void solve_state(int state[N][N], int row)
{
int i;

/* if all queens have been placed at non conflicting positions */
if (row == N)
{
print_solution(state);
return;
}

/* Place queens on all positions in a given row and
check if the state is acceptable
Continue the process till all possibilities found */
for(i=0; i<N; ++i)
{
if(accept(state, row, i))
{
state[row][i] = 1;
solve_state(state, row+1);
}
state[row][i] = 0;
}
}

int main()
{
/* initialise the board */
int state[N][N] = {0};

solve_state (state, 0);

return 0;
}

This code can be easily converted to C, just make amendments to bool values. Rest of the program deals with the board matrix, so C won’t have problems.

Result: Backtracking is pretty easy if you get the idea.


Create your own website, free on WordPress.com.Create your own website.
Start free