Finding elements in a STL multimap

Posted by tux4life on June 24, 2009

Working more and more with STL is helping me learn some subtle nuances of STL.  One such nuance that I learnt today was how to search for an element in a multimap.

Trust me, this slightly more complicated than just using the find method.  Yes, the find method returns an iterator to the matching element.  But remember, this is a multimap.  So, what if there is more than one element with the same key.

We would ideally want to retrieve all the elements with the search key.  But what “find” method does not give is an iterator to the end position to the last instance of the matching key.  So, if you loop through till end of the map, you will go through the matched elements and also the elements that follow the matched elements till the last element in the map.

Fortunately, STL provides a method “equals_range” to get ONLY the items that match the key.  Usage of this function is illustrated below.

Code

#include <iostream>
#include <map>

typedef std::multimap<int, std::string> IntToStringMap;
typedef std::pair<int, std::string> IntStrPair;

int main()
{
IntToStringMap theMap;

//Add elements into the map by constructing pairs
theMap.insert( IntStrPair(1, “ONE”) );
theMap.insert( IntStrPair(3, “THREE”) );
theMap.insert( IntStrPair(2, “TWO”) );
theMap.insert( IntStrPair(2, “ANOTHER TWO”) );
theMap.insert( IntStrPair(2, “YET ANOTHER TWO!”) );

//Use the equal_range function to get a pair of iterators
//pair.first has the iterator pointing to the first key match
//pair.second has the iterator pointing to the last element with matching key
std::pair<IntToStringMap::iterator, IntToStringMap::iterator> itrPair =
theMap.equal_range(2);

IntToStringMap::const_iterator itr = itrPair.first;
if ( itr == theMap.end() ) {
//Search key not found
std::cout<<”Element Not Found”<<std::endl;
}
else {
//Search key found, perhaps more than once
//Loop through till the last match
for ( ; itr != itrPair.second; ++itr)
std::cout << itr->first << “–>” << itr->second << std::endl;
}

return 0;
}

Output

2–>TWO
2–>ANOTHER TWO
2–>YET ANOTHER TWO!

As explained in the comments, the equal_range function returns a pair of iterators.  The first pointing to the first instance of the match and the second pointing to the last instance of the match.  We can use these iterators to loop through our matches.

If there are better solutions for this, please let me know.

Posted in Programming | Tagged: , , , | Leave a Comment »

Sorting using STL Algorithms

Posted by tux4life on June 23, 2009

After a long hibernation, I’m back with a post on how to use STL Algorithms to sort (virtually anything).

The following code snippet shows how to sort a vector of integers in ascending and descending order.  The same idea can be used to sort a vector, set etc.

Code

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

typedef std::vector<int> IntVector;
void print(const IntVector &);

int main()
{
IntVector intVector;
intVector.push_back(10);
intVector.push_back(13);
intVector.push_back(4);
intVector.push_back(11);
intVector.push_back(2);

print(intVector);

//Sort in ascending order
sort(intVector.begin(), intVector.end());
print(intVector);

//Sort in descending order
sort(intVector.begin(), intVector.end(), std::greater<int>());
print(intVector);
}

void print(const IntVector &vec)
{
IntVector::const_iterator itr = vec.begin();
for( ; itr != vec.end(); ++itr )
std::cout << *itr << ” “;

std::cout << std::endl;
}

Output

Original Vector: 10 13 4 11 2
Sorted Ascending:  2 4 10 11 13
Sorted Descending: 13 11 10 4 2

After inserting few elements into the vector, we can use the “sort” algorithm provided by STL to sort the vector.  The first two arguments are iterations to the starting position and ending position of the vector.

We can also specify the comparison function that is to be used for comparison while sorting.  By default the std::less function object is used.  So the first sort call sorts the vector in ascending order.

To the second sort call, the std::greater function object is used.  So, the vector is sorted in descending order.

There are various function objects available in STL and they can be used as we need them.  You can find a comprehensive list of function objects here.

PS: WordPress is not letting me format the code snippet.  I will find a workaround soon.

Posted in Programming | Tagged: , , , | Leave a Comment »

Born Brave

Posted by tux4life on March 18, 2009

This is one of the most visually descriptive and at the same time factually true pictures that I stumbled upon.. Guess almost everyone would agree ;)

Born Brave

Born Brave

Posted in Uncategorized | Leave a Comment »

How To Sopcast on Ubuntu

Posted by tux4life on March 18, 2009

