Tuesday 27 January 2015

Populating nested array data into table using ng-repeat.

Today working on nested json data I thought of trying to populate data into table using ng-repeat, something kind of nested ng-repeat, I am not finding any proper word for it. So it happened like this. I have created one array having to fields Name and Children, where children consists of another child array having gain 2 fields, Name and Age. So I have use 2 nested type ng-repeat, outer one parsing the parent array while inner ng-repeat parsing inner child array. So here is the code and I have not put it into separate script and included everything into one single HTML page.

<!DOCTYPE html>
<html data-ng-app="app">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Transclude example</title>
    <style>

        li 
       {
        list-style-type:none;   

        }
    </style>
    <script src="https://code.angularjs.org/1.0.8/angular.js"></script>
    <script>

      var app = angular.module('app', []);
      app.controller('MainCtrl', function($scope) {
      $scope.mydata = [
        {Name:'Smith',Children:[
        {Name:'Max',Age:'5'},
        {Name:'Mini',Age:'3'},
        {Name:'Jango',Age:'4'}]
        },
        {Name:'Jacko',Children:[
        {Name:'Alia',Age:'4'},
        {Name:'Alexa',Age:'3'},
        {Name:'Pinto',Age:'7'}]
        },
        {Name:'Patrick',Children: [
        {Name:'Blanc',Age:'9'},
        {Name:'Minova',Age:'13'},
        {Name:'Jude',Age:'14'}]
        },
        {Name:'Julia',Children:[
        {Name:'Mama',Age:'2'},
        {Name:'Maggi',Age:'11'},
        {Name:'Troy',Age:'12'}]
        }
        ];
    });
   </script>
  </head>

  <body data-ng-controller="MainCtrl">
    <table border=1>
    <tr ng-repeat="data in mydata">
    <th>{{data.Name}}</th>
    <td ng-repeat="dt in data.Children">{{dt.Name}}</td><td>{{dt.Age}}</td>     
    </tr>
    </table>
  </body>
</html>

AngularJS Transclude example
{{data.Name}} {{dt.Name}}{{dt.Age}}

Populating list with nested json data using ng-repeat

Today working on nested json data I thought of trying to populate data into list tag using ng-repeat, something kind of nested ng-repeat, I am not finding any proper word for it. So it happened like this. I have created one array having to fields Name and Children, where children consists of another child array having gain 2 fields, Name and Age. So I have use 2 nested type ng-repeat, outer one parsing the parent array while inner ng-repeat parsing inner child array. So here is the code and I have not put it into separate script and included everything into one single HTML page.

<!DOCTYPE html>
<html data-ng-app="app">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Transclude example</title>
    <style>

        li 
       {
        list-style-type:none;   

        }
    </style>
    <script src="https://code.angularjs.org/1.0.8/angular.js"></script>
    <script>

      var app = angular.module('app', []);
      app.controller('MainCtrl', function($scope) {
      $scope.mydata = [
        {Name:'Smith',Children:[
        {Name:'Max',Age:'5'},
        {Name:'Mini',Age:'3'},
        {Name:'Jango',Age:'4'}]
        },
        {Name:'Jacko',Children:[
        {Name:'Alia',Age:'4'},
        {Name:'Alexa',Age:'3'},
        {Name:'Pinto',Age:'7'}]
        },
        {Name:'Patrick',Children: [
        {Name:'Blanc',Age:'9'},
        {Name:'Minova',Age:'13'},
        {Name:'Jude',Age:'14'}]
        },
        {Name:'Julia',Children:[
        {Name:'Mama',Age:'2'},
        {Name:'Maggi',Age:'11'},
        {Name:'Troy',Age:'12'}]
        }
        ];
    });
   </script>
  </head>

  <body data-ng-controller="MainCtrl">
    <ul ng-repeat="data in mydata">
    <li>{{data.Name}}</li>
    <li ng-repeat="dt in data.Children">  {{dt.Name}} - {{dt.Age}}</li>
    </ul>
  </body>
</html>

AngularJS Transclude example
  • {{data.Name}}
  • {{dt.Name}} - {{dt.Age}}

Using transclude in AngularJS


 

It's actually not possible to define transclude right here now but all I can say is that it is something like appending inner element of custom directive. Here as you can see there is a custom element called button-directive and one span element inside it. And in the script on the directive declaration you can see one addition transclude:true, if this is made to false, span tag will not be included or precisely to say not shown inside the button. If the transclude is set to false button caption will be Where is the mouse, but if it is set to true then 'Lets find it' will be included.



