Thursday, 8 January 2015

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>

Monday, 1 December 2014

Problems with software coders in India.


We don't often think about coding tricks but it's comes into picture when you are no more into a

project and new guys come into it and need to understand the system. You are no where and it

depends on your coding style that whether they are jumping into an ocean or a little pool. Depth

should be in implementation not in complexity of the code, it's not about showing off how much you

know but it's important how much you are able to make the readers understand your code what

you tried to do. Let us assume that there are no documentation about what is stuff you have done,

now the psychology that's comes into  play about coders as per my experience is that they are more

concerned about showing of their knowledge rather than making it simple as if they are on to a

eligibility test with newbies. It's really seems to be a foolishness or stupidity to do such things.
         

  As per my experience I have worked in very few fresh project and most of them are existing

application and making the situation HELL like. In maximum case I didn't found any comment about

what stuff is fed into the system. Comments are missing, approach to a problem is such that you are

writing program for some microchips or space science when the actual program is for some simple

calculation of some say debit - credit. And this goes on with every new programmers come into the

system making it a disaster day by day.

So a proper convention for writing code is required  and that convention is not only to follow a proper

structure of coding but also make a coding simpler to understand where the approach will be not to

SHOW OFF you SKILL but to make the process smooth as well make it as simple and

understandable with proper comments and documentation.

And to add to this there is a lot to think about coding convention which is an essential part of coding.

Coding convention is definitely necessary but conventions should have the freedom for amendment

based on situations which actually does not happen and project leaders are found to be biased and

follow strictly some conventions which might be build when the system designed and following the

same thing after a decade. Developer should be given freedom and flexibility which will of course

make a system readable and understandable.

Good coder does not mean good developer.

Coding is not a big deal in any language but all it matters is a proper and thorough understanding of the existing system whether it is computer based or manual. It's not rocket science indeed. It's all about understanding user requirement. The main problem with coders is that whenever they got into studying about the requirements they immediately starts thinking about how they should be coding it. It's a very wrong way to think, because coding depends on requirements not the system depends on coding. If you have a proper understanding of the system requirements coding is not a big deal.
    Another problem with developers is when they started thinking that their code can never be wrong, ok so is it!. So you should be siting above GOD, because even GOD's creation have a lots of flaws. Jokes apart never try to rectify users rather rectify yourself, learn from your mistakes. It's not important what user wants, it's important the problem they face with their job and the interface they work with. User can never always say what problem they face, circumstances of their problems may be fragmented, but you have to accumulate all their problems and their requirements to design the system . Remember it's not about how well you code but it's about how well you understand the system.
Let us take an example. Suppose user needs to upgrade employee salary periodically after every six months for a particular rate. Now he has to do this manually fetching every record one by one. Now automation is required. But there are some issues. Date for increment is not fixed but lies within a range. So you can create a notification asking user to run the update process within the date range and also give freedom to user about stopping the notification on his system and when he stop the notification an email might be send to him notifying that updation is not done. If it is a top priority even you can block any operation in the system on the last day of such updation until process is done. That is it does not only depends on users choice only but also to the whole system and it's job priority. Now the question is about if the rate of increment varies. Increment rate can be categorised into employee grade or group or designation and can also be employee wise for any special case. So you cannot be biased when designing the system. User will never conform itself for the system, system needs to be designed as such to understand the user. I hard many designers or coders that system is such so you need to follow it, it's totally wrong because what happens in that case that system is designed at the will of the designer but when problems are faced later on system need to be modified in AD-HOC method which turns it into a hotchpotch and it's slowly started becoming complex one, not in the sense of performance but in the sense of poor designing.
And last but not the least. Every system when designed needs a proper documentation. Why?. Does anyone guarantees that he or she will stay with the system for lifetime? no of course so proper knowledge transfer is necessary and that is possible with your documentation about the system. And in that case you should take help of a technical writer because it's not necessary that if you are good programmer you can be a good technical content writer. You can learn a whole lot of books about designing but all that matters is your real life interaction.