Book Review #3 “Very good introduction into Apache Cordova”

Attached below the review of Werner Punz (a Web and Mobile Development Expert) about the “JavaScript Mobile Application Development” book:

JavaScript Mobile Application Development Book

JavaScript Mobile Application Development Book

Very good introduction into Apache Cordova
“This book is a very good introduction into Apache Cordova. It basically guides you from the basics to the API integration, then to the most common APIs. After that you get an overview on how to unit test the application and how to write your own plugins and in the end you will get a guide to the implementation of a complex Cordova app.
The only thing I personally found missing was in the IDE section a description on how to integrated Cordova in the Android Studio instead of Eclipse, since Eclipse is on its way out in the Android area of programming.”

Reference:

http://www.amazon.com/review/R19ORB0DCN16PA/

The book in Amazon:

http://www.amazon.com/JavaScript-Mobile-Application-Development-Hazem/dp/1783554177/

[JavaScript] Getting All Possible Permutations

One of the most interesting mathematical stuff is Permutation. A permutation is the act of re-arranging all the members of a set into some sequence or order, such that the order of selection always matters (unlike combination).

Assume that we have 3 balls (Red, Green and Blue). If we want all the possible permutation then we will have the following 6 possible permutation:

  • Red, Green, Blue.
  • Red, Blue, Green.
  • Green, Blue, Red.
  • Green, Red, Blue.
  • Blue, Red, Green.
  • Blue, Green, Red.

Mathematically, the number of permutations of n distinct objects is n factorial usually written as n!. Now, let’s write a simple function in JavaScript that gets the unique permutation for a set of objects.

var Util = function() {
};

Util.getPermuts = function(array, start, output) {
	if (start >= array.length) {
		var arr = array.slice(0); //clone the array		
		output.push(arr);
	} else {
		var i;
		
		for (i = start; i < array.length; ++i) {
			Util.swap(array, start, i);	
			Util.getPermuts(array, start + 1, output);	
			Util.swap(array, start, i);	
		}
	}
}

Util.getAllPossiblePermuts = function(array, output) {
	Util.getPermuts(array, 0, output);
}

Util.swap = function(array, from, to) {
	var tmp = array[from];
	array[from] = array[to];
	array[to] = tmp;
}

// Test API ...
var array = ['R', 'G', 'B'];
var output = [];

Util.getAllPossiblePermuts(array, output);
console.log(output);

As shown in Util.getPermuts, it takes three parameters as follows:
1. array parameter represents the array of objects that we have.
2. start parameter represents the current start index.
3. output parameter represents the array that holds all the possible arrays of permutations.

Util.getPermuts recursively swaps the array elements in order to get all the possible permutations of the input array.

The previous code covers permutation without repetition which means that we use every element that we have only once in every possible permutation.

What about if we want to get all the possible permutations with repetition. Assume that we have 4 blank papers and we would like to paint them with all the possible ways using Red, Green and Blue colors.

Can you write a JavaScript function that can get all the possible 4 papers’ paintings?

According to Permutation with repetition, all the possible 4 papers’ paintings with 3 colors can be calculated as (3 power 4) which equal to 81. The formula is very simple: n P(with repetition) r = n ^ k.

Now, let’s use recursion in order to get all the possible permutation with repetition.

var Util = function() {
};

Util.getRPermuts = function(array, size, initialStuff, output) {
	if (initialStuff.length >= size) {
		output.push(initialStuff);
	} else {
		var i;
		
		for (i = 0; i < array.length; ++i) {	
			Util.getRPermuts(array, size, initialStuff.concat(array[i]), output);
		}
	}
}

Util.getAllPossibleRPermuts = function(array, size, output) {
	Util.getRPermuts(array, size, [], output);
}

As shown in Util.getRPermuts, it takes four parameters as follows:
1. array parameter represents the array of objects (colors in our case) that we have.
2. size parameter represents the size of every permutation item.
3. initialStuff parameter represents a temp array that holds every possible permutation with repetition.
4. output parameter represents the array that holds all the possible arrays of permutation with repetition.

In order to know all the possible 4 papers’ paintings using the available 3 colors, you can call the permutation with repetition API simply as follows:

// Create the array of the possible 3 colors ...
var possibleColors = ['R', 'G', 'B'];
var output = [];
var papersNo = 4;

// get all the possible painting for the 4 papers that we have.
Util.getAllPossibleRPermuts(possibleColors, papersNo, output);
console.log(output);

In the console, you will find all the possible 81 permutation with repetition as follows:

[["R", "R", "R", "R"], ["R", "R", "R", "G"], ["R", "R", "R", "B"], ["R", "R", "G", "R"], ["R", "R", "G", "G"], ["R", "R", "G", "B"], ["R", "R", "B", "R"], ["R", "R", "B", "G"], ["R", "R", "B", "B"], ["R", "G", "R", "R"], ["R", "G", "R", "G"], ["R", "G", "R", "B"], ["R", "G", "G", "R"], ["R", "G", "G", "G"], ["R", "G", "G", "B"], ["R", "G", "B", "R"], ["R", "G", "B", "G"], ["R", "G", "B", "B"], ["R", "B", "R", "R"], ["R", "B", "R", "G"], ["R", "B", "R", "B"], ["R", "B", "G", "R"], ["R", "B", "G", "G"], ["R", "B", "G", "B"], ["R", "B", "B", "R"], ["R", "B", "B", "G"], ["R", "B", "B", "B"], ["G", "R", "R", "R"], ["G", "R", "R", "G"], ["G", "R", "R", "B"], ["G", "R", "G", "R"], ["G", "R", "G", "G"], ["G", "R", "G", "B"], ["G", "R", "B", "R"], ["G", "R", "B", "G"], ["G", "R", "B", "B"], ["G", "G", "R", "R"], ["G", "G", "R", "G"], ["G", "G", "R", "B"], ["G", "G", "G", "R"], ["G", "G", "G", "G"], ["G", "G", "G", "B"], ["G", "G", "B", "R"], ["G", "G", "B", "G"], ["G", "G", "B", "B"], ["G", "B", "R", "R"], ["G", "B", "R", "G"], ["G", "B", "R", "B"], ["G", "B", "G", "R"], ["G", "B", "G", "G"], ["G", "B", "G", "B"], ["G", "B", "B", "R"], ["G", "B", "B", "G"], ["G", "B", "B", "B"], ["B", "R", "R", "R"], ["B", "R", "R", "G"], ["B", "R", "R", "B"], ["B", "R", "G", "R"], ["B", "R", "G", "G"], ["B", "R", "G", "B"], ["B", "R", "B", "R"], ["B", "R", "B", "G"], ["B", "R", "B", "B"], ["B", "G", "R", "R"], ["B", "G", "R", "G"], ["B", "G", "R", "B"], ["B", "G", "G", "R"], ["B", "G", "G", "G"], ["B", "G", "G", "B"], ["B", "G", "B", "R"], ["B", "G", "B", "G"], ["B", "G", "B", "B"], ["B", "B", "R", "R"], ["B", "B", "R", "G"], ["B", "B", "R", "B"], ["B", "B", "G", "R"], ["B", "B", "G", "G"], ["B", "B", "G", "B"], ["B", "B", "B", "R"], ["B", "B", "B", "G"], ["B", "B", "B", "B"]]

Speaking in JavaLand Germany 2015

Speaker in JavaLand 2015

Speaker in JavaLand 2015

@Wednesday, March 25 04:00 PM, I will be speaking in JavaLand Germany conference (that will be held from 24 March to 26 March @Brühl, Germany) about “Developing Mobile Applications using JavaScript”. My session will be a practical one, I will discuss mobile apps development using JavaScript and Apache Cordova. My session will also include Apache Cordova Integration tips with jQuery mobile on the three popular mobile platforms (Android, iOS and Windows Phone 8).

There is a JavaScript quiz at the end of my session, the one who will be able to answer it correctly will have a free copy of my new JavaScript book:
Books

I hope it will be an interesting session for all the mobile development passionate :):
https://www.doag.org/konferenz/konferenzplaner/konferenzplaner_details.php?locS=0&id=483801&vid=491546

Personally, it is my first time to visit Brühl, Germany, beside enjoying technical stuff, I would like to visit some tourist places there, any suggestions are welcome :D?

I really wish to see all of you there in JavaLand Germany 2015!

[JavaScript] Getting All Possible Combinations

One of the most interesting mathematical stuff is Combination. A combination is a way of selecting members from a grouping, such that the order of selection does not matter (unlike permutation).

For example, assume that we have 6 balls (numbered from 1 to 6), and a person can select only 4 balls at a time.

Can you write a JavaScript function that can get all the possible 4 ball selections from the available 6 balls?

According to Combination, all the possible 4 ball selections from the 6 balls are (6 Choose 4) which equal to 15. The formula is very simple: n C r = n! / r! n-r!.

Now, let’s use recursion in order to get all the possible combinations.

var Util = function() {
};

Util.getCombinations = function(array, size, start, initialStuff, output) {
    if (initialStuff.length >= size) {
        output.push(initialStuff);
    } else {
        var i;
		
        for (i = start; i < array.length; ++i) {	
	    Util.getCombinations(array, size, i + 1, initialStuff.concat(array[i]), output);
        }
    }
}

