Our Feeds

Wednesday 30 July 2014

Ajith KP

Microsoft Office 365 Pro Plus Product Key


KDVQM-HMNFJ-P9PJX-96HDF-DJYGX
WTFN9-KRCBV-2VBBH-BC272-27GXM
N2P94-XV8HD-W9MHF-VQHHH-M4D6X
433NF-H7TMK-TPMPK-W4FGW-7FP9K
7TPNM-PMWKF-WVHKV-G869H-9BQ6X
XRNFT-HG2FV-G74BP-7PVDC-JB29K

GYWDG-NMV9P-746HR-Y2VQW-YPXKK
6HDB9-BNRGY-J3F83-CF43C-D67TX
X2YWD-NWJ42-3PGD6-M37DP-VFP9K
GPT9W-CWNJK-KB29G-8V93J-TQ429
46DNX-B4Q98-PQVPW-Q8VM6-FVR29

DJC4N-DX7PC-GM3GK-V8KKW-XWYGX
N7PXY-WR4XP-D4FGK-K66JH-CYQ6X
XRNFT-HG2FV-G74BP-7PVDC-JB29K

366NX-BQ62X-PQT9G-GPX4H-VT7TX
4HNBK-863MH-6CR6P-GQ6WP-J42C9
6KTFN-PQH9H T8MMB-YG8K4-367TX
KBDNM-R8CD9-RK366-WFM3X-C7GXK
MH2KN-96KYR-GTRD4-KBKP4-Q9JP9
2MNJP-QY9KX-MKBKM-9VFJ2-CJ9KK
N4M7D-PD46X-TJ2HQ-RPDD7-T28P9
NK8R7-8VXCQ 3M2FM-8446R-WFD6X
2B8KN-FFK6J-YWMV4-J3DY2-3YF29
MTDNG-PDDGD-MHMV4-F2MBY-RCXKK
PBTFM-WWN3H-2GD9X-VJRMG-C9VTX
G9N3P-GRJK6-VM63J-F9M27-KHGXK
DMXHM-GNMM3-MYHHK-6TVT2-XTKKK

PNP4F-KY64B-JJF4P-7R7J9-7XJP9

Enjoy!!!!!.......

Sunday 27 July 2014

Ajith KP

Create a file compressor in Java

          It is not a tutorial. But its to share a source code of a Java application which for compressing files into ZIP archive. The line by line explanations are given in the source code.

          Download Netbeans Project File: http://downloads.ziddu.com/download/23930727/FileZip.zip.html


/*
 *  []
 *  []
 *  []
 *  [] ----> WwW.TerminalCoders.BlogSpot.DE <----
 *  []
 *  []
 *  []
 */
