Aug 232014

When using Omniauth’s oauth strategy for authenticating to any oauth enabled website, we often run into the problem of expired access tokens.

To refresh the access token, another call must be made to oauth2/token endpoint with the client id, client secret and the refresh token. Since this is not available out of the box in Omniauth-OAuth, I wrote some additional code in the User model file.

This call will return another JSON with a new access token and an updated expiry time. We need to save the access token and update the expiry time in our model. Keep in mind that this flow works only till the refresh token is valid. Once that expires, the entire oauth authorization workflow needs to be repeated.

This is the code I added in the user.rb model class of my rails application

def refresh_token_if_expired
  if token_expired?
    response    = "#{ENV['DOMAIN']}oauth2/token", :grant_type => 'refresh_token', :refresh_token => self.refresh_token, :client_id => ENV['APP_ID'], :client_secret => ENV['APP_SECRET'] 
    refreshhash = JSON.parse(response.body)
    self.token     = refreshhash['access_token']
    self.expiresat = + refreshhash["expires_in"].to_i.seconds
    puts 'Saved'

def token_expired?
  expiry = 
  return true if expiry < # expired token, so we should quickly return
  token_expires_at = expiry
  save if changed?
  false # token not expired. 😀

The ENV[‘DOMAIN’] is the endpoint of the oauth provider. The client_id and client_secret would be provided at the time of application creation. And while making any authenticated calls, simply call this method which would check if the access token has expired already and calls the refresh method if it has.

#refresh the token if it has expired

P.S: There is a dependency on rest-client gem.

P.P.S: Click here to read OAuth standards page for the refresh-token and its workflow

Sep 012011

A few days ago, there was a discussion on a cricket site regarding who is the better bowler amongst Waqar/Pollock/Donald. Though very good bowlers in their era, they failed to break into the all time great list of Marshall, Akram, Ambrose, Mc Grath ,Warne amongst a few others.

Donald had sheer pace and meancing swing. Waqar was feared for his toe-crushing yorkers and Pollock though not a express pace – still had amazing discipline with which he picked up wickets. So I pulled up their statistics and this is the nationwide distribution of their average and strike rate.

Waqar’s average is great in Pakistan, Bangladesh, Zimbabwe and Sri Lanka. In Pakistan bowling on flat wickets and maintaining that kind of average is quite laudable. In India the sample size is too small to draw any meaningful conclusions out of it. His main bugbear seems to be bowling in South Africa, England and Oz. In England and Saffers under bowling friendly conditions, Waqar has underperformned by quite a margin. In Australia he averages 40 which is even worse. Donald’s worst bowling performance is in Pakistan where he averages 32 followed by 28 in Oz. Everywhere else, he averages a commendable sub-25 level. Pollock has a similar problem in performing in Australia – averaging 34 there. 28 and 27 in Windies and India are another place where he has not performed at his best.

Lets see their year wise performance in their career.

Waqar’s career: Waqar’s first few years were the cream of his career. From 1990 to 1994, his bowling performances were superlative. It was during his prime that he tormented the English batsman with the lethal toe-crushers and banana swing. However he suffered an injury in 1995 after which his performance became wayward. His place in the team was in and out in the next few years. Though he gave some inspiring performances in the coming years, the waqar of yore was not seen again.

Donald’s career: Donald’s prime was from 96 – 2000. This period was a relatively easier period to bat than the early 90s which still favored bowlers to an extent. Still Donald’s stats dont give that away. His consistency during the prime years was remarkable, going above 20 in just one year. I still remember his delivery to an UAE batsman who had the gall to bat to Donald without a helmet on. The ball was a lethal bouncer which the batsman on the head, who remarkably escaped without any injuries

Pollock’s career: Unlike the other two bowlers being discussed, Shaun Pollock was an allrounder – He didnt have the same express pace that Waqar or Donald had, but he was ever the workhorse who was disciplined and bowled a consistent line and length with great swing. He took 421 wickets at an average of 23 odd, which in itself is quite remarkable. Add to that his batting ability and you have a match winner. Pollock’s prime was from 98 to 2003 barring slightly poor performance in the one year of 2002.

