Monday, November 12, 2012

Object Oriented (OO) to Relational Mapping – Guidelines


1. Classes: If there is a class called Class_A:

a. Create a table Table_A
b. Include all the attributes of the class Class_A as columns of the table table_A.
c. Add a surrogate key to Table_A.
d. Add semantic constraints to the Table_A (unique key, NOT NULL, value
constraints, etc.)
2. 1:N Association: If there is a 1:N relationship between two classes Class_A and Class_B:
a. Add the surrogate key of Table_A as foreign key in Table_B.
b. The name of the foreign key should be the name of the role.
3. N:1 Association: Same as 1:N Association above but in reverse
4. M:N Association: If there is a M:N relationship between two classes Class_A and Class_B:
a. Create a new table Table_C having the same name as the association name.
b. Add the surrogate keys of Table_A and Table_B as composite key of the new
table.
c. Add a surrogate key to Table_C
d. Add any association attributes that may be present as columns of Table_C
5. Association attributes: If there is a 1:N relationship between two classes
Class_A and Class_B and there are association attributes represented by
association class called Class_C:
a. Apply guidelines applicable for 1:N association given above
b. Create a new table Table_C corresponding to the association class Class_C.
c. Add the attributes of the association class Class_C as columns Table_C
d. Add the surrogate key key of Table_C.
e. Add a surrogate key to the new table Table_C
6. Aggregation: If there is aggregation relationship between Class_A (whole) and
Class_B (part):
a. Treat it as 1:N association between Class_A and Class_B
7. Composition: If there is aggregation relationship between Class_A (whole) and Class_B (part):
a. add the surrogate key of Table_A as foreign key in Table_B.
b. Add a NOT null constraint on the foreign key
c. Ensure CASCADE DELETE is done whenever deleting data
8. Inheritance: If Class_A is the super class and Class_B is the subclass:
a. Make the surrogate key of Table_B both as a primary key and as a foreign key that references Table_A..
b. Add a discriminant attribute to Table_A to indicate the name of the subclass to which a given instance belongs

Command to install grub (of Fedora)


Insert Fedora CD/DVD

Run below commmand

$chroot /mnt/sysimage

$grub-install /dev/sda

How Redirect Console / Terminal output to File and Console Both in Linux


1 . >> operator [redirect all output to file]

    #./a.out >> op.txt

2. | tee [redirect all output to file & Console both]

    #./a.out | tee op.txt

Saturday, October 20, 2012

How to roundoff given real number to nearest integer(Optimizing Algorithm/Program Step by Step)

Without using builtin function round,ceil,floor..

Example:
if f = 3.7 then i = 4
if f = 3.2 then i = 3

Code:

General logic:

int roundoff(float n)
{
int k = (n *10) %10;
if(k>5)
k=n+1;
else
k=n;
return k;
}

Optimized : int roundoff(float n)
{
int k = n + 0.5;
return k;
}

How to Check for given number is Prime or Not (Optimizing step by step)

General Algorithm:

for(i=2;i<n;i++)
{
if(n%2==0)
break;
}
if(i==n)
puts("Prime");
else
puts("Not Prime");

Better Solution:


for(i=2;i<n/2;i++) //perfect divisor will be less than n/2
{
if(n%2==0)
break;
}
if(i==n)
puts("Prime");
else
puts("Not Prime");


Even Better Solution:

int k = sqrt(n);
for(i=2;i<k;i++) //At least one factor will be less than square_root(n)
{
if(n%2==0)
break;
}
if(i==k)
puts("Prime");
else
puts("Not Prime");


Even more Better Solution:

if(n%2==0)
{
puts("Prime");
}
else
{
for(i=3;i<k;i+=2)
//if it is not divisible by 2, then no need to check for multiple of 2
{
if(n%2==0)
break;
}
if(i==k)
puts("Prime");
else
puts("Not Prime");
}

Optimizing Program for Fibonacci Series (Optimizing Algorithm/Program Step by Step)


Problem:
F(0)=0;
F(1)=1;
F (n)=(F(n-1)+F(n-2)) mod 10
efficient algorithm that computes this function.


Algo I :

int rec (int n){
    if (n<2)
     return (n);
   else
     return((rec(n-1)+rec(n-2))%10);

}


Exponential time

Linear Space


Algo II : 

int dp (int n){
f[0]=0;
f[1]=1;
for (i=2;i<=n; ++i)
f [n] =(f[n-1]+f[n-2])%10;
}