package filezip;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class FileZip extends JFrame {
        JButton btn = new JButton("OPEN");
        JTextArea area = new JTextArea();
        JPanel pnl = new JPanel(new GridLayout(1,1));
        JScrollPane pane = new JScrollPane();
    FileZip()
    {
        super("FILE ZIP - AJITH KP"); // Title
        setLayout(new BorderLayout()); // Set Layout to BorderLayout
        area.setEditable(false); // Textarea field cannot edit
        area.add(pane); // Adding scroll bar to Textarea
        area.setForeground(Color.black); // Textarea foreground is Black
        area.setBackground(Color.yellow); // Textarea backgrond is Yellow
        area.setFont(new Font("Times New Roman", Font.BOLD, 15)); // Textarea font is Time New Roman, Bold & size is 15
        pnl.add(btn); // Add button to panel
        add(pnl, BorderLayout.NORTH); // Add panel to Frame
        add(area, BorderLayout.CENTER); // Add Textarea to Frame
        btn.addActionListener(new ActionListener() // Button click capture
        {
            @Override
            public void actionPerformed(ActionEvent e) {
                area.setText("");
                showDlg();
            }            
        });
    }
    void showDlg()
    {     
        JFileChooser c = new JFileChooser(); // File chooser
        c.setFileSelectionMode(JFileChooser.FILES_ONLY); // Can select files only
        c.setMultiSelectionEnabled(true); // Multi selection is enabled
        int res = c.showOpenDialog(c); // Get result of file dialog
        if(res==JFileChooser.CANCEL_OPTION) // If you click cancel or closed the dialog
        {
            return;
        }
        File[] fls = c.getSelectedFiles(); // Else
        if(fls[0].toString().equals("")) // If you didn't select any file
        {
            return;
        }
        for(int i=0;i<fls.length;i++) // Else
        {
            area.setText(area.getText()+"Added:\t\t"+fls[i].getName()+"\n");
        }
        try {
            zipFile(fls); // Calling function zipFile
        } catch (FileNotFoundException ex) {
            Logger.getLogger(FileZip.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(FileZip.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    void zipFile(File[] file) throws FileNotFoundException, IOException
    {
        int num = file.length; // Number of files you selected
        FileInputStream in[] = new FileInputStream[num]; // FileInputStream array
        File f2 = new File(file[0].getParent()); // Get the name of parent directory
        for(int i=0;i<num;i++)
        {
            in[i] = new FileInputStream(file[i]);
        }
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(file[0].getParent()+"\\"+f2.getName()+".zip")); // Setting zip archive name
        for(int i=0; i<num; i++)
        {
            out.putNextEntry(new ZipEntry(file[i].getName())); // Adding files to zip archive
        }
        for(int i=0; i<num; i++) // Compressing each files you selected
        {
            byte[] b = new byte[1024];
            int count;
            while ((count = in[i].read(b)) > 0) {
                System.out.println();
                out.write(b, 0, count);
            }
        }
        for(int i=0; i<num;i++)
            in[i].close();
        out.close();
        area.setText(area.getText()+"\n\nFiles Zipped Successfully: "+f2.getName()+".zip");
    }
    public static void main(String[] args) throws FileNotFoundException, IOException {
        FileZip z = new FileZip();
        z.setSize(700, 500);
        z.setVisible(true);
        z.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

Saturday 26 July 2014

Ajith KP

FTP Management Script In PHP

Read Article Here[Authored By Me]: http://www.codeproject.com/Articles/551374/FTP-Management-Script-In-PHP

Introduction 

Hi Guys, I would like to introduce PHP functions to connect your Server to FTP server. I have created an application using PHP functions do it.  I have published this application in some websites before.
 

Advantages

I would like to inform its advantages because you will think whats the use of this PHP script when there are highly advanced application like "FILEZILLA" is available.
It have its own uses.
  • It allows to connect your Server to FTP Server
  • You don't want an intermediate computer to upload a file from FTP Server to your Server

Background

This idea of FTP Client using PHP is originated when I want to upload a file to my server. It is not good when I download the file to my computer and upload it to my server.
From here the idea of making FTP Client that will help to connect Server to FTP Server

Using the code

Lets check how the application is implemented in PHP.
First of all, I want a storage medium to store the host, username and password of FTP Server. It is not good when use
$user   = $_GET['usrname'];
$passwd = $_GET['passwrd'];
$host  = $_GET['host']; 
I want to store the value of variable in a medium. So I selected session cookies to store the value of variables for later use. Now the code will like this,
$user = $_COOKIE['ftpuser'];
$passwd = !$_COOKIE['ftppassword']?"":$_COOKIE['ftppassword'];
$host = $_COOKIE['host'];
So when the user fills the form and submit it, I will store the values of forms like this,
if(isset($_GET['host']) && isset($_GET['usrname']) && isset($_GET['passwrd']))
{
 global $user, $passwd, $host;
 setcookie("ftpuser", $_GET['usrname']);
 setcookie("ftppassword", $_GET['passwrd']);
 setcookie("host", $_GET['host']); 
}
Now let us check the FTP function of PHP which will help to connect FTP Server. To connect a FTP Server use, $connect = ftp_connect($host);
It will try to connect to FTP Server. The function ftp_connect() will return a boolean value to $connect< br/> Now if it is success next step is to login to FTP Server. To login to FTP Server use function ftp_login()
So the code will become, $login = ftp_login($connect, $user, $passwd);
The function ftp_login() will return a boolean value to $login
Later now next step is to read the files in FTP Server. The are two function to do a listing of files in FTP Server. ftp_nlist() and ftp_rawlist()
So here, ftp_rawlist() is advanced type of directory listing because It will return almost every details of files in FTP Server.
function dirDetails($directory=".")
{
 global $connect;
 if(is_array($directs=ftp_rawlist($connect, $directory)))
 {
  $prop = array();
  $nl=count($directs);
  foreach($directs as $dirx)
  {
   $chunks = preg_split("/[\s]+/", $dirx, 9);
   list($prop['perm'], $prop['num'], $prop['user'], $prop['group'], $prop['size'], $prop['mon'], $prop['day'], $prop['time']) = $chunks;
   $prop['type']=$chunks[0]{0}==='d'?'Directory':'File';
   $prop['name']=$chunks[8];
   array_splice($chunks, 0, 8);
   $props[implode(" ", $chunks)]=$prop;
  }
  return $props;
 }
}
The function dirDetails() will read files in directory when we call the function with path as parameter(current worling directory '.' as default).
The inner fuction will split the output from ftp_rawlist() according to permission, user, group, size(in bits), last modified date(month, day, time), type of file and name of file.
To show the details of files and directories in the FTP Server, the bellow function is used
$property = dirDetails($fpath);
foreach($property as $prop)
{
 global $fpath;
 $modified = date("F d Y",ftp_mdtm($connect, $prop['name']));
 if($prop['type']=='Directory')
 {
  print "[ ".$prop["name"]." ]".$prop['type']."".filesizex($prop['size'])."$modified".$prop['perm']."".$prop['user']."".$prop['group']."Rename | Delete";
 }
 else
 {
  print "".$prop['name']."".$prop['type']."".filesizex($prop['size'])."$modified".$prop['perm']."".$prop['user']."".$prop['group']."Download | Rename | Delete";
 }
}
To download a file from FTP Server $down = ftp_get($resource, $fname, $fname, FTP_ASCII); here $resource is connection stream, fisrt $fname represents in what name the file download, second $fname represents the remote file and the third parameter FTP_ASCII represents resumepos of download.
function download($resource, $fname)
{
 $down = ftp_get($resource, $fname, $fname, FTP_ASCII);
 if($down)
 {
  success("The file ".$fname." downloaded sucessfully");
 }
 else
 {
  failed("The file ".$fname." failed to download");
 }
}
The above snippet is exact function I used. To delete a file from FTP Server, you can use function ftp_delete($connect, $file);
function deleteFiled($file, $dire)
{
 global $connect;
 ftp_chdir($connect, $dire);
 $del = ftp_delete($connect, $file);
 if($del)
 {
  success("The file $file deleted sucessfully");
 }
 else {
  failed("The file $file cannot delete");
 }
}
The above snppet is used by me to delete the file.
To delete a directory you can simply call the function ftp_rmdir($connect, $file);
But it will fail to execute if the directory is not empty. So before delete directory you should delete all files and directories from desired directory. You can use a recursive function to do it,
function deleteDir($file, $cdir)
{
 global $connect, $fpath;
 $arraay = dirDetails("$fpath/$file");
 ftp_rmdir($connect, $file);
 foreach ($arraay as $key)
 {
  if($key['type']!='Directory')
  {
   deleteFiledd($fpath."/".$file."/".$key['name']);
  }
  else
  {
   deleteDir($fpath."/".$file."/".$key['name']);
  }
 }
 if(ftp_rmdir($connect, $file))
 {
  success("The directory $file has deleted succssfully");
 }
 else 
 {
  failed("The directory $file cannot delete");
 }
}
The function deleteDir() will delete a directory successfully if deletion of directory is set to user.
To upload a file from Server to FTP Server the PHP function ftp_put($connect, $file, $file, FTP_ASCII); will help. The first $file represents name of remote file you like to give and second $file represents the current name of file in server.
The exact function I used in application is,
function uploadf()
{
 $file=$_GET['upload'];
 global $connect, $host;
 $uploadd = ftp_put($connect, $file, $file, FTP_ASCII);
 if($uploadd)
 {
  success("Successfully uploaded file $file to FTP Server $host");
 }
 else 
 {
  failed("Failed to upload file $file to FTP Server $host");
 }
}
Now we have uploaded, downloaded and deleted from server. Now we want to maintain files in server. I would like to show how to rename a file in server, the PHP function to rename a file is ftp_rename($resource, $fname, $nfname);
The $fname represent the current name of file and $nfname represents new name for file. Exact function I used is,
function renamef($resource, $fname, $nfname)
{
 $ren = ftp_rename($resource, $fname, $nfname);
 if($ren)
 {
  success("The file ".$fname." renamed sucessfully");
 }
 else
 {
  failed("The file ".$fname." failed to rename");
 }
}
Next is to change permission of file in FTP Server. The PHP function to change permission is ftp_chmod($connect, $mode, $file);
You can use function like this ftp_chmod($connect, 0777, "ajithkp.jpg"); to change permission of file "ajithkp.jpg" to mode 777.
The exact code I used is,
function changeperm()
{
 global $connect, $fpath;
 ftp_chdir($connect, $fpath);
 $mode = $_GET['new_perm'];
 $file = $_GET['fname'];
 $mode = octdec(str_pad($mode, 4, '0', STR_PAD_LEFT));
 if(ftp_chmod($connect, $mode, $file) != FALSE)
  {
   success("The file $file permission changed successfully");
  }
  else 
  {
   failed("The file $file permission cannot changed");
  }
}
The other functions I used in this application are bellow. To convert bit size to KB, MB and GB, I used the bellow function,
function filesizex($size)
{
    if ($size>=1073741824)$size = round(($size/1073741824) ,2)." GB";
    elseif ($size>=1048576)$size = round(($size/1048576),2)." MB";
    elseif ($size>=1024)$size = round(($size/1024),2)." KB";
    else $size .= " B";
    return $size;
}
To logout from current session, you need to delete the session cookies stored in your browser. To delete cookies I used PHP function setcookie("ftpuser", ""); The exact function I used is,
function logout()
{
 setcookie("ftpuser", "");
 setcookie("ftppassword", "");
 setcookie("host", "");
}
To change the current directory: ftp_chdir($connect, $fpath);
To get FTP System Type: ftp_systype($connect);
To get current timeout: ftp_get_option($connect, FTP_TIMEOUT_SEC); 
I hope you have enjoyed this article and the application 
Ajith KP

Creating Animation from Sequence of Images in JavaFX


Read Article Here[Authored By Me]: http://www.codeproject.com/Tips/788527/Creating-Animation-from-Sequence-of-Images-in-Java





  • Download project files - 812.5 KB
  • Download JAR binary file - 798.5 KB

  • Introduction

    JavaFX is a software platform for creating and delivering rich internet applications (RIAs) that can run across a wide variety of devices. JavaFX is used for creating Rich Internet Application like online games, etc. While browsing, I got a sequence of image of a walking dog. This image lead me to write this tip.

    Using the Code

    We need a sequence of images to create animations. Using this trick, we can create animation of walking, flying, swimming, etc.
    Make the sequence to single images using Gimp/Photoshop. It is important to make the background as transparent. Otherwise the animation will not be good.
    Now, the next step is to create objects of images in JavaFX.


    final static Image DOG_1 =  new Image(JavaFX_12.class.getResource("1.png").toString());
    final static Image DOG_2 =  new Image(JavaFX_12.class.getResource("2.png").toString());
    final static Image DOG_3 =  new Image(JavaFX_12.class.getResource("3.png").toString());
    final static Image DOG_4 =  new Image(JavaFX_12.class.getResource("4.png").toString());
    final static Image DOG_5 =  new Image(JavaFX_12.class.getResource("5.png").toString());
    final static Image DOG_6 =  new Image(JavaFX_12.class.getResource("6.png").toString());
    final static Image DOG_7 =  new Image(JavaFX_12.class.getResource("7.png").toString());
    final static Image DOG_8 =  new Image(JavaFX_12.class.getResource("8.png").toString());
    final static Image DOG_9 =  new Image(JavaFX_12.class.getResource("9.png").toString());    
    final static Image BG =  new Image(JavaFX_12.class.getResource("bg.jpg").toString());


    "DOG_x" is my dogs' images object, "JavaFX_12" is my main class, "x.png" is my first image and BG is my background image's object. (x - Integers).

    final ImageView dog1 = new ImageView(DOG_1);
    final ImageView dog2 = new ImageView(DOG_2);
    final ImageView dog3 = new ImageView(DOG_3);
    final ImageView dog4 = new ImageView(DOG_4);
    final ImageView dog5 = new ImageView(DOG_5);
    final ImageView dog6 = new ImageView(DOG_6);
    final ImageView dog7 = new ImageView(DOG_7);
    final ImageView dog8 = new ImageView(DOG_8);
    final ImageView dog9 = new ImageView(DOG_9);
    final ImageView bg = new ImageView(BG);

    The above code is to create image views from image objects previously created. So now we have created ImageViewobjects of images.
    The next step is to create a Group object to incude images of "dog".
    private Group dog;
    dog = new Group(dog1);
    dog.setTranslateX(300);
    dog.setTranslateY(450);

    The first ImageView object "dog1" is added to the group and set position of dog using member functions "setTranslateX" and "setTranslateY".
    The next step is to create animation of walking. To create animation from images, we need to show the images sequentially in fast. According to the number of sequence images, we can set the set the fast. If the number of images is great, then we need less number of images to show in an unit time.


    TimelineBuilder.create()
            .cycleCount(Animation.INDEFINITE)
            .keyFrames(
                new KeyFrame(Duration.millis(100), new EventHandler(){
                    @Override
                    public void handle(ActionEvent t) {
                        dog.getChildren().setAll(dog1);
                    }
                }),
                new KeyFrame(Duration.millis(200), new EventHandler(){
                    @Override
                    public void handle(ActionEvent t) {
                         dog.getChildren().setAll(dog2);
                    }
                }),
                new KeyFrame(Duration.millis(300), new EventHandler(){
                    @Override
                    public void handle(ActionEvent t) {
                         dog.getChildren().setAll(dog3);
                    }
                }),
                new KeyFrame(Duration.millis(400), new EventHandler(){
                    @Override
                    public void handle(ActionEvent t) {
                         dog.getChildren().setAll(dog4);
                    }
                }),
                new KeyFrame(Duration.millis(500), new EventHandler(){
                    @Override
                    public void handle(ActionEvent t) {
                         dog.getChildren().setAll(dog5);
                    }
                }),
                new KeyFrame(Duration.millis(600), new EventHandler(){
                    @Override
                    public void handle(ActionEvent t) {
                         dog.getChildren().setAll(dog6);
                    }
                }),
                new KeyFrame(Duration.millis(700), new EventHandler(){
                    @Override
                    public void handle(ActionEvent t) {
                         dog.getChildren().setAll(dog7);
                    }
                }),
                new KeyFrame(Duration.millis(800), new EventHandler(){
                    @Override
                    public void handle(ActionEvent t) {
                         dog.getChildren().setAll(dog8);
                    }
                }),
                new KeyFrame(Duration.millis(900), new EventHandler(){
                    @Override
                    public void handle(ActionEvent t) {
                         dog.getChildren().setAll(dog9);
                    }
                })
            )
            .build().play();

    From the 0 to 100 milli seconds, the first image "1.png" will show, and next 100 milli seconds next image, until all 9 images are shown. After the last image is shown, the process of showing image will start again from the first image. This is because we have set the cycle of animation indefinite "cycleCount(Animation.INDEFINITE)".
    Now our dog has life and has started to move legs!!! But still the dog is standing there, not moving!!!. To move the dog along X-axis to generate a feeling of walking.

    private void startWalking() 
    {
        walk = TranslateTransitionBuilder.create()
                .node(dog)
                .fromX(-200)
                .toX(800)
                .duration(Duration.seconds(5))
                .onFinished(new EventHandler()
                        {
                            @Override
                            public void handle(ActionEvent t) {
                                startWalking();   
                            }
                        }).build();
        walk.play();
    }

    The function "startWalking()" is created for move the dog from -200 to 800 along in X-axis. The object to move is Group "dog" and the dog will travel from -200 to 8.00 position within 5 seconds. The Animation "walk" will finish when it reaches position 800 on X-axis. When the "walk" finishes, it will restart again from position -200.
    Now we are going to the last step. Add these objects bg(Background ImageView), dog(Group) to a Group named "root".

    final Group root = new Group(bg, txt, dog);        
    Scene scene = new Scene(root, 800, 600);        
    primaryStage.setTitle("Designer: AJITH KP");
    primaryStage.setScene(scene);
    primaryStage.show();
    startWalking();

    Now create a Scene object with "root" Group and set the size of window to 800x600. To load the scene to window, we have to use "setScene()" function of Stage class. To show the current stage, we have to call "show()" function of Stage class. And at last, we have to call the function "startWalking()" to animate to dog.
    I hope you enjoyed this tip and animation trick. 
    Ajith KP

    Online HTML Encoder

    Representing first online tool by us... Hope you will enjoy it...




    Ajith KP

    Swap values of variables without using intermediate variable

              Swap values of variables is basic practical question for programming beginners. It is very easy and usually we are doing it using a 3rd variable to store value temporary.



    Algorithm by using 3rd variable:

    tempVar = firstVar;
    firstVar = secondVar;
    secondVar = tempVar;

    Now for a change one asks to you to do it by without using a 3rd variable. This question made a brain storm when I was studying basics of C programming. My wild thoughts didn't give the answer for first 1 minute. I would like to share the code.


    #include <iostream>
    using namespace std;
    int main()
    {
        int a, b;
        a = 10;     // variable `a` gets value of 10
        b = 20;     // variable `b` gets value of 20
        cout<<"Before swap, a : "<<a<<", b: "<<b<<endl;
        a = a+b;    // now `a` is 10 + 20 = 30
        b = a-b;    // now `b` is 30 - 20 = 10
        a = a-b;    // now `a` is 30 - 10 = 20 -----> Swapped values
        cout<<"After swap, a : "<<a<<", b : "<<b<<endl;
    }

    Friday 25 July 2014

    Ajith KP

    Ordered Linear Search in CPP

              I hope you have read this page: http://terminalcoders.blogspot.com/2014/07/searching.html. If you didn't read it, please read it before using the source code.


    #include <iostream>
    using namespace std;
    class OLS
    {
        int list[256], n, i, k;
        public:
            void read()
            {
                cout<<"Enter the number of items: ";
                cin>>n;
                cout<<"Enter "<<n<<" Items in ascending order: ";
                for(i=0;i<n;i++)
                {
                    cin>>list[i];
                }
                cout<<"Enter key to search: ";
                cin>>k;
                o_l_s();
            }
            void o_l_s()
            {
                i=0;
                while(i<n && k>list[i])
                {
                    i++;
                }
                if(list[i]==k)
                {
                    cout<<"Key has found!!!";
                }
                else
                {
                    cout<<"Key hasn't found!!!";
                }
            }
    };
    int main()
    {
        OLS o;
        o.read();
    }
    Ajith KP

    Unordered Linear Search in CPP

              I hope you have read this page: http://terminalcoders.blogspot.com/2014/07/searching.html. If you didn't read it, please read it before using the source code.


    #include <iostream>
    using namespace std;
    class UOLS
    {
        int list[256], n, i, k;
        public:
            void read()
            {
                cout<<"Enter the number of items: ";
                cin>>n;
                cout<<"Enter "<<n<<" Items in ascending order: ";
                for(i=0;i<n;i++)
                {
                    cin>>list[i];
                }
                cout<<"Enter key to search: ";
                cin>>k;
                o_l_s();
            }
            void o_l_s()
            {
                i=0;
                while(i<n && k != list[i])
                {
                    i++;
                }
                if(list[i]==k)
                {
                    cout<<"Key has found!!!";
                }
                else
                {
                    cout<<"Key hasn't found!!!";
                }
            }
    };
    int main()
    {
        UOLS o;
        o.read();
    }
    Ajith KP

    Binary Search in CPP

              I hope you have read this page: http://terminalcoders.blogspot.com/2014/07/searching.html. If you didn't read it, please read it before using the source code.


    #include <iostream>
    using namespace std;
    class BIN
    {
        int list[256], n, i, k;
        public:
            void read()
            {
                cout<<"Enter the number of items: ";
                cin>>n;
                cout<<"Enter "<<n<<" Items in ascending order: ";
                for(i=0;i<n;i++)
                {
                    cin>>list[i];
                }
                cout<<"Enter key to search: ";
                cin>>k;
                binary(0, n);
            }
            void binary(int f, int l)
            {
                if(f>l)
                {
                    cout<<"Key hasn't found!!!";
                }
                else
                {
                    int mid = (f+l)/2;
                    if(k==list[mid])
                    {
                        cout<<"Key has found!!!";
                    }
                    else if(k < list[mid])
                    {
                        binary(f, mid-1);
                    }
                    else
                    {
                        binary(mid+1, l);
                    }
                }
            }
    };
    int main()
    {
        BIN o;
        o.read();
    }
    Ajith KP

    Searching

              "Try to find something by looking or otherwise seeking carefully and thoroughly" is the meaning of searching. Likewise, the computer uses searching to find some thing. There are so many searching algorithms used in computers [^]. The most popular searching techniques are Linear search and Binary search.


              The linear search are of two types,

    • Ordered Linear Search
    • Unordered Linear Search
              The only difference is ordered linear search uses sorted list to search the `key`, but unordered linear search uses unordered list to search `key`.

              Ordered Linear Search : Algorithm

    function UNORDERED_LINEAR SEARCH():
              // n => size of list; k => key to be searched; list => array of elements where we want to search key
              i = 0; 
               while i < n and k > list[i]: 
                        i++;
              if(k==list[i]):
                        "Key Found"
              else:
                        "Key Not Found"

              Unordered Linear Search : Algorithm 

    
    
    function UNORDERED_LINEAR SEARCH():
              // n => size of list; k => key to be searched; list => array of elements where we want to search key
              i = 0; 
               while i < n and k != list[i]: 
                        i++;
              if(k==list[i]):
                        "Key Found"
              else:
                        "Key Not Found"

              Binary Search : Algorithm

    function BINARY SEARCH(int first, int last):
              // n => size of list; k => key to be searched; list => array of elements where we want to search key
              if first > last:
                        "Key Not Found"
              else:
                        midpoint = (first+last)/2;
                        if k == list[midpoint]:
                                  "Key Found"
                        elif k < list[midpoint]:
                                  BINARY SEARCH(first, midpoint-1)
                        else:
                                  BINARY SEARCH(midpoint+1, last)

    Source Codehttp://terminalcoders.blogspot.com/2014/07/binary-search-in-cpp.html 

    Wednesday 23 July 2014

    Ajith KP

    Conversion of Post-fix expression to In-fix expression

              The last post is about conversion of In-fix expression to Post-fix[^]. Now we are going to convert Post-fix to In-fix expression.


    #include <iostream>
    #include <stdio.h>
    #include <string.h>
    using namespace std;
    class stacks
    {
        char stack[256][256], t;
        public:
            stacks()
            {
                t=-1;
            }
            void push(char str[256])
            {
                strcpy(stack[++t], str);
            }
            char* top()
            {
                return stack[t];
            }
            void pop()
            {
                t--;
            }
            void show()
            {
                cout<<"Postfix: "<<stack[0];
            }
    };
    
    int isOperator(char c)
    {
        if(c=='+'||c=='-'||c=='/'||c=='*')
        {
            return 1;
        }
        return 0;
    }
    
    int main()
    {
        stacks s;
        char str[256], *ptr, tmp[256];
        cout<<"Enter string: ";
        cin>>str;
        ptr = str;
        while(*ptr!='\0')
        {
            if(isOperator(*ptr))
            {
                char *a, *b;
                a = s.top();
                s.pop();
                b = s.top();
                s.pop();
                sprintf(tmp, "%s%c%s", b, *ptr, a);
                s.push(tmp);
            }
            else
            {
                sprintf(tmp, "%c", *ptr);
                s.push(tmp);
            }
            *ptr++;
        }
        s.show();
    }

    Sunday 20 July 2014

    Ajith KP

    In-fix to Post-fix using stack [C++]

              We have already discussed about stacks in previous post. There said stacks are used to evaluate mathematical statements. Now we can discuss how stacks are using evaluate mathematical statements.

              We are writing mathematical statements in in-fix form. An example is `A+B`. Here the operator `+` is embedded between two operands `A and B`. We know this format very well. But the computers are using other type of form called `post-fix` form. In this form the operator is fixed after the operands. The post-fix form of `A+B` is `AB+`. The advantage of using this format is that  computer can reduce complexity of  in parenthesis statements. The compiler pushes whole statement which is in post-fix into stack and pops single element from stack. If the popped element is operator then appropriate number of operands will popped out and do the operation. After finish the operation push the answer into stack. After whole elements is evaluated the answer will popped out to use later operations.


    /*
        [][][]
        [][][]
        [][][]
        [][][]  TerminalCoders.Blogspot.Com
        [][][]
        [][][]
        [][][]
    */
     
    #include <iostream>
    #include <stdio.h>
    #include <string.h>
    using namespace std;
    class stacks
    {
        char stack[256];
        int topx;
        public:
        stacks()
        {
            topx = -1;
        }
        int empty()
        {
            if(topx==-1)
            {
                return 1;
            }
            return 0;
        }
        char top()
        {
            return(stack[topx]);
        }
        char pop()
        {
            return(stack[--topx]);
        }
        void push(char c)
        {
            stack[++topx] = c;
        }
    };
    int isOperator(char character)
    {
        if (character == '+' || character == '-' || character == '*' || character == '/' || character=='^') {
            return 1;
        }    
        return 0;
    }
    int isOperand(char character)
    {    
        if (isOperator(character) == 0 && character != '(' && character != ')') {
            return 1;
        }
        return 0;
    }
    int priority(char op) {
     switch(op)
     {
      case '+':
      case '-':
       return 1;
       break;
      case '*':
      case '/':
       return 2;
       break;
      case '^':
       return 3;
       break;
      return 0;
      break;
     }
    }
    int main()
    {
        char post[256], input[256], *cptr, tmp[256];
        stacks stack;
        cout<<"Enter infix: ";
        strcpy(post, "");
        strcpy(tmp, "");
        cin>>input;
        cptr = input;
        while(*cptr!='\0')
        {
            if(isOperand(*cptr))
            {
                sprintf(tmp, "%c", *cptr);
                strcat(post, tmp);
            }
            else if(isOperator(*cptr))
            {
                while(stack.empty()==0 && stack.top()!='(' && priority(stack.top())>priority(*cptr))
                {
                    sprintf(tmp, "%c", stack.top());
                    strcat(post, tmp);
                    stack.pop();
                }
                stack.push(*cptr);
            }
            else if(*cptr == '(')
            {
                stack.push(*cptr);
            }
            else if(*cptr==')')
            {
                while(stack.empty()==0)
                {
                    if(stack.top()=='(')
                    {
                        stack.pop();
                        break;
                    }
                    if(stack.top()==')')
                    {
                        continue;
                    }
                    sprintf(tmp, "%c", stack.top());
                    strcat(post, tmp);
                    stack.pop();
                }
            }
            *cptr++;
        }
        while(stack.empty()==0)
        {
            sprintf(tmp, "%c", stack.top());
            strcat(post, tmp);
            stack.pop();
        }
        cout<<post<<endl;
        cin.get();
    }
    

    Saturday 19 July 2014

    Ajith KP

    Program to calculate Days between two dates in C++

              This question is very basic and confusing for beginners. Calculate the days between two dates is bit easy if you think deeply.



              Calculating Days : Algorithm

             
              If day2 - day1 <= -1 :
    
                        days = daysOfMonth(month1)-day1+day2;
    
              Else:
    
                        days = day2-day1;
    

              Calculating Months : Algorithm:

           
              If day2 - day1 <= -1:
    
                        If month2 - month1 <= -1:
    
                                  months = 12+month2-month1-1;
    
    
                        Else:
    
                                  months = month2-month1-1;
    
              Else:
    
                        If month2 - month1 <= -1:
    
                                  months = 12+month2-month1;
    
                        else:
    
                                  months = month2-month1;
    
    

              Calculating Years : Algorithm


              If month2 - month1 <= -1:
    
                        years = year2-year1-1;
    
              Else:
    
                        years = year2-year1;

              Source Code


    /*
        [][][]
        [][][]
        [][][]
        [][][]  TerminalCoders.Blogspot.de
        [][][]
        [][][]
        [][][]
    */
    #include <iostream>
    using namespace std;
    class date
    {
        public:
            int day, month, year;
            void read()
            {
                cout<<"Enter date: ";
                cin>>day>>month>>year;
            }
            date operator -(date);
            int daysOf(int m, int y)
            {
                int days=0;
                if(m==1||m==3||m==5||m==7||m==8||m==10||m==12)
                {
                    days=31;
                }
                else if(m==2 && y%4==0 && !(y % 100 == 0))
                {
                    days = 29;
                }
                else if(m==2)
                {
                    days = 28;
                }
                else
                {
                    days = 30;
                }
                return days;
            }
    };
    date date::operator -(date d)
    {
        date df;
        int days    = daysOf(month, year);
        df.day      = ((-1>=d.day-day)?days-day+d.day:d.day-day);
        df.month    = ((-1>=d.day-day)?(-1>=d.month-month?12+d.month-month-1:d.month-month-1):(-1>=d.month-month?12+d.month-month:d.month-month));
        df.year     = ((-1>=d.month-month)?d.year-year-1:d.year-year);
        return df;
    }
    
    int main()
    {
        date d1, d2, d3;
        d1.read();
        d2.read();
        d3 = d1 - d2;
        cout<<"Days between are: "<<d3.day<<" Days : "<<d3.month<<" Months : "<<d3.year<<" Year";
        cin.get();
        return 0;
    }
    

    Thursday 17 July 2014

    Ajith KP

    Stacks

              Stack is another data structure like queue, also the stack is ordered list like queue. The difference is stack allows addition and deletion of items at one end only. This end is called bottom of stack and inactive end is called bottom of stack. The slices of bread is a daily life example for stack. We are usually takes bread from one end and places the bread at same end. So we can say that the stack follows LIFO(Last In First Out) principle.

    http://www.visualphotos.com/image/2x3535478/stack_of_sliced_bread


              We can perform two operations on stack. They are,
    • PUSH: Addition of new item.
    • POP: Deletion of item.
              The stacks have important data structure in computer. They are applied in evaluation of mathematical expressions, execution of programs, etc.

    Wednesday 16 July 2014

    Ajith KP

    BINGO - A Simple Game on Java

              BINGO[^] is a simple Game which can be played by two peoples. This game needs a 5x5 matrix box which is filled by 1 to 25 numbers in any manner. One of the player will say a number in box and both player should mark the number. After it the other player will say another number and should mark both player. The aim of game is to mark rows or column fully. If you mark a row or column completely you will get a score. The player who score 5 points will won.

              This is very basic version. It have no features like connecting friends via internet and auto marking. I will give the advanced version's code later.

    BINGO GAME IN JAVA




    /*
     *  []
     *  []
     *  []
     *  []                     [a][j][i][t][h][k][p][5][6][0]
     *  []      -------------> http://terminalcoders.blogspot.in <-------------
     *  []                     [a][j][i][t][h][k][p][5][6][0]
     *  []
     *  []
     *  []
     */
    
    package bingo;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.*;
    public class BINGO extends JFrame {
        JTextField flds[] = new JTextField[25];
        JButton btn = new JButton("SUBMIT");
        JPanel pnl = new JPanel(new GridLayout(5,5, 2, 2));
        TextHandle hld = new TextHandle();
        JLabel lbl = new JLabel("Coded By Ajith Kp");    
        public BINGO()
        {        
            super("BINGO --- AJITH KP");
            setLayout(new BorderLayout());  
            
            lbl.setForeground(Color.BLUE);
            lbl.setFont(new Font("Times New Roman", Font.BOLD, 25));
            lbl.setBorder(BorderFactory.createMatteBorder(3, 3, 3, 3, Color.green));
            lbl.setHorizontalAlignment(JLabel.CENTER);
            for(int i=0; i<flds.length; i++)
            { 
                flds[i] = new JTextField();
                flds[i].addMouseListener(null);
                flds[i].setForeground(Color.BLACK);
                flds[i].setHorizontalAlignment(JLabel.CENTER);
                flds[i].setBorder(BorderFactory.createMatteBorder(0, 0, 0, 0, Color.red));
                flds[i].setBackground(Color.CYAN);
                flds[i].setFont(new Font("Times New Roma", Font.BOLD, 25));
                pnl.add(flds[i]);
            }
            
            
            btn.addActionListener(
                    new ActionListener()
                    {
                        @Override
                        public void actionPerformed(ActionEvent e) {
                            pnl.repaint();
                            int num[] = new int[25];
                            for(int i=0; i<flds.length; i++)
                            {
                                try 
                                {
                                    num[i] = Integer.parseInt(flds[i].getText());
                                    flds[i].setBorder(BorderFactory.createMatteBorder(0, 0, 0, 0, Color.red));
                                } 
                                catch (Exception ex) {
                                    Logger.getLogger(BINGO.class.getName()).log(Level.SEVERE, null, ex);
                                }
                            }
                            Boolean flg = false;
                            for(int i=0; i<flds.length; i++)
                            {
                                if(num[i]<1 || num[i]>25)
                                {
                                    flds[i].setBorder(BorderFactory.createMatteBorder(3, 3, 3, 3, Color.red));
                                    flg = true;
                                }
                                for(int j=i+1; j<flds.length; j++)
                                {
                                    if(num[i] == num[j])
                                    {
                                        flds[i].setBorder(BorderFactory.createMatteBorder(3, 3, 3, 3, Color.red));
                                        flds[j].setBorder(BorderFactory.createMatteBorder(3, 3, 3, 3, Color.red));
                                        flg = true;
                                    }
                                }
                            }
                            if(flg == false)
                            {
                                btn.setEnabled(false);
                                for(int i=0;i<flds.length;i++)
                                {
                                    flds[i].setEditable(false);
                                    flds[i].setBorder(BorderFactory.createMatteBorder(3, 3, 3, 3, Color.green));
                                    flds[i].addMouseListener(hld);
                                    
                                }
                            }
                        }
                    });
            add(pnl, BorderLayout.CENTER);
            add(btn, BorderLayout.SOUTH);
            add(lbl, BorderLayout.NORTH);
        }
        public class TextHandle extends MouseAdapter 
            {
                @Override
                public void mouseClicked(MouseEvent e) {            
                    JTextField fld = (JTextField) e.getSource();
                    fld.setForeground(Color.red);
                    fld.setBorder(BorderFactory.createMatteBorder(3, 3, 3, 3, Color.red));
                    fld.setText("X");
                    check();
                }
    
                private void check() {
                    Boolean check;
                    int n = 0;
                    char[] bingo = {'B', 'I', 'N', 'G', 'O'};
                    String bin = "";
                    for(int i=0;i<5;i++)
                    {
                        check = false;
                        for(int j= i*5; j< (i+1)*5; j++)
                        {
                            if(!flds[j].getText().equals("X"))
                            {
                                check = true;
                            }
                        }
                        if(check == false)
                        {
                            n++;
                        }
                    }
                    for(int i=0; i<5; i++)
                    {
                        check = false;
                        for(int j=i; j<25; j=j+5)
                        {
                            if(!flds[j].getText().equals("X"))
                            {
                                check = true;
                            }
                        }
                        System.out.println();
                        if(check == false)
                        {
                            n++;
                        }
                    }
                    if(n!=0)
                    {
                        for(int i=0;i<n;i++)
                        {
                            bin+=bingo[i];
                        }
                        lbl.setText(bin);
                    }
                    if(n==5)
                    {
                        lbl.setForeground(Color.red);
                    }
                }
            }
        public static void main(String[] args) {
            BINGO b = new BINGO();
            b.setSize(400, 420);
            b.setVisible(true);
            b.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }
    }
    

    Sunday 13 July 2014

    Ajith KP

    Circular Queue Implementation n CPP

    Circular Queue implementation in C++....



    //Coded By AJITH KP
    //http://terminalcoders.blogspot.com/
    #include <iostream>
    using namespace std;
    class circQ
    {
     int q[100], n, i;
     int ch, cnt, item, FR, RR;
     public:
     circQ()
     {
      cnt = 0;
      FR = RR = 1;
     }
     void read()
     {
      cout<<"Enter the limit: ";
      cin>>n;
      for(i = 0; i < n; i++)
      {
       q[i] = 0;
      }
      menu();
     }
     int menu()
     {
      cout<<"\t\t\tMENU\n";
      cout<<"\t1. Add Element\n";
      cout<<"\t2. Remove Element\n";
      cout<<"\t3. Display Elements\n";
      cout<<"\t4. Exit\n";
      while(ch!=4)
      {
       cout<<"ENTER CHOICE: ";
       cin>>ch;
       switch(ch)
       {
        case 1:
         addQ();
         break;
        case 2:
         delQ();
         break;
        case 3:
         disQ();
         break;
        case 4:
         break;
        default:
         cout<<"Your choice is wrong\n";
         break;
       }
      }
      cout<<"\nExiting...\n";
      return 0;
     }
     int addQ()
     {
      if((RR+1)%n == FR)
      {
       cout<<"\nQueue is full\n";
       return NULL;
      }
      cout<<"Enter Element: ";
      cin>>item;
      q[RR] = item;
      RR = ++RR%n;
      return 0;
     }
     int delQ()
     {
      if(FR == RR)
      {
       cout<<"\nQueue is empty\n";
       return NULL;
      }
      item = q[FR];
      cout<<"\nItem "<<item<<" deleted"<<endl;
      q[(FR%n)] = 0;
      FR = ++FR % n;
      return 0;
     }
     void disQ()
     {
      cout<<"\nQUEUE:";
      for(i = 0; i < n; i++)
      {
       cout<<" "<<q[i];
      }
      cout<<endl;
     }
    };
    
    int main()
    {
     circQ q;
     q.read();
     cin.get();
    }
    


    Ajith KP

    Circular Queue

              Circular queue[^] is implemented to overcome the limitations of Linear Queue. As name indicates, this type of queue has a logical structure of queue even though it is stored in 1D in memory. The two flags called "Front" and "Rear" gives the logical circular structure.These flags moves in circular fashion to give circular structure.



              In this queue, the new item is added at position `(Rear + 1) % Size` (% - Modular Division). And check the queue "Full" and "Empty" condition using `Rear = Front`. So the queue can check whether the queue is physically full or not. So this mechanism uses memory space efficiently than linear queue.

             Circular Queue implementation in CPP: http://terminalcoders.blogspot.in/2014/07/circular-queue-implementation-in-c.html

    Saturday 12 July 2014

    Ajith KP

    Queue Implementation - CPP

    /*
        Implementation of Queue in CPP
        [][][]
        [][][]
        [][][]
        [][][]  Terminalcoders.Blogspot.de
        [][][]
        [][][]
        [][][]
        
        EXPLAIN VARIABLES PROGRAM
        
        [] q     ---> Queue
        [] size  ---> Size of queue
        [] fr    ---> Front
        [] rr    ---> Rear
        [] item  ---> Iteam from queue
    */
    #include<iostream>
    using namespace std;
    class queue
    {
        int q[100], size, fr, rr, i, item;
        public:
            void read()
            {
                cout<<"Enter the size of queue: ";
                cin>>size;
                fr = rr = 0;
            }
            void menu()
            {
                int opt = 0;
                while(opt!=4)
                {
                    cout<<"\t\t\tMENU\n";
                    cout<<"\t1. Insert item\n";
                    cout<<"\t2. Delete item\n";
                    cout<<"\t3. Show\n";
                    cout<<"\t4. Exit\n";
                    cout<<"Option: ";
                    cin>>opt;
                    switch(opt)
                    {
                        case 1:
                            insert();
                            break;
                        case 2:
                            delet();
                            break;
                        case 3:
                            show();
                            break;
                        case 4:
                            break;
                    }
                }
                cout<<"Exiting...";
            }
            void insert()
            {
                while(rr==size) // Queue is full
                {
                    cout<<"Queue is full\n";
                    return;
                }
                cout<<"Enter item to insert: ";
                cin>>q[rr++];
            }
            void delet()
            {
                while(fr==rr) //Queue is empty
                {
                    cout<<"Queue is empty\n";
                    return;
                }
                item = q[fr++];
                cout<<"The item "<<item<<" is deleted\n";
            }
            void show()
            {
                cout<<"\nQueue: ";
                for(i=fr;i<rr;i++)
                {
                    cout<<q[i]<<" ";
                }
                cout<<endl;
            }
    };
    
    int main()
    {
        queue q;
        q.read();
        q.menu();
    }
    
    
    
    Ajith KP

    Queues

              Queue is a linear data structure represented in One Dimensional ( 1D ) array. Queue follows principle of FIFO ( First In First Out ). So the first item, that is item at "Front" is serviced first and remove first. The new item will be added after the last item at "Rear" and change the position of "Rear" to new item added.



              There are two operations that can be done in queue.
           

    • Insert
    • Delete
              Insertion operation also called en-queuing and deletion also called de-queuing .

              Queue have disadvantage that the queue checks only one condition to check whether queue is full or not. The condition is "Rear = Size". But it is not checking whether the queue is physically full or not. This disadvantage leads another implementation of queue called "Circular queue".

              Implementation of queue: http://terminalcoders.blogspot.in/2014/07/queue-implementation-cpp.html

    Friday 11 July 2014

    Ajith KP

    Efficiency of Algorithm

         Every problem can be solved in many ways. So we need to take care to select the algorithm which is preferable and best among them.



         The performance of algorithm can be measured in terms of time and space consumed by the algorithm. The characteristics of best algorithm is it use less time and space  compared to other algorithms.

        Time Complexity: Running time of an algorithm.
        Space Complexity: Memory space needed by algorithm.

        The time and space complexity of algorithm is calculated in two ways. The first one is practically calculating the time and space needed by algorithm. The second one is theoretically calculating the time and space needed by algorithm.

        Empirical Approach: Calculate the time and space needed by algorithm by executing it on a computer.
        Theoretical Approach: Mathematically calculating the time and space needed by algorithm.

        The empirical approach depends on various factors that the machine on which program is executed, programming language which is implemented, etc.

        Eg. The same code implemented in C and Python. The executable file of C will execute faster than interpretation of Python code.

         But the theoretical approach is independent from these factors. So theoretical approach is believable than. 

    Friday 4 July 2014

    Ajith KP

    Algorithm: An Introduction

              Algorithm is step procedure  for calculation, data processing, and automated reasoning.[^].
              Arabic mathematician Al Khwarizmi is considered to be first algorithm designer. Also the word algorithm derived from Arabic word "Algorism".


              The algorithm should follow these properties.

    • Finiteness: Algorithm must have finite number of steps and terminate after these steps.
    • Effectiveness: Algorithm must be effective to solve the problem in a simple way.
    • Definiteness: The steps must be defined clearly and may not be ambiguous.
    • I/O: An algorithm should have inputs and outputs that will generate intermediate and final results.
            This is an introduction for "ALGORITHM". There are many things to say about algorithms.