Thursday, 8 January 2015

Using http get in AngularJS to retrieve json data, generated from Oracle database.


angularjs
Here are 2 programs one written in php to export data from Oracle 12c release 1 database to json file. And the second file is the html file which retrieves data from the exported JSON file using Angular JS. Here I have used $http.get which when succeed use the response object to retrieve data. After retrieving data it is generated into a html table which can be sorted column wise as well as filtered using a ng-model 


SearchField.

The first code is the php code to generate json data..


<?php

//Change your connection parameter as per you database.
 

$conn=oci_connect('hr','hr','192.168.0.109/orcl.localdomain');
if(!$conn)
{
    echo "Connection failed";
    $err = oci_error();
    trigger_error(htmlentities($err['message'], ENT_QUOTES), E_USER_ERROR);   
}


//Change your sql code as per your tables in database
 

$stid = oci_parse($conn, "SELECT emp_code, emp_name,decode(emp_grade,'S','Staff','Worker') emp_grade,to_char(nvl(date_of_birth,sysdate),'dd/mm/rrrr') dob FROM employee_master");
    oci_execute($stid);
    echo "[\n";
    while (true) {


/* I have put the condition in if statement instead of while loop because  I have to exclude the last comma when the last record is retrieved, after that it goes to the else statement where it generates one blank record */


    if(($row = oci_fetch_array($stid, OCI_BOTH)) != false)
       echo "{\"emp_code\":\""  . $row[0] . "\",\"emp_name\":\"" . $row[1] .  "\",\"emp_grade\":\"" . $row[2] .  "\",\"dob\":\"" . $row[3] . "\"},\n";
 

    else
    {
        echo "{\"emp_code\":\""  . $row[0] . "\",\"emp_name\":\"" . $row[1] .  "\",\"emp_grade\":\"" . $row[2] .  "\",\"dob\":\"" . $row[3] . "\"}\n]";
        break;
    }
}
oci_free_statement($stid);
oci_close($conn);
?>


The next one is the html file which uses Angular JS which not only retrieve data from the json file but also uses ng-repeat to generate it into a table which can also be filtered as well as sorted columnwise.

<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>

Retrieve remote data with http get using AngularJS

AngularJS

Using http get to retrieve data from remote URL which correspondingly send response which should be in json format.




<!DOCTYPE html>
<html>
  <head>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>    <script>
      angular.module('myApp',[])
        .controller('angController',function($scope,$http) {
      $http.get("http://www.w3schools.com/website/Customers_JSON.php")
      .success(function(response) {$scope.names = response;});
        }
);

    </script>
  </head>
  <body ng-app="myApp">
  <div ng-app="" ng-controller="angController">
  <table border=1>
    <tr ng-repeat="x in names">
      <td>{{ x.Name }}</td>
      <td>{{ x.Country }}</td>
    </tr>
  </table>
  </div> 
</body>
</html> 

Output of this is code is given below :


{{ x.Name }}{{ x.Country }}

Currency conversion with currency symbol with AngularJS.

AngularJS 

Converting numbers to currency pipe feature and set currency symbol.
Formatting a number as a currency (ie $1,234.56). When no currency symbol is provided, default symbol for current locale is used

<html>
  <head>
    <link rel="stylesheet" href="style.css">
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
    <script>
      angular.module('myApp',[])
        .controller('AngController',function($scope) {
          $scope.dataSet = [
          {Name:'Keyboard',Price:90},
          {Name:'Mouse',Price:150},
          {Name:'Monitor',Price:3500},
          {Name:'Pen Drive',Price:550},
          {Name:'Wifi Dongle',Price:600},
          {Name:'Blue Tooth',Price:300}
          ];
          $scope.myData = $scope.dataSet[0];
        });
    </script>
  </head>
  <body ng-app="myApp">
    <div ng-controller="AngController">
      <ul>
        <li ng-repeat="data in dataSet">{{data.Name}} - {{data.Price | currency : "Rs.":0}}</li>
      </ul>
    </div>
  </body>
</html>


Demo :

  • {{data.Name}} - {{data.Price | currency : "Rs.":0}}

Piping Uppercase / Lowercase for case coversion in AngularJS.