Linear time.
Linear space.

Algo III:
int linear (int n){
a=0; b=1; c=n;
for (i=2;i<=n; ++i){
c=(a+b)%10;
a=b;
b=c;
}
return c;
}

Linear time.
Constant space.

Algo IV:

For further optimization, we should analyse the output sequence and check whether it is periodic or not.
If it is periodic @ x then find value till x and use (n mod x ) to compute nth term of series.
e.g, Fibonacci series is periodic (not known exactly but 'x' is between 61-72).

Max Subsequence Problem (Optimizing Algorithm/Program Step by Step)



Problem:
Given a sequence of integers A1, A2, …, An, find the maximum possible value of a subsequence Ai, …, Aj.
Numbers can be negative.
You want a contiguous chunk with largest sum.

Example:   -2, 11, -4, 13, -5, -2
The answer is  20    (subseq.  A2 through A4).

    Algo I :

        int Sum = 0;

 for( int i = 0; i < a.size( ); i++ )
 for( int j = i; j < a.size( ); j++ )
 {
 int thisSum = 0;
 for( int k = i; k <= j; k++ )
 thisSum += a[ k ];
 if( thisSum > maxSum ) maxSum   = thisSum;
 }
 return maxSum;

    Complexity: O(n3)               [algo not good for large number of inputs e.g, size > 10 ^7]

    Algo II :

    into maxSum = 0;

 for( int i = 0; i < a.size( ); i++ )
 int thisSum = 0;
 for( int j = i; j < a.size( ); j++ )
 {
      thisSum += a[ j ];
      if( thisSum > maxSum )
   maxSum   = thisSum;
 }
 return maxSum;

    Complexity: O(n2)               [just good... ]
 
     
    Algo III:

        This algorithm uses divide-and-conquer paradigm. The max subsequence is entirely in the left half, entirely in the right half, or it straddles the midpoint.
Example:
 left half  | right half
 4   -3   5 -2 |    -1  2  6   -2
 Max in left is  6  (A1 through A3); max in right is  8  (A6 through A7). But straddling max is 11 (A1 thru A7).  


    How do we find the straddling max subsequence?
    Key Observation:
        Left half of the straddling sequence is the max subsequence ending with -2.
        Right half is the max subsequence beginning with -1.

        A linear scan lets us compute these in O(n) time.

        The divide and conquer is best analyzed through recurrence:

 T(1) = 1
 T(n) = 2T(n/2) + O(n)

        This recurrence solves to T(n) = O(n log n).
   
    Complexity: O(nlog(n))               [better ...still not best ]


    Algo IV:


 int maxSum = 0, thisSum = 0;

  for( int j = 0; j < a.size( ); j++ )
 {
 thisSum += a[ j ];

 if ( thisSum > maxSum )
 maxSum = thisSum;
 else if ( thisSum < 0 )
 thisSum = 0;
 }
     return maxSum;
        }

     Complexity: O(n)               [ best ]

Conversion of a relation (table ) from 1NF to 2NF to 3NF to BCNF


Normalization:
Definition
    Normalization can be viewed as a series of steps (i.e., levels) designed, one after another, to deal with ways in which tables can be "too complicated for their own good". The purpose of normalization is to reduce the chances for anomalies to occur in a database. The definitions of the various levels of normalization illustrate complications to be eliminated in order to reduce the chances of anomalies. At all levels and in every case of a table with a complication, the resolution of the problem turns out to be the establishment of two or more simpler tables which, as a group, contain the same information as the original table but which, because of their simpler individual structures, lack the complication. 
    Through normalization we want to design for our relational database a set of files that (1) contain all the data necessary for the purposes that the database is to serve, (2) have as little redundancy as possible, (3) accommodate multiple values for types of data that require them, (4) permit efficient updates of the data in the database, and (5) avoid the danger of losing data unknowingly. 

Advantage/Disadvantage
Adv.         -   Remove redundancy, Anomaly, Storage Efficiency 
Dis. Adv.  -  Time Consuming, Difficult, maintenance overhead (higher NF-> more tables)

