Showing posts with label Coding practises/Programming. Show all posts
Showing posts with label Coding practises/Programming. Show all posts

HTML5 Client side Image puzzle

Posted: Wednesday, September 12, 2012 by Unknown in Labels:
0

As part of js13kGames competition i developed Client side Image puzzle game.

Game details:- 

User will upload an image of any pixel ratio. The uploaded image will be turned into puzzle. The puzzle will be a 4x4 matrix of jumbled tiles with one missed position. User will have to re-arrange the tiles into the image which was originally uploaded.

Would like to highlight some of the cool stuff that i used.

HTML5 File API
- Uploaded image is not sent to server rather HTML5 File API is used to set the users image to div background.

CSS3 background-size property
- User will upload image of any pixel ratio but the game needs only 500x500 image. CSS3 "background-size" is used to scale the image.

CSS3 scale property
- Legally movable tile is highlighted. Again thanks to CSS3, "scale" property is used  to highlight the legally movable tile on mouse hover.

Drag/Tap (Desktop/Mobile)
- To make sure drag works in both desktop and mobile browsers, I developed simple Drag library which makes use of mouse & touch events.

Code Modularity
- The code is very well distributed and spread across model,controller & view scopes under the main scope "slider". window.scope is the main variable which comprises the whole game.

And here is the entry link http://js13kgames.com/entries/image-puzzle/.

Future enhancements will be tracked here https://github.com/polavenki/HTML5-Client-side-Image-puzzle

Please stop there and play the game and don't forget to like the game too if you really like it :) :)

Welcome your feedback.

Last but not least great thanks to js13KGames for conducting it. Nice leanings !!!

Cheers!!!
Peda Venkateswarlu Pola

HTML5 Webworker best practices

Posted: Saturday, August 18, 2012 by Unknown in Labels:
0


Recently i explored HTML5 web workers and this caught my interest. Am very much excited to use it in performing heavy computation tasks in Javascript. Webworkers really smashes the single thread bottle neck problem in Javascript to some extent. Would like to share few thoughts on how i organized my code base with respect to my requirements.

Requirement 1:-

I had a hard requirement to have frequent communication between the page where the worker is spawned and the worker where all of my business logic resides. Due to which i had to call different functions multiple times to and fro.

So i don't want to bloat up the "worker.onmessage & self.onmessage" callbacks in both parent page and worker with lot of if..else with some conditions.

Here is what i come up with some smart approach where i defined the data structure something like below

{"cmd" : "func_call" , "scope" : ["add", "Controller","task1"],"params" : [1,2]}

If the command is func_call then i will fetch function object specified in the scope array right staring from the "self" as base scope object and is called with the respective params given in the array. In the below code you can find function "callFunction" which takes scope and params arrays and calls respective function with necessary params. Please refer to "worker.onmessage & self.onmessage" callbacks in the below sample code for the usage.

Requirement 2:-

I don't want to mess up my business logic JS files with the web worker specific code because these might be used by non worker application.

"importScirpts" is very helpful to accomplish it.

importScripts.apply(self,["task1.js","task2.js"]); // Assuming task1.js , task2.js are business logic files

Requirement 3:-

I too had to send too much JSON data with deep hierarchy in it between base page & worker. Even though "postMessage" inbuilt supports sending JSON objects in it. I found that sending big JSON's with too much hierarchy in it is causing some problems in webkit and in the receiver side it is coming as empty string.

I suggest to send the JSON data by manually stringifying it.
worker.postMessage(JSON.stringify({"a":{"b":"c"}}));

Requirement 4:-

If we try to load the worker js files using file:// protocol for testing purpose then it will end up with "Uncaught Error: SECURITY_ERR: DOM Exception". You can avoid it by opening chrome.exe with command line param --allow-file-access-from-files

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --allow-file-access-from-files

Below is the sample example alternatively you can download the code from my github account here Worker-Best-Practices
 
index.html - Base page where the web-worker is spawned
myTaskWorker.js - Worker file
task1.js,task2.js - Contains business logic.