Util.getAllPossibleCombinations = function(array, size, output) {
    Util.getCombinations(array, size, 0, [], output);
}

As shown in Util.getAllPossibleCombinations, it takes five parameters as follows:
1. array parameter represents the array of objects that we have.
2. size parameter represents the size of every selection from the array.
3. start parameter represents the current start index.
4. initialStuff parameter represents a temp array that holds every possible combination.
5. output parameter represents the array that holds all the possible arrays of combinations.

In order to know all the possible 4 balls selections from the available 6 balls, you can call the API simply as follows:

// Create an array that holds numbers from 1 ... 6.
var array = [];

for (var i = 1; i <= 6; ++i) {
    array[i - 1] = i;
}

var output = [];

// Select only 4 balls out of the 6 balls at a time ...
Util.getAllPossibleCombinations(array, 4, output);
console.log(output);

In the console, you will find all the possible 15 combinations as follows:

[[1, 2, 3, 4], [1, 2, 3, 5], [1, 2, 3, 6], [1, 2, 4, 5], [1, 2, 4, 6], [1, 2, 5, 6], [1, 3, 4, 5], [1, 3, 4, 6], [1, 3, 5, 6], [1, 4, 5, 6], [2, 3, 4, 5], [2, 3, 4, 6], [2, 3, 5, 6], [2, 4, 5, 6], [3, 4, 5, 6]]

Tip #2: Boosting Cordova’s jQuery Mobile Apps Performance

One of the common issues when you use jQuery Mobile with Apache Cordova in many of the platforms especially in the old versions Android platform is that you feel that the transitions between the app pages are slow.

The solution for this problem is to disable jQuery mobile transition effects as follows when the jQuery mobile is loaded as follows.

    $.mobile.defaultPageTransition   = 'none';
    $.mobile.defaultDialogTransition = 'none';

Disabling transition effects will dramatically boost your Cordova’s jQuery mobile app’s transition performance.

Do not believe people who say jQuery Mobile is slow with Apache Cordova.

Reference:

“JavaScript Mobile Application Development” Book:

Back from JMaghreb 2014

JMaghreb 2014
I just get back from JMaghreb 2014 that was held in Casablanca, Morocco 05-06 November 2014. The conference organization was fantastic and there were a lot of attendees in the conference sessions.
Picture1
I had the chance to present “Developing JavaScript Mobile Apps Using Apache Cordova” in 06 November, the session had many attendees and I was really amazed by the energy, enthusiasm, and responsiveness of the attendees during the session.
Picture2
Picture3
Picture3

The session went great and I was glad to give a copy of my “JavaScript Mobile Application Development” book to one of the attendees who answered a JavaScript quiz at the end of my session.
Books

I uploaded my session below:

JAX-RS + Cloudant in Bluemix as a service and Worklight App as a client

In the service side, I developed a very simple JAX-RS service which retrieve JSON documents of a Cloudant Database using ektrop over Bluemix.

Below is the JAX-RS service code:

package com.test.todos.service;

import java.util.ArrayList;
import java.util.List;

import javax.naming.InitialContext;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.ektorp.CouchDbConnector;
import org.ektorp.CouchDbInstance;

@Path("/todo")
public class TodoService {
    protected static CouchDbInstance _db;      
    
    static {
        try {
            _db = (CouchDbInstance) new InitialContext().lookup("couchdb/todos-cloudant");
        } catch (Exception e) {
            e.printStackTrace();
            
            //Handle error nicely here ...
        }
    }
    
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public List<Todo> getAllTodos() {
        List<Todo> todos = new ArrayList<>();

        try {            
            CouchDbConnector dbc = _db.createConnector("todos_db", false);

            List<String> ids = dbc.getAllDocIds();

            for (String id : ids) {
                Todo todo = dbc.get(Todo.class, id);

                todos.add(todo);
            }
        } catch (Exception e) {
            todos = new ArrayList<>();
            e.printStackTrace();
            //Handle error nicely here ...
        }

        return todos;
    }
    
    static class Todo {
        String _id;
        String _rev;
        String title;
        String description;
        
        public Todo() {
        }        
        
        public Todo(String id, String title, String description) {
            super();
            
            this._id = id;
            this.title = title;
            this.description = description;
        }
        
        public String get_id() {
            return _id;
        }

        public void set_id(String _id) {
            this._id = _id;
        }

        public String get_rev() {
            return _rev;
        }
        public void set_rev(String _rev) {
            this._rev = _rev;
        }

        public String getTitle() {
            return title;
        }
        public void setTitle(String title) {
            this.title = title;
        }
        
        public String getDescription() {
            return description;
        }
        public void setDescription(String description) {
            this.description = description;
        }
    }
}