Terminology
Keys – Super, Candidate, Primary.
Attributes – Prime/key , Non prime/non key.
Functional Dependency 1- Full, Partial, Transitive, overlapping, trivial, non trivial, complete non trivial.
Decomposition - Lossless Join (Algo for 2R and >2R). & Dependency preserving.
Armstrong Axioms – Reflexivity, Augmentation, Transitivity.
Closure –Attribute, F.D (If F is a set of functional dependencies for a relation R, then the set of all functional dependencies that can be derived from F, F+, is called the closure of F. ).
Redundant F.D.

Steps/Process/flowchart

1st Normal Form (1NF): 
            A table (relation) is in 1NF  
            1. If There are no duplicated rows in the table.
            2. Each cell is single-valued (i.e., there are no repeating groups or arrays).3. Entries in a column (attribute,         field) are of the same kind.
            Note: The order of the rows is immaterial; the order of the columns is immaterial. 
            Note: The requirement that there be no duplicated rows in the table means that the table has a key (although the key might be made up of more than one column—even, possibly, of all the columns). 

2nd Normal Form (2NF) : 
            A table is in 2NF 
            1. If it is in 1NF and 
            2. if all non-key attributes are dependent on all of the key.
            Note: Since a partial dependency occurs when a non-key attribute is dependent on only a part of the (composite) key, the definition of 2NF is sometimes phrased as, "A table is in 2NF if it is in 1NF and if it has no partial dependencies."

3rd Normal Form (3NF): 
            A table is in 3NF  
            1. If it is in 2NF and 
            2. If it has no transitive dependencies.

Boyce-Codd Normal Form (BCNF) : 
        A table is in BCNF 
        1. If it is in 3NF 
        2. If every determinant is a candidate key.

4th Normal Form (4NF): 
        A table is in 4NF 
        1. If it is in BCNF 
        2. If it has no multi-valued dependencies.

5th Normal Form (5NF): 
        A table is in 5NF, also called "Projection-Join Normal Form" (PJNF), 
        if it is in 4NF and if every join dependency in the table is a consequence of the candidate keys of the table.

Domain-Key Normal Form (DKNF): 
        A table is in DKNF if every constraint on the table is a logical consequence of the definition of keys and domains. 























Saturday, September 1, 2012

Car Race Game in C++ and C Graphics

Car Race

//*************************************************************************//
//*************************************************************************//
//       -*-     "Program For Game of Car Racing."     -*-                //
//-------------------------------------------------------------------------//
//       -*-       Language  :-  C-Graphics & C++.     -*-                //
//-------------------------------------------------------------------------//
//       -*-       Compilier :-  Turbo C & C++.        -*-                //
//-------------------------------------------------------------------------//
//      -*-         By- Vikrantsingh Bisen.           -*-                //
//*************************************************************************//
//*************************************************************************//


       //*************************************************//
       //      -*-   Including Header File       -*-      //
       //*************************************************//

#include <iostream.h>
#include <graphics.h>
#include <process.h>
#include <iomanip.h>
#include <stdlib.h>
#include <conio.h>
#include <stdio.h>
#include <time.h>
#include <dos.h>


       //*************************************************//
       //     -*-   Class For Attractive look    -*-      //
       //*************************************************//

Kaun Banega Crorepati Game in C - Graphics and C++

Kaun banega Crorepati

//*************************************************************************//
//*************************************************************************//
//       -*-        "Program For Game of K.B.C."       -*-                //
//-------------------------------------------------------------------------//
//       -*-       Language  :-  C-Graphics & C++.     -*-                //
//-------------------------------------------------------------------------//
//       -*-       Compilier :-  Turbo C & C++.        -*-                //
//-------------------------------------------------------------------------//
//      -*-         By- Vikrantsingh Bisen.           -*-                //
//*************************************************************************//
//*************************************************************************//

       //*************************************************//
       //       -*- Including  Header  File  -*-          //
       //*************************************************//

#include<iostream.h>
#include<graphics.h>
#include<stdlib.h>
#include<conio.h>
#include<time.h>
#include<dos.h>

Hotel / Lodging Management software / program in C C++ and C Graphics

Lodging Management

//*************************************************************************//
//-------------------------------------------------------------------------//
//        -*-    PROGRAM FOR HOTEL (i.e.,Lodging) MANAGEMENT.      -*-    
//-------------------------------------------------------------------------//
//        -*-             Language :- C & C++.       
//-------------------------------------------------------------------------//
//        -*-           Compiler :- Turbo C & C++. 
//-------------------------------------------------------------------------//
//        -*-  Designed by :- Vikrantsingh Bisen
//-------------------------------------------------------------------------//
//*************************************************************************//



