Posts

My FIRE Journey

Image
Welcome to my blog. Just to give some background about myself, I am Amar, working as Member of technical Staff in Paypal.  Moved to US in 2012 and have been staying here for 8 years. I have two boys one is 10 years and another one is 3 years old. "Idle money is like a radio-active material, its value depreciates over-time" I came to know above FIRE (Financial Independence and Retire Early) in 2013 while searching for investment opportunities. Let's jump into the topic. My goal was to be financially independent by 40. I just want to have the financial independent and perceive my interests instead of wasting my precious time churning out money for my family. The investments are broadly classified as the following categories Indian Real-estate - Stable and reliable and it never disappoints as long as the decision is good Indian stock market - Unreliable  US real estate - Very slow growth (non bay-area) with lots of wait times and a bit unreliable US stock ...

Some thoughts on MongoDB Nodejs driver

I am in the process of evaluating mongoDB for one of the product requirements. We were on the J2EE stack and MongoDB has java driver with which we got awesome results compared to the existing framework in terms of not only speed and resource utilization but also in terms data replication and fail-over behavior. I was curious about mongoDB nodejs driver and tried to test its performance over java driver. It was very easy to write code as I was already familiar with javascript and the footprint, startup time are far less compared to the J2EE stack. Now comes the real problem with NodeJS. My application typically tries to connect to different database for each request and existing nodejs api does not support to use same driver across different requests rendering the connection pooling offered by the framework useless !!!. I need to create server instance for each request. With  read preference as NEAREST, the reads are not shared across the replica set members and only the...

MongoDB index completion status

MongoDB allows you to create indexes and run them in the background using the ensureIndex . Often indexing is a time consuming process and may take long if indexed upon string and the collection contains millions of records. For example, Indexing on my collection having 50 million records took almost 15 minutes. Here is the script that can be used to monitor index operation status. var ops = db.currentOp(); if(ops.inprog && ops.inprog.length > 0) {     for(o in ops.inprog) {         var op = ops.inprog[o];         if(op.msg && op.msg.match(/bg index build/)) {             print(op.opid+' - '+op.msg);         }     } } copy above code into test_index_status.sh, execute mongo index_status.sh and see the magic!!!

Configuring jawr to use YUI compressor instead of JSMinifier for minifying js files

Jawr  is the framework that is developed to make the versioning, compression, minifying css, js files  more stream lined. It can also be integrated with smartsprites and people can write their custom handlers for their application needs. I am not here to explain about various features supported by jawr. Please go to the link mentioned above for more details. JSMin is the default post processor used by jawr, it is too old, does not understand some semantics and bothers you throwing errors during minifying process, or the minified version has some bugs which are not present if you set debug mode to true. So the other option is YUI Compressor,  Jawr identifies which post processor to use based on  jawr.js.bundle.factory.bundlepostprocessors property in jawr.properties it is defaulted to JSMin if none is specified. We can set the property to YUI to notify jawr to use YUI compressor instead. Download YUI Compressor from  http://yuilibrary.com/download/build...

CORS issues with IE9 and workarounds

CORS(Cross-Origin-Resource-Sharing) is one of the features in HTML5 feature stack that enables a page to make AJAX requests to other domains. This feature is introduced to circumvent the Same-Origin-Policy . I am not discussing about CORS in detail here as there are lots of online resources available. I am working on a product where html files are served from one domain and back-end requests should be made to another domain (of course sub-domain) for security reasons and API clarity. Luckily we need to support browsers with HTML5 capabilities like Chrome > 14, Safari  > 5.0.5 , Firefox > 9, IE >8. I thought that IE9 is HTML5 complaint and promised to have support for it. I could have investigated a little bit  Application was implemented and we are running for release. Suddenly while going through entire flow we realized that IE9 is not making any CORS requests. From then on our hunt started. Searching blogs, articles, stackoverflow for solutions. I am her...

Difference in core javascript and jquery event handling

