Tuesday, September 03, 2013

Mutithreading and Multiprocessing in Python

Recently someone asked me about multithreading in Python. The last time i wrote any multithreading code in python was at least 5 years ago, that too using the thread module for some very basic stuff. As i was brushing up on this topic, I came across some very useful articles. I am using this blog post to link to these articles for my future reference.

Multithreading in CPython is really very limited due to the existence of Global Interpreter Lock (GIL), but multiprocessing seems more promising.

Due to existence of GIL, multithreading in Python is useless for tasks that are CPU bound. For example, mathematical computations. Multithreading is best utilized in programs that are IO intensive. The IO operation could be on disk (listing files and directories, or reading/writing files, etc) or on network (communicating with websites). The important modules for this are - thread and threading. Thread is considered low-level API but has limited capabilities, while threading is considered high-level and provides more functions. This tutorial provides a quick overview of both these module via simple examples.

An important decision that you would have to make when writing multithreaded programs is whether the child threads should merge back with the parent/main thread. This will be required if you ever have to reconcile the output from all child threads to determine the next course of action for the parent thread. This decision is made by calling the join() function available with every thread object. I found the textual representation in this stack exchange answer to be very intuitive and useful to understand join() for different kind of threads.

To overcome the limitations of using multithreading in Python, the multiprocessing module side-steps the GIL by using subprocesses instead of threads. This allows the programmers to fully leverage the benefits of multi core or multiple processor architecture on a machine. This article does a good job of explaining OS forking and multiprocessor modules in python.

Finally, most programmers are interested in multithreading and multiprocessing mainly to speed up the execution of their programs. In Python, it is important for the programmer to understand the difference between these to concepts, else they could end up slowing the program execution instead of speeding it up it. I found these this article to be very helpful in showing the difference between the two. It generates benchmarks using simple examples. Additionally, the following blog post explains how python sees and uses cores on a machine.

In summary, if your Python program does a lot of IO, use multithreading, but if you are looking to speed up the CPU bound work of your program, use multiprocessing.

Saturday, August 10, 2013

Converting MP4 videos to audio CD (wav) on Ubuntu