/*-------------------------- Header Files -------------------------------*/
#include<iostream.h>
#include<fstream.h>
#include<graphics.h>
#include<process.h>
#include<string.h>
#include<stdio.h>
#include<conio.h>
#include<time.h>
#include<dos.h>
void intro (void);
class Admin;
class customer;
class Staff;
class Extra;
class Room;


Medical Shop Automation Software / Program in C C++ and C Graphics with Mouse Programing

Tested with : Windows XP and turbo C Compiler

 

 

Medical Shop Automation

//************************************************************************
//------------------------------------------------------------------------------------------
//                                                                       
//                -*-    VIRTUAL SOFTWARE MACHINE     -*-                
//                                                                       
//------------------------------------------------------------------------------------------
//        -*- Language.: C & C++. -*- Compiler.: Turbo C & C++.  -*-     
// -*- Designed by.: Vikrantsingh.M.Bisen [vikrantsingh.it@gmail.com] -*-
//------------------------------------------------------------------------------------------
//************************************************************************

//************************************************************************
//             -*-      Including Header File         -*-                
//************************************************************************

#include<iostream.h>
#include<graphics.h>
#include<iomanip.h>
#include<process.h>
#include<fstream.h>
#include<string.h>
#include<stdlib.h>
#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<time.h>
#include<dos.h>


//************************************************************************//
//            -*-     CLASSES IN THE PROGRAM         -*-                  //
//************************************************************************//
class Home;
class Display;
class Admin;
class Database;
class Bill;
class CRM;

how to make a bootable perndrive Operating system (OS)

Insert Pen-drive, Open command prompt and type following command one after another.


  1. diskpart
  2. list disk
  3. select disk X
  4. clean
  5. create partition primary
  6. format fs=fat32 quick
  7. active
  8. assign
  9. exit


Now copy your operating system to pendrive.

(Avoid burning  CD/DVD for  every os...... use bootable pendrive, Goo Greennn)

How to create Extensible Application in Java

import java.io.* ;

class Store {
    int x ;

    void write(String data) {
        x = 10 ;
    }

    String read( ) {
        x = 10 ;
        return "Cannot read." ;
    }
}

class FileStore extends Store {

    int y ;

    void write ( String data ) {
        System.out.println ( data + " written to the file" ) ;
    }

    String read( ) {
        return "Hello read from the file" ;
    }
}

class DatabaseStore extends Store {

    int z ;

    void write ( String data ) {
        System.out.println ( data + " written to the database" ) ;
    }
}

class DynamicArray {
    String items[ ] = new String[0] ;

    void add ( String item ) {
        String temp[] = new String[items.length+1] ;
        for ( int i = 0 ; i < items.length ; i++ ) {
            temp[i] = items[i] ;
        }
        items = temp ;
        items[items.length-1] = item ;
    }
   
    int getCount( ) {
        return items.length ;
    }

    String getItem ( int index ) {
        return items[index] ;
    }
}

class UserInteraction {
    Store takeInput( ) {
        DynamicArray names = new DynamicArray( ) ;
        try {
        File f = new File(".") ; // current directory
        String[] files = f.list( ) ; // get all the files
        for ( int i = 0 ; i < files.length ; i++ )  {
            if ( files[i].contains(".class") ) { // get only .class files
                Class c = Class.forName ( files[i].split(".class")[0] ) ;
                if ( c.getSuperclass().getName().equals( "Store" ) ) 
                    names.add ( files[i].split(".class")[0] ) ;
            }

        }

        // Display the menu....
        for ( int i = 0 ; i < names.getCount() ; i++ ) {
            System.out.println ( (i+1) + ": " + names.getItem(i) ) ;
        }

        java.util.Scanner scan = new java.util.Scanner(System.in) ;
        int choice = scan.nextInt() ;

        Class c = Class.forName ( names.getItem(choice-1)) ;
        return (Store) c.newInstance( ) ;
        } catch ( Exception ex ) {
            System.out.println ( ex ) ;
            return null ;
        }
    }
}

class Program { 
    public static void main ( String[] args )  {
        UserInteraction ui = new UserInteraction( ) ;
        Store  f =     ui.takeInput( ) ;
        f.write ( "Hello" ) ;
        String item = f.read( ) ;
        System.out.println ( item ) ;
    }
}