angulajs
Piping features for conversion of lettercase from / to uppercase / lowecase using AngularJS.

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="style.css">
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
    <script>
      angular.module('myApp',[])
        .controller('AngController',function($scope) {
          $scope.dataSet = [
          {Name:'Larry',Company:'Google'},
          {Name:'Mark',Company:'Facebook'},
          {Name:'Steve',Company:'Apple'},
          {Name:'Bill',Company:'Microsoft'},
          {Name:'Michael',Company:'Dell'},
          {Name:'Ellison',Company:'Oracle'}
          ];
          $scope.myData = $scope.dataSet[0];
        });
    </script>
  </head>
  <body ng-app="myApp">
    <div ng-controller="AngController">
  <select ng-model="myData" ng-options="data.Name | uppercase for data in dataSet" ng-change="getCompany"></select> - {{myData.Company | lowercase}}
 <br>
 <select ng-model="myData" ng-options="data.Name | lowercase for data in dataSet" ng-change="getCompany"></select> - {{myData.Company | lowercase}}
    </div>
  </body>
</html>

The demo for the above code is here..

- {{myData.Company | uppercase}}
- {{myData.Company | lowercase}}

Binding select tag with ng-options in AngularJS..


angularjs
When I am onto creating a combo list using select tag first I thought of using ng-repeat then I thought let me try something more useful so that I can reduce my code and make it more effective and readable. So I worked out with ng-options which helped me to populate my list with a single line of code. So here is the code where I have commented the <option></option> section which actually containing the ng-repeat.



<!DOCTYPE html><html>
  <head>
    <link rel="stylesheet" href="style.css">
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
    <script>
      angular.module('myApp',[])
        .controller('AngController',function($scope) {
          $scope.dataSet = [
          {Name:'Larry',Company:'Google'},
          {Name:'Mark',Company:'Facebook'},
          {Name:'Steve',Company:'Apple'},
          {Name:'Bill',Company:'Microsoft'},
          {Name:'Michael',Company:'Dell'},
          {Name:'Ellison',Company:'Oracle'}
          ];
          $scope.myData = $scope.dataSet[0];
        });
    </script>
  </head>
  <body ng-app="myApp">
    <div ng-controller="AngController">
    <select ng-model="myData" ng-options="data.Name for data in dataSet" ng-change="getCompany"></select> - {{myData.Company}}
    <!--    <select ng-model="myData">
        <option ng-repeat="data in dataSet">{{data}}</option>
      </select> -->
    </div>
  </body>
</html>

 
Here is the demo output..


- {{myData.Company}}

Adding and removing from list using push and splice in AngularJS.



angularjs
Since the last time I tried to manipulate ng-repeat and suddenly came up with how about making it more dynamic such as add or remove from the list. So I have added one input box and a button to add to the list and correspondingly added one remove link beside every list element to remove from the list. I felt so excited when it's worked out, so I thought of sharing the code with you..


//---------------------------------------------------------------------------------------------------------------------------

<!DOCTYPE html>
<!-- Declaringf directives -->
<html ng-app="myApp">
<head>
<meta charset="utf-8">
<title>Add remove elementsr</title>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script>
myApp = angular.module('myApp',[]);
//Creating controller
myApp.controller('NameCtrl',function($scope) {
    $scope.names=['Larry Page','Mark Zukerberg','Steve Jobs','Bill Gates'];
 //Data added
//addNames function to add new data into the list
$scope.addNames = function () {
    $scope.names.push($scope.addedName);
    //addedNames input box is cleaned up after name have been added
    $scope.addedName = '';
}
//Remove name function to remove elements from the list.
$scope.removeNames = function (name) {
    $scope.names.splice($scope.names.indexOf(name),1);

}

});

</script>
</head>
<!--Controller set to body scope -->
<body ng-controller='NameCtrl'>
<ul id="nav" role="navigation">
<!-- ng-repeat to repeat list for number of elements  and ng-click set to href link to remove elements-->
<li ng-repeat="name in names">{{name}}  <a href ="" ng-click="removeNames(name)">Remove </a></li>
</ul>
<!--ng-model set to input box -->
<input type=text ng-model="addedName" />
<!--function addNames will be called on form submit ng-submit is used which prevents reloading of the page -->
<form ng-submit="addNames()">
<input type="submit" value="Add" />
</forms>
</body>
</html>

Here is the demo apps just look into this,
Add remove elementsr

Wednesday, 7 January 2015

Piping filter and order by with ng-repeat in AngularJS.



In the last few example as I have gone through how to generate html list / table using constant array value or importing json data, now in this example we will go through using filter and order by to enhance search capability without reloading the page. This can be done by piping filter where filter can use any constant string value or can bind to any user input to make filter dynamic, the search capability will be more dynamic when user type it's search key and list gets filtered. Same can be done with orderBy. orderBy will set data of table in order by the key mentioned. In this program I have set link to headers the data gets sorted for the column clicked.