Setting up Sopcast in linux can be  bit of a pain.  But recently, I stmbled across a very nice project called sopcast-player hosted in Google Code.  This project offers a GUI based windowed player similar to the Windows version of Sopcast.

The authors are also kind enough to compile the project and give installable packages for various distributions.

Enough said, this is how you install Sopcast on Ubuntu.

Download the package sp-auth_3.0  from here

This package has the script that acts as the streaming server for the video.

Download the package sopcast-player from here

This package has the GUI for the player.

Install both the packages and you are all set.

Sopcast

Sopcast

PS: The authors also provide packages for other architectures and distributions.  You can find it here.

Posted in Ubuntu HowTo's | 1 Comment »

Download Albums From Picasa Web

Posted by tux4life on February 8, 2009

Recently, one of my friends shared a picasa web album to me.  The photos were good and I wanted to download all the photos in the album to my hard drive.

There is an option in the picasa web interface to download a photo.  But it allows you to download only one photo at a time and so downloading the entire album can be a real pain.

But there is a much easier way of doing this.  You will need Firefox and an addon called DownThemAll.

Here is how to do it.

Install the firefox addon DownThemAll from here.

Go the picasa web albu that you want to download and click on the “RSS” link.  (You will find this link on the right hand side.)

From the page that comes up, right click and select DownThemAll.

Select the “Images” checkbox, choose a download location for the photos and click “Start!”

DownThemAll !!

DownThemAll takes care of the rest.

For all those tech geeks, you also use the Google APIs to achieve the samething.  I am working on developing a perl script for the same.

I am also working on developing a script to download Youtube favourites as MP3 files.  Will post about those once I complete them.

Posted in Ubuntu HowTo's, Uncategorized | 2 Comments »

Windows 7 Beta- First Impressions

Posted by tux4life on January 25, 2009

I have always been a curious observer of Microsoft technology developments, be it Windows or Office or Visual Studio.  Not that I am a big fan of Microsoft but just that I want to have a keen eye on what the largest software maker in the world has to offer.

The only product that really impressed me was Office 2007.  Visual Studio has also evolved a lot and it has a lot of nice features.  But I have always been cribbing a lot about Windows, especially Windows Vista for being very very sluggish.

So I was keeping a close eye on the developments with Windows 7.  On reading about the release of the first public beta of Windows 7, I was eager to give it a test.

I did  a fresh install (as opposed to running it under VM) since I wanted to see how Windows 7’s performance compared with XP / Vista.

Here are some of my observations .

Installation and Booting

Installing Windows 7 was seamless.  No issues with partitioning as the partitioning tool did a fair job.  I was able to create  a new partition without too much trouble.  The installation itself took about 30 to 35 minutes, a big improvement over Vista.  Also Windows 7 booted in considerably less time compared to Vista.

But however, if you need to upgrade an existing Windows Vista installation to Windows 7, you need Vista SP1 to be installed previously.

User Interface

On the user interface front, Windows 7 is more or less Vista’ish.  There are minor changes here and there but over all no big complaints.  The interface has become more zippy. E.g. Opening Windows explorer in Vista would take for ever but that has improved a lot and the windows come up very fast.  Again another improvement over Vista.

Task Bar

The task bar has been completely re-designed.  You see icons for each type of application that is open and when mouse is hovered over them, a small visual preview of the windows that are open for that application comes up.  Pausing the mouse over the preview brings up the actual window in front for a preview.  Clicking the preview takes you to that window.

Right clicking an icon the task bar pops up a list of recently opened documents using that application.

You can catch a glimpse of this here.

Overall, the new task bar is kind of ok but there are certain nagging issues.  E.g. If I have Internet Explorer open, clicking on the task bare IE icon wont open up a new window.  To do so, I need to go to an already existing IE window and do Ctrl + N or Fil -> New Window.  This is the case with all the applications.

Also, needless to say that the inspiration of the new task bar came from Mac.

Will Microsoft ever have OWN Innovative Ideas ?? All they do is borrow ( or steal ) ideas, make some minor changes and the end product turns out to be an actual mess.

Internet Explorer

Windows 7 comes with IE 8 Beta 2 bundled.  I have to say, IE8 Beta 2 is a very big improvement over what was considered a lackluster IE7.  To start with, IE8 starts up very fast, almost immediately after you launch the application.  Also the pages load much much faster.   To go with this, there are some new features added to IE8 like Web Slices, Private Mode etc. Some of the are new and some of them borrowed from other browsers.