class XMLStore extends Store {
    void write ( String data ) {
        System.out.println ( data + " written to XML file." ) ;
    }
    String read( ) {
        return "Hello read from the XML file" ;
    }
}

Linked List Implementation in Java

Many of Us feel that one can't implement Link List in Java since Pointer is not available... But its not true...check the below program... :) .... It will change your concept about Objects in Java ....


class LinkList{
                int data;
                LinkList next=null;
                static int count=0;
                static LinkList head;
                 void add(int item){
                                 if(head==null){                                          
                                               head= new LinkList();
                                                head.data = item;
                                                head.next=null;
                                                count++;
                                }
                                  else{
                                                LinkList t=head;
                                                while(t.next!=null){
                                                                t=t.next;
                                                }                                             
                                                t.next = new LinkList();
                                                t.next.data = item;
                                                t.next.next=null;             
                                                count++;
                                }
                }
                void display(){
                                 LinkList t=head;
                                if(t==null){
                                        System.out.println("List Empty");
                                                return;                     
                                }
                while(t!=null){
                        System.out.println(" "+t.data);
                                                t=t.next;

                }
             }
               
                void menu()
                {
                                System.out.print("\n : Link List Using Java :\n 1.ADD, 2.Display and 3.Exit");                                       
                                while(true){
                                                java.util.Scanner sc = new java.util.Scanner(System.in);
                                                System.out.print("\nEnter Your Choice:");
                                               
                                                int c = sc.nextInt();
                                               
                                                switch(c){
                                                                case 1 :
                                                                                System.out.print("\nEnter Number to insert in LL.:");
                                                                                c = sc.nextInt();
                                                                                add(c); 
                                                                break;                                                  
                                                                case 2 :
                                                                                display();            
                                                                break;                                                  
                                                                case 3 :
                                                                                System.out.print("\nThank You :) .. ");
                                                                return; 
                                                                                                               
                                               
                                                }
                                }
                               
                }

}

class Program{

  public static void main(String args[]){

                                LinkList l=new LinkList();

                                l.menu();

                               
                }
}

How to Prevent SQL injections by adding slashes to Query String (GET / POST Parameters)


<?php
//create array to temporarily grab variables
$input_arr = array();
//grabs the $_POST variables and adds slashes
foreach ($_POST as $key => $input_arr) {
    $_POST[$key] = addslashes($input_arr);
}
//create array to temporarily grab variables
$input_arr = array();
//grabs the $_POST variables and adds slashes
foreach ($_GET as $key => $input_arr) {
    $_GET[$key] = addslashes($input_arr);
}
//create array to temporarily grab variables
$input_arr = array();
//grabs the $_POST variables and adds slashes
foreach ($_REQUEST as $key => $input_arr) {
    $_REQUEST[$key] = addslashes($input_arr);
}

?>

How to do Paging in PHP MYSQL ?



<?php 
///////database connection here
include("../include/database.php");
?>
<?php
$currentPage = $_SERVER["PHP_SELF"];
////////////no. of pages to display $maxRows_profile = 5;////////////////////////edit here
$pageNum_profile = 0;
if (isset($_GET['pageNum_profile'])) {
  $pageNum_profile = $_GET['pageNum_profile'];
}
$startRow_profile = $pageNum_profile * $maxRows_profile;
$colname_profile = "-1";
if (isset($_GET['Id'])) {
  $colname_profile = (get_magic_quotes_gpc()) ? $_GET['Id'] : addslashes($_GET['Id']);
}
/////////////////////your query goes here
$query_profile ="SELECT * FROM student where STUDENT_NAME like '%".$_GET['Id']."%'"; /////////////edit here
$query_limit_profile = sprintf("%s LIMIT %d, %d", $query_profile, $startRow_profile, $maxRows_profile);
$profile = mysql_query($query_limit_profile) or die(mysql_error());
$row_profile = mysql_fetch_assoc($profile);
/////////////////////////////////////////////PAGING LOGIC STARTS HERE ///////////////////////////////
///////////!!!!!!!!!!DO NOT EDIT BELOW THIS!!!!!!!!!!!/////////////
if (isset($_GET['totalRows_profile'])) {
  $totalRows_profile = $_GET['totalRows_profile'];
} else {
  $all_profile = mysql_query($query_profile);
  $totalRows_profile = mysql_num_rows($all_profile);
}
$totalPages_profile = ceil($totalRows_profile/$maxRows_profile)-1;
//////////////////////////////////////////////////////////Paging
$queryString_profile = "";
if (!empty($_SERVER['QUERY_STRING'])) {
  $params = explode("&", $_SERVER['QUERY_STRING']);
  $newParams = array();
  foreach ($params as $param) {
    if (stristr($param, "pageNum_profile") == false && 
        stristr($param, "totalRows_profile") == false) {
      array_push($newParams, $param);
    }
  }
  if (count($newParams) != 0) {
    $queryString_profile = "&" . htmlentities(implode("&", $newParams));
  }
}
$queryString_profile = sprintf("&totalRows_profile=%d%s", $totalRows_profile, $queryString_profile);
///////////////////////////////////////////////////////////////////PAGING END LOGIC////////////////////////////////////
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>My Document</title>
</head>