Download angularjs api from http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js 
or you can also use this link in you script src.

<html ng-app="myApp">
<head>
<meta charset="utf-8">
<title>Angular.js example</title>

//Included the script 
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script>
myApp=angular.module('myApp',[]);
myApp.controller('myCtrl',function($scope) {
$scope.allinfo = [
{Name:'Jim',Age:22,Sex:'Male'},
{Name:'Jane',Age:23,Sex:'Female'},
{Name:'Alex',Age:21,Sex:'Male'},
{Name:'Paul',Age:19,Sex:'Male'},
{Name:'Britney',Age:23,Sex:'Female'}
];
$scope.reverse=true;
});
</script>
</head>
<body ng-controller="myCtrl">
Search : <input type=text ng-model="SearchField" />
<table border=1>
    <tr>
        <th><a href="" ng-click="sortField = 'Name'; reverse=!reverse">Name</a></th>
        <th><a href="" ng-click="sortField = 'Age'; reverse=!reverse">Age</a></th>
        <th><a href="" ng-click="sortField = 'Sex'; reverse=!reverse">Sex</a></th>
    </tr>
    <tr ng-repeat="perinfo in allinfo | filter:SearchField | orderBy:sortField:reverse">
        <td>{{perinfo.Name}}</td>
        <td>{{perinfo.Age}}</td>
        <td>{{perinfo.Sex}}</td>
    </tr>
</table>
</body>
</html>

Angular.js example Search :
Name Age Sex
{{perinfo.Name}} {{perinfo.Age}} {{perinfo.Sex}}

Another ng-repeat example for AngularJS.

angularjs
Here is another ng-repeat example in AngularJS. It actually takes a dataset which contains some search engine links with Description and provide link to the actual URL.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title></title>
    <link href="style.css" rel="stylesheet" />
    <!--<script src="cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js" data-semver="2.1.1" data-require="jquery"></script>-->
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>
    <script>
      myApp=angular.module("myApp",[]);
      myApp.controller("DemoController",function($scope) {
        $scope.Links = [
        {"Name":"Google","LinkURL":"https://www.google.com"},
        {"Name":"Yahoo","LinkURL":"https://search.yahoo.com"},
        {"Name":"Bing","LinkURL":"https://www.bing.com"}
        ];
      });
    </script>
  </head>

  <body ng-app="myApp">
    <!-- Put your html here! -->
    <h1>Basic plunk!</h1>
    <p>The top search engine to work with!</p>
    <ul ng-controller="DemoController">
      <li ng-repeat="link in Links"><a href={{link.LinkURL}}>{{link.Name}}</a></li>
    </ul>
  </body>
</html>

Here is the preview of the above code..


Basic plunk!

The top search engine to work with!

Tuesday, 6 January 2015

Changing attribute value using jquery.

jquery ajax

In this program to change html element attribute value using jquery. The main html code is as such.










<html>
<body>
<h1 class="h1">I am sad when you leave me alone</h1>
<br>
<img id="pic" src="sad.jpg" height="100" width="100">
</body>
</html>


And here is the jquery code. I have used id value for img and h1 tag for h1. There are 2 events one is mouseenter  and another is mouseleave, on changing from mouseenter to mouseleave and viseversa theimage changes. Just follow the code.

$(document).ready(function() {

$(".h1").mouseenter(function() {
$("#pic").attr("src","happy.jpg");
});

$(".h1").mouseleave(function() {
$("#pic").attr("src","sad.jpg");
});

});


Here is the demo for this code. Move your mouse over the Header text below.

I am sad when you leave me alone


An example of mouseenter and mouseleave event in jquery.


jquery

Here is a small jquery code to understand how mouseenter and mouseleave event work by hiding and showing p tag element activity

Here is jquery code written in a file say myjquery.js

 



1. First scenario is where all the p tag is hidden during loading. And on mouse enter on the h1 tag all p tag element are shown.

$(document).ready(function() {
$("p").hide();
$("h1").mouseenter(function() {
$("p").show();
});
});

2. In the second scenario when the mouse leave on the h1 tag all p tag element are hidden.

$(document).ready(function() {
$("h1").mouseleave(function() {
$("p").hide();
});
});

3. In the third scenario all the above action is repeated but in a slow motion (1000 milisecond)

Show..

$(document).ready(function() {
$("p").hide();
$("h1").mouseenter(function() {
$("p").show(1000);
});
});

