Apache2: Smarter Virtual Host Configuration for Ubuntu 14.04

Configure Your site smartly:

There are only one step if you configure once (first configuration is little lengthy but not hard). This will be as simple as:

Create a directory for the site’s files. Something like:
/var/www/html/local/{your project directory} (for my case)

And you are done! Your URL will be http://your_project_directory.local

Let see how can we configure for this. There are only 2 step out from LAMP installation.

Enable vhost_alias_module

sudo a2enmodule vhost_alias_modul

Create a site configuration

sudo vim /etc/apache2/sites-available/local.conf

add this configuration in to this file and save the file

<VirtualHost *:80>
UseCanonicalName Off
ServerAlias *.local
VirtualDocumentRoot "/var/www/html/local/%-2"

ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined

Now enable site configuration

sudo a2ensites local.conf

Everything is done except dynamic DNS, I mean I want to use wild card like *.local. So that any domain .local will point on my host pc. dnsmask is the most easiest solution for this simple purpose. Install dnsmask and add wild card for your domain.

sudo apt-get install dnsmasq

Now edit its configuration:

sudo vim /etc/dnsmasq.conf

Add this line at the end of this file


Now restart dnsmasq

sudo service dnsmasq restart

Your configuration is done. This settings is only for *.local URLs.

To add a new site in local environment, just put your project directory in the /var/www/html/local/ and browse with URL like http://directoryname.local, cheers..

In VirtualDocumentRoot I used a dynamic URI to point the dynamic %-2 returns the 2nd part of the URL from the last.

You can use any pattern you like, Please refer here for more details of the URI pattern those are supported by Apache.

AngularJS: Sometime OrderBy does not work in ng-repeat

You must noticed that sometime OrderBy does not works, sometime works very nicely.

For example: if you have the data with following structure:

$scope.friends = [
      { name: 'John', phone: '555-1212', age: 10 },
      { name: 'Mary', phone: '555-9876', age: 19 },
      { name: 'Mike', phone: '555-4321', age: 21 },
      { name: 'Adam', phone: '555-5678', age: 35 },
      { name: 'Julie', phone: '555-8765', age: 29 }

Then it works if you code use the following code:

<tr ng-repeat="friend in friends | orderBy:'-age'">

But if your data structures changes a bit as follows:

$scope.peoples = [{
      'friend':{ name: 'John', phone: '555-1212', age: 10 },
      'relative':{ name: 'Mary', phone: '555-9876', age: 19 },
      'cousin':{ name: 'Mike', phone: '555-4321', age: 21 },
      'uncle':{ name: 'Adam', phone: '555-5678', age: 35 },
      'aunt':{ name: 'Julie', phone: '555-8765', age: 29 }


<tr ng-repeat="people in peoples | orderBy:'-age'">

Now, order by will not. This is because, previous data structure was an array and order by works fine on array. Now it is an Object. Order by does not works on Objects. So, first you have to make this objects to an array and then it will fine.

To make this object to an array we will use an filter. Following code will create an filter for throughout the module:

 ng.module('yourmodule').filter('toArray', function() {
  return function(obj, addKey) {
    if (!(obj instanceof Object)) {
      return obj;

    if (addKey === false) {
      return Object.values(obj);
    } else {
      return Object.keys(obj).map(function(key) {
        return Object.defineProperty(obj[key], '$key', {enumerable: false, value: key});

Now you just add this filter to html code:

    <tr ng-repeat="people in peoples | toArray | orderBy:'-age'">

😉 Order by will work like magic. Cheers!

View complete code in Plnkr.co

AngularJS: Add enter key to check/uncheck the check box

Sometimes clients want something different. We all know that if we check/uncheck the check box through keyboard then we have do it by space bar. But sometimes clients wants this through enter key in addition to the space bar specially for keyboard only user. So, this code can reduce your effort to write your own.

For AngularJS:

// Assume that your main module name is app, it can be anything you like.
var App = angular.module('app', []);

// Adding as directive.
App.directive('input', ['$interval', function($interval) {
    return {
      restrict: 'E', // It restricts that the directive will only be a HTML element (tag name), not an attribute.
      link: function(scope, elm, attr) {
        if (attr.type === 'checkbox') {
          elm.on('keypress', function(event) {
            var keyCode = (event.keyCode ? event.keyCode : event.which);
            if (keyCode === 13) {
              event.preventDefault(); // only when enter key is pressed.

Same thing on jQuery is pretty easy:

jQuery(document).ready(function() {
  jQuery('input:checkbox').keypress(function(event) {
    var keyCode = (event.keyCode ? event.keyCode : event.which);
    if (keyCode === 13) {
      event.stopPropagation(); // only when enter key is pressed.

Very Basics of Angular JS

Recent years was a bright year for JavaScript developers, many JavaScript frameworks were born. With the advent of these frameworks, it can be quite a pain for developers to choose one suitable framework. Today we will talk with another JavaScript framework, which is Angular JS. This is very basic level discussion to kick start the Angular JS SPA (Single Page Application) Development.

Angular JS claims itself as super heroic JavaScript framework. Angular enhances HTML for web apps. It has functionalities to ease the process of developing web apps. HTML was first intended to build dynamic web apps that are Angular. Angular is what HTML would have been if it were designed to build web apps.

Before dig deeper to Angular features, we want to let you know that Angular is brought to you by Google. At least this fact can give you assurance Angular comes from the right people you can trust.

A strong understanding of basic JavaScript will be required to use Angular. If you feel that you’re beginner, keep going, Angular is not necessarily for advanced developers, but you will be dealing with a lot of objects so you have to be familiar with object oriented paradigm in JavaScript.

Digging into Angular JS:

– Angular JS is such a powerful SPA framework which allows writing client side application without JS coding or JS knowledge.

  • Here is an example how a simple app can be built without having any JS code.

– Angular JS is a full featured SPA Framework. It has all that needs for a good SPA[Single Page Application].

– So, the Big Picture of the Angular JS is like follows:

– Now, digging more deeper-

  • Directives and Data Binding: Directives refers to a feature to extends the vocabulary of HTML, it also can be seen as a way to teach your browser new tricks . With directive feature, we can create new HTML vocabulary that the browser will understand what it means and what it should do. You will find here all directives: http://docs.angularjs.org/api/ng#directive

  • View & Controller: between view controller there is a term $scope. Scope is a glue between view and controller. We also can call it Dependency Injector.

– Controller doesn’t know about the view. So, when a view calls a controller, it injects the scope automatically.

– View can be a full body DOM or a particular div. Different div can be used as different view in same html. Here the scope is the div in which the controller has declared.

  • Module:

– In Big Picture of Angular JS we saw Module is the root of everything. For a single page only one module can be added, but module can add many other module inside it by mentioning the dependencies or other module.

– Here is how module is defined with and without dependency- [We call it Dependency Injection]

  • Routers: In a configuration we can define the router. Router takes the URL after a “#” and loads related views. View can be defined in different html file.

  • Factories: factories are similar to Data-Model. There are four things in Angular JS for manage data. These are Factory, Service, Provider, Value.

registerForRemoteNotificationTypes: is not supported in iOS 8.0 and later, so?

Some body must have faced the problem like me that the registerForRemoteNotificationTypes: doesn’t works on iOS 8 or later device. I found the solution and I think this is the better way to keep backwards compatibility and make workable the remote notification for iOS 8.0 and later versions if we go with this approach, it is working for my case and will hope work for you. Also pretty easy to understand.

So to register write this code in AppDelegate’s - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { method:

    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
        [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
             (UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert)];

Now you will get a confirmation dialog at the starting time. if you all this app for push notifications, then you will get the device token for notification service from following delegate:(if supports all the versions we have)

#pragma mark - Notification delegates
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
    NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSLog(@"content---%@", token);

If it fails for any reason like certification error or any other reason, following delegate will be called.

- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
    NSLog(@"Error %@", err);

So, now you have device token and you can do anything you like..

How to make a UITableView scroll to the text field and also prevent from the hiding by keyboard when text field is selected

Most of us faced some problem with UITextField is hidden by keyboard, I found a solution for my case, I hope it will also help you. My solution as follows. I am expecting that you already have a cell with UITextField. So on preparing the cell just keep the row index into the text field’s tag.

    cell.textField.tag = IndexPath.row;

Create an activeTextField, instance of UITextField with global scope as below:

    @interface EditViewController (){

        UITextField *activeTextField;


So, now you just copy paste my code at the end. And also don’t forget to add UITextFieldDelegate

    #pragma mark - TextField Delegation

    - (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{

        activeTextField = textField;

        return YES;

    - (void)textFieldDidEndEditing:(UITextField *)textField{

        activeTextField = nil;


Registers keyboard notifications

    #pragma mark - Keyboard Activity

    - (void)registerForKeyboardNotifications


        [[NSNotificationCenter defaultCenter] addObserver:self


                                                 name:UIKeyboardDidShowNotification object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self


                                                 name:UIKeyboardWillHideNotification object:nil];


Handles Keyboard Notifications:

Called when the UIKeyboardDidShowNotification is sent.

    - (void)keyboardWasShown:(NSNotification*)aNotification


        NSDictionary* info = [aNotification userInfo];

        CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

        UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);

        [self.tableView setContentInset:contentInsets];

        [self.tableView setScrollIndicatorInsets:contentInsets];

        NSIndexPath *currentRowIndex = [NSIndexPath indexPathForRow:activeTextField.tag inSection:0];

        [self.tableView scrollToRowAtIndexPath:currentRowIndex atScrollPosition:UITableViewScrollPositionTop animated:YES];


Called when the UIKeyboardWillHideNotification is sent

    - (void)keyboardWillBeHidden:(NSNotification*)aNotification


        UIEdgeInsets contentInsets = UIEdgeInsetsZero;

        [self.tableView setContentInset:contentInsets];

        [self.tableView setScrollIndicatorInsets:contentInsets];


Now one thing is left, Call the registerForKeyboardNotifications method in to ViewDidLoad method as follows:

    - (void)viewDidLoad {

        [super viewDidLoad];

        // Registering keyboard notification

        [self registerForKeyboardNotifications];

        // Your codes here...


You are done, hope your text fields will no longer hidden by the keyboard.

Tracking source URL with Google Analytic when redirecting by .htaccess

I got a situation like client have some URLs but the content or path doesn’t exists. So, clients need to redirect these URLs to other page. In addition he wanted to know, does the user came directly to that page or came through redirecting from those sources. So, I found a solution that worked for me and I liked to share it with you guys so that it solves your needs if your in the same situation. As the destination page already had the GA codes, I went through .htaccess solution. I just added two line codes in the .htaccess file as below: Consider http://yourdomain.com/abc.php is the source and http://yourdomain.com/xyz.php is the destination.

RewriteCond %{REQUEST_URI} ^/abc.php   
RewriteRule ^abc.php(.*)$ http://yourdomain.com/xyz.php?utm_source=redirects&amp;utm_medium=abc.php&amp;utm_campaign=301_Redirects [L,R=301]

So three things you need to add:

  1. utm_source=redirects
  2. utm_medium=abc.php (which is the source url)
  3. utm_campaign=301_Redirects

Now browse the source URL and you will be redirected to destination page. And then go to your GA account and see in real time view, you will found this URL is listed as redirect source.

I am open to answer any question…

Smarter Virtual Host Configuration on Windows

Sometimes our QA and Designer colleagues feels irritate when they need to setup some sites locally to test or fix design issues. Same thing for developers also. For setting up a new site we need to go through 4/5 steps. How about if we can reduce these steps into one?

Yeah, we can reduce these steps into one step. Just put your project folder maintaining an easy convention and you are done.

For example: you want to setup a site in your local machine with the following URL:
Then the folder structure will be
    --> domain

that’s it..

I found that Apache supports VirtualDocumentRoot, which give us some dynamic document root. Let, see how we can use this to achieve an smarter way to setup a site locally very easily. Before going ahead I just want to take a look on our OLD steps.

OLD Way: Setup a site for http://domain.local on your PC

  1. Create a directory for the site’s files.
  2. Create a line in hosts file for the domain, i.e. domain.local
  3. Add a few lines to my Apache conf file to configure the virtual host

    <VirtualHost *:80>
        ServerName domain.local
        DocumentRoot D:\Projects\domain.local
  4. Restart Apache

But the New and Smarter way is

  1. Create a directory for the site’s files. Something like:
    D:\Projects\local\domain (for my case)

And you are done..😉

Now, for achieving this we have to do some configuration level changes for once.

  1. Edit your hosts file to add *.local domain in to host entry as bellow:       localhost       *.local
    ::1             localhost

  2. Enable vhost_alias_module modules/mod_vhost_alias.so in httpd.conf file (Apache configuration file). This will add VirtualDocumentRoot feature in the Apache.
    • usually you will find this file in [installed folder]\apache\conf\httpd.conf.
    • in this file find the above line and remove the preceding “#”.
  3. Now, go to {installed folder}\apache\conf\extra\ and edit httpd-vhosts.conf file as follows:

    NameVirtualHost *:80

    # Adding folder permissions
    <Directory "D:\Projects\local\*">
        Options Indexes FollowSymLinks
        AllowOverride All
        Order allow,deny
        Allow from all
        Require local

    # Pointing folder for URLs.
    <VirtualHost *:80>
        UseCanonicalName Off     # This is a must.
        ServerAlias *.local
        VirtualDocumentRoot "D:\Projects\%-1\%-2"

  4. Restart your Apache service

So, Your configuration is done. This settings is only for .local URLs.

Now, to add a new site in local environment, just put your project folder in the local folder and browse with URL like http://{foldername}.local, cheers..

Here, ServerAlias *.local to limit to the .local URLs. You can add more pattern like ServerAlias *.local *.dev *.stg etc.

In VirtualDocumentRoot I used a dynamic URI to point the dynamic folder. The %-1 returns last part from the URLs (which is local for our case) and the %-2 returns the 2nd part of the URL from the last. I prefer this structure because this helps me when I want to point multiple URLs on a single folder. It can be for multi-site in Drupal CMS. For example: abc.xyz.local and aaa.xyz.local need to point on local\xyz folder.

You can use any pattern you like, Please refer here for more details of the URI pattern those are supported by Apache.

For any confusion or problem, please comment here or send me a message..

Caman JS – an amazing library for JS lovers

I found an amazing JS library for image processing. This is very effective JS but little slower. The specialty is it works in browser as well as with node JS. So you can make an image processing tool for Android/iOS by JS now. You will find more details on their site: http://camanjs.com/ but here I experimented myself for browser. Here is the simplest code example for learning the very basic in couple of minutes. You may love it.

Download from here.

ExtJS: Horizontal sliding style paging for long panel using jQuery

Here we will see Horizontal sliding style paging for long panel using jQuery. Though in Horizontal sliding style paging for long panel [Part-2] and Horizontal sliding style paging for long panel [Part-1] we saw sliding with having scroll bar as viewable. In this part we will see how we implement a Horizontal sliding style paging for long panel without scroll bar.

There must have some other way. But, using jQuery seems easy and efficient to me. You can have a look How to use jQuery with ExtJS. Because, here I will show just the codes I used.

In my previous tutorials I told that the inner contents (Grid panels for my case) is dynamically added. So i don’t know the exact width.

So what i have to do is:

  1. Calculate the window width
  2. Calculate how many grids can be showing per slide
  3. Shift the Left position to slide the Inner Grids

Now, lets start coding.

ExtJS view Settings:

    Ext.define('MyProj.view.AllPacksPanel', {
    extend: 'Ext.panel.Panel',
    alias: 'widget.allpackspanel',
    title: 'All Packs',
    layout: 'hbox',
    id: 'allpackspanel',

overflowX: 'scroll' has been removed, because default value is hidden.

And the buttons:

    dockedItems: [{
        xtype: 'toolbar',
        items: [
            text: '',
            iconCls: 'icon-page-prev',

            xtype : 'tbtext',
            text : 'Page 1 of 1',
            text: '',
            iconCls: 'icon-page-next',

You may have noticed all handler we have removed.

For jQuery add an anonymous function, which will protect inner codes from outer scope and we will be able to avoid conflict.

(function (jQuery) {
    //my codes will go here...

Now I will add some variable so that in future we can use less effort to modify anything.

    var prevEl = '#allpackspanel-page-prev-btnEl'; //next button id
    var nextEl = '#allpackspanel-page-next-btnEl'; //prev button id
    var pageNumberEl = '#allpackspanel-page-number'; //id for: in the middle of these 2 button page number shows.
    var showButtonEl = '#show-packs-btnEl'; // this button was used to load the grids inside the panel
    var gridEl = '.x-panel.x-grid'; //common grid classes
    var viewContainerEl;
    var viewContainerElId='#allpackspanel-body';  //parent panel body
    var viewableWidth;
    var totalInnerWidth;
    var innerViewEl;
    var innerViewElId='#allpackspanel-innerCt'; //inner div in the panel body
    var positionLeftX = 0;
    var elWidth = 300; //width for each grid
    var moveDelta = 5; // how much grid will be moved per slide
    var totalEl=0;  //totla grids
    var currPage = 1;
    var totalPage = 1;
    var moveFactor = parseInt(moveDelta * elWidth); //the exact pixel to move finally

Now adding button actions.
As contents are adding dynamically, we will use jQuery on() function to bind elements dynamically.

    //grid loading button action
    jQuery(document).on('click', showButtonEl, function(){
        currPage = 1;
    //next button action
    jQuery(document).on('click', nextEl, function(){
        if(++currPage <= totalPage){
            currPage = totalPage;
    //prev button action
    jQuery(document).on('click', prevEl, function(){
        if(--currPage > 0){
            currPage = 1;

We see here few functions (updateEl(), updateVars() and updateViewableArea()) which are still not defined. So lets define those.

    function updateEl() {
        //each time we need update the elements
        //because element may replaced with new one.
        //if you are sure then you can use only in loader button's action
        viewContainerEl = jQuery(viewContainerElId);
        innerViewEl = jQuery(innerViewElId);
    function updateVars() {
        totalEl = viewContainerEl.find(gridEl).length;
        viewableWidth = parseInt(viewContainerEl.width(),10);
        moveDelta = parseInt(viewableWidth / elWidth);
        totalPage = parseInt((totalEl / moveDelta),10);
        if(totalEl % moveDelta) totalPage++;

    function updateViewableArea(direction) {
        if (typeof direction == "undefined" ) 
            direction = 1;

        var prevPos = viewableWidth * direction;

        var show = 0;
        for(var i=0; i < totalEl; i++){
            if(i < (currPage * moveDelta) && i >= ((currPage - 1) * moveDelta)){
                    'left':(show * elWidth)+'px'
        jQuery(pageNumberEl).text('Page '+currPage+' of '+totalPage);

We are done. But, if the inner contents are grid panels then the hidden grids will miss something. Like header and footer buttons etc.

But if we show hide with the EXT object then it wont happened.

    var id = viewContainerEl.find('.x-panel.x-grid').eq(i).attr('id');

So lets change the code:

    function updateViewableArea(direction) {
        if (typeof direction == "undefined" ) 
            direction = 1;

        var prevPos = viewableWidth * direction;

        var show = 0;
        for(var i=0; i < totalEl; i++){
            var id = viewContainerEl.find('.x-panel.x-grid').eq(i).attr('id');
            if(i < (currPage * moveDelta) && i >= ((currPage - 1) * moveDelta)){
                    'left':(show * elWidth)+'px'
        jQuery(pageNumberEl).text('Page '+currPage+' of '+totalPage);

Now, we can see fully animated and functional Horizontal sliding style paging..

Please, feel free for any kind of suggestion or discussion….