<body>
<!--------------Paging Status starts here-------------->
<p>&nbsp;
Records <?php echo ($startRow_profile + 1) ?> to <?php echo min($startRow_profile + $maxRows_profile, $totalRows_profile) ?> of <?php echo $totalRows_profile ?> </p>

<!--------------Paging Status ends here-------------->
<table border="1">
  <tr>
    <td>Id</td>
    <td>Child_Name</td>
    <td>Gender</td>
  </tr>
  <?php do { ?>
    <tr>
      <td><?php echo $row_profile['MD5']; ?></td>
      <td><?php echo $row_profile['STUDENT_NAME']; ?></td>
      <td><?php echo $row_profile['SURNAME']; ?></td>
    </tr>
    <?php } while ($row_profile = mysql_fetch_assoc($profile)); ?>
</table>
<!--------------Paging Links starts here-------------->
<table border="0" width="42%" >
  <tr>
    <td width="23%" align="center"><?php if ($pageNum_profile > 0) { // Show if first page ?>
          <a href="<?php printf("%s?pageNum_profile=%d%s", $currentPage, 0, $queryString_profile); ?>">&lt;&lt;First</a>
          <?php } else  { echo '&lt;&lt;First';  }   ?>
    </td>
    <td width="31%" align="center"><?php if ($pageNum_profile > 0) { // Show if not first page ?>
          <a href="<?php printf("%s?pageNum_profile=%d%s", $currentPage, max(0, $pageNum_profile - 1), $queryString_profile); ?>">&lt;Previous</a>
          <?php }else   { echo '&lt;Previous';  }   ?>
    </td>
    <td width="23%" align="center"><?php if ($pageNum_profile < $totalPages_profile) { // Show if not last page ?>
          <a href="<?php printf("%s?pageNum_profile=%d%s", $currentPage, min($totalPages_profile, $pageNum_profile + 1), $queryString_profile); ?>">Next&gt;</a>
          <?php }  else  { echo 'Next&gt;';  }       ?>
    </td>
    <td width="23%" align="center"><?php if ($pageNum_profile < $totalPages_profile) { // Show if last page ?>
          <a href="<?php printf("%s?pageNum_profile=%d%s", $currentPage, $totalPages_profile, $queryString_profile); ?>">Last&gt;&gt;</a>
          <?php } else  { echo 'Last&gt;&gt;';  }   ?>

    </td>
  </tr>
</table>
<!--------------Paging Links ends here-------------->
</body>
</html>
<?php
mysql_free_result($profile);
?>

How to use PHP MYSQL and AJAX together


index.php

Code listing:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script src="ajax.js"></script>
</head>

<body>
<form action="" method="get">
  <p> Enter no </p>
  <p>
    <input name="no" type="text" onkeyup="sq(this.value)" />
  </p>
  <p><div id="res"></div></p>
</form>
</body>
</html>

result.php

Code listing:

<?php
echo $_REQUEST['no']*$_REQUEST['no'];

?>


ajax.php

Code listing:

var xmlhttp

function sq(str)
{
  
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
  {
  alert ("Your browser does not support XMLHTTP!");
  return;
  }
var url="result.php";
url=url+"?no="+str;
url=url+"&sid="+Math.random();
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}

function stateChanged()
{
if (xmlhttp.readyState==4)
  {
  document.getElementById("res").innerHTML=xmlhttp.responseText;
}
else
{
  document.getElementById("res").innerHTML="PROCESSING..<img src='images/3.gif' />";
}
}

