Monday, October 22, 2012

Copy file in Java

Program to copy a file content in java is as follows:

 import java.io.*;

class FileCopy
{
  public static void main(String args[]) throws IOException
  {
    FileInputStream fin = new FileInputStream("d:/java/stk.java");
    FileOutputStream fout = new FileOutputStream("d:/java/txtfile.txt");
    int b;

    while(true)
    {
      b = fin.read();
      if(b == -1)
      {
        break;
      }
      System.out.print((char)b);
      fout.write(b);
    }

    fin.close();
    fout.close();
  }
}

Polynomial operations in Java

Program for Ploynomial expression in java is as follows:


import java.lang.*;
import java.io.*;
class term
{
  int coeff,exp;
}
class poly
{
    term pl[] = new term[10];
    int n;
    poly()throws Exception
    {
        poly p[]=new poly[10];
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter the no. of terms: ");
        n=Integer.parseInt(br.readLine());
    }
    public void getPoly()throws Exception
    {
        poly p[]=new poly[10];
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter the base & exponent:");
        for(int i=0;i<n;i++)
        {
            p[i].coeff=Integer.parseInt(br.readLine());
            p[i].exp=Integer.parseInt(br.readLine());
        }
    }   
    public void putPoly()
    {
        poly p[]=new poly[10];
        System.out.println("Polynomial is : ");
        for(int i=0;i<n;i++)
        {
            System.out.println(" "+p[i].coeff+"x^"+p[i].exp);
        }
    }
    public void evalPoly()throws exception
    {
        poly p[]=new poly[10];
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        int x,ans=0;
        System.out.println("Enter the value for x:");
         x=Integer.parseInt(br.readLine());   
        for(int i=0;i<n;i++)
        {
            ans=ans+p[i].coeff*pow(x,p[i].exp);
        }
        System.out.println("Ans : "+ans);
    }
    public static void main(String args[])throws Exception
    {
        poly p1=new poly();
        poly p2=new poly();
        p1.getPoly();
        p2.getPoly();
        p1.putPoly();
        p2.putPoly();
        p1.evalPoly();
       
    }   
}

Matrix in Java

Program for matrix in java is as follows:


import java.io.*;

class matrix
{
  int mat[][],r,c;

  matrix()
  {
     mat = new int[10][10];
  }
  public void getMat() throws Exception
  {
   // mat = new int[10][10];
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("\nEnter the Dim of the matrix : ");    
    r = Integer.parseInt(br.readLine());
    c = Integer.parseInt(br.readLine());

    System.out.println("\nEnter the matrix elements : ");    
    for(int i = 0 ; i < r ; i++)
    {
      for(int j = 0 ; j < c ; j++)
      {
        mat[i][j] = Integer.parseInt(br.readLine());
      }
    }
  }

  public void addMat(matrix m1,matrix m2)
  {
     r = m1.r;
     c = m1.c;

     for(int i = 0 ; i < r ; i++)
    {
       for(int j = 0 ; j < c ; j++)
       {
          mat[i][j] = m1.mat[i][j] + m2.mat[i][j];
       }
    }
  }

  public void putMat()
  {
    System.out.println("\nMatrix is : \n");
    for(int i = 0 ; i < r ; i++)
    {
      for(int j = 0 ; j < c ; j++)
      {
        System.out.print(" " + mat[i][j]);
      }
      System.out.println("");
    }
  }

  public static void main(String args[]) throws Exception
  {
    matrix m1 = new matrix();
    matrix m2 = new matrix();
    matrix m3 = new matrix();

    m1.getMat();
    m2.getMat();

    m1.putMat();
    m2.putMat();

    m3.addMat(m1,m2);
    m3.putMat();
  } 
}

Linear Search in Java

Below is simple program in java which shows the linear search.


import java.io.*;

class LinearSearch
{
  int ar[];
  int ele,n;

  public void setData() throws Exception
  {
     ar = new int[10];
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter the size for array : ");    
    n = Integer.parseInt(br.readLine());

    System.out.println("Enter the data for array : ");    
    for(int i = 0 ; i < n ; i++)
    {
      ar[i] = Integer.parseInt(br.readLine());
    }
    
    System.out.println("Enter the data to be searched : ");
    ele = Integer.parseInt(br.readLine());
  }

  public void putData()
  {
    System.out.println("The array is : ");
    for(int i = 0 ; i < n ; i++)
    {
      System.out.println(" " + ar[i]);
    }
  }