<!DOCTYPE html>
<html data-ng-app="app">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Transclude example</title>
    <link href="style.css" rel="stylesheet" />
    <script src="https://code.angularjs.org/1.0.8/angular.js"></script>
    <script >
       var app = angular.module('app', []);

      app.controller('MainCtrl', function($scope) {
         $scope.name = 'World';
     })
     .directive('buttonDirective',function() {
      return {
      restrict: 'AE',
      transclude:true,
      template:'<button ng-transclude class="btn btn-primary" type="button">' +
      'Where is the mouse</button>'
       }
     })
   </script>
  </head>

  <body data-ng-controller="MainCtrl">
    <button-directive>
      <span class="innertext">Let's find it</span>
    </button-directive>
    <p>Hello {{name}}!</p>
  </body>

</html>

Sunday 25 January 2015

Binding element with event listener in custom directive - AngularJS

This program actually started with an intention to explain custom directive and is well going on changing inner html during loading of the page, suddenly I thought that why not bind some event listener to the element with custom directive, so I came up with 2 event listener, mouseenter and mouseleave. Here I am writing the code,  Assuming the reader is already aware of some angularjs and so I am explaining a few thing. 'E', 'A', 'C' and 'M' are Element directive, Attribute directive, Class directive and Comment directive. Element directive are directive with custom element name. Attribute directive are directive with custom attribute, Class is for custom class name and comment directive is for comment section inside some i.e. div tag. directive name is the first parameter in the directive declaration and this name is used in the html section. 
restrict indicates type of directives.
link set link to the function which actually do something when the page loads.
element[0] is the element whose innerHTML is to be modified.
element.bind actually binds the event to the element.

Just follow the script

I hope you like it.

<!DOCTYPE html>
<html ng-app="app">
  <head>
    <meta charset="utf-8" />
    <title>AngularJS</title>
    <script src="https://code.angularjs.org/1.0.8/angular.js"></script>
    <script>
app=angular.module('app',[]);
app.controller('MainController',function($scope){
  $scope.data="Hello World!";
})

.directive('elementrestriction',function(){
  return {
    restrict:'E',
    controller:'MainController',
    link:function(scope,element,attrs) {
        element[0].innerHTML="<b>This is an element</b>";
    }
  }
})

.directive('attributerestriction',function(){
  return {
    restrict:'A',
    controller:'MainController',
    link:function(scope,element,attrs) {
      element.bind('mouseenter',function(){
        element[0].innerHTML="<b>Inside the attribute element</b>"; 
      });
      element.bind('mouseleave',function(){
        element[0].innerHTML="<b>Outside the attribute element</b>"; 
      });
    }
  }
})

.directive('classrestriction',function(){
  return {
    restrict:'C',
    controller:'MainController',
    link:function(scope,element,attrs) {
      element.bind('mouseenter',function(){
        element[0].innerHTML="<b>Inside the class element</b>"; 
      });
      element.bind('mouseleave',function(){
        element[0].innerHTML="<b>Outside the class element</b>"; 
      });
    }
  }
})

.directive('commentrestriction',function(){
  return {
    restrict:'M',
    controller:'MainController',
    link:function(scope,element,attrs) {
       alert("This is a comment");
    }
  }
});
    </script>
  </head>

  <body ng-controller="MainController">
    <elementrestriction>Element</elementrestriction>
    <div attributerestriction>{{data}}</div>
    <div class="classrestriction">{{data}}</div>
    <div id="commentsection">
      Comment Section
    <!-- directive:commentrestriction -->
    </div>
  </body>
</html>

Wednesday 21 January 2015

List of custom directives in AngularJS

angularjs

Here we are going to talk about creating custom directives in AngularJS. Here we will discuss about four type of custom directives. They are as following

 


1. 'E' ->  Restricted to element.
2. 'A' -> Restricted to attribute.
3. 'C' -> Restricted to class.
4. 'M' -> Restricted to comment.

For every directive we have set a console text which you will find in your console tab in browser developer section after the page loads/ reloads..
   We are going to write two program files. One is the script file myApp.js and another is the html file directives.html.

myApp.js
//------------------------------------------------------------------------------------------------------------------------

var app = angular.module('myApp',[]);
      app.controller('myCtrl',function($scope){
        $scope.data='Subhroneel'; //this is for some text in the custom tag
      })
      .directive('commentrestirict',function(){
        return { 
          restrict:'M', //this is for comment directive
          link:function(){
            console.log('I am a comment');
          }
        };
      })
      .directive('classrestirict',function(){
        return { 
          restrict:'C', // this is for class directive
          link:function(){
            console.log('I am a class');
          }
        };
      })
      .directive('elementrestirict',function(){
        return { 
          restrict:'E', //this is for element directive
          link:function(){
            console.log('I am an element');
          }
        };
      })
      .directive('attributerestirict',function(){
        return { 
          restrict:'A', //this is for attribute directive
          link:function(){
            console.log('I am an attribute');
          }
        };
      });