But in my perspective, IE8 is a very big improvement over previous versions.

Drivers & Compatibility

Windows 7 by default installed all the drivers that are required.  My laptop was usable with these drivers but I was missing certain features such as scrolling with touch pad, monitor refresh rate was kind of low.

Normally, installing drivers from the vendors would fix these minor issues.  But being a beta, vendors have not developed drivers for Windows 7 yet and the existing Vista drivers fail to work. (E.g Synaptics touch pad driver failed to install on the first attemt but some how it installed the second time)

Installing Cisco VPN client corrupted the system and Windows 7 refused to boot ever since.  (Not even in safe mode without networking)  So, there are certainly some issues on the driver front but I guess these issues will be ironed out in the final release.

Search & Indexing

Microsoft claims that the search box on the start menu performs better.  I did notice a slight improvement in performance.  But nothing big or innovative to write home about.   Again, this search feature was stolen from Mac ( remember Spotlight in Mac ).

Conclusion

Overall, Windows 7 is a real improvement over Vista.  OS has become very responsive and zippy, boots fast.  There are still some issues that needs some work and I hope that Microsoft is already working on them.

I am looking forward for the final release of Windows 7 and I hope that the performance improvement is not lost in the final gold build.

And a final note, Microsoft – Please have your own ideas.  New innovative ideas makes the difference.

Posted in Reviews | Tagged: , | 1 Comment »

Who’s The Culprit ?

Posted by tux4life on January 15, 2009

By this time, most of us would know about the scam involving Satyam Computers.

Former CEO and founder of Satyam, Mr. Ramalinga Raju confessed on January 7th that he had fudged the accounts of the company and inflated earnings / profits / cash on hand etc.

There are a lot of facts that does not go along with Mr. Raju’s confession.

In his confession he says “He pulled of the entire scam himself and the rest of management including the board of directors were not aware if”.

This is a dumb statement and even a common man can easily figure out that such a thing would not be possible at all.

To briefly quote what might have happened, Mr. Raju started making good profits out of Satyam.  Being a entrepreneur, he had other business interests and needed capital to support them (Maytas Infra and Maytas Properties).  More over, the greed for money had set in Mr. Raju and this might have made him lift money out of the company and invest on benami accounts as cash and as fixed assets (such as land).  Per sources from IBN, Mr. Raju’s family owns 6500 acres of land (mysteriously bought through Maytas Infra) in Andhra Pradesh.

He was true when he said, “I was riding on the back of a tiger” but the only difference is he was the one who started the ride thinking that he can fool the entire nation.

But as it turned out, his attempts to cover up the money that he possibly squandered out of the company failed.  The most notable one being the attempt to acquire Satyam’s sister concern Maytas owned by his very own decedents.  This way he tried to make the fictitious money into fixed assets.  Looks like this is straight out of a hollywood blockbuster !!

Why would an IT company want to acquire a construction company ? Precisely ! This was the question asked by many of Satyam’s investors and the deal failed and so did Mr. Raju’s attempt to cover up the fraud.

As a result of the failure to acquire Maytas (can be interpreted as failure to cover up the scam), four independent board of directors quit the company in a span of 3 days (between Dec 26th and 29th 2008).

Enough evidence to prove that the scam involved more than just Mr. Raju.  If you do not think so, here is more.

Mr. Raju had nearly 23% stake in the company but he had sold most of the shares and had only about 8% by September 2008.  Other top officials in Satyam also sold most of their shares.  Most notable ones being Mr. Ram Mynampati (interim CEO) sold 7 lakh shares and 2.5 lakh American Depository Recepits, Mr. Srinivas Vadalamani (former CFO) about 1 lakh shares. (Source IBN).

Why would all the top brass management people sell stake in the company within a short span of time?  Again enough proof that the entire top management was involved in the scam.

Not convinced still or you think thats the end of it ? Hold on.. There is more to it..

How did Satyam’s balance sheet escape the audit.  Well.. Mr. Raju might have made sure that both the internal auditors and the external auditors (PriceWaterHouseCoopers) were “taken care of” to give a clean sheet for the company.  The involvement of Satyam’s auditors and the external auditors (who never verified if the money reflected in the balance sheets was actually real) in the scam is blatantly apparent here.

Mr. Raju might have also needed help from banks to show the FD’s that never existed as real ones. Details of this have not come out. Perhaps the govt would make sure that it does not come out so that its (Bank and Govt) skin is saved.

