Friday, December 16, 2016
Java HashMap - Infinite loop; another reason not use it in a non-thread safe way!
Tuesday, September 01, 2015
A case for Bloom Filter
Sunday, August 09, 2015
Port Unification with Netty in Proxy Mode
However, in my case, the Netty implementation was mimicking the behaviour of a proxy server. This means that a client will make a CONNECT request before any actual data request is sent. CONNECT request is always non-SSL - even if the protocol to follow is HTTPS.
The approach to use in this scenario is as follows:
Implement a ChannelInboundByteHandlerAdapter; on inbound buffer update - check if the request is CONNECT request. In case of CONNECT request, pass on the incoming bytes to the next handler in the chain.
If its not a CONNECT request, do the SSL data encryption check and add the SSL handler to the chain if necessary. Before passing on the bytes to the next handler, the unification handler should remove itself from the chain.
Monday, July 20, 2015
Threading Race Deque
private final NavigableSet scenarios = new ConcurrentSkipListSet()
public void fireCompletedScenarios() {
while (!scenarios.isEmpty()) {
InMemoryScenarioRecord firstScenario = scenarios.first();
if (firstScenario.completed()) {
synchronized (completedScenarios) {
completedScenarios.offer(scenarios.pollFirst());
}
continue;
}
//exit when you find first uncompleted scenario
break;
}
}
There is a navigable set of scenarios, ordered by scenario time. We pull out completed scenarios from it and add it to another queue. We break when we find the first incomplete scenario.
The issue I have been facing is - incomplete scenarios getting into the queue of completed scenarios. As usual, the case does not happen in local environment - happens in non-prod environments -under high load. Hence, it must be some race condition causing the issue.
Finally it stuck to me is the bug in the above code that manifests under high load. The bug is as follows:
The scenarios.first() just gives me access to the first scenario and does not remove it from the navigable set. After the completion check, pollFirst is called to remove it from the set.
This is the bug - under high load - the element returned by first and the element removed by pollFirst are not same!
There can be another incomplete scenario that came in to the set; to the top because it had lower scenario time; but arrived late into the set because of the asynchronicity that existed in this system. This resulted in adding a incomplete scenario returned by pollFirst to the completed queue!
huh! I fixed this over sight and learnt a valuable lesson !
Sunday, February 16, 2014
Farey Series
def farey = {
def a = 1, b = it, c = 1, d = it - 1;
printf "%d/%d ", a, b
while (c != 1 || d != 1) {
printf "%d/%d ", c, d
z = (int) ((it + b) / d)
(a, b, c, d) = [c, d, z * c - a, z * d - b]
}
}
farey(7)
Output:
1/7 1/6 1/5 1/4 2/7 1/3 2/5 3/7 1/2 4/7 3/5 2/3 5/7 3/4 4/5 5/6 6/7
Saturday, January 25, 2014
Learning OAuth 2.0
+--------+ +---------------+
| |--(A)- Authorization Request ->| Resource |
| | | Owner |
| |<-(B)-- Authorization Grant ---| |
| | +---------------+
| |
| | +---------------+
| |--(C)-- Authorization Grant -->| Authorization |
| Client | | Server |
| |<-(D)----- Access Token -------| |
| | +---------------+
| |
| | +---------------+
| |--(E)----- Access Token ------>| Resource |
| | | Server |
| |<-(F)--- Protected Resource ---| |
+--------+ +---------------+
OAuth 2.0 defines quite a few API endpoints. The RFC provides examples for the request and expected responses for these APIs.
One of the good ways to understand the RFC is build the OAuth endpoints and try out the samples mentioned in it. Apigee Edge support of OAuth 2.0 is a quick help here.
This github project oauth20_apigee contains the proxy and the postman client requests.
Apart from the RFC,following are two good resources about OAuth 2.0
- Good Explanation of OAuth 2.0 By Aaron - OAuth 2 Simplified
- If you wondered (like me) why Authorization Code is required in OAuth 2.0 - Stack Overflow Question
Friday, December 13, 2013
brew install octave fails on OS X - Mountain Lion
make install phase with the following error:make install ./plot.texi:3957: warning: node `Multiple Plot Windows' is prev for `Printing and Saving Plots' in menu but not in sectioning make[3]: *** [octave.info] Error 1 make[2]: *** [install-recursive] Error 1 make[1]: *** [install-recursive] Error 1 make: *** [install] Error 2The solution seems to be the manual patch indicated here: http://goo.gl/nq0H5b
In summary:
--enable-docs=no makes it work.
Sunday, June 03, 2012
Post S2 I9100G ICS Upgrade: Only Samsung Logo Left?
The only way to get the phone back to work is to revert to Gingerbread! This has to be done manually by downloading the firmware and installing it.
Thanks to this link , it provides a detailed explanation for doing the same.
Appreciate Samsung for such robust update release which only shows their logo after its applied!
Of course, I can visit the Samsung service center in Bangalore which is worse than their upgrade package!
Sunday, May 20, 2012
loadClass - JDK 1.6.0_18 vs JDK 1.6.0_27
This classloader worked on JDK 6 Update 27 (dev env) but failed to work on JDK 6 Update 17 (test env).
Its a rare skill to write code in Java that fails between minor revisions!! :-)
The class loader code was written looking at the Java source code for Classloader. This was the cause of the issue - the custom loader implementation did not adhere to the documented contract for the loadClass method.
The documentation of the loadClass method clearly states
ClassNotFoundException - If the class could not be foundJdk 1.6 Update 27
The if check c==null in the Update 27 made the loadClass method work even though it did not adhere to the documented contract.
The bottom line is to code against documented contract and not look at the implementation to write code!
Monday, February 06, 2012
Analytical Reasoning With Prolog
Problem:
Monday, December 26, 2011
C#: Timer, Deferred Evaluation & GC
- The Loc 1 in the code is a Select expression which is implemented by deferred execution.
- The Loc 2 in the code exists to ensure the Select is executed and timer is created/scheduled.
- The key issue with the code is no reference to the Timer object created is retained. Hence, the Timer object is garbage collected.
- Even though the Loc 1 seems to indicate that the reference to the Timer is assigned to the _timers field, it's not so. The _timers field holds the reference to the Select iterator. In other words, the lambda code itself.
GetType() on _timers will return System.Linq.Enumerable+WhereSelectListIterator`2 [System.Threading.TimerCallback,System.Threading.Timer]
- If the timer is garbage collected, what is the observed behavior in the Dispose method of the JobScheduler ?
The foreach loop actually creates new timers as a result of Select execution again and disposes them.
- Timer will not be fired if the GC runs.
- Timer created will never be stopped by Dispose if the GC does not collect it.
Sunday, December 11, 2011
Prolog: List Difference
minusAcc(L,[],_,L) :- !.
minusAcc([],_,A,A) :- !.
minusAcc([H|T],SL,A,W) :- \+memberchk(H,SL),!,
append([H],A,AL),
minusAcc(T,SL,AL,W).
minusAcc([_|T],SL,A,W) :- minusAcc(T,SL,A,W).
minus(L,SL,W) :- minusAcc(L,SL,[],W).
Sunday, November 13, 2011
Installing Io on Snow Leopard
In case you intend to do the same, here is the gist of the steps required to get going
- Download Io source from git-repo
- Next step is to run the build.sh file in the cloned git io directory. You might get the following error
- You need to modify the file ~/software/io/libs/basekit/source/Common_inline.h change
in the section #if defined(__APPLE__) to
#define NS_INLINE static inline
- Now run the build.sh file again. Io binary will be ready for use!
- Here is the Vim plugin for Io: http://www.vim.org/scripts/script.php?script_id=2116
Friday, April 15, 2011
Trying REBOL
The application should be able to convert time from Indian timezone to Munich and Boston timezone. This conversion is related to my current project.
With this weird requirement, I decided to use the most weird way to convert time. I decided to use the timeanddate.com timezone converter to do the conversion. As a result, the application has to make an
HTTP GET call to this link and parse the resulting web page to find the converted time.Summarizing the Approach:
- Write a REBOL UI application that takes the Indian time as input
- On click of
Convert, makes anHTTPcall to the website with input given by the user. - Parse the resulting web page and find the converted time.
- Show the converted time on the UI !!
Here is the REBOL code for the application.
This is a REBOL code for timezone convertor
REBOL
[
Title: "Timezone Convertor IN to BOS & MUN"
Author: "Srikanth Seshadri"
]
t-time: to-string now/time
time-get: func [inp-time tz] [
page: reform [
"http://www.timeanddate.com/worldclock/converted.html?hour="inp-time/hour"&min="inp-time/minute"&sec="inp-time/second"&p1=438&p2="tz]
tzurl: to-url page
tz-text: load/markup tzurl
zone-found: false tg-time: now
foreach item tz-text [
if all [string? item zone-found ] [ tg-time: item break]
if all [string? item any[ find item "(U.S.A" find item "(Germ"] ] [zone-found: true]
]
tg-time
]
gui: layout [
backdrop effect [gradient 0x1 white]
across
h3 "Timezone Converter IN -> BOS & MUN" black return
lab "Indian Time"
t-time: field t-time 60x24 return
tab
button "Convert Time" [
inp-time: (to-time t-time/text)
if inp-time
[
boslbl/text: reform ["Time in Boston: " time-get inp-time 43]
munlbl/text: reform ["Time in Munich: " time-get inp-time 83]
show boslbl
show munlbl
]
] keycode [#"^m"] return
boslbl: h4 "[---------------------------------------------------------------------]" return
munlbl: h4 "[---------------------------------------------------------------------]" return
]
view center-face gui
and the output

This is most strange way to do timezone conversion, but the learnings and development was fun; all the effort was worth it!
Monday, September 06, 2010
World War II + India + Java
DateFormat indiaDtFmt = new SimpleDateFormat("dd/MM/yyyy HH'h'mm");DateFormat gmtDtFmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");indiaDtFmt.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));gmtDtFmt.setTimeZone(TimeZone.getTimeZone("GMT"));Date worldWarIIDate = indiaDtFmt.parse("02/02/1944 06h30");Date nonWorldWarIIDate = indiaDtFmt.parse("02/02/2006 06h30");System.err.println(gmtDtFmt.format(worldWarIIDate) +" GMT");System.err.println(gmtDtFmt.format(nonWorldWarIIDate) +" GMT");
1944-02-02 00:00:00 GMT2006-02-02 01:00:00 GMT
Saturday, July 31, 2010
Auto Fare Converter

![]() | ![]() |
- Enter the current fare in the meter.
- Click Convert button.
- The amount you need to pay, the new fare, will be shown.
Monday, July 26, 2010
BMTC Bus Ticket Cost Calculation
Note: The calculation is performed by the ticketing machine given to the bus conductor so the conductor cannot cheat you!
BMTC divides the routes into stages. Following is the 'Fare Table' of BMTC Bus No 45. You can get the 'Fare Table' for your route from the conductor....Please Ask!
| FARE TABLE-010 | ||
| Stage | Name | Fare |
| 1 | KAMAKYA | 0.00 |
| 2 | KATTRIGUPPE | 5.00 |
| 3 | HOSAKERE HALLI | 9.00 |
| 4 | BANK COLONY | 10.00 |
| 5 | GANESH BHAVAN | 13.00 |
| 6 | CHAMARAJPET | 15.00 |
| 7 | GOODS ROAD | 16.00 |
| 8 | KBS | 16.00 |
Now the stage you climb the bus is the Stage 1 for you and of course the stage you get off is the last stage for you. Lets see the following examples of fare calculation with the previous assumption.
Fare from
- KAMAKYA to KBS = Stage 8 - Stage 0 = 8 Stages crossed = Rs 16
- BANK COLONY to GOODS Road = Stage 7 - Stage 4 = 3 Stages Crossed = Rs 9
- GOODS ROAD to KBS = Stage 8 - Stage 7 = 1 Stage crossed = Rs 5
List stageList=[KAMKYA...KBS]
List fareList=[0..16]
int start= stageList.indexOf[YOUR START STAGE]
int end = stageList.indexOf[YOUR END STAGE]
Fare= fareList[end-start]
Hope the calculation is clear!
Sunday, May 30, 2010
Reading Java Concurrency
Here is the study plan for that worked for me...
- Locks, Conditions And Fairness
- Understanding the Java Memory Model and its fix by JSR 133
- Happens-Before and volatile.
- LL/SC, CAS concepts
- Atomic package
- Concurrent Data Structures & Synchronizers
- Executors,Futures and other threading concepts.
- Articles by Brian Goetz, Doug Lea
- Java concurrency Interest group.
Two useful books:
- Concurrent Programming In Java by Doug Lea.
- Java Concurrency in Practice By Brian Goetz
Sunday, January 31, 2010
rmToMp3.pl
- Perl
- mplayer
- lame
- wget
#!/usr/bin/perl -w
use strict;
BEGIN{
$\="\n";
}
&usage if @ARGV!=1;
my $fileName=shift;
&usage if ($fileName !~ m#\.(ram|rm)$#);
&process_ram($fileName) if ($fileName =~ m|\.ram$|);
&process_rm($fileName) if ($fileName =~ m|\.rm$|);
sub usage(){
print STDERR "usage: $0 filename.rm/ram\n";
exit 1;
}
sub process_ram(){
my $fileName=shift;
$fileName=&processUrl($fileName);
open RAM_FILE, $fileName || die "Failed To Process File: $!";
while(){
chomp;
chop if ~ m/\r$/;
$_ = &processUrl($_);
&convertToMp3($_);
}
close RAM_FILE;
}
sub process_rm(){
my $fileName=shift;
$fileName=&processUrl($fileName);
&convertToMp3($fileName);
}
sub convertToMp3(){
my $fileName=shift;
chomp($fileName);
chop($fileName) if $fileName =~ m/\r$/;
print "Processing File...$fileName";
my ($dirName,$baseName)=&dirname($fileName);
$baseName =~ s/\.rm/.mp3/;
die "Invalid File: ${fileName}" unless(-e $fileName);
`mplayer $fileName -ao pcm 2>/dev/null`;
`lame -h -b 128 audiodump.wav $dirName/$baseName`;
`rm audiodump.wav`;
}
sub dirname(){
return (".",$_[0]) unless $_[0] =~ m|^/|;
return $_[0]=~ m|(.*/)(.*)$|;
}
sub processUrl(){
my $fileName=shift;
chomp($fileName);
if(&isUrl($fileName)){
&download($fileName);
return $fileName =~ m|.*/(.*)$|,$1;
}
return $fileName;
}
sub isUrl(){
$_[0] =~ m/^http.*/;
}
sub download(){
print "Downloading File...$_[0]";
system("wget -c $_[0]")==0 || die "Failed to download file: $_[0]";
}
Wednesday, November 04, 2009
Encroachers Hammering Project
Recent anti-encroachment drive of Mysore is an example of admirable planning and execution. The drive was directed and managed by the MCC commissioner K. S Raykar.
Planning Phase:Almost 6 months
a) to get approvals from higher ups including district minister Shobha Karandlaje
b) to develop project execution plan.
Departments Involved: MCC, MUDA, Mysore Police (KSRP, CAR, DAR...etc), Telecom Department
Project Leads: K.S Raykar( MCC Commissioner), Manivannan (DCP), Sunil Agarwal (Police Commissioner)
Project Team Structure/Resourcing:
Commanded by: 2 teams of MUDA and MCC
Executed By: 27 teams of workers!!!
The team organization and composition of each team is shown below.

Risks/ Risk Mitigation:
Stay Order from Court: The operation was started on a Sunday, early in the morning - no court is open at that time.
Influence from elected representatives: All the phone lines, land line and mobile, were jammed with help of Telecom providers - physical presence required for any kind of influence.
People gathering to protest: Jamming of phone lines prevent mobilization of people. Also, 500 policemen providing security would deter anyone raising voice.
Result: More than 450 encroachments cleared by noon!
Issues Encountered: There was protest by the elected representatives at the demolition site. The threat of arrest, and few arrests, by the police was enough to diffuse the crowd.
Post Execution: MCC Commissioner goes on a 3 day sick leave from Monday – leaving all the encroachers and their supporters with the rubble!