//----------------------------------------------------------------------------------------------------------------------

directives.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link href="style.css" rel="stylesheet" />
   <script src="https://code.angularjs.org/1.0.8/angular.js"></script>
    <script src="app.js">
    </script>
  </head>

  <body ng-app="myApp" ng-controller="myCtrl">
    <p class="classrestirict" attributerestirict>Hello {{data}}</p>
    <elementrestirict>Hello {{data}} this is an element</elementrestirict>
    <!-- directive:commentrestirict -->
  </body>
</html>

Below here you will find the demo, (sorry it does not work sometimes)


AngularJS
Hello {{data}}
Hello {{data}} this is an element

Tuesday 20 January 2015

Managing system monitor in Ubuntu Mate

Mate is an alternative to gnome 2 desktop environment. We are working on mate desktop environment version 1.8.1 on Ubuntu  release 14.0.4 (trusty), Kernel Linux 3.13.0-39-generic.
   As we know about the process tab which shows the currently running process, so we are going to talk about resources tab. Resources tab gives you total description of

1. CPU History for the last 60 seconds

    CPU history explains consumption of cpu in percentage i.e. how much cpu is used my the system in percentage for the last 60 seconds. The graph is % to last 60 seconds. This graph gives you an idea about your cpu's current state. This gives an idea about whether any process is eating up cpu usage, if the graph is in high percentage for a long time, i.e. in almost a parallel line,  you can assume some program is unnecessarily wasting cpu usage. There is also a color picker to changes the line colour of the graph of CPU history.

2. Memory and swap history.

    The second graph consists of 2 lines. The first one is memory usage in  percentage for the last 60 seconds and swap area occupied in percentage. As swap area is either auto configured or manually configured (here it is manually configured) so program calculates the percentage (total swap area currently used out of total allocated) of swap memory used. Memory percentage is used memory out of total physical memory.

3. Network history
     Network history also shows network speed in KiB/s, i.e. Kilo Byte / second for the last 60 seconds. Here is also 2 lines, one showing upload speed and another download speed.


Binding to input field through filters in AngularJS


  



1. Filtering with search pattern.

Filters are used to control the information bound to form elements or to say it binds data to the field.
In this lesson we will be creating a list of data and bind it to a search field to filter out the list based on the search criteria. Search field will be an input element, so when user type on the input the data will be filtered out to show only the list data matching the searched pattern. To bind the input element to the list the first thing we need to do is and one directive ng-model to the input field and the next thing to do is pipe (|) our ng-repeat directive value with the ng-model name given within the input field. So when we start typing in the input field our model will change correspondingly matching the value enter in the input field.

2. Filtering with sort by column.

    The next thing we are going to do is add one select element to create a combo list which will have the name of all the individual field used within the list and sort accordingly by a certain field. Say the data we fed into the page be [{'Name':'Sachin','Country':'India','Age':'40'}], so here fields are Name, Country and Age so we will feed Name, Country and Age into the combolist and when we will select any of the value then it will get sorted with that field.

3. Filter with orderby 

    Here we will add 2 radio buttons which will be labelled Sort by Ascending and Descending order. When we select the first radio it will be sorted in ascending order or else descending.

So here is the code given below showing all the 3 functionality.

<html ng-app>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
    </head>
    <body ng-init="myData=[
    {'Name':'Sachin Tendulkar','Country':'India','Age':'40'},
    {'Name':'Ricky Ponting','Country':'Australia','Age':'38'},
    {'Name':'Brian Lara','Country':'West Indies','Age':'39'},
    {'Name':'Jaque Kallis','Country':'South Africa','Age':'41'},
    {'Name':'Kumara Sangakara','Country':'Sri Lanka','Age':'37'}
    ]">
    <label>Search : </label> <input type="text" value="" ng-model="query" autofocus />
    <label>Order By</label>
    <select name="orderByKey" ng-model="orderByKey" >
        <option value="Name">Name</option>
        <option value="Country">Country</option>
        <option value="Age">Age</option>
    </select>
    <label>Order In</label>
        <input type="radio" ng-model="orderIn" name="orderIn" checked />
        <input type="radio" ng-model="orderIn" name="orderIn" value="reverse" />
        <ul>
            <li ng-repeat="data in myData | filter : query | orderBy : orderByKey : orderIn ">{{data.Name}} - {{data.Country}} - {{data.Age}}</li>
        </ul>
    </body>