Hide..

$(document).ready(function() {
$("h1").mouseleave(function() {
$("p").hide(1000);
});
});

<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
</head>
<body>
<h1 class="h1">
This is a simple jquery example</h1>
<div class="p1">
Now this is how I am displayed</div>
<div class="p1">
Is my appearance look exciting to you?</div>
<div class="p1">
I don't care what you feel about me.</div>
</body>
</html>





A sample html demo for your testing.

This is a simple jquery example

Now this is how I am displayed
Is my appearance look exciting to you?
I don't care what you feel about me.

Hide and show paragraph text on click event using jquery.

jquery

Here is a small jquery code to understandhow click event work and how to show or hide text within such event.

Here is jquery code written in a file say myjquery.js

 

1. First scenario is where all the p tag is hidden during loading. And on clicking on the h1 tag all p tag element are shown.

$(document).ready(function() {
$("p").hide();
$("h1").click(function() {
$("p").show();
});
});

2. In the second scenario all the p tag element are visible (by default) and on clicking on h1 tag all the p tag element are hidden.

$(document).ready(function() {
$("h1").click(function() {
$("p").hide();
});
});

3. In the third scenario all the p tag element are hidden initially and p tag element visibility toggle on each click on h1 tag.

$(document).ready(function() {
$("p").hide();
$("h1").click(function() {
$("p").toggle();
});
});

4. In the fourth scenario all the above action is repeated but in a slow motion (1000 milisecond)

Show..

$(document).ready(function() {
$("p").hide();
$("h1").click(function() {
$("p").show(1000);
});
});

Hide..

$(document).ready(function() {
$("h1").click(function() {
$("p").hide(1000);
});
});

Toggle...

$(document).ready(function() {
$("h1").click(function() {
$("p").hide(1000);
});
});

A sample html demo only for toggle for your testing.

This is a simple jquery example

Now this is how I am displayed
Is my appearance look exciting to you?
I don't care what you feel about me.

Display list of data with ng-repeat using JSON data in AngularJS.


angularjs

I scratched my head of writing a HELL lot of code, but then I found AngularJS. An awesome tool just make it so simple not only creating tables from data nut the real thing is after that... User interactivity. Filter Data, order data, without any interaction to your datasource and without page reloading. I am putting the code here just go though it. I think this should be helpful to you.




<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="utf-8">
<title>HTML Starter</title>
<script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script>
myApp = angular.module('myApp',[]);
myApp.controller('NameCtrl',function($scope) {
    $scope.names=['Subhro','Somoshree','Sayani'];
   
$scope.addNames = function () {
    $scope.names.push($scope.addedName);
    $scope.addedName = '';
}

$scope.removeNames = function (name) {
    $scope.names.splice($scope.names.indexOf(name),1);
//    $scope.addedName = '';
}

});

</script>
</head>
<body ng-controller='NameCtrl'>
<ul id="nav" role="navigation">
<li ng-repeat="name in names">{{name}}  <a href="" ng-click="removeNames(name)">Remove</a></li>
</ul>
<input type=text ng-model="addedName" />
<form ng-submit="addNames()">
<input type="submit" value="Add" />
</forms>
</body>
</html>



#angularjs #json #ngRepeat #directive 

HTML Starter

Sunday, 4 January 2015

A simple example of MVC with AngularJS.

angularjs

My first program with Angular JS... Wow. This is simple awesome, Blast your page without reloading, do anything just anything with MVC.





First thing you need to do is download angular.min.js from AngularJS official website by Google.

https://angularjs.org/. Either you can download the angular.min.js file and save it in your root directory or you can also use the link like this <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js" />. I have created one webpage with client side AngularJS and at server side using JSP to retrieve data from Oracle 12c Release 1 database. I have used two tables employee_master consisting of columns emp_code, emp_name and employee_salary consisting of gross_pay and calculated field tot_pay. So here is the code given below, the main script written within the same page, but you can write it in a different script file.
-----------------------------------------------------------------------------------------------------------------------

<!DOCTYPE html>

<html ng-app="myApp">

<head>


<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>

<script>


// JS code

myApp = angular.module('myApp',[]);
<%@ page import = "java.sql.*" %>

<%
Class.forName("oracle.jdbc.driver.OracleDriver");

Connection conn = DriverManager.getConnection ("jdbc:oracle:thin:@192.168.0.109:1521:orcl", "HR","HR");


Statement stmt = conn.createStatement();