  public void LinSrch()
  {
    int i;
   
    for(i = 0 ; i < n ; i++)
    {
      if(ar[i] == ele)
      {
        break;
      }
    }
    if(i == ar.length)
    {
      System.out.println("\nElement not found");
    }
    else
    {
      System.out.println("\nElement found at " + i);
    }
  }

  public static void main(String args[]) throws Exception
  {
    LinearSearch ln = new LinearSearch();
    ln.setData();
    ln.putData();
    ln.LinSrch();
  }

}

Vector Demo in Java

Program for vector in java.

Below is the program.

import java.util.*;

class vectorDemo
{
    public static void main(String args[])
    {
        Vector v = new Vector(3,2);

        System.out.println("Intial Size : " + v.size());
        System.out.println("Intial Capacity : " + v.capacity());

        v.addElement(new Integer(1));
        v.addElement(new Integer(2));
        v.addElement(new Integer(3));
        v.addElement(new Integer(4));

        System.out.println("Capacity after 4 additions : " + v.capacity());
        v.addElement(new Double(4.55));
        System.out.println("Capacity after adding double element : " + v.capacity());       
    }
}

Array Keys and Array Values

Below is Simple Example which shows how the array keys or array values can be obtained from a array.


<?php

     $personinfo=array(array("name"=>"john","address"=>"pune","age"=>30),
          array("name"=>"Sathya","address"=>"Nashik","age"=>39),
          array("name"=>"madhav","address"=>"pune","age"=>22));

      $arr1=array_keys($personinfo);

      $arr2=array_values($personinfo);

       echo "OUTPUT AS ONLY KEYS FOR GIVEN ARRAY";
       echo "<br><br>";
       print_r($arr1);

      echo "<br><br>";   
      echo "OUTPUT AS ONLY VALUES FOR GIVEN ARRAY";
      echo "<br><br>";
      print_r($arr2);

?>

PHP Function to create slug from string

Here is simple Function to create slug from string.



function getSlug($title)
             {
                        $slug = preg_replace("/[^a-zA-Z0-9 ]/", "", $title);
                           $slug = str_replace(" ", "-", $slug);
                        $slug=strtolower($slug);
                        return($slug); 
  }

PHP Function to generate random unique string.

Here is a Simple Function to generate random unique string.



            function GenerateNumber($min, $max)
{
                        // Create the meta-password
                        $sMetaPassword = "";
                        global $CONFIG;
                        $ahPasswordGenerator = array(
                        "C" => array('characters' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 'minimum' => $min, 'maximum' => $max),
//"S" => array('characters' => "!@()-_=+?*^&", 'minimum' => 2, 'maximum' => 2
"N" => array('characters' => '1234567890', 'minimum' => $min, 'maximum' => $max)
);
                        foreach ($ahPasswordGenerator as $cToken => $ahPasswordSeed)
$sMetaPassword .= str_repeat($cToken, rand($ahPasswordSeed['minimum'], $ahPasswordSeed['maximum']));
                                    $sMetaPassword = str_shuffle($sMetaPassword);
                        // Create the real password
                        $arBuffer = array();
                        for ($i = 0; $i < strlen($sMetaPassword); $i ++)
$arBuffer[] = $ahPasswordGenerator[(string)$sMetaPassword[$i]]['characters'][rand(0, strlen($ahPasswordGenerator[$sMetaPassword[$i]]['characters']) - 1)];
                        return implode("", $arBuffer);

PHP Function to check whether the given number is decimal or not.

Below is a simple Function to check whether the given number is decimal or not.



function check_decimal($dec_val, $decimals = 2)
{
                        $pattern = "/^[-]*[0-9][0-9]*\.[0-9]{".$decimals."}$/";
                        if (preg_match($pattern,  $dec_val))
                                    return true;
                        else
                                    return false;
}

PHP Function to check whether a given date is valid or not.

Here is a Simple Function to check whether a given date is valid or not.



           function is_valid_date($value, $separator='-')
{
              if(strlen($value) <= 10)
                        {
                        // check date
                        $arr=explode($separator,$value);
                        $day=$arr[2];
                        $month=$arr[1];
                        $year=$arr[0];
                        if(@checkdate($month, $day, $year))
                                    return true;
              }
             return false;
}

MS SQL : How to identify fragmentation in your indexes?

Almost all of us know what fragmentation in SQL indexes are and how it can affect the performance. For those who are new Index fragmentation...