</html>

Using ng-init directive in AngularJS

angularjs

Hey as I am new to angularjs but still I am loving it, it's a really wonderful technology by google. The main thing I find interesting in it is it's single page website concept, it's really awesome. You don't need to reload the page, everything is within a single page. Anyway I am not going into that details, which actually requires ng-view to be explained. So here I am with a small program to show that you can work with angularjs directive without even writing a single line of javascript code. All you need is to tell the browser that you will be using angularjs by declaring ng-app, initialize you data in an array using ng-init, and display data using ng-repeat. So here is a small attempt with such an example which is script less, the only script required is the angular api.

<html ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.min.js"></script>
</head>
<!-Data is initiallized into myData  within the body tag using ng-init-->
<body ng-init="myData=['Shane Watson','Bret Lee','Glen Mcgrath','Shane Warne','Ricky Ponting','Adam Gilchrist']"> 
 <!-Data is repeated within p tag using ng-repeat  and data diplayed within {{}}-->
<p ng-repeat="data in myData">{{data}}</p>
</body>
</html>

Monday 19 January 2015

Read news from network news group using python


This lesson consists of a program to demonstrate how to read network news group using python. Here we are going to use a comp language python news group, how to pick an article from that news group and read it.

So here is a python script to do this operation.

# import function from nntplib (network news transfer protocol library) library.
from nntplib import *
# Create a server with NNTP from url which stores network news.
server = NNTP('news.aioe.org') 
#Connect to the server and return five different element that are going to be returned
#  resp -> response send after we made a connection to the server
# count -> the number of news article that has been retrieved.
# first -> number of the first article.
# last-> the number of the last article.
# name -> name of the returned articles.
(resp, count, first, last, name) = server.group('comp.lang.python')
#After receiving the above we need to return the list of subject from the server using a function 
# called  xhdr which is used to return a range of subject from the news group.
# 'subject we are interested in and first - last is the range, converting to string and concatenating with 
# a dash (-)
(resp, subjects) = server.xhdr('subject', (str(first) + '-' + str(last))) # i.e. '1-10'
#  Now we will list the subject with a for loop, here we are retrieving all subjects, but you can also 
# specify range of subjects to be retrieve say subjects[-15:]
for subject in subjects[-15:]:
    print(subject)

#Now prompt the user which article he wants to read
n = int(input('Enter number of the article you want to read : '))
#Retrieve the body of the article using a function called body. Convert the number to a string when 
# sending value to body.Data will be stored in the list below (reply, num....)

(reply, num, id, list) = server.body(str(n))
#So now we are going to read the content of the body stored in list
for line in list
  print(line)
 

# End of program..

Output of the program after execution


File operation in Python using FTP

In real world of internet we know the value of file transfer between places, whether it be within one room, building or city or even countries. When the time comes of using FTP in web programming Python Language seems to be one of the best solution. Here are three programs demonstrating 



i.  File upload to remote server.
ii  Retrieve directory listing from remote server to confirm file upload and
iii Read the uploaded file.

-------------------------------------------------------------------------------------------------------------------------
File upload to remote server.

# program  includes 2 library ftplib and sys, ftplib is for ftp related operation and sys is for command 
# related operation
import ftplib
import sys




# argv is the argument vector which is an array storing arguments passed by the user with the 
# program name. i.e. argv[0] is the program name, argv[1] is the argument (here the filename to be 
# uploaded

filename = sys.argv[1]


#ftplib.FTP connects to the remote server via ftp and returns connection object to connect.

connect = ftplib.FTP("192.168.0.109")

# connect object calls login function to ftp login to server using credential as we use during ftp login 
# from command line.

connect.login("oracle","oracle")
# sys library is used here to open the file to be uploaded, returning object to file.

file = open(filename,"rb")

#storbinary function of connect object actually fires an ftp command STOR filename which acutally 
#uploads the file to server ftp root directory.

connect.storbinary("STOR " + filename,file)
# connection terminated
connect.quit()



# local file closed.
file.close()

-------------------------------------------------------------------------------------------------------------------------

Retrieve directory listing from remote server to confirm file upload

#Purpose of ftplib, ftplib.FTP and connect.login is described above.

import ftplib
connect = ftplib.FTP("192.168.0.109")
connect.login("oracle","oracle")



# data variable initialized to an empty array.
data = []