String sql="select a.emp_code,ProperCase(a.emp_name) emp_name,to_char(to_date(b.pay_month_year,'mm/rrrr'),'Month RRRR') pay_month_year,b.gross_pay, " + "sum(b.gross_pay) over (partition by b.pay_month_Year) tot_pay " + "from employee_master a inner join employee_salary b on b.emp_id = a.emp_id and b.pay_month_year='01/2009' and a.emp_grade='S'";


ResultSet rs = stmt.executeQuery(sql);

try
{
if(rs!=null) {


%>


// JS code

myApp.controller('empCtl',function($scope) { $scope.empData = [


<%
rs.next();
while(true)
{
%>
{"emp_code":"<%=rs.getString("emp_code")%>","emp_name":"<%=rs.getString("emp_name")%>","pay_month_year":"<%=rs.getString("pay_month_year")%>","gross_pay":"<%=rs.getString("gross_pay")%>","tot_pay":"<%=rs.getString("tot_pay")%>"}<%if(rs.next()) {%> , <% } else break;
}
}
}
catch(SQLException e)
{
e.printStackTrace(); }


stmt.close();
rs.close();
conn.close();
stmt=null;
rs=null;
conn=null;
%>
];
$scope.sortField='emp_name'; $scope.reverse=true;


});

</script>

</head>

<body ng-controller="empCtl">


Search: <input ng-model="query" type="text" />

<table border=1 cellpadding=5>
<tr><th><a href="" ng-click="sortField = 'emp_code'; reverse=!reverse">Emp Code</a></th>
<th><a href="" ng-click="sortField = 'emp_name' reverse=!reverse">Emp Name</a></th>
<th>Month Year</th><th>Gross Pay</th><th>Tot Pay</th></tr>
<tr ng-repeat="emp in empData | filter:query | orderBy:sortField:reverse">
<td>{{emp.emp_code}}</td>
<td>{{emp.emp_name}}</td>
<td>{{emp.pay_month_year}}</td>
<td>{{emp.gross_pay}}</td>
<td>{{emp.tot_pay}}</td>
</tr>
</table>
</body> </html>



#angularjs #json #ngRepeat #directive #mvc

Create webpage using AngularJS retrieving data from Oracle using JSP.


angularjs

My first program with Angular JS... Wow. This is simple awesome, Blast your page without reloading, do anything just anything with MVC.






First thing you need to do is download angular.min.js from AngularJS official website by Google.

https://angularjs.org/. Either you can download the angular.min.js file and save it in your root directory or you can also use the link like this <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js" />. I have created one webpage with client side AngularJS and at server side using JSP to retrieve data from Oracle 12c Release 1 database. I have used two tables employee_master consisting of columns emp_code, emp_name and employee_salary consisting of gross_pay and calculated field tot_pay. So here is the code given below, the main script written within the same page, but you can write it in a different script file.
-----------------------------------------------------------------------------------------------------------------------

<!DOCTYPE html>

<html ng-app="myApp">

<head>

<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>

<script>

// JS code

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

<%@ page import = "java.sql.*" %>

<%

Class.forName("oracle.jdbc.driver.OracleDriver");

Connection conn = DriverManager.getConnection ("jdbc:oracle:thin:@192.168.0.109:1521:orcl","HR","HR");

Statement stmt = conn.createStatement();

String sql="select a.emp_code,ProperCase(a.emp_name) emp_name,to_char(to_date(b.pay_month_year,'mm/rrrr'),'Month RRRR') pay_month_year,b.gross_pay, " +

"sum(b.gross_pay) over (partition by b.pay_month_Year) tot_pay " +

"from employee_master a inner join employee_salary b on b.emp_id = a.emp_id and b.pay_month_year='01/2009' and a.emp_grade='S'";

ResultSet rs = stmt.executeQuery(sql);

try
{

if(rs!=null)
{

%>

// JS code

myApp.controller('empCtl',function($scope) {

$scope.empData = [

<%

rs.next();

while(true)

{

%>

{"emp_code":"<%=rs.getString("emp_code")%>","emp_name":"<%=rs.getString("emp_name")%>","pay_month_year":"<%=rs.getString("pay_month_year")%>","gross_pay":"<%=rs.getString("gross_pay")%>","tot_pay":"<%=rs.getString("tot_pay")%>"}<%if(rs.next()) {%> , <% } else break;

}

}

}

catch(SQLException e)
{

e.printStackTrace();

}

stmt.close();

rs.close();

conn.close();

stmt=null;

rs=null;

conn=null;

%>

];

$scope.sortField='emp_name';

$scope.reverse=true;

});