I was surprised to see that jquery handles events in a different way as compared to core javascript event handling. Here is the case jQuery("#testAnchor").click(function() { //do some thing return false; }); If you are returning false in an event handler in jquery, that means you are stopping propagation and preventing default. All the handlers listening on the click event on that element will be called and the event will not be propagated to the parent element. If you use document.getElementById("testAnchor").onclick = function(event) { event = event || window.event; //do some thing return false; returning false in this case wont stop propagating the event. we should indeed say event.cancelBubble= true or event.stopPropagation() based on the browser.

Knowing whether control key is pressed while an event happened

If you are listening to click events of anchors to do some operation of showing a dialog or doing something else, you have to know whether ctrl key is pressed or not as you may not want your custom logic to kick in when ctrl key is pressed as user wants to open the link in the new tab. He is the solution, assuming jquery is used jQuery("a.link").click(function(event) { if(event.metaKey || event.ctrlKey) { //ctrl key is pressed } }); checking for metaKey apart from ctrlKey property of event as mac's command key press will set metaKey property to true and ctrlKey for remaining browsers.

Knowing whether a javascript code is being executed inside an iframe

Sometimes it is required to know whether the code is being executed inside an iframe or not. Following code works for all browsers. var inIframe=false; try { inIframe = window.top.document == document; }catch(ex) { inIframe = true; } The reason for keeping try catch in the above logic is when ever window.top.document is accessed and if that document belongs to different domain, then IE throws Access Denied error.

Accessing state property of xmlhttprequest before readyState 4 in IE

Like IllegalStateException in java, IE also throws Undefined Error when you try to access xmlhttprequest's status property before reaching steady state 4. For example in the following code if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { var status = xmlhttp.status; var isSuccess = status >= 200 && status if (xmlhttp.readyState==4 && isSuccess) { alert(xmlhttp.responseText); } } alert("in ajax"); ...

JQuery filesize plugin

Converting raw bytes size into human readable string is a very frequently used task. I developed a plugin that converts raw bytes into KB or MB and its usage is very simple. Suppose if you want to show 1000 bytes in human readable form inside a span assign the value as size attribute <span class="jqfilesize" size="1000"></span> and use jQuery(".jqfilesize").filesize(); output will be <span class="jqfilesize" size="1000">1 KB</span> Download the plugin here

Ellipsis class that works in almost all browsers

Applying ellipsis class will put three dots at the end of single line of the content. Remember that it works only for block elements. .ellipsis { white-space: nowrap; overflow:hidden; text-overflow:ellipsis; -o-text-overflow:ellipsis; -ms-text-overflow:ellipsis; -moz-binding:url("ellipsis-xbl.xml#ellipsis") } and ellipsos-xbl.xml is required for firefox

Using javascript array function splice to modify array contents

Image
Javascript array object has lots of pre-defined functions that makes life easy. Among them, splice is the method lot of developers are not aware of. Using splice, you can remove an element in array, replace array contents without copying, iterating through entire elements. Prototype uses existence of splice method to identify whether an object is an array or not (Object.isArray). so, no need to worry about browser compatibilities. I used to iterate through entire array object to remove an element like the following v ar arrObj = ['1', '4', '3', '2']; var anotherArray = []; for (var i = 0;i <=arrObj.length; i++) { if(arrObj[i] != '3') { anotherArray.push(arrObj[i]); } } We need to iterate through entire array to remove an element if above method is followed. Using splice method, v ar arrObj = ['1', '4', '3', '2']; for(var i = 0; i <=arrObj.length; i++) { if(arrObj[i] == '3...

Retaining license details in javascript files while minifying using YUICompressor

Minification is one of the methods suggested by yahoo's yslow plugin . During minification process all comments in a javascript file are removed, long variables names are replaced with shorter ones, removing unwanted spaces, removing empty lines, making the minified file size as minimum as possible. If we are using a third party javascript file whose license should be intact while sending to the outside world. Using YUICompressor 's default setting it removes all the comments while include license info as well. If you want a comment block not to be removed by compressor while minifying, then that comment block should start with ! For example if the input is /*! this is my js should include license */ var myFunc = function() { /* this comment i dont want in minified version*/ ... } Then the output of compression will be like /*this is my js should include license */ var myFunc= function() {...} thus retaining the comment after minification as well.

Browser behaviour when 403 Response with Content-Disposition Attachment header

If client requests for a file download for which the logged in user does not have permissions, server should not set content-disposition:attachment header. If the header is set and if 403 (Forbidden) status code returned by the server, then client shows weird message as file not found.

Proper way to have an anchor tag with onclick event

Anchor tags are one of the most common HTML tags used in pages. If the user right clicks on the anchor tag he/she will be provided with an option of 'Open in new Window/Open in new Tab'. This will happen only if the anchor has href attribute. Sometimes it is required to do some other action (like making ajax request) on click of the anchor link and also provide the right click option for the same anchor. Natural practice by web developers. <a href="javascript:void(0);" onclick="alert('i am here');">Click Me! </a> Click Me without link for anchor! Correct way to add anchor tags without losing anchor properties. <a href="http://www.blogger.com/amareswar.blogspot.com" onclick="alert('i am here'); return false;">Click Me! </a> Click Me! In the above link, you can observe that the user can right click on go to the respective link and onclick will do the custom action provided by the developer.

My Son my life

Image
Life changed a lot after my son 'Harshith' came into my life. It is the feeling that you can nerver forget. I am enjoying the most happiest phase of my life. Missing him a lot as he is staying away from me with her mother. Hoping to be with him as soon as possible.

Prefer primitives over boxed primitives in java

This blog is one of the item in famous "Effective Java 2/e" by Joshua Bloch. In java, we got a flexibility of auto boxing and auto-unboxing of Java primitives like int,long,boolean etc.., int i=0; Integer j = i; In the above example i is autoboxed to j and the vice-versa is also possible. Consider the following example: public class TestClass { private static Integer i; public static void main(String[] args) { if(i == 42) { System.out.println("Unbelievable"); } } } If the above program is executed, what do you expect? it prints "unbelievable" ? no it wiil not but it behaves as strange are printing "unbelievable". It throws NullPointerException !!. What might be the reason? well this is caused because of one of the side effects of famous auto-boxing. When ever a primitive and boxed primitive involves in an operation, then auto-unboxing of boxed primitive happens. In the above example, i will be auto unboxed and it is a null refer...

Be careful before setting innerHTML

When working with javascript, the most common thing a developer will do for adding content by setting innerHTML of container element. ele.innerHTML ='<div><span>This is working fine</span>'; if(user == 'amar') { ele.innerHTML += '<span>Hello amar welcome to your blog!</span>'; } ele.innerHTML+='</div>'; Above code seems to be ok but there is a big mistake. Element's innerHTML is set and the div is not closed before evaluating the condition. Browser closes the div at the point and the span that is added in the condition will be sibling of div instead of child !!. This problem can be solved by using a variable, adding the content to that variable and finally setting innerHTML to the element.

Enhancing user experience by improving website performance

From my experience I device some points and tools used in the development of the website. Any website's user experience depends on the speed of data transfer( including images, js and actual page content), amount of the data transferred and number of requests made. Caching the static content : All the static files like js, css and images can be cached by the browser so that the same content will not be requested and thus reducing the data transferred through wire. Server can tell the browser to cache the content by setting the following headers. ( Tested in chrome, IE, and firefox). Expires header (setting near future expires header with one year from current time) Cache control header (Cache-control header (public, max-age= ) Adding these headers will permanently cache the files on the client side. Versioning of the static content is must for controlling of the data flow between client and server. Versioning of the static implies including version number in the url which ...

Returning content type of 'application/json' using jQuery ajax form

Ajax form in the jQuery is a wonderful feature for the developers as it allows multi-part upload without refreshing the page. Ajax form call creates a iframe which is invisible and then submits the form from with in iframe. Browser checks for the content type of the returned content and verifies whether it can handle or not before passing content to the iframe. If the response content type is appliction/json, the browser donot know how to handle the content and opens popup to save the content instead of handling to the iframe, the source of the request. So basically, ajax form of jQuery cannot be used for api calls returning content type of application/json which is a major issue while working with REST API calls that accepts multi-part/formdata requests and return content of type application/json. Alternatives : Return content of type application/xml and parse the same on the client side. Use servelts to handle the multi-part request and return json string form of the object you wis...