index.html

<html>
<head>
<script>

var loggerDiv;
var postToWorker = function(worker , data){
worker.postMessage(JSON.stringify(data));
};

var callFunction = function(funcScope , params){
for(var i =funcScope.length - 1  , funcObj = self; i>=0 ; i-- ){
if(funcObj) funcObj = funcObj[funcScope[i]];
}
if(typeof funcObj === "function") return funcObj.apply(this , params);
};

var logMessage = function(msg){
loggerDiv.innerHTML+=msg+" < br/>";
};

var worker = new Worker("./js/myTaskWorker.js"),
jsFiles = ["./task1.js","./task2.js"];

worker.onmessage = function(event) {
var instruction = event.data;
instruction = JSON.parse(instruction);

if(instruction["cmd"]==="func_call"){ // Worker trying to talk to function in base page
callFunction(instruction["scope"] , instruction["params"]);
}
 
};

worker.onerror = function(e){
console.log("Exception in Worker : "+e.message);
};


var onPageLoad = function(e){
loggerDiv = document.getElementById("log");
postToWorker(worker,{"cmd" : "start" , "data" : jsFiles}); // Start the worker.

postToWorker(worker,{"cmd" : "func_call" , "scope" : ["add", "Controller","task1"],"params" : [1,2]}); // Calls function directly in worker task1.Controller.getInfo()
postToWorker(worker,{"cmd" : "func_call" , "scope" : ["multiply", "Controller","task2"],"params" : [3,4]}); // Calls function directly in worker task1.Controller.getInfo()

}
</script>
</head>
<body onLoad="onPageLoad();">
<div id="log"> </div>
</body>
</html>

myTaskWorker.js

var postToParent = function(data){
self.postMessage(JSON.stringify(data));
};


var callFunction = function(funcScope , params){
for(var i =funcScope.length - 1  , funcObj = self; i>=0 ; i-- ){
if(funcObj) funcObj = funcObj[funcScope[i]];  
}
if(typeof funcObj === "function") return funcObj.apply(this , params);
};
    
self.onmessage = function(event) {
var instruction = event.data;
instruction = JSON.parse(instruction);
if(instruction["cmd"]==="start"){
importScripts.apply(self,instruction["data"]);
postToParent({"cmd" : "func_call" , "scope" : ["logMessage"],"params" : ["Worker establishment done"]});
}else if(instruction["cmd"]==="func_call"){ // Parent page trying to call worker function
try{
var retValue = callFunction(instruction["scope"] , instruction["params"]),
scope = instruction["scope"].reverse(),
params = instruction["params"];
postToParent({"cmd" : "func_call" , "scope" : ["logMessage"],"params" : ["Value for "+scope.join(".")+" for params "+params.join(",")+" = "+retValue]});
}catch(err){
}
}
};

task1.js

(function(w){
var task1 = {};
task1.Controller = {};
task1.Controller.add = function(a,b){
return a+b;
};
w.task1 = task1;
})(self);

task2.js

(function(w){
var task2 = {};
task2.Controller = {};
task2.Controller.multiply = function(a,b){
return a*b;
};
w.task2 = task2;
})(self);

Cheers!!! Hope you find it useful. 

Google IO 2012 - The Web can do That?

Posted: Saturday, June 30, 2012 by Unknown in Labels:
0

A very wonderful session about future of the WEB. Rapid growth and very great to see WEB having most of the native capabilities. You can find the slides here. Can't wait to play with these things!!


Chrome document.title issue

Posted: Tuesday, June 12, 2012 by Unknown in Labels:
0

We generally rotate the page title for the sake of notifications and once the user gains focus of the concerned tab we reset the page title to old one.

This works out mostly in all browsers but in chrome there is a small problem.

Focus gain / lost of chrome browser works fine but there is a problem in focus gain / lost browser tab. In case of browser tab focus gain / lost, Chrome hides the whole browser tab DOM as the tab is not visible to the user and redraws whole DOM as soon as the tab gains focus. I would say this is really a great performance technique.