It is very difficult to pick and choose among these three bowlers as who is the best of them. However my personal choice would be to go with Donald, followed by Waqar and Pollock.

Mar 132011

India’s defeat against South Africa today was very painful, not because of the loss per se, but because we squandered two wonderful opportunities to win it. One in the 40th over where despite being 267 for 1, India collapsed to 296 all out. And the other in the death overs where tighter bowling could have still got us home.

More than the match loss, it was plain disappointing to see Sachin haters dishing the usual ignorant tripe about how India loses every time he scores a century. After years of unsuccessfully searching for reasons to put down Sachin’s record because of his 21 year career at the pinnacle of cricket, uncontroversial career and humble image, the haters have settled for frivolous reasons like Sachin’s centuries being unlucky for India.

To firmly discredit such irrational theories being floated, I dug up some stats to determine if there is truly a corelation between Sachin’s centuries and India’s defeats. My stats dont contain the world cup data so its behind by 3 matches.

Lets do the Simplest math first:

India has won 33 times out of 45 (73.33%) when Sachin has scored a century. Two of the matches had ended up in no result

Now for the more in depth analysis. These are the 12 matches when Sachin had lost. This is the query that I used for analyzing this.

select /*,m.scorecard_url,*/ pbs.runs_scored as Sachin_Score,
	   i.runs as Team_Score,
	   CASE when i.match_innings = 1
		    then "Batting_First"
			when i.Match_innings = 2
			then "Chasing"
	   End as "Team position",
	   ceil((pbs.runs_scored/pbs.balls_faced)*100) as Strike_Rate,
	   pbs.departure_score as Departure_Score
	/*   pbs.departure_wickets as Departure_Wickets, */
	   /*pbs.departure_overs as Departure_Overs,
	   round((pbs.departure_score - pbs.arrival_score)/(pbs.departure_overs),2) as RunRate_duringStay,
	   round((i.runs-pbs.departure_score)/(i.overs-pbs.departure_overs),2) as RunRate_afterStay,
	   round(i.overs-pbs.departure_overs,2) as Overs_afterStay,
	   round((i.runs/i.overs),2) as MatchRunRate
	  /* (pbs.runs_scored/i.runs)*100  as Percentage_of_teamScore,*/
	    /*t.Name as opposing_team,
	    Team_Scores.runs as Oppositon_Score
	    from Players p,
              PlayerBattingStats pbs,
			 Matches m,
			 Innings i,
			 Teams t,
			 (select matchid,runs,batting_teamid from Innings) Team_Scores,
		 (Select p1.cname,pbs1.matchid,runs_scored,i1.batting_teamid from Players p1,PlayerBattingStats pbs1,Innings i1
					where = pbs1.playerid and pbs1.matchid = i1.matchid) Oppn_Scores
		where = pbs.playerid and
			  pbs.matchid = and
			  i.matchid = and = Team_Scores.matchid and
		       Team_Scores.batting_teamid <> 6 and = Oppn_Scores.matchid and
			  Oppn_Scores.batting_teamid <> 6 and
			  m.winning_teamid = and
		      m.matchtype = 'ODI' and
			  (m.winning_teamid <> 6 or m.winning_teamid is null) and
			  i.batting_teamid = 6 and
			  pbs.runs_scored >= 100 and
			  p.cname = 'Sachin Tendulkar'
group by pbs.runs_scored ,
			--  order by Percentage_of_teamScore desc;

It is notable that Sachin scored more than 45% of the entire team’s runs on 9 of these 12 occasions that India lost. So In effect he was carrying the whole batting alone. And there were only 3 occasions chasing where he was expected to get India home. But an overwhelming majority of 9 times, India was the team batting first and the bowlers were unable to defend targets ranging from 328 to 224

The next reason touted is that Sachin bats too slow to get to his century. This is also not true. 10 times out of 12, Sachin scored at a strike rate of 80 or above. 8 times out of 12, the Strike rate was 90+. When chasing, Sachin’s centuries have come at more than a run a ball.

Next is the run rate, out of the 12 occasions for 4 Sachin carried his bat throught the innings, and pretty much made sure the team reached a decent total. On the other 8 occasions, there is only .5 increase in run rate after Sachin lost his wicket to the match run rate. Even this increase can be attributed to the aggressive batting in the death overs. During chasing under pressure, there is actually a dip after Sachin loses his wicket showing the inability of following batsmen to handle pressure.

There are a lot of other stats that can be displayed to reinforce this fact, eg the Indian’s bowlers economy rate or the misfields and dropped catches by the fielders. At the end of the day, Cricket is a team game and it takes more than one player to win a match for a country. An individual brilliant performance can only do so much to get a team near victory, but it takes the rest of the team to also chip to cross the finish line. Its about time, few of us stop blaming one individual for the mistakes of 10 others.

Jan 122011

After seeing twitterati abuzz with claims of Google goggles being able to solve Sudoku puzzles, I decided to verify on my own. Turns out Goggles does solve the puzzles by itself, and within 10 seconds too.

It took artificial intelligence to the pinnacle when it emulated human behavior by changing a number from 6 to 9 in the top center square, to make the puzzle solving easier!! 😛

Here are the results. The original puzzle on the net  (

After scanning the puzzle from the computer monitor, this is what the Goggles app analyzed

And this after Goggles solved it, in all of 10 seconds!!

Dec 312010

Lets face it, there is no such thing anymore as an unbiased news source in today’s world. Every piece of information which reaches you irrespective of how its packaged (Print, television, Internet, or even your friendly neighbour) has a lingering bias attached to it. The difference lies merely in the fact whether its in-your-face kind of right winged lies that Fox News peddles, or the more subtle, traces of leftist bias that is often seen in BBC news articles.

Till the infamous Barkhagate scandal broke, I had quite a forgiving view of the mainstream media in India. Sure they sensationalized their articles a bit too much, sure they had less news and more of entertainment in their programmes, sure they encouraged superstition by promoting pseudo religious crap. Inspite of all these flaws, I still believed that the media were good at heart and they relentlessly pursued the course of justice in the today’s contrived Indian society. But the Radia tapes turned out to reveal far more than what was actually said on them, they revealed how the media when confronted with a ethical fault in one of their own, chose simply to ignore what should have been the biggest stories of the year.

Given the sorry state of affairs, is it even possible to get an bipartisan view of the world today, where individual biases of another entity doesn’t cloud their judgement while reporting news. The good news is – it is. A few points below on how to go about achieving that

  • Dont rely on a single source Cellphone GPS doesnt depend on one satellite to get an accurate location, and you shouldnt do the same for your news either. I have a simple way to do it. Every piece of news has at least two stakeholders that have a deep interest in the issue and are most likely to be biased. For e.g. the Kashmir issue – The more commercial mainstream media in India (say TOI) and in Pakistan (Geo, The News) would probably carry over the top pieces reporting the same thing each consciously ignoring anything which might hurt the sensibilities of their respective audiences. Now choose one more source which has the least incentive to particularly please one party, preferably a news agency that operates in multiple countries or a media house which avoids sensationalism – something like Reuters, Christian Science Monitor etc. Even a cursory read/ comparison of these three articles are likely to present a viewpoint much closer to the truth than each one alone.
  • Separate Facts from Opinions: Every article in the mainstream media is full of facts interspersed with opinions to make the news suitable to one side even without making the article seem too slanted (in Vir Sanghvi’s words). An exercise to dissect any newspiece is by making a bulleted list of verifiable facts in each article. Any sentence which cannot be classified into a fact that cannot be verified must be done away with. Consider this article. Most of the content, including the headline has no connection whatsoever to what really happened and is present just to sensationalise the article.
  • Remove Facts which have  no relation to the rest of the news piece: I have often observed this technique employed in the more respectable newspapers (BBC, Dawn, The Hindu) and the bias is borne more out of ideology than the need to sell newspapers. It involves citing (actual) facts which are intended to cloud/distort the primary news item in the article hence leading the user to make his own biased inference rather than the newspaper relying on opinionated statements.

All this being said, its next to impossible to make media houses completely objective in their reporting. They are too much a part of the very system they claim to be guardians of. When its the choice between profitability/honesty, profitability will always come first for the stakeholder. However as end consumers of the news, it is ultimately our responsibility not to take anything at face value and make our own judgements based on hard-to-refute facts.

Dec 282010

A lot of people asked me about the usage details of Kindle in India, so I decided to write a post to clear the doubts. There are two ways to buy and get the Kindle in India

  • Get it delivered straight from Amazon : This is the most convenient option but be prepared to pay a hefty import duty on the product. It usually get delivered in 2-3 business days. Last time I checked this was around $56-60 plus the $139 for the Kindle
  • Get someone to get it for you from the US: If you have any friends in the United States, they can buy the Kindle there and bring it for you. This is the cheapest option as you get it for the base price of $139.

If you chose the second option, the Kindle’s base location would still be USA, so what are the implications of using it in India with a different base location? First, on the 3G version your internet will still work free of cost. So you can check mail, browse Wikipedia without any additional charge regardless of the actual and the base location of the Kindle. To get personal documents delivered to your Kindle, you have to pay a charge of $0.15 per megabyte. The transfer would be charged only if the document is send through 3G. If you want to have it delivered for free it can be sent to your free kindle email id ( But if you send it to your free Kindle email, it can only be delivered through WiFi and not 3G.

The base location of the Kindle matters only when you are buying books/magazines from the Amazon store. At locations other than the United States, books are typically more expensive (usually by $2-3) and also the number of free books is lesser in India. So is it possible to keep using the Kindle from India if your base location is US? It is but you need to be quite careful about it.

Every time you make a purchase from the Amazon store, they have some geolocation code to detect your actual location. if you use a USA based proxy or VPN every time you access Amazon store, then there would be no issues. However if you directly access the store with base location as USA, the account gets flagged as being accessed outside the base area. Once the account gets flagged you will see the following message whenever you try to buy.

You attempted to purchase an item while in a different country than listed on your Amazon account.

Once the account is flagged, you cannot purchase anything new from the Amazon store even if you access the internet behind a proxy / VPN account. However all the existing purchases will hold valid including magazine subscriptions which were made before the account was flagged.

I hope this clears any doubts on using the Kindle in India. Please post any other questions in the Comments section and I’ll answer them to the best of my knowledge

Dec 242010

I am starting a series of blog posts for users who are new to Ubuntu. After spending all the time working on Windows, users face a learning curve for even doing simple tasks in Linux. I am going to explain some of those tasks and hopefully it makes things simpler.

The first task many users struggle with is usually shortcut keys. Having gotten used to a few short cut keys in Windows, users find it adapt to the different keys in Linux. I am going to explain how to see existing key mappings and add your own keys. Unlike Windows which usually comes with a single desktop management software – Windows Explorer, Linux has a multitude of options. The two most popular ones are GNOME and KDE. A list of keyboard shortcuts for both these environments can be found here.

Apart from the ones given, there might be scenarios where you want to add your own shortcut keys. Lets see how to do that. First on the top navigation menu, click System -> Preferences -> Keyboard Shortcuts

You will see the Shortcut keys window which can be collapsed to four main categories – Sound, Desktop, Accessibility and Windows Management.

Clicking on any of the categories gives you a list of functions and the shortcut keys assigned for them. Some functions are not assigned shortcuts and given as disabled. If you click on any function, it is highlighted and the shortcut changes to “New Shortcut…” The window is now ready to accept the new key combination and you can enter your desired key to it.

Dec 212010

I was shocked to see this below mail in my Gmail inbox (not spam) which promises to send 100,000 bulk SMS at a cost of only Rs 3000 (~ $60). In addition to this obviously annoying measure of spamming many phones’ inboxes, what is more worrying is that they promise a free database of 150,000 mobile phone numbers without the least bid of respect for an individual’s privacy.

Such open trading of mobile numbers is the main reason behind the increasing amount of cold calls trying to sell me everything from bank credit cards, to personal loans and supposedly free overseas vacations. Databases not only contain phone numbers but also personally identifiable information like Name, workplace, home address, profession etc.

I hope TRAI brings in strict regulations to prevent bulk SMS misuse and forces the telecom sector to discourage telemarketers and fly by night operators who have made a commodity of people’s information.