function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
  {
  // code for IE7+, Firefox, Chrome, Opera, Safari
  return new XMLHttpRequest();
  }
if (window.ActiveXObject)
  {
  // code for IE6, IE5
  return new ActiveXObject("Microsoft.XMLHTTP");
  }
return null;
}

How to use PHP MYSQL and AJAX together


index.php

Code listing:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script src="ajax.js"></script>
</head>

<body>
<form action="" method="get">
  <p> Enter no </p>
  <p>
    <input name="no" type="text" onkeyup="sq(this.value)" />
  </p>
  <p><div id="res"></div></p>
</form>
</body>
</html>

result.php

Code listing:

<?php
echo $_REQUEST['no']*$_REQUEST['no'];

?>


ajax.php

Code listing:

var xmlhttp

function sq(str)
{
  
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
  {
  alert ("Your browser does not support XMLHTTP!");
  return;
  }
var url="result.php";
url=url+"?no="+str;
url=url+"&sid="+Math.random();
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}

function stateChanged()
{
if (xmlhttp.readyState==4)
  {
  document.getElementById("res").innerHTML=xmlhttp.responseText;
}
else
{
  document.getElementById("res").innerHTML="PROCESSING..<img src='images/3.gif' />";
}
}

function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
  {
  // code for IE7+, Firefox, Chrome, Opera, Safari
  return new XMLHttpRequest();
  }
if (window.ActiveXObject)
  {
  // code for IE6, IE5
  return new ActiveXObject("Microsoft.XMLHTTP");
  }
return null;
}

PHP HTML DOM PARSER

Description, Requirement & Features

  • A HTML DOM parser written in PHP5+ let you manipulate HTML in a very easy way!
  • Require PHP 5+.
  • Supports invalid HTML.
  • Find tags on an HTML page with selectors just like jQuery.
  • Extract contents from HTML in a single line.

How to get HTML Element
// Create DOM from URL or file
$html = file_get_html('http://www.google.com/');

// Find all images
foreach($html->find('img') as $element)
       echo $element->src . '<br>';

// Find all links
foreach($html->find('a') as $element)
       echo $element->href . '<br>';

How to modify HTML element
// Create DOM from string
$html = str_get_html('<div id="hello">Hello</div><div id="world">World</div>');

$html->find('div', 1)->class = 'bar';

$html->find('div[id=hello]', 0)->innertext = 'foo';

echo $html; // Output: <div id="hello">foo</div><div id="world" class="bar">World</div>

Extract Content from HTML
// Dump contents (without tags) from HTML
echo file_get_html('http://www.google.com/')->plaintext;

Scrapping Slashdot
// Create DOM from URL
$html = file_get_html('http://slashdot.org/');

// Find all article blocks
foreach($html->find('div.article') as $article) {
    $item['title']     = $article->find('div.title', 0)->plaintext;
    $item['intro']    = $article->find('div.intro', 0)->plaintext;
    $item['details'] = $article->find('div.details', 0)->plaintext;
    $articles[] = $item;
}

print_r($articles);

Sample uses
// Include the library
include('simple_html_dom.php');

// Retrieve the DOM from a given URL
$html = file_get_html('http://davidwalsh.name/');

// Find all "A" tags and print their HREFs
foreach($html->find('a') as $e)
    echo $e->href . '<br>';

// Retrieve all images and print their SRCs
foreach($html->find('img') as $e)
    echo $e->src . '<br>';

// Find all images, print their text with the "<>" included
foreach($html->find('img') as $e)
    echo $e->outertext . '<br>';

// Find the DIV tag with an id of "myId"
foreach($html->find('div#myId') as $e)
    echo $e->innertext . '<br>';

// Find all SPAN tags that have a class of "myClass"
foreach($html->find('span.myClass') as $e)
    echo $e->outertext . '<br>';

// Find all TD tags with "align=center"
foreach($html->find('td[align=center]') as $e)
    echo $e->innertext . '<br>';
   
// Extract all text from a given cell
echo $html->find('td[align="center"]', 1)->plaintext.'<br><hr>';

AJAX Multiple request / Load Multiple Pages Simlultaneously in Ajax


     In this example we are loading first.php, second.php and third.php asynchronously in the same page simultaneously by making multiple ajax function calls.


index.html

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Ajax Multiple Calls</title>
<script type="text/javascript" src="content_loader.js"></script>