But the problem comes here only, as the document.title is part of DOM and it is redrawing what ever we set from Javascript in the onfocus listener gets overrides.

As a hack of this we could reset the title in asynch manner something like below,

window.onfocus = function(){

setTimeOut(function(){
document.title = your_title
},200) ;

}
Note : - If you still face the problem even with this approach also, then better increase the title rotation speed to 1-2 sec.
Enhanced by Zemanta

Responsive web design

Posted: Thursday, June 7, 2012 by Unknown in Labels:
0

Responsive web design allows users across a broad range of devices and browsers will have access to a single source of content, laid out so as to be easy to read and navigate with a minimum of resizing, panning, and scrolling.

We generally accomplish it using CSS3 media queries. Found below interesting article which makes use of Javascirpt API's to accomplish it.
https://hacks.mozilla.org/2012/06/using-window-matchmedia-to-do-media-queries-in-javascript/?utm_source=html5weekly&utm_medium=email

Enhanced by Zemanta

Front end development Vs server side development

Posted: Saturday, May 12, 2012 by Unknown in Labels:
0

I think today's most of the front end developers are so called yesterdays server side developers.
In fact, it happens with me. :)

I took lot of interviews on front end position, most of them are had to work on front end. I come across very few pure front end profiles.

I would say, every developer should be very cautious towards the below distinction of both developments.


Server side : - Both development & the environment that it runs is in your hand.
Client side  : - Only development is in your hand but the environment that it runs is on your users hands.

So, in server side as the environment is in our hand, we can scale the machines to any extent based on the complexity of the app. Hence we can do multi threading , optimum utilization of CPU. The goal is to how max we can make use of machines to get our things done.

But in client side, the environment varies from one user to user.
Some might be in lower end machines/ browsers and some might be in high end machines / browsers.
We don't know what other heavy apps are loaded in the other tabs of the user browser.
More over, in client side Responsive UI matters rather than how much of work is being done.
So never try to flood the browser with heavy tasks. Always suggested to have some event manger which takes care of jobs to be done one by one using setTimeouts.

Last but not least, Just keep in mind that in client side development "Slow and steady wins the race".

Happy development...
Cheers!!!!

Clan of browser internals resources

Posted: Sunday, April 15, 2012 by Unknown in Labels:
0

I think every Javascript/html developer should have a look at it. Very nice collection of resources about browser internals..
Round-up of Web Browser Internals Resources

Cross tab communication with in a browser

Posted: Wednesday, January 4, 2012 by Unknown in Labels:
4

I wonder in this fast pace browser war, why not browsers provide native cross tab communication something like

window.getMyDomainBrowserTabs() -> returns array of windows

Once we get the array of window objects of all browser tabs which hold webpages severed from my domain, Using HTML5 window.postMessage we can communicate with all the browser tabs using its respective window object.

Though we accomplish it using localStorage, cookie polling..etc but obviously native is more reliable.

Hope to see this kind of native support in future

Chrome dev tools Auto save

Posted: Sunday, December 18, 2011 by Unknown in Labels:
0

Auto-saving CSS And JavaScript Changes Locally From The Chrome Developer Tools.
Pretty cool stuff, saves lot of development time.

Chrome DevTools AutoSave (HD) from Addy Osmani on Vimeo.

Javascript performance

Posted: Tuesday, November 1, 2011 by Unknown in Labels:
0

Very simple things but yields greater performance.

Native apps in browser

Posted: Saturday, September 17, 2011 by Unknown in Labels:
0

We are moving towards a world where desktop and web based applications merge. Where the term personal computer doesn't just mean desktops but also includes mobile devices. Where applications and data belong to the cloud and can move from one device to another.

IMO, the credit for merging desktop and web based applications goes to Google and the credit for creating the 'personal devices' market and providing a common way to access data and applications across these devices goes to Apple.

Here is the Chrome latest release where we can run c/c++ apps inside browser.

Very cool stuff!!!

Javascript Memory leaks detection