As you notice here, the Cloudant DB connector resource name follows "couchdb/[service_name]" naming which is ("couchdb/todos-cloudant" in our case). Note that all of the Cloudant DB connector resources have the prefix "couchdb/". _db connector variable is used to access the Cloudant Database which is created in Bluemix as shown below.
Bluemix config

As you see we have a Liberty for Java app called ("todos") and a Cloudant Database service which is bound to it. Do not forget to make sure your Cloudant service name matches the last part of the Cloudant DB connector name after “/”.

In order to allow the service to be accessed using Ajax without facing cross domain boundaries issues from the Worklight mobile client, I created a simple Filter servlet that wraps the JSON response in a JSONP format as shown here:
https://github.com/hazems/bluemix-java-cloudant-worklight-sample/blob/master/todos/src/com/test/todos/filter/JSONPRequestFilter.java

Finally, in order to deploy our WAR file, just do the following:
1. Make sure to install Cloud Foundry CLI from https://github.com/cloudfoundry/cli.

2. After this, type the following cf login command as follows:

cmd> cf login

3. You will be introduced to the API endpoint prompt then enter "https://api.ng.bluemix.net" and your email and password as shown follows:

API endpoint> https://api.ng.bluemix.net

Email> [email protected]
Password> yourPassword

4. After this, you can go ahead and install our WAR as follows:

cmd> cf push <unique_app_name> -m 512M -p <path_to_your_war_file> 

which is in our case:

cmd> cf push todos -m 512M -p todos.war

5. Finally, you can access the working application using simply:

[APP_URL]/todo

In the Worklight project, a call to the TODO service is done using jQuery $.ajax as follows to get the list of TODOs as follows:

$.ajax({
	url: "http://hs-todos.mybluemix.net/todo",
	jsonp: "callback",
	dataType: "jsonp", 
	success: function(todos) {
	    //Display TODOs here ...
	},
	error: function(jqXHR, textStatus, errorThrown) {
	    console.log("An error occurs");            	
	}
});  

The final result of the WL project in iPhone is displayed as shown below:
iPhone screenshot

Finally, it worth mentioning that you can directly call Cloudant from your JavaScript client, Cloudant offers a powerful REST API over the database as indicated in the links below:
https://docs.cloudant.com/api/documents.html#crud-operations-on-documents
https://docs.cloudant.com/api/index.html

The mentioned example above introduces JAX-RS with Cloudant to show you how you can use them together with Bluemix and to give you the ability to decouple the REST client JavaScript code from the underlying Cloudant Database structure which will give you the ability to change Cloudant DB JSON structure in the future without affecting your REST API clients code.

I placed the working sample (JAX RS project and Worklight project) in GitHub for reference:
https://github.com/hazems/bluemix-java-cloudant-worklight-sample

Enjoy!

Speaking in ApacheCon North America 2014

ApacheCon Conference
@Monday, April 7 4:00 PM, I will be speaking in ApacheCon North America conference (that will be held from 07 April to 09 April @Denver, USA) about “Developing Native mobile applications using JavaScript”. My session will be a practical one, I will discuss how to develop native mobile applications using JavaScript and Apache Cordova. I hope it will be an interesting session for all the mobile development passionates :):
http://apacheconnorthamerica2014.sched.org/speaker/hazems

Personally, it is my first time to visit Denver, beside enjoying technical stuff, I would like to visit some tourist places there, any suggestions are welcome :D?

I really wish to see all of you there in ApacheCon North America 2014!

Speaking in Geecon 2014

Geecon
I will be speaking in Geecon conference (From 14 May to 16 May @Krakow, Poland) about “Jasmine Automated Tests for JavaScript”. My session will be a practical one, I will discuss how to develop unit tests for the JavaScript code of the applications using Jasmine as a powerful descriptive JavaScript unit testing tool and how to “automate” running Jasmine tests on the web browsers. The session also discusses how to generate Jasmine reports from the build management tools:
http://2014.geecon.org/speakers/hazem-saleh

Personally, it is my first time to visit Poland, beside enjoying technical stuff, I would like to visit some tourist places there, any suggestions are welcome 🙂 ?

I really wish to see all of you there in Geecon Poland 2014!

JavaScript Quiz #12

Assume that we have the following short JavaScript code:

<script>
    var number = 50;
    var obj = {
        number: 60,
        getNum: function () {
	    var number = 70;
	    return this.number;
	}
    }; 

    alert(obj.getNum());
    alert(obj.getNum.call());
    alert(obj.getNum.call({number:20}));
</script> 

Will this code succeed or fail? and if it succeeds, what is the output of the alerts?

Read the complete answer