<script type="text/javascript">
function loader(){
f=GetXmlHttpObject(); 
vloader(f,'first.php','con1');
s=GetXmlHttpObject(); 
vloader(s,'second.php','con2');
t=GetXmlHttpObject(); 
vloader(t,'third.php','con3');
}</script>
</head>

<body onload="loader();">

<h1>First.php</h1>
<div id="con1" ></div>
<h1>Second.php</h1>
<div id="con2" ></div>
<h1>Third.php</h1>
<div id="con3" ></div>

</body>
</html>


Content loader.js
function vloader(xmlhttp,url,container)
{
//alert('hi'+url+container);
if(xmlhttp==null)
{alert ("Your browser does not support XMLHTTP!");return;}  
if(url.indexOf("?")>= 0){}
else{url=url+"?";}
url=url+"&sid="+Math.random();
        xmlhttp.onreadystatechange= function (){
if (xmlhttp.readyState==4)
{ document.getElementById(container).innerHTML=xmlhttp.responseText; } else
{ document.getElementById(container).innerHTML="<img src='loader.gif' />"; } };
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
/////////////////////////////////////////////////////////////////////////////////////////////
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}

first.php

<?php
for($i=0;$i<1000000;$i+=0.1);/////just to show  animated loading gif
echo 'First.php..loaded';
?>

second.php

<?php
for($i=0;$i<1000000;$i+=0.1);/////just to show  animated loading gif
echo 'second.php..loaded';
?>

third.php
<?php
for($i=0;$i<1000000;$i+=0.1);/////just to show  animated loading gif
echo 'third.php..loaded';
?>

How to run c and c++ program in gcc on linux platform


Running C Program in gcc on Linux Platform:


Steps:
1. Create a file demo.c with a C code inside it.
      $gedit <filename>
      $gedit demo.c
                  - It will create and open demo.c file in gedit text editor where you can type your c code, save and close it.  e.g.,
#include<stdio.h>
void main()
{
    printf("Hello C");
}
2. Compile demo.c
      $gcc <source file name>
      $gcc demo.c
                 - It will compile C program and create a.out executable binary file.
3. Running demo.c
      $./<executable file name>
      $./a.out
         
Note: If you are dealing with multiple c files at a time, then it is favorable to specify a name executable which can be done as below during compile time.
    $gcc <Source file name> -o <output file name>
    $gcc demo.c -o demoout
    now you can run it as
    $./demoout  


     

Running C++ Program in gcc on Linux Platform:


Steps:

1. Install the 'build-essential' package.
$ sudo apt-get install build-essential                         { For Ubuntu }

2. Create a file demo.cpp with a CPP code inside it.
      $gedit <filename>
      $gedit demo.cpp
                  - It will create and open demo.cpp file in gedit text editor where you can type your cpp code, save and close it.  e.g.,
#include <iostream>
using namespace std;

int main()
{
cout << "Hello  C++";
return 0;
}
3. Compile demo.cpp
      $g++ <source file name> -o <output file name>
      g++ demo.cpp -o hellocpp
                 - It will compile C program and create a.out executable binary file.
4. Running demo.cpp
      $./<executable file name>
     $ ./hellocpp
         

Debugging C Program in GCC on Linux platform:

  • Create C program as below
    • $ gedit demo.c
  • type your code in this demo.c file
  • example:
#include<stdio.h>
void main()
{
   int i=0;
  while(i<10)
  {
      printf("\n %d",i); 
      i++;
  }
}
  • Compile this program with -g option so that compiler can embed debugging information in executable.
  • $gcc -g demo.c -o demo
  • Next to start debugger run below given command.
  • $gdb demo
  • gdb --- debugger gets loaded.
  • Now make us of below commands for various operations.
  • Important gdb commands
    • help [gdb-command]
    • run args
      • Run the program till breakpoint / end
    • break [function-name | line-number]
      • Insert breakpoint at specific line.
      • You can have one or more breakpoints.
    • delete [bp-number]
      • To delete breakpoint.
    • next [N]
      • Debugger will execute the next line as single instruction.
      • next 3,  jumps 3 lines.
    • step [N]
      • Same as next, but does not treats function as a single instruction, instead goes into the function and executes it line by line.
    • finish
      • run till end.
    • continue
      • continue until next breakpoint.
    • where
      • Same as next, but does not treats function as a single instruction, instead goes into the function and executes it line by line.
    • quit
      • quit debugger.