Posted: Tuesday, August 30, 2011 by Unknown in Labels:
0

I have spent enough time in finding memory leak detection tool and explored few tools such as sIEve, Drip, Software Verification Javascript memory observer, IEMemoryleakDetector....etc.

Unfortunately i could not find them helpful to me. After further investigation i realized that browser system process private bytes consumption is the best way to identify if the app is leaking memory or not.

I used processexplorer.exe to monitor private bytes of a process but here there is no option to record and play the memory consumption.

One of my earlier posts will be useful in recording private bytes of any windows system process.

How browsers work

Posted: Sunday, August 21, 2011 by Unknown in Labels:
2

I have been searching for an article about the internals of the browser for so many days. At last i found it here.

Very interesting. Go through it and enrich your self :)

http://www.html5rocks.com/en/tutorials/internals/howbrowserswork/

Record & Play windows system process memory consumption

Posted: Friday, August 19, 2011 by Unknown in Labels:
2

I don't find any tool which can be used for recording windows system process memory and used for later review.

There are some tools like process explorer but these are live it won't allow us to record the memory graph. So i decided to write java client which will poll periodically using DOS command WMIC and get the private bytes of a system process.


Usage :-

Paste the below code and put in MemoryMonitor.java

javac MemoryMonitor.java
java MemoryMonitor process_name poll_interval test_duration file

java MemoryMonitor firefox.exe 5 60 d:\\test.csv

So ideally, test.csv contains private bytes data of all intervals later you can use this file for drawing graphs.


Cheers!!!!!!!!!!

Here is the program code:-


import java.awt.Toolkit;
import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;


//java MemoryMonitor firefox.exe 5 60 d:\\test.csv

public class MemoryMonitor {

public String PROCESS_NAME = "eclipse.exe";
public int TIME_INTERVAL = 5; // in seconds
public int TOTAL_TEST_TIME = 60; // in seconds
public String DESTINATION_FLE = "d:\\memory_usage.csv";

Toolkit toolkit;

Timer timer;
Timer timer1;
List memoryList;

public MemoryMonitor(String args[]){
PROCESS_NAME = args[0] ; TIME_INTERVAL = Integer.parseInt(args[1]) ; TOTAL_TEST_TIME = Integer.parseInt(args[2]) ; DESTINATION_FLE = args[3];
memoryList = new ArrayList();
toolkit = Toolkit.getDefaultToolkit();
timer = new Timer();
timer1 = new Timer();
timer1.schedule(new ExitTimerTask(), TOTAL_TEST_TIME * 1000);
scheduleTimer();
}

public void scheduleTimer(){
getMemoryDetails();
timer.schedule(new MemoryDetailsTask(), TIME_INTERVAL * 1000);
}

public void getMemoryDetails(){
try {
Process proc = Runtime.getRuntime().exec("WMIC PROCESS where Caption=\""+PROCESS_NAME+"\" get PageFileUsage");
InputStream procOutput = proc.getInputStream();
String value = readInputStreamAsString(procOutput);
String array[] = value.split("\n");
double privateBytesValue = 0;
for(int i = 1 ; i < array.length ; i++){
if(array[i].trim().length()>0){
String privateBytes = array[i].substring(0, array[i].indexOf(" "));
privateBytesValue+= Double.parseDouble(privateBytes) / 1024;
}
}
System.out.println(privateBytesValue);
memoryList.add(privateBytesValue);
} catch (Exception e) {
System.out.println("Error occured");
e.printStackTrace();
System.exit(0);
}
}

public String join(List list, String conjunction)
{
StringBuilder sb = new StringBuilder();
boolean first = true;
for (Object item : list)
{
if (first)
first = false;
else
sb.append(conjunction);
sb.append(item);
}
return sb.toString();
}

public String readInputStreamAsString(InputStream in) throws IOException {

BufferedInputStream bis = new BufferedInputStream(in);
ByteArrayOutputStream buf = new ByteArrayOutputStream();
int result = bis.read();
while (result != -1) {
byte b = (byte)result;
buf.write(b);
result = bis.read();
}
return buf.toString();
}

class MemoryDetailsTask extends TimerTask {
public void run() {
getMemoryDetails();
scheduleTimer();
}
}

class ExitTimerTask extends TimerTask {
public void run() {
try {
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(DESTINATION_FLE),"UTF8"));
out.write(join(memoryList,","));
out.close();
System.out.println("Please find this file for the report "+DESTINATION_FLE);
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("Not able to write to the file "+DESTINATION_FLE);
e.printStackTrace();
};
System.exit(0);
}
}