So, without doubt, as rightly termed by the media, this is India’s Biggest Corporate Scam involving not only Mr. Raju but also the top management, internal and external auditors and possibly some banks. :|

Lets all hope that Satyam is a lesson for all the Indian Corporates and that such a thing does not happen in the future.

Posted in Business | Tagged: , | 6 Comments »

The Darker Side

Posted by tux4life on January 14, 2009

The movie Slumdog Millionaire has been in the news recently for having won multiple Golden Globe awards.

I was happy to see some Indian faces in (behind) the movie have performed really well.  Particularly, the music of A.R. was awesome to say the least and was appropriately awarded with a golden globe.

I myself saw the movie and found it to be really compelling.  But I wish whatever I saw was unreal and fictitious.

Unfortunately, this is not the case as the movie undermined the darker side of Mumbai (I would say poorer India as a whole). Some of them include,

Police torturing suspects during inquires
Poor education system
Terrible sanitary conditions in the slums
Communal riots between Hindus and Muslims
Children living in waste dumps
Child begging
Forcible maiming of children
Prostitution
Child trafficking
Fleecing foreign tourists
Petty theft just to make a living
Poorly Managed Call Centers
Underworld

Its a bitter truth that most of these things are in fact real.

The movie has done its part in successfully undermining the disparity between the rich and the poor in India.

But would it make the politicians, government or the people of India react and take some efforts to correct the disparity? This still remains a “Million” dollar question.

Posted in Uncategorized | Tagged: , | Leave a Comment »

Printing to PDF File in Ubuntu

Posted by tux4life on January 12, 2009

We all know that OpenOffice has a very nice feature to export any document to a PDF file.

But still, I was looking for a solution to print to a PDF file.  Yet again, with google’s help I found out that this functionality is provided by the package cups-pdf.

Follow the steps below to install and configure this package.

Open up a terminal and use the following command to install this package.

sudo apt-get install cups-pdf

Restart the printer service using

sudo /etc/init.d/cups restart

Finally, open up the printer configuration dialog using

System -> Administration -> Printing

Add a new printer by selecting “PDF Printer”, continue by selecting defaults.

Now when printing, you can select the newly created printer to print to a PDF file.

Posted in Ubuntu HowTo's | Tagged: , , | Leave a Comment »

Change MPlayer Playback Speed

Posted by tux4life on January 7, 2009

Being a university student, I tend to see lots of lecture videos.  Often, these lectures tend to be very tedious and would take for ever to complete.

I was happy to see a feature in Windows Media Player that allowed faster playback without affecting the audio or video quality.  (For once, Microsoft had implemented a feature that actually works and is useful ;) ) But this made me restart and change to Windows just for the sake of viewing the videos, clearly an annoying thing.

Being a trusty Ubuntu user for more than 4 years, I somehow had a hunch that there would be a solution for this in the Open World.  With some help from Google, I was able to achieve the same with MPlayer.

MPlayer 1.0rc2 that is present in Intrepid Ibex repos allows one to decrease or increase playback speed using the keys “[" and "]” respectively.  (More MPlayer keyboard shortcuts can be found here) When used to increase of decrease the playback speed, audio goes bad as the pitch does not change with respect to playback speed.

This audio problem can be corrected by using the audio filter scaletempoScaletempo filter automatically adjusts the pitch according to the playback speed.  Unfortunately, this filter is not bundled with MPlayer 1.0rc2 but is part of the latest development build which can be installed as follows.

Add the following lines to the /etc/apt/sources.list file (Click Here to visit the webpage for this repo)

deb http://ppa.launchpad.net/rvm/ubuntu intrepid main
deb-src http://ppa.launchpad.net/rvm/ubuntu intrepid main

To install the latest build of MPlayer, open up a terminal and run

sudo apt-get update
sudo apt-get install mplayer

If you already have MPlayer, open up a terminal and run

sudo apt-get update
sudo apt-get upgrade

This should upgrade MPlayer to the latest version and also installs scaletempo audio filter.

To test if scaletempo filter is installed, run the following command in a terminal.

mplayer -af help

This would display the list of audio filters available and scaletempo should be one of them.

To enable this filter while startup, use in a terminal

mplayer -af scaletempo

(You can also update the MPlayer shortcut to include this filter)

Now the keys “[", "]” should decrease / increase the playback speed and also adjust audio’s pitch automatically.

Posted in Ubuntu HowTo's | Tagged: , | 3 Comments »