</script>


</head>


<body ng-controller="empCtl">


Search: <input ng-model="query" type="text" />


<table border=1 cellpadding=5>


<tr><th><a href="" ng-click="sortField = 'emp_code'; reverse=!reverse">Emp Code</a></th>

<th><a href="" ng-click="sortField = 'emp_name' reverse=!reverse">Emp Name</a></th>

<th>Month Year</th><th>Gross Pay</th><th>Tot Pay</th></tr>

<tr ng-repeat="emp in empData | filter:query | orderBy:sortField:reverse">

<td>{{emp.emp_code}}</td>

<td>{{emp.emp_name}}</td>

<td>{{emp.pay_month_year}}</td>

<td>{{emp.gross_pay}}</td>

<td>{{emp.tot_pay}}</td>

</tr>

</table>

</body>

</html>


#angularjs #json #ngRepeat #oracle #mvc #oracledatabase #jsp

Saturday, 3 January 2015

Matrix programming in C language


This program is written totally with pointer, where rows and columns are allocated dynamically.
There are 3 sets of array with equal rows and columns. The program generate automatic values for first 2 array by using rand() function. Then it uses 2 functions which are also defined. One is to add the 2 matrix and assign the result into a third and another subtract 2 matrix and assign the result into the third.

Here is the program.

#include<stdio.h>

#include<conio.h>

#include<malloc.h>
#include<stdlib.h>

void printArray(int **arr,int row,int col)
{


    int i,j;


    for(i=0;i<row;i++)
    {


        for(j=0;j<col;j++)
          printf("%d\t",*(*(arr + i) + j));
        printf("\n\n");


   }
}

void sum(int **retarr,int **farr,int **sarr,int row,int col)
{


    int i,j;


    for(i=0;i<row;i++)
        for(j=0;j<col;j++)
            *(*(retarr + i) + j)=*(*(farr + i) + j) + *(*(sarr + i) + j);

}

void diff(int **retarr,int **farr,int **sarr,int row,int col)
{


    int i,j;


    for(i=0;i<row;i++)
        for(j=0;j<col;j++)
            *(*(retarr + i) + j)=*(*(farr + i) + j) - *(*(sarr + i) + j);

}

void main()
{


    int **firstArr;
    int **secondArr;
    int **resultArr;
    int col,row;
    int i,j;


    printf("\nEnter number of columns : ");
    scanf("%d",&col);
   
    printf("\nEnter number of rows : ");
    scanf("%d",&row);
   
    firstArr = (int **)malloc(row);
    secondArr = (int **)malloc(row);
    resultArr = (int **)malloc(row);

    for(i=0;i<row;i++)
    {
   
        *(firstArr+i) = (int *)malloc(col);
        for(j=0;j<col;j++)
          *(*(firstArr + i) + j) = rand()%100+1;
         
    }

    for(i=0;i<row;i++)
    {

        *(secondArr+i) = (int *)malloc(col);
        for(j=0;j<col;j++)
          *(*(secondArr + i) + j) = rand()%100+1;

    }

    for(i=0;i<row;i++)
        *(resultArr+i) = (int *)malloc(col);

    diff(resultArr,firstArr,secondArr,row,col);

    printArray(firstArr,row,col);
    printf("\n........................\n");
    printArray(secondArr,row,col);
    printf("\n........................\n");
    printArray(resultArr,row,col);
}

 #clanguage #cprogramming #programminginc #turboc #matrix

Custom concatenation function in C programming.

If you ever used strcat function in C / C++ you know it is a function which is used to concatenate 2 string.