# connect.dir function is called which returns the directory listing (same as when we type ls -l 
# command in linux or dir in windows) and appended to data array object.
connect.dir(data.append)
# data is traversed in a loop line by line and printed into console 
for line in data:
    print(line)


 Output will be something like this
ftp python







-------------------------------------------------------------------------------------------------------------------------
Read the uploaded file.

import ftplib
import sys

filename = sys.argv[1]
connect = ftplib.FTP("192.168.0.109")
connect.login("oracle","oracle")




# This line is actually retrieving content of the remote file line by line firing an ftp command RETR 
# filename

connect.retrlines("RETR " + filename)
 

connect.quit()

This is a console based programming, but actual objective is to show that this program can be implemented in web programming for file operation.

You can watch the video tutorial on youtube on this lesson : https://www.youtube.com/watch?v=GvPM0Uuqa98

Python sending email using smtp


 #Sending email using python in a few simple steps. All you need a few libraries like smtplib, #email.mime.






import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

fromaddress = 'subhroneelganguly@gmail.com'  # example
toaddress = 'subhro1976@gmail.com' # example
text = 'This is my first email from python'  # Subject
username = 'subhroneelganguly'  # username
password ='password'                  # password
msg = MIMEMultipart()            # this is the message object
msg['From'] =fromaddress
msg['To'] = toaddress
msg['Subject'] = text            

msg.attach(MIMEText(text))   # Attaching subject tect to body, you can provide you own custom 
                                                  # body text.

server = smtplib.SMTP('smtp.googlemail.com')  # port is not mentioned in the argument, you can 

                                                                              #provide the port  after mail server address
                                                                             # i.e. smtp.googlemail.com,465
server.ehlo()            # say hello to server
server.starttls()        # telling server you want to tls encrypted connection.
server.ehlo()            # say hello to server once more
server.login(username,password)              # login to server server.sendmail(fromaddress,toaddress,msg.as_string())   # call sendmail function to send the mail. 

                                                                              # Convert the msg to string before sending.
server.quit()

Saturday 17 January 2015

An example of show-password using ng-model in Angular JS


angularjs
It's sometime become so disgusting while typing password, dealing with all those **** or $$$$ or sometimes all blank. God save us.. but not all of them, some sites or apps provide an option like show password while typing, where you can see the password you type. I think it's more user interactive when it's become your choice to reveal your password on the screen while typing. 
   I found it so easy to do such thing in angularjs  all you need is ng-model directive and a little jquery coding and that will prepare your meal.
      The ng-model binds the data of HTML element (custom form control) like input, select, textarea etc.). It actually binds the control to a property on the scope using NgModelController, which is created and exposed by this directive.

Here is a small example how ng-model binds input control to a view.

<!DOCTYPE html>
<html ng-app>
  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js" data-semver="1.0.8"></script>
    <script>
    $(document).ready(function() {
    if($(this).prop("checked")==true)
      $("p").show();
    else
      $("p").hide();

      $("#chk").click(function() {
        if($(this).prop("checked")==true)
          $("p").show();
        else
          $("p").hide();
      });
});
    </script>
  </head>

  <body>
    <input type="password" id="pass" value="" ng-model="pass">
    <br>Show password : <input type="checkbox" id="chk" ><br>
    <p id="showPass">{{pass}}</p>
  </body>
</html>
AngularJS Plunker
Show password :
{{pass}}

Friday 16 January 2015

How to create a package.json file using npm

node js, nodejs

The package.json file identifies a project, who authored it and which file is the entry point. This file will also keep track of the module this project depends on.







So first open terminal / command line and create a directory (i.e. subhro) where you want to create the package.json file.

Next change to the created directory.

To generate a package.json file type "npm init" on command line and press enter

npm init


after you press enter it will prompt you to enter a name. If you do not provide any name it will take the default name which is the name of the directory you are working on.

name: (subhro)

Next it will ask for the version and you can keep it empty to take the default.

version: (0.0.0)

Next it will ask for a description. Type a description of your own.

description: Keeps track an train's time

Next one is the entry point. Every project that you create should have one entry point. You can also accept the default which is index.js.

entry point: (index.js)

Then it will ask for test command, later on you can automatically set this up for unit test. For now on you can keep it blank.

test command:

After test it allows you to set path to a git repository, you can keep it blank if you are using it for yourself unless you plan to distribute your project to someone else.

git repository:

 Next one is keywords, this is also for distributing the project, so you can keep it blank for yourself.

keywords:

Next it will prompt for author, enter your name and email address (in angle brackets>, as I am entering mine and email.

author : "Subhroneel Ganguly <subhro1976@gmail.com>"

Then it will prompt for license, you can enter any license you like, or you can also use default as I have done here.

license: "BSD-2-Clause"
 

After you press enter the following preview of package.json file and then asking for confirmation. You can press enter if you want to add it or type no and press enter if you don't want to.

 {
  "name": "subhro",
  "version": "0.0.0",
  "description": "Keeps track an train's time",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Subhroneel Ganguly <subhro1976@gmail.com>",
  "license": "BSD-2-Clause",
  "dependencies": {
    "express": "~3.4.8"
  }
}


Is this ok? (yes)

After this it will return back to command prompt. Now check for whether package.json file is been created and can also look for the content of the file.

How to start nodejs server and set listening to a port.


node js nodejs


Here is a program server.js that one server object which listens through port 3000 on localhost.







/* require function includes http module  */

var http = require('http');




/* res.writeHead writes the meta content type and res.end writes  body text that is to be displayed in the page*/

var handleRequest = function (req,res) {
    res.writeHead(200,{'Content-Type':'text/plain'});
    res.end('Message : Server localhost listening to port 3000\n');
};

/*Function createServer  of http object is called that creates the server object server. */

var server = http.createServer(handleRequest);

/* server starts listening to port 3000 */

server.listen(3000,'localhost');

Save this file as server.js.

Now go to the terminal and cd to the directory where server.js is saved.
Type the command node server or node server.js.

Node starts listening on port 3000.

Now go to your web browser and enter url http://localhost:3000.

You browser should display  


Message : Server localhost listening to port 3000

Thursday 15 January 2015

How to install Google Chrome in Ubuntu Mate

google chrome ubuntu


Here are the steps to install google chrome in Ubuntu Mate OS.

You can either download and install google repository for linux or run the following commands in your terminal using sudo.

1.  First one to install the key.

wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | sudo apt-key add

2. After downloading the key add it to the repository by the following command.

sudo sh -c 'echo "deb http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google-chrome.list'

3. Update you repository.

sudo apt-get update


4. Now you are ready to install google chrome.

    i.  To install the most stable version..

        sudo apt-get install google-chrome-stable

   ii.  To install the beta version

         sudo apt-get install google-chrome-beta

  iii.   Unstable version

         sudo apt-get install google-chrome-unstable

 

Tuesday 13 January 2015

Manipulate sorting order and sorting by in AngularJS



angularjs
In this angularjs program we will go through parsing JSON data into html table and sort it by column header as well as sort it in ascending and descending order.





<html ng-app="myApp"> <!-- Tell broswer that you are going to use angular js -->
<head>
<meta charset="utf-8">

<1-- include angular.min.js library from googleapis.com -->
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script>
/* Create module */

myApp = angular.module('myApp',[]);
 

/* define controller with name  myController */

myApp.controller('myController',function($scope) {
/* Declaring set of array element within scope variable myData  */
    $scope.myData = [
        {"Name":"Sayani","Age":27},
        {"Name":"Somoshree","Age":6},
        {"Name":"Somarothi","Age":28},
        {"Name":"Allen","Age":32},
        {"Name":"Peter","Age":22},
        {"Name":"Daniel","Age":34},
        {"Name":"Samantha","Age":44}
];
});
</script>
</head>

<!- setting body as scope of myController -->
<body ng-controller="myController">
<!-- Adding Combolist with two columns Name and Age of table in which  data will be parsed. 

      setting ng-model as sortBy-->
Sort By : <select ng-model="sortBy">
<option value="Name">Name</option>
<option value="Age">Age</option>
</select>
<!-- Adding to options Ascending and Descending to change the sort order, setting ng-model as 

       sortOrder -->
<br>Sort In : Ascending : <input type="radio" name="sortOrder" ng-model="sortOrder" checked />
Descending :<input type="radio" name="sortOrder" ng-model="sortOrder" value=reverse />
<table border=1>
<tr>
<th>Name</th>
<th>Age</th>
</tr>

<!-- setting ng-repeat into "tr " that will parse array data into "td"  orderBy is set to sortBy of list object and  sortOrder of radio button-->
<tr ng-repeat="data in myData | orderBy : sortBy : sortOrder">
<td>{{data.Name}}</td>
<td>{{data.Age}}</td>
</tr>
</table>
</body>
</html>
 




<html ng-app="myApp">
<head>
<meta charset="utf-8">
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script>
myApp = angular.module('myApp',[]);
myApp.controller('myController',function($scope) {
    $scope.myData = [
        {"Name":"Sayani","Age":27},
        {"Name":"Somoshree","Age":6},
        {"Name":"Somarothi","Age":28},
        {"Name":"Allen","Age":32},
        {"Name":"Peter","Age":22},
        {"Name":"Daniel","Age":34},
        {"Name":"Samantha","Age":44}
];
});
</script>
</head>
<body ng-controller="myController">
Sort By : <select ng-model="sortBy">
<option value="Name">Name</option>
<option value="Age">Age</option>
</select>
<br>Sort In : Ascending : <input type="radio" name="sortOrder" ng-model="sortOrder" checked />
Descending :<input type="radio" name="sortOrder" ng-model="sortOrder" value=reverse />
<table border=1>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
<tr ng-repeat="data in myData | orderBy : sortBy : sortOrder">
<td>{{data.Name}}</td>
<td>{{data.Age}}</td>
</tr>
</table>
</body>
</html>
Sort By :
Sort In : Ascending : Descending :
NameAge
{{data.Name}}{{data.Age}}

Routing and multiple views example in Angular JS


angularjs 
In this angularjs example  we will see how to create routing, that will load multiple pages i.e. load multiple views within a single page without reloading, using an Angular module called ngRoute.






<html ng-app="myApp">
</head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular-route.min.js"></script>
<script>
/* Creating one module, you need to specify ngRoute if you are using this module for routing

    myApp=angular.module('myApp',['ngRoute']), this name 'myApp' functions as the directive in the

    html tag before which tells that this html page is going to use angular js.*/

   /* Calling config function which has $routeProvider as  parameter which actually handles routing
       of parameters. Here we have used 2 scenario comp_mst and emp_mst which routes to 2  
       different pages comp_mst.html and emp_mst.html, and controller is specified for the pages, this
      controller will control to which <div> (if we are using divider) tag the page will be viewed.   */

  myApp.config(function($routeProvider) {
            $routeProvider.
                when('/comp_mst', {
                    templateUrl: 'comp_mst.jsp',
                    controller: 'RouteController'
                }).
                when('/empl_mst', {
                    templateUrl: 'emp_mst.jsp',
                    controller: 'RouteController'
                }).
                when('/shift_mst', {
                    templateUrl: 'shift_mst.jsp',
                    controller: 'RouteController'
                }).
                when('/desig_mst', {
                    templateUrl: 'designation_mst.jsp',
                    controller: 'RouteController1'
                }).
                otherwise({
                    redirectTo: '/'
                });
        })
    /*Route param is defined in controller for RouteController routing to comp_mst */

     app.controller('RouteController',function($scope,$routeParams) {

         $scope.page_name = $routeParams.comp_code + ' ' + $routeParams.comp_namee;

    });

    /*Route param is defined in controller for RouteController1 routing to emp_mst */
    app.controller('RouteController1',function($scope,$routeParams) {

         $scope.page_name = $routeParams.emp_code + ' ' + $routeParams.emp_namee;

    });


</script>
</head>
<body>

 <h1>Routing example</h1>





<!--  Two separate div is pointed to two different controller using ng-controller this controller will decide which template will be loaded to which div   --> 
<div ng-controller="RouteController">
    <div id="divRoute" ng-view>
</div>

<div ng-controller="RouteController1">
    <div id="divRoute1" ng-view>
</div>
</body>
</html>


Now the file comp_mst.html has it's content like

<div>
<h1>Company Code and Name : {{comp_code}}  {{comp_name}};
</div>

Now the file emp_mst.html has it's content like
<div>
<h1>Employee Code and Name : {{emp_code}}  {{emp_name}};
</div>

Oracle 12c data generator in JSON by dynamic sql using JSP.



angularjs
I have actually written this program generating data in json  format to be used to retrieve data using http get in Angular JS. This project has 2 different program.


1. HTML page in which a script is embedded using angular js script which sends sql string as post object to JSP page which parses the SQL string to generate data in json format along with table column and then http service in angular js is used to retrieve data generate by jsp engine.

2. JSP page parses the sql string received post method and open with recordset object and writes to the page with out.print in json format. This data written in the page is retrieved by http service in angular js.

I am writing the jsp program first 


  <%@ page import = "java.sql.*" %> 
  <%
    /* Class.forName is only required post 11g Oracle version, 11g and prior 11g you need to 
       download ojdbc.jar depending on oracle version, then you have to omit Class.forName function 
      call.*/
    Class.forName("oracle.jdbc.driver.OracleDriver");
   /* DriverManager creating connection object, didn't put it into try block but you can do so. Format 
       for connection string is {jdbc:oracle:thin:@[ipaddress or hostname]:oracle_sid" , 
       "user_name",""password"}. */

    Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@192.168.0.109:1521:orcl",  
    "HR","HR"); 
 /* request.getParameter reads from post object sqlStr which is actually an input element in the 
      html  page consisting of the sql statement */

    String sql=request.getParameter("sqlStr");
 

    try
{

       /* Statement object  need to parse sql statement and return the cursor */
        Statement stmt = conn.createStatement();
       /* Resultset (recordset) object  used to create cursor object */
        ResultSet rs = stmt.executeQuery(sql);
       /* ResultSetMetaData object is used to retrieve column name and table name and number of 
           columns from parse recordset object using getMetaData function. Since we are attempting to 
           make table columns dynamic and not be hard coded that's why we are using metadata. */

        ResultSetMetaData rsMetaData = rs.getMetaData();

        int numberOfColumns = rsMetaData.getColumnCount();

        /* JSON data starts here */
        out.print("[");
        rs.next();

        /* Outer loop for each row. */
        while(true)
        {   
           /*  Inner row for each column */           
            for(int i=1;i<=numberOfColumns;i++)
                out.print("{\"" + rsMetaData.getColumnName(i) + "\",\""  + 

                rs.getString(rsMetaData.getColumnName(i)) + "\"}"); 
            /* This if statement serves two purpose, first one is it's takes cursor to the next record and it's 
                also check whether it is not at EOF, if not it prints a comma and a newline, as you know 
                each row in json data is in curly braces and separated by comma. i.e. 
               {"Name":"Simon","Age":"26"}, and if reaches EOF prints the closing bracket of the array 
               and exists loop */
           if(rs.next())
                out.print(",\n");
            else
                {
                out.print("]");
                break;
                }
        }

/*        Object closed and released.*/        stmt.close();
        rs.close();
        stmt=null;
        rs=null;
   
    }
    catch(SQLException e)
    {
        out.println("SQL Error encountered "+e.getMessage());
    }
    conn.close();
    conn=null;   
    %>
 

 The next one is the html code which send request to the jsp engine by invoking the url and get the response object anddisplays the data in respective views using controller.