public static void main(String args[]) {
new MemoryMonitor(args);
}

}

Web hacking techniques

Posted: Sunday, July 31, 2011 by Unknown in Labels:
0

Make use of Javascript wisely

Posted: Saturday, June 18, 2011 by Unknown in Labels:
0

In javascript, We can write programs in very optimized manner as we can send functions as arguments or as return values. Here is a small snippet of code where we can avoid repeat work.

function addHandler(elem, event, handler){
if(elem.addEventListener){ // DOM2
addHandler = function(elem, event, handler){
elem.addEventListener(event, handler, false);
}
}else{ // IE
addHandler = function(elem, event, handler){
elem.attachEvent("on" + event, handler);
}
}

addHandler(elem, event, handler);

During addHandler fist call the function definition varied.

Enhanced by Zemanta

Learn javascript from Jquery source

Posted: Saturday, February 19, 2011 by Unknown in Labels:
0

I hope you will really enjoy following video and will get to know new way of javascript coding from Jquery source.

Paul Irish : 10 Things I Learned from the jQuery Source from yayQuery on Vimeo.


Enhanced by Zemanta

Reflection in programming

Posted: by Unknown in Labels:
0

Generally we might need to modify the structure and behaviour of a program at runtime
(or )
we have to call a method of a class but we will get class name and method at runtime only. I mean during compile time we dont know what to use.

In these type of scnerios we can opt for reflection style of programming. I will show you sample program how to use in different languages.

Java:-
// No Reflection
new Foo().hello();
// After Reflection
Class cls = Class.forName("Foo");
cls.getMethod("hello", null).invoke(cls.newInstance(), null);

Javascript:-
// No Reflection
new Foo().hello()
// After Reflection
new (eval('Foo'))()['hello']()

Python:-
# No Reflection
Foo().hello()
# After Reflection
getattr(globals()['Foo'](), 'hello')()

Enhanced by Zemanta

Javascript memory leaks

Posted: Wednesday, February 9, 2011 by Unknown in Labels:
0

Javascript memory leaks especially in IE during removal of any DOM element (or) setting innnerHTML property. During those actions we should explicitly set "null" to their event handler's property. Have a look at "purge" function in the following link.

Source:- http://javascript.crockford.com/memory/leak.html

Enhanced by Zemanta

jwebsocket - Java/Javascript bidirectional communication

Posted: Wednesday, January 26, 2011 by Unknown in Labels:
0

In my last post i wrote about HTML5 websocket. As i dig into it i found jwebsocket.

Here is my observation:-

Pros:-

1) jWebSocket is a pure Java/JavaScript high speed bidirectional communication solution for the Web - secure, reliable and fast.
2) Make use of websockets if the browser does not support this then it will fallback to flashbridge.
3) Standalone jwebsocket server is provided. You can even add jwebsocket capabilities to existing web servers like jetty,tomcat..etc.
4) Client side plug-in is available so that you can think about only on application logic.
5) Can be used in different ways like Chat, Steaming, RPC, Shared object, Shared canvas. Lot of demos are there in the site.

Cons:-

1) What if flash crashed because of some other application in the browser.
2) Could have provided long polling too as another fallback option.
3) Need to support SSL for all browsers.
4) Could have provided some tool to perform load/stress tests. Since it is not http communication we can not perform load tests using Jmeter..etc.

Finally it is pretty awesome and very good. I am exploring it. If anyone of you using it please let me know about its performance.

Enhanced by Zemanta