My little one loves his nursery rhymes. At home he gets to listen to them on the ipad or on the phone, but this unnecessarily drains the battery out. Plus when we travel by car, i would rather use the car stereo than play it loudly on my phone. So i decided to convert the MP4 videos to an audio CD (unfortunately my care stereo does not support mp3 :-( ).

Here are the steps i followed:

1. After doing a bit of research MPlayer seemed to be the best option suited for my needs. The latest version is 1.1.1. Since my Ubuntu release is quite old (I use 10.10), apt-get returned no matches for mplayer. So i downloaded the source from the site and installed it. This process is rather simple:
  a. cd to the directory where you extracted the mplayer tar
  b. ./configure (add the --enable-gui switch to the command if you wish to use the player in GUI mode)
  c. make (this took forever)
  d. sudo make install

Note: during compilation, i discovered that the yasm library was missing. I had to install yasm 1.2.0 (the latest version) to resolve this.

2. The conversion process itself is quite simple. This simple invocation does the trick.
    >> mplayer -ao pcm:file=inputfile.wav outputfile.mp4

3.  I had over 28 files to convert, so doing this one by one was not an option. A bash for loop took care of this:
>> for i in `ls`
  > do  mplayer -ao pcm:file=${i//.mp4/.wav} $i
  > done
>>

line 1: we loop over the output of the `ls` command. Note the use of backticks around the ls command, this tells the shell to execute the command and present its output to the for function.

line 2: This is the mplayer function to do the conversion with a bit of bash magic to rename the converted file. Say the original file is called foo.mp4, now i want the converted file to be called foo.wav. To make this happen, I use substring replacement. The syntax is as follows: 
 >> ${string//substring/replacement}
In my case, I am replacing the extension .mp4 with .wav

line 3: close the for loop

4. The conversion process is very CPU intensive (as per top, cpu was 75%). Unfortunately, my laptop is quite old and is single CPU. This meant i couldn't do anything GUI based while this was going on. Thankfully the conversion is rather quick, only a few minutes per video.

In some cases, for causes unknown, the conversion process would get stuck despite having successfully converted the video. I simply killed that iteration and my loop continued with the next file.

With the major work done, now i just have to burn a CD and enjoy the music!!

Sunday, May 05, 2013

Change keyboard layout in Ubuntu 12.04 from command prompt

Instead of installing Ubuntu 12.04 from scratch, i decided to download a prepacked virtual box template from http://virtualboxes.org/images. Unfortunately, the keyboard configuration did not match my Lenovo T430, causing all sorts of havoc. Plus, i did not have x-windows installed so the mouse was useless as well.

To change the keyboard configuration from the command prompt, use the following syntax:
sudo dpkg-reconfigure keyboard-configuration 
  This will let you configure your keyboard settings, and also persist the changes after a reboot.

Wednesday, December 24, 2008

Video Contest: I'm Linux

The Linux Foundation, a Non-Profit Organization, is sponsoring a Video Competition to create a commercial for Linux on the lines of "I'm a Mac'" and "I'm a PC" as done by Apple and Microsoft respectively. Linux is owned by its community and its only fitting that the community should participate in its promotion on Television, hence this Video contest. The winner gets no cash but a an all expense trip (airfare and hotel for 3 days) to Tokyo, Japan to participate in the Linux Foundation Japan Linux Symposium in October 2009.

There are some basic guidelines:
- Keep the video under a minute
- Comply with their ToS
- Watch your language and keep it clean
- Make it original and interesting

For more details check out their website and more importantly, get busy.

PEP 8

Ran into PEP 8 (Python Style Guide) written by Guido. It was nice to realize that i follow majority of his recommendations. At the same time i learned some new things which i had never thought of.

Good read!

Thursday, November 27, 2008

Snip Snip Time

In the current tough economic conditions (I am kind of getting sick and tired of hearing this phrase) downsizing is preeminent. The stories of how someone had to change city, state or country to find another job have become commonplace.

During the last bubble burst a lot of first-time CEOs and Managers were entrusted with the task of guiding the companies through similar times and not all of them were successful at it. In fact in almost all cases the complete downsizing process was deemed ruthless. This was a problem not just for the first time leaders but even for seasoned campaigners.

This time good advice is more forthcoming. People who were burnt or involved in those times are giving out advice freely. One such interesting post i came across was by Guy Kawasaki. I recommend reading it even if you are not at the downsizing stage.

Wednesday, November 26, 2008

iPhone Firmware 2.2

Its strange but since I have installed the 2.2 firmware the cell phone signal strength has improved slightly. Prior to this update the max i ever got was 2 bars but now its almost always 3 bars.

This is strange as i always thought that the signal strength received was a function of power transmitted by the cell phone towers and antenna design. The iPhone antenna surely hasn't changed and i haven't read/heard of ATT putting up new towers around my apartment so its got to be the firmware update.

The developers at Apple must have really messed up the 'check signal strength and then make calls' part of code or maybe they just add some artificial gain to improve the signal strength representation with each release. Either way currently i will accept anything that will improve my iPhone calling experience.

I also noticed that now apps are updated in place unlike earlier where the new version was downloaded in a different location and then moved to the current. Subtle but slick.

-------------------

Oh on a side note, still no sign of my replacement USB power adapter.
Hurray to Apple support.

Saturday, November 15, 2008

How to send a courier Apple style

Trips to the Apple Store - 1
Calls to Apple Support - 2
Alleged couriers sent by Apple - 4
Days since first attempt - 35
Minutes spend on hold - 50
Amount of frustration - Infinite

...... still no sign of my replacement for the iPhone 3G power adapter.

Thursday, October 23, 2008

iPhone App: Mocha VNC

Mocha VNC Lite is (as the name suggests) a VNC viewer for the iPhone. I installed the Lite version to try out the experience and i have to say its really cool. The performance is awesome and the clarity is just astonishing. Maybe its just me but i never expected this app to behave this well. You are required to install either TightVNC or RealVNC server on Windows based machine (I used TightVNC on my Win XP laptop) and voila you are set. They have a custom vnc server for Mac.

The need for such an application is still questionable but for now i am just having fun with it.

Note: The Lite version does not support Ctr-Alt-Del combination so i cannot lock/unlock my computer which is a smart move by the developers mainly because without this ability the application is unsafe to use say with your work computer.

TiPB claims that the Jaadu VNC app is much better than Mocha so check it out. Unfortunately it does not have a Lite version and it costs around 24 bucks, quite steep.

Friday, October 17, 2008

Snaps from India

Beautiful snaps from India. If you plan to visit India make sure you cover all these places.

Thursday, October 09, 2008

My first paid iPhone Application : Subway Shuffle

I recently moved over to the Dark Side. I ditched my old trusted Palm Treo 680 for a new and shiny iPhone 3G about 2 months ago. Truth be told it was just too hard to resist the temptation. I totally love the device and don't hesitate to express my obsession openly much to the frustration of my friends and colleagues.

Listing the things i like about it would be impractical (since it will be a long list) so instead let me list the things i don't like about it:

1. The battery life sucks although its slightly better since the 2.1 update.
2. If i install a lot of applications without syncing it with iTunes the iPhone starts to hang and the UI gets really sluggish. This is quite irritating since i am on the road a lot and sometimes its weeks before i get my hands on my personal laptop.
3. The Exchange support is great but there are still some features like flagging emails, directly dialing numbers listed in calender notes, etc which i miss from the Goods Messaging service on my Palm Treo.
4. The App Store policies are too stringent. There are tons of cool applications which are not allowed by Apple for strange reasons but can be installed if you jail break the iPhone (and i don't wish to go that route).
5. Can't download new podcasts directly to the iPhone. (Apple please bring back Podcaster)
6. Cannot use my iPhone as a modem.

I guess you gotto lose some to gain some. I hope Apple addresses these issue soon.

I have so far downloaded and deleted tons of applications most of which were free. The one application i really enjoyed and eventually ended up buying is the Subway Shuffle by Aubrey's Puzzles. Initially i played the Lite version which allows you to solve 6 puzzles of varing complexity but the game is so addictive that i was compelled to spend the $2.99 for the paid version.

Who took my domain name?

My attempt to register a domain based on my name (afulay) went for a toss when i discovered that it had already been taken. The site afulay.com is written in Arabic and had references to Morocco. Onto another combination now.

Update:
Bummer fulay.com is taken too. :(

Monday, October 06, 2008

The Trick to Problem Solving

When a problem presents a disjunction, you need to list all its possibilities (define Solution Space) and reason from each of them.

- quoted from the book How would you move Mt Fuji.

Saturday, September 27, 2008

Christian Invasion in India

For years the world has blamed the Islamic groups for spreading terrorism and forcing atrocities on innocent people. No doubt this is true. We all know about the Al-Qaeda, Saddam's Regime, the ISI and many more but this blog post is not about them.

For once i want to focus on the Christian Missionaries and other groups which cloaked under their message of spreading peace and education is really forcibly converting the poor and innocent villagers of India. This video i came across comes from a Scandinavian woman who investigated the immoral tactics of the various Christian Missionaries in Western India.

The alarming aspect of this video is that these conversions are taking place in one of the most economically and industrially advanced regions of the country. Such conversions are rampant in the eastern part of India, the collection of 7 states (also known as the 7 Sisters) which were very evident during my short stint in the eastern parts of the country.

The pattern is quite simple. The Missionaries would start by setting up a school in the one of the poorest regions of the state. They provide the children with free food and medical attention which attracts other people to the church. Soon they start luring more people by unfairly comparing Hindu practices and Gods with the Christian religion and if this does not work by promising them money or free facilities. The people are eventually brain washed and forced to denounce their religion and country.

Despite the amount of money and efforts invested by the Indian government in the Eastern regions the people are still largely under the influence of the Christian Missionaries. The people their refuse to call themselves Indians and detest other Indians. This was quite evident during my brief stay in the region. More than once when we stopped on streets to ask for directions the local people turned away totally ignoring us. Some times when the person did respond we were told to either speak in English or their local language and not Hindi (Our National language). This is extremely sad and disappointing as this happens to be one of the more beautiful regions of the country with a rich culture and heritage.

All these incidents make me wonder if this is a passive form of terrorism. Terrorism to me is a way of forcing an ideological change, they may be enforced with either use of violence as most Islamic militant groups do or could be a covert operation by providing false hopes and biased comparisons of cultures as done by Christian Missionaries. I guess this is for every individual to decide for himself.

Monday, August 18, 2008

How to connect your ipod nano to your laptop

First insert the USB connector in to the laptop and then connect the ipod jack to your ipod nano. When ever i reverse this process my ipod nano hangs and has to be reset. To reset press the center and menu key together for a few seconds.

Monday, August 04, 2008

Python Exceptions >>> raise

A neat trick i found in the python tutorial:

If you need to determine whether an exception was raised but don't intend to handle it, a simpler form of the raise statement allows you to re-raise the exception:

>>> try:
... raise NameError, 'HiThere'
... except NameError:
... print 'An exception flew by!'
... raise
...
An exception flew by!
Traceback (most recent call last):
File "", line 2, in ?
NameError: HiThere

For more read the Errors and Exceptions section

Saturday, May 03, 2008

Windows Services Management via VBScript

If you have ever used any Unix/Linux based systems you know that windows does not even come close to providing as reliable service management as its counterparts. I have been burnt  by the stuck services issue so many times that it was natural for me to look for alternate mechanisms.

VB script is a scripting language developed by Microsoft and is a limited variation of Visual Basic programming language. To me its a much better and more powerful alternative to Batch Scripting.

Being new to VBScript i had to spend some time initially to grasp the basics but when i did it was quite easy. Here is a simple VBscript to manage windows services.  You just need to modify the number of services to manage and their names and the script lets you bulk start/stop, check status and individually control each service. Thankfully since i have used this script i have not experienced the stuck services issue and i am strongly inclined to believe that most services start/stop issues may be caused by bugs in the GUI based Windows Services Manager (this is just speculation and i have no conclusive evidence to prove it).

Execute the following from your command prompt to run this script:
cscript [path to script]

The script:

============================================================

dim input
dim strComputer
dim svrList


rem Main Body

input = 0
do
    input = getInput()

    processInput(input)
loop until input=5

rem Supporting Functions


function processInput(input)

    if input = "5" then
        s_quit()

    else
        strComputer = "."
        
        ' Modify this array size to add or remove services. The length of this array should be    
        ' exactly same as the number of services.
        ' Note: If you want to initialize this array to hold 4 services, set its size to 3. The array
        ' like most has a zero based index i.e. 0 to 3.
        dim myservices(3)

        ' specify the actual service names here
        myservices(0)="<service-mgmt1>"
        myservices(1)="<service-mgmt2>"
        myservices(2)="<service-mgmt3>"
        myservices(3)="<service-mgmt4>"

        'get service object
        Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
        
        'debug statement
        'wscript.echo cstr(ubound(myservices))
        
        k = 0
        svrList = ""
        for each service in myservices
            svrList = svrList & "Name='" & service & "'"
            
            ' do not end the services string with an 'or' this causes the query to fail
            if k < ubound(myservices) then
                svrList = svrList & " or "
            end if
            
            k = k+1
        next
        
        'debug statement
        'wscript.echo svrList
        
        Set colServiceList = objWMIService.ExecQuery("Select * from Win32_Service where " & svrList)

        ' debug statement
        'for each s in colServiceList
        '    WScript.Echo s.name
        'next
        
        select case input

            case "1"
                staggard_start(colServiceList)
            case "2"
                startSrv(colServiceList)
            case "3"
                stopSrv(colServiceList)
            case "4"
                statusSrv(colServiceList)
            case else
                Wscript.echo "Invalid Input!"
                's_quit()
                
        end select

    end if
end function


rem Quit Script
function s_quit()
    WScript.Echo "bye!"
    WScript.Quit
end function


rem Fetch script option
function getInput()
    WScript.echo
    WScript.echo "Select one of the options below:"
    WScript.echo "1 - Staggard Start"
    WScript.echo "2 - Start services"
    WScript.echo "3 - Stop service"
    WScript.echo "4 - Service status"
    WScript.echo "5 - Exit"
    getInput = textInput("Input = > ")
end function


rem Fetch user input
function textInput(prompt)
    WScript.StdOut.Write prompt
    textInput = WScript.StdIn.ReadLine
    rem WScript.StdOut.WriteLine username
end function


rem Staggard Start services
function staggard_start(serviceObjs)

    WScript.Echo "staggard start :: 1 - start; 2 - stop; 3 - ignore; q - quit"
    flag = "0"
    
    do
        For each serviceObj in serviceObjs

            flag = textInput(serviceObj.name & " -> ")

            select case flag

                case "1"
                    errReturn = serviceObj.StartService()
                    'WScript.Echo errReturn
                    WScript.Sleep 15000

                    if errReturn=0 then
                        WScript.Echo " ...started service"
                    else
                        WScript.Echo " ...failed to start service/running already"
                    end if

                case "2"
                    errReturn = serviceObj.StopService()
                    'WScript.Echo errReturn
                    WScript.Sleep 15000

                    if errReturn=0 then
                        WScript.Echo " ...stopped service"
                    else
                        WScript.Echo " ...failed to stop/not-running service"
                    end if

                case "q"
                    's_quit()
                    exit do

                case else
                   WScript.Echo " ...ignored"

            end select
        Next        
    loop
    
end function


rem Start services
function startSrv(serviceObjs)

dim tempObj
WScript.Echo "starting services ..."
    For each serviceObj in serviceObjs
    
        errReturn = serviceObj.StartService()
        'WScript.Echo errReturn
        WScript.Sleep 15000

        if errReturn=0 then
            WScript.Echo "started service - " & serviceObj.name
        else
            WScript.Echo "failed to start/running already service - " & serviceObj.name
        end if
            
    Next
        
end function


rem Stop services
function stopSrv(serviceObjs)

WScript.Echo "stopping services ..."
    For each serviceObj in serviceObjs
        errReturn = serviceObj.StopService()
        'WScript.Echo errReturn
        WScript.Sleep 15000

        if errReturn=0 then
            WScript.Echo "stopped service - " & serviceObj.name
        else
            WScript.Echo "failed to stop/not-running service - " & serviceObj.name
        end if

    next    
    
end function


rem Service status
function statusSrv(serviceObjs)

WScript.Echo "Service Status"
    For each serviceObj in serviceObjs
        WScript.Echo "Name: " & serviceObj.name
        WScript.Echo "State:" & serviceObj.State
    next
    
end function

===========================================================

Hope this script helps you alleviate some of your windows services woes.

Disclaimer: I am not a VBScript developer. If you find any bad coding practices please do let me know and i will be more than happy to fix my script. Also the exception handling could be done in a much better fashion.