Now suppose I want to concatenate 2 string Subhroneel and Ganguly. Now when we concatenate these 2 string output is SubhroneelGanguly, it is really irritating, so strcat return the concatenate string so that we can use it in a nested fashion. i.e. strcat(strcat("Subhroneel," "),"Ganguly"), so we get the output as Subhroneel Ganguly. We may have given a space before Ganguly that might have solve the problem but the really objective is to show how to concatenate more than 2 string within a single line, this is possible only because strcat returns the concatenate string after concatenating with target string.
I have written the concatenate function in small C program. Just go through this and see how concatenate function works.

#include<stdio.h>
#include<conio.h>

char *strconcat(char *target,char *source)
{
    char *head=target;
/*  Copied the head address of target string into head pointer this will help us to return the target string after concatenation.*/

    while(*++target);
/*  Moved the pointer to the end of the string (NULL) while(NULL) is false. Pre increment is used so that target pointer does not get incremented after reaching NULL. */

    while(*source)  // looped until source string reaches NULL
        *target++=*source++;   // Copying each element and then incrementing both.

    *target=NULL;  // Set target to NULL as while loop exits while reaching NULL for source.

    return head; // returning the entire string.
}

void main()
{
    char sourcestring[50],targetstring[100];

    printf("\nEnter first string : ");

    gets(targetstring);  // Target string

    printf("\nEnter second string : ");

    gets(sourcestring); // Source String



   // Just look carefully to the function call strconcat is called twice in a nested form. First one returning i.e. "Subhroneel " and then second one "Subhroneel Ganguly"

    printf("\nConcated string : %s",strconcat(strconcat(targetstring," "),sourcestring));

    getch();
}

Binary search in C programming

Binary search is a search method used in programming language which use divide and rule logic.
Suppose there are 10 elements in an array and the rule of binary search is the array must be pre-sorted. So here is the list of elements in the array.





array elements - 3   4   6   8  12   16   18  24   39  44
array index      - 0   1   2   3    4     5    6   7      8     9

So there are 10 elements 0-9. Now in binary search we need to divide the array into 2 half taking the middle element and checking whether the element is greater / lesser or equal to the search key. If it is greater than the search key then the search key should be on the right half of the array therefore we can discard the left half and set the mid element as the lower bound of the array, if it is lesser than the search key then the search key should be on the left half of the array therefore we can discard the right half. Now we repeat this task by again and gain dividing the array and taking the mid element and comparing it with the search key.

Now let us test with the above array elements. Let our search key be 18.

1.

array elements - 3   4   6   8  12   16   18  24   39  44
array index      - 0   1   2   3    4     5    6   7      8     9

Mid element is (9+0)/2 = 4 which is 12.

12<18, therefore we can set lower bound of the array as 4+1 = 5 and discard 0 to 4.

2. 
array elements - 16   18  24   39  44
array index      -  5     6    7     8     9

Now  Mid element is (9+5)/2 = 7 which is24.

24>18, therefore we can set upper bound of the array as 7-1 = 6 and discard8 and 9.

3.
array elements - 16   18  24
array index      -  5     6    7 

Now  Mid element is (7+5)/2 = 6 which is18

18=18, therefore this is our search element. So we found the result.

4. 
Now suppose search key does not exists, in that case lower bound will be greater than upper bound and the loop terminates, displaying a message as search element not found.

Here is a C program on Binary search. Please go through the program.

Now  Mid element is (9+5)/2 = 7 which is24.

24>18, therefore we can set upper bound of the array as 7-1 = 6 and discard8 and 9.


#include<stdio.h>

void main()
{

//Array is pre-initiated to save time, we are not concern about user input or sorting of array here.

int arr[]={5,8,9,13,17,23,29,34,39,45,49,54,59,62,79,81,84,88,93,96,99,102};

int num; // num variable is declared for search  key input from user.

int low,high,mid,flag; // low, high and mid variable are lower bound, upper bound and mid element.

printf("\nEnter number to search : ");

scanf("%d",&num); //User enters the search key.

low=0; //lower bound is initially set to 0

high=21; // Upper bound is initially set to actual upper bound of the array

mid=(low+high)/2; //mid position is set.

while(low<=high) // This condition is important, checking goes on until low<=high

{

    if(num<arr[mid]) // if search key less than mid element

    high=mid-1; // set upper bound to one element left to mid element

    else if(num>arr[mid]) // if search key greater than mid element

        low=mid+1; // set lower bound to one element right to mid element

    else
    {

        break; //else search key matches mid element so exit the loop.

    }

    mid=(low+high)/2; // this process goes on after setting lower / upper bound

}

/* check if low<=high then the loop is terminated because mid element matched
search key*/
if(low<=high)  

    printf("%d found in %d position",num,mid); // print the search key and position where it is found.

}


#clanguage #cprogramming #programminginc #binarysearch

Creating a simple linked list in C language.

Linked list programming is the best method to learn memory optimization in C. While we use array we actually it is static bind of memory, and works like a multistoried apartment which consists of thousands of flat but only a few is used while rest of them are empty (unused). Same can be with simple pointers, where you allocate blocks dynamically but as you went on deleting values memory cannot be reduced. But in linked list you create node when you need it delete it when you don't need it, like building flats only when someone comes to stay.
Here I have written a program which simply demonstrate a linked list program

#include"stdio.h"
typedef struct node
{
int val;
struct node *next;
} NODE;
NODE *createnode(int val)
{
NODE *tmp=(NODE *)malloc(sizeof(NODE));
    if(tmp)
    {
        tmp->val=val;
        tmp->next=NULL;
        return tmp;
    }
    return NULL;
}
void deletenode(NODE **n,int key)
{
NODE *prev=NULL;
NODE *n1=*n;
while(n1)
{
    if(n1->val==key)
    {
        if(!prev)
        {
            NODE *t=*n;
            (*n)=(*n)->next;
            free(t);
            return;
        }
        else
        {
            prev->next=n1->next;
            return;
        }
    }
    prev=(n1);
    n1=n1->next;
   
}
}
void print(NODE *n)
{
    printf("\nValues in the list : ");
    while(n)
    {
        printf("%d,",n->val);
        n=n->next;
    }
}
void main()
{
NODE *node=NULL,*node1=NULL,*tmp;
int key=0,opt=0;
    while(1)
    {
        printf("\nEnter 1 to add, 2 to delete 3 to print 4 to exit : ");
        scanf("%d",&opt);
        switch(opt)
        {
        case 1:
            printf("\nEnter value : ");
            scanf("%d",&key);
            if(key==-99)
            {
                break;
            }
            if(!node)
            {
                node=createnode(key);
                node1=node;
            }
            else
            {
                tmp=createnode(key);
                node1->next=tmp;
                node1=node1->next;
                tmp=NULL;
            }
            break;
        case 2:
            printf("\nEnter search value : ");
            scanf("%d",&key);
            deletenode(&node,key);
            break;
        case 3:
            print(node);
            break;
        case 4:
            return;
        }
    }
}

Inheritance and constructor overloading in JSP

Inheritance is probably the back bone of OOPS.
I have done it so many times in Java, C++, even python also. But this is my first time in JSP. Alas I am not writing any servlet!. This is just a JavaServer Page.

And this is how I did it. Use this code, build your own JSP. Just remember one thing that when you write your class do it within <%!  %> instead of <%  %>. Copy paste the code and save it with .jsp extension.

//---------------------------------------------------------------------------------------------------------------------

<html>
<head>
<%@ page language="java" import ="java.lang.*,java.io.*" %>
<%!
class Shape
{
 int Radius;
 int Width;
 int Height;
 Shape()
 {
  this.Width=0;
  this.Height=0;
  this.Radius=0;
 }
 Shape(int Radius)
 {
  this.Radius=Radius;
 }

 Shape(int Width,int Height)
 {
  this.Width=Width;
  this.Height=Height;
 }
}

class Circle extends Shape
{
 Circle()
 {
  super();
 }
 Circle(int Radius)
 {
  super(Radius);
 }
 double Area()
 {
  return Math.round(Math.PI*Radius*Radius * 100.00)/100.00;
 }
}

class Rectangle extends Shape
{
 Rectangle()
 {
  super();
 }
 Rectangle(int Width,int Height)
 {
  super(Width,Height);
 }
 double Area()
 {
  return Math.round(Width*Height * 100.00)/100.00;
 }
}
%>
</head>
<body>
<form action="classexample.jsp" method="post">
<select id="choice" onchange="displayelement()">
 <option>Circle</option>
 <option>Rectangle</option>
</select>
<div id="inputdiv"></div>
<script>
function displayelement()
{
obj=document.getElementById("choice");
if(obj.value=="Circle")
 inputdiv.innerHTML="Enters Radius : <input name='rad1' type=text value='' /><br><input type='submit' value='Calculate' />";
else if(obj.value=="Rectangle")
 inputdiv.innerHTML="Enter Width : <input name='width1' type=text value='' /><br>Enter Height     : <input name='height1' type=text value='' /><br><input type='submit' value='Calculate' />";
}
</script>
</form>
<form>
<%
 if(request.getParameter("rad1")!=null)
 {
  int rad=Integer.parseInt(request.getParameter("rad1"));
  Circle c = new Circle(rad);
  %><div><%= c.Area() %></div> <%
 }
 else if(request.getParameter("height1")!=null&&request.getParameter("width1")!=null)
 {
  int width=Integer.parseInt(request.getParameter("width1"));
  int height=Integer.parseInt(request.getParameter("height1"));
  Rectangle r = new Rectangle(width,height);
  %><div><%= r.Area() %></div> <%
 }
%>
</form>
</head>