<html ng-app="myApp">
<head>
<meta charset="utf-8">
<title>Angular.js example</title>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script>
myApp=angular.module('myApp',[]);
angular.module('myApp',[])
        .controller('angController',function($scope,$http) {
      $http.get("ora_export_json.php")
      .success(function(response) {
          $scope.allinfo = response;
      });
        });
</script>
</head>
<body ng-controller="angController">
Search : <input type=text ng-model="SearchField" />
<table border=1>
    <tr>
        <th><a href="" ng-click="sortField = 'emp_code'">Emp Code</a></th>
        <th><a href="" ng-click="sortField = 'emp_name'">Emp Name</th>
        <th><a href="" ng-click="sortField = 'emp_grade'">Emp Grade</a></th>
        <th><a href="" ng-click="sortField = 'dob'">Date of Birth</th>
    </tr>
    <tr ng-repeat="perinfo in allinfo | filter:SearchField | orderBy:sortField">
        <td>{{perinfo.emp_code}}</td>
        <td>{{perinfo.emp_name}}</td>
        <td>{{perinfo.emp_grade}}</td>
        <td>{{perinfo.dob}}</td>
    </tr>
</table>
</body>
</html>

Monday 12 January 2015

Advantages of using JQuery callback function.



jquery
It sometime happens that you write code x, y, z on line number 1, 2 and 3. Now x is not yet finished while y and then z started running. This can creates a serious problem when x need to be finished before y or z started. This problem can be solved using call back function. I will here demonstrate a program in jquery where I will show function called with and without call back function.

This code is with call back function

$("#btn1").click(function() {
  $("#divText").text(function() {
    alert('Div text element set with Call back function');
    return "This click is with callback function";
  });
});


Here as you can see the alert message is popped up before the div text is set. But if we have done it without call back function like this...

$("#btn1").click(function() {
  $("#divText").text("This click is with callback function");
    alert('Div text element set with Call back function');
});


then div text have been set first then alert message is popped up.

 Here is the full program

<html>
<head>
<meta charset="utf-8">
<script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$("document").ready(function() {
$("#btn1").click(function() {
  $("#divText").text("This click is with callback function");
  alert("Div text element set with Call back function"); 
});


$("#btn2").click(function() {
  $("#divText").text("This click is with callback function");
    alert('Div text element set with Call back function');
});

 });
</script>
</head>
<body>
<input type="button" id="btn1" value="Click Me" /><br>
<br><input type="button" id="btn2" value="Click Me" /><div id="divText">
</div>
</body>
</html>