Skip to main content

Posts

Showing posts with the label JavaScript

Determining image file size in Javascript

After a lot of googling and searching, I realized the best way to do this is to create a service call to the backend witht he url of the image whose size needs to be figured out. This service should make a HEAD call to the server to get the content - length. And pass it along as a response. Not all servers support HEAD calls so as a fallback make a GET call to the get the request and determine the file size from the headers. We need to set few headers for this to work universally. One of them is user-agent. Code for the same is : private void makeRequest( @FormParam ( "url" ) String url, Map response, String requestMethod) { try { HttpURLConnection urlCon = (HttpURLConnection) new URL(url).openConnection(); urlCon.setRequestMethod(requestMethod); urlCon.setRequestProperty( "User-Agent" , "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0" ); //urlCon.setDoOutput...

Promises vs EventEmitters vs Callbacks

There is a lot of material online about these and I would try to keep it short and sweet to explain what is my current understanding of these. Promises are syntax to implement callbacks, so lets get rid of callback from the proportions. Now we are left with Promises vs EventEmitters . Internally or performance wise all are quite similar. So based on coding practices these are my observations: Promise : Promise are good abstraction of asynchronous commands which will happen in given amount of time. Making a db query is a promise, making a rest cal is a promise. Your code needs to wait for promise to be fulfilled. Lets give it an analogy,  a cab driver promises to come to pick you up at 6AM and when he fulfills the promise, you promise him to sit in the cab and reach office. I know analogy is little lame, but hope it explains the idea. EventEmitters : EventEmitters are used for truely async events, like someone clicked on a particular button on a page, or while opera...

Email Validation Jquery Plugin.

Recently I wrote a jquery plugin which would allow you to validate an email address for: Syntax checks (RFC defined grammar)   DNS validation Spell checks  Email Service Provider (ESP) specific local-part grammar (if available)  MX  Validation . Free Email Service Check Disposable Email Service check. Sanatize email id based on service provider. In future, I am planning to incorpoprate: Corporate Company details. If you have any suggestion then you can comment.  You can download the plugin here . Try a demo here . Some screenshots of the demo are: Media mention:  Its featured in  10+ Newest Free jQuery Plugins For This Week #16 (2015)   In  10+ Newest Free jQuery Plugins For This Week April #10 (2015) In  4月份本周超过 10 款最新免费 jQuery 插件 In  4月份本周超过 10 款最新免费 jQuery 插件

NPM Install Failing with EROFS in npm-debug.log on VirtualBox shared Drive [Updated for ETXTBSY]

I have a set up where I use my IDE on my host system and build my code on an Ubuntu server and deploy there. To achieve this I have used virtual box to install and run Ubuntu as a guest system. My host system is Windows.  I have shared a drive across to the guest. Every time my ubuntu comes up, I mount the drive using the command: sudo mount -t vboxsf SHARE_NAME folder_to_mount_on Things were working fine, with my Java server development. Now I decided to move my js and node environment to the same set up and BOOM! it failed. Only hint was EROFS error on the npm-debug.log. Some googling and I find out that VirtualBox has a bug and it does not support sysmlink and since ubuntu by default support symlink creation, npm was failing at the time of creation of sysmlink. My initial solution was to write a build script which rsynced my working directory to a level above and run the build command there. I worked but was slow and hacky. Then I found out that we can switch on sym...

Breaking open https://web.whatsapp.com/

Today whatsapp have launched an online/web version of their overly popular smartphone messaging app. I was very much interested in seeing the architecture of this app because as far as i knew, they never stored messages on their server but all the data was only stored in users phone. So I started to look under the hood of the webapp and what I saw was a beauty. First let me list down the frameworks they have used in creating this app: React .js : A JAVASCRIPT LIBRARY FOR BUILDING USER INTERFACES from Facebook. Underscore.js  : Unerscore is a JavaScript library that provides a whole mess of useful functional programming helpers without extending any built-in objects. It’s the answer to the question: “If I sit down in front of a blank HTML page, and want to start being productive immediately, what do I need?” … and the tie to go along with jQuery's tux and Backbone's suspenders. Velocity.js : Velocity is an animation engine with the same API as jQuery's $.animate(...

Understanding Code Execution in Javascript

If you are doing any form of programming in Javascript then understanding its eventloop is very important. Any javascript engine has three kinds of memory models: Stack, which has the current function pointer an gets executed sequentially. Heap, this stores all the objects, functions basically anything that is initiated is stored here. Queue, all things to be executed is stored here and stack picks up tasks to do from the queue. So, to understand this further, when a function is getting executed its loaded in the stack and if it encounters any setTimeouts then it would be added in the queue and when the current stack gets empty then the new function to be executed from the queue. This code run will explain the process: console.log("Add this code to queue"); setTimeout(function() {                                                //This goes and si...

JS Event Bubbling Vs Event Capturing.

In Javascript or HTML DOM to be precise, there are two methods of event propagation, those are: Event Capturing. Event Bubbling. This defines the way event flow in case of multiple event listeners. Suppose you have a img  element inside a div element then and both have an event listener defined, then whose event listener should be called first? In case of event bubbling , the inner most elements event listener will be called first and it would be propagated out. So first the event listener of img will be called followed by the event listener of div element. In case of event capturing , the outer most elements event listener is called first followed by inner elements. So, in above example, div's event listener would be called first followed by inner most element that is img's event listener. The event propagation method can be selected by passing third optional boolean argument to addEventListener method of JS. The syntax is: addEventListner(event,event_h...

Twitter typehead.js basic example with token field.

A simple example for twitter typehead.js. The server should return an array of type: [ { name: "asas", value: "1234" }, { name: "asas", value: "121212" } ] Include following CSS and js: < link href = "http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel = "stylesheet" > < link href = "tokenfield-typeahead.css" rel = "stylesheet" > < link href = "bootstrap-tokenfield.css" rel = "stylesheet" >      < script src = "http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js" ></ script >      < script src = "http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js" ></ script >      < script src = "http://cdnjs.cloudflare.com/ajax/libs/typeahead.js/0.10.4/typeahead.bundle.min.js" ></ script >       < script src = "bootstrap...

How to call js code/file in Java?

Found this interesting part which could possible used in a number of ways like a rule engine. If I would have known this before might have considered this approach over Jexl, or would have evaluated for its performance compared to JEXL.  But for sure have other use cases like testing, data crawling, etc. Calling into Javascript scripts from Java code: Calling Java objects from a script is only half of the story: The Java scripting environment also provides the ability to invoke scripts from within Java code. Doing so just requires instantiating a  ScriptEngine , then loading the script in and evaluating it, as shown in Listing 5: Listing 5. Scripting on the Java platform import java.io.*; import javax.script.*; public class App {     public static void main(String[] args)     {         try         {             ScriptEngine engine =    ...

SmartGWT Calendar widget scroll to Current Time in month view

The calendar widget of smartgwt is quite powerful. But it lacks one important functionality, that is, scroll to the current time in case of month view. But this feature can easily be enabled by working on the Workday feature which smartGWT calendar widget supports. I wrote a simple function to achieve the same: private void scrollToCurrentTime() { int[] workDays = new int[1]; Date now = new Date(); workDays[0] = now.getDay(); int currentHour = now.getHours(); now.setHours(currentHour-1); String start = DateTimeFormat.getFormat( PredefinedFormat.TIME_SHORT).format(now); now.setHours(currentHour+7); String end = DateTimeFormat.getFormat( PredefinedFormat.TIME_SHORT).format(now); calendar.setWorkdays(workDays); calendar.setWorkdayStart(start); calendar.setWorkdayEnd(end); calendar.setScrollToWorkday(true); calendar.setShowWorkday(true); }

How to hide a html5/flash video, so that it does not reloads when its again made visible?

Have you ever faced a problem where once you 4hide an html5 or flash video by setting the visibility:none or simply using jquery $('#div-video-container').hide() and then doing a $('#div-video-container').show() actually reloading the video. Which means you would loose the position where you actually paused the video on hide. This behavior is seen mostly on firefox. I recently faced the problem, and after lots of googling also I never got a solution which can work across all the browsers and be simple. Then finally i devised my own solution. The simplest hack can be to lower the z-index of the div and introduce a newer div over it of higher z-index. Make sure this new div does'nt have a transparent background else the the video element would still be seen. I hope this would be helpful.

Node.js vs PHP response time metrics

I recently did a small Hello World Time Metric Test to see response time on Node.js and PHP and plotted the graph to see the performance difference between the two. PHP was hosted on a LAMP stack while node.js was downloaded via apt-get install. Instructions can be found on http://nodejs.org . The node.js script was simple hello world script: var http = require('http'); http.createServer(function (req, res) {   res.writeHead(200, {'Content-Type': 'text/plain'});   res.end('Hello World\n'); }).listen(1337, "127.0.0.1"); console.log('Server running at http://127.0.0.1:1337/'); While the PHP script used was: echo "Hello World"; ?> The tester script was: $j=0; while($j<100) { $time1=microtime(true); $i=0; while($i<10000) {     file_get_contents("http://localhost/hello.php"); $i++; } $time2=microtime(true); print($time2-$time1); print(' '); $j++; } Any gu...

XSS vulnerability

Cross-site scripting (XSS) is a type of computer security vulnerability typically found in web applications which enable malicious attackers to inject client-side script into web pages viewed by other users. An exploited cross-site scripting vulnerability can be used by attackers to bypass access controls such as the same origin policy. One common way to solve is: Ensure that parameters and user input are sanitized by doing the following: # Remove # Remove > input and replace with > # Remove ' input and replace with ' # Remove " input and replace with " # Remove ) input and replace with ) # Remove ( input and replace with (

How to send JSON object using JQUERY to PHP?

After struggling for hours and googling more, finally i succeeded in commincating over Json object. I will share the code: JS side: var datastring=JSON.stringify(obj); $.post('getmessage.php',{data:datastring},function(res){ alert("HIIII"+res); },"text"); }); php side: $data=json_decode(stripslashes($_REQUEST['data']),true); echo $data['page']; ?>

How to creata a form using javascript and submit it..

var myForm = document.createElement("form"); myForm.method="post" ; myForm.action = "./Actionpath"; var myInput = document.createElement("input") ; myInput.setAttribute("type","hidden"); myInput.setAttribute("name", "imput name") ; myInput.setAttribute("value", input value); myForm.appendChild(myInput) ; document.body.appendChild(myForm) ; myForm.submit() ; document.body.removeChild(myForm) ; o ok, I’ve run into this problem in the past where I’m using an onclick event to submit a form from a button control. When you click the button you get a nice little Javascript error stating: “this.form.submit is not a function” Bugger…wtf? This only seems to happen when you have a form element named “submit” already on your page, so the browser treats that “submit” element as an object which is of course NOT a function. I seem to run into this when I want 2 ways of submitting the fo...