Tuesday, December 31, 2013

A Broken Loop C puzzle

Question:

Find three ways to make the following program to print 20 times - (dash) by changing / adding just one character.

int i, n=20;
for(i=0; i < n; i--)
printf("-");


Answers:

/* FileName: printdash.c */

#include <stdio.h>
void main()
{
  int i, n=20;

  for(i=0; i+n; i--)
  printf("- ");
  printf("\n");

  for(i=0; -i < n; i--)
  printf("- ");
  printf("\n");

  for(i=0; i < n; n--)
  printf("- ");
  printf("\n");

}

To Run: gcc printdash.c
               ./a.out



Monday, December 30, 2013

Mapping - UnMapping A XWindow

                Because of race condition lot of people face problems in Mapping or UnMapping  a particular Xwindow and all of its sub-windows that have had map / unmap requests in X11R6. In this post I am going to show you how to Map and UnMap a Xwindow based on MapNotify and UnmapNotify events.



 /* FileName: Map_UnMap.cpp */

#include <X11/Xlib.h>
#include <assert.h> 
#include <unistd.h>
#include <iostream>
#include <stdio.h>
#define NIL (0)

int main()
{

      Display *dpy = XOpenDisplay(NIL);
      assert(dpy);

      int blackColor = BlackPixel(dpy, DefaultScreen(dpy));
      int whiteColor = WhitePixel(dpy, DefaultScreen(dpy));


      Window w = XCreateSimpleWindow(dpy, DefaultRootWindow(dpy), 0, 0,
                     200, 100, 0, blackColor, blackColor);

      XSelectInput(dpy, w, StructureNotifyMask);

      XMapWindow(dpy, w);
      sleep(2);
      printf( "Mapping : : 0x%x\n", (unsigned int)w);
      int count=1;
           
      GC gc = XCreateGC(dpy, w, 0, NIL);
      XSetForeground(dpy, gc, whiteColor);

      XEvent event;

      while ( 1 ) {
        XNextEvent( dpy, &event );
        if ( event.type == MapNotify ) {
            XMapEvent *mapevent = (XMapEvent *)&event;
            printf( "UnMapping    : 0x%x\n", (unsigned int)(mapevent->window) );
            ++count;
            XUnmapWindow(dpy, w);
            sleep(2);
        }

    if ( event.type == UnmapNotify ) {
            XUnmapEvent *unmapwindowevent = (XUnmapEvent *)&event;
            printf( "Mapping : 0x%x\n", (unsigned int)(unmapwindowevent->window) );
            ++count;
            XMapWindow(dpy, w);
            sleep(2);
        }
           if(count==10)
              break;

        if ( event.type == DestroyNotify ) {
            XDestroyWindowEvent *destroywindowevent = (XDestroyWindowEvent *)&event;
            printf( "Destroyed : 0x%x\n", (unsigned int)(destroywindowevent->window) );
        }
    }

      XFlush(dpy);
      sleep(3);
      return 0;
}

To Run: g++ Map_UnMap.cpp -lX11
             ./a.out

Programming A Webcam Recorder using OpenCV

There are 4 important steps in capturing video / images from webcam programmatically.
  1. Initialize webcam
  2. Capture frames from webcam for a particular duration
  3. Stop capturing frames from Webcam
  4. Release resources for escaping from memory leaks
Above mentioned 4 functionalities are implemented in the following class

/* File Name: WCRecorder.hpp */

#include <stdio.h>
#include <math.h>
#include <iostream>
#include <opencv/cv.h>
#include <opencv/highgui.h>
static int argc;
static char **argv;

class WebcamVideoRecorder
{
 public:
 CvCapture *capture;
 IplImage* rgb_image;
 bool initialized;
public:
 WebcamVideoRecorder(); /* constructor of  WebcamVideoRecorder calss */
 void Initialize(); /* Function to initialize webcam */
 void ProcessFrame(); /* Function to Capture frames from webcam */
 void StopProcessFrame(); /* Function to unCapture frames from webcam */
 void ReleaseResources(); /* function to release all resources */
};

/* File Name: WCRecorder.cpp */

#include <stdio.h>
#include <math.h>
#include <opencv/cv.h>
#include <opencv/highgui.h>
#include "WCRecorder_GUI.hpp"
/* Pre-requisite OpenCV-2.1.0 http://sourceforge.net/projects/opencvlibrary/files/opencv-unix/2.1/ */
/* Command to Run: g++ WCRecorder.cpp `pkg-config --cflags --libs opencv` */
using namespace std;

WebcamVideoRecorder::WebcamVideoRecorder() {
    capture = 0;
    rgb_image = 0;
    initialized = false;
}

void WebcamVideoRecorder::Initialize() {
    printf("OpenCV version %s (%d.%d.%d)\n", CV_VERSION, CV_MAJOR_VERSION,
            CV_MINOR_VERSION, CV_SUBMINOR_VERSION);
    capture = cvCaptureFromCAM(0);
    if (!capture) {
        fprintf(stderr, "Error in Capture...!!!\n");
        initialized = false;
    } else {
        cvNamedWindow("WebCam-Video-Recorder", 0);
        initialized = true;
    }
}

void WebcamVideoRecorder::ProcessFrame() {
    if (initialized) {
        string p_path(pfile_path);
        string p0_path(pfile_path);
        char str[10];
        CvVideoWriter *writer;
        IplImage *bgr_frame = cvQueryFrame(capture);
        CvSize size = cvGetSize(bgr_frame);
        rgb_image = cvCreateImage(cvGetSize(bgr_frame), bgr_frame->depth,
                bgr_frame->nChannels);
        if (vflag || pflag) {
            strcat((char*) vfile_path, ".avi");
            if (vflag)
                writer = cvCreateVideoWriter(vfile_path,
                        CV_FOURCC('I', 'Y', 'U', 'V'), 10.0, size);
            while (((bgr_frame = cvQueryFrame(capture)) != NULL)) {
                if (vflag)
                    cvWriteFrame(writer, bgr_frame);
                if (!bgr_frame)
                    break;
                cvCopy(bgr_frame, rgb_image);
                cvShowImage("WebCam-Video-Recorder", rgb_image);
                if (pflag) {
                    sprintf(str, "%d", ++nFrame);
                    p_path.append(str);
                    p_path.append(".jpeg");
                    cvSaveImage(p_path.c_str(), rgb_image);
                    p_path = p0_path;
                }
                char c = cvWaitKey(10);
                if (c == 27)
                    break;
            }
            cvReleaseVideoWriter(&writer);
        }
    }
    ReleaseResources();
}

void WebcamVideoRecorder::StopProcessFrame() {
    cvReleaseCapture (&capture);
}

void WebcamVideoRecorder::ReleaseResources() {
    cvReleaseImage (&rgb_image);
    cvReleaseCapture (&capture);
    cvDestroyWindow("WebCam-Video-Recorder");
}

int main(int argc_, char **argv_) {
    argc = argc_;
    argv = argv_;
    WebcamVideoRecorder WVR;
    WVR.Initialize();
    for(int i=0 ; i < 200 ; i++) /* here you can use timer to record that much of time */
    WVR.ProcessFrame();

    WVR.StopProcessFrame();
    WVR.ReleaseResources();
    return 0;
}

Friday, October 18, 2013

UNIX Shared Memory Implementation

-Shared Memory Allows two unrelated processes to access the same memory.
-Shared memory is created by one process and appears to other processes by attach.
-If one process writes to shared memory, the changes immediately visible to any
other process that has access to shared memory.
-Shared Memory provides no synchronization.


Header files to include: <sys/types.h> ,<sys/ipc.h>, <sys/shm.h> <unistd.h>

Creating Shared Memory:
int shmget (key_t key, size_t size, int shmflg);
- Key: unique identification to memory
- Size: of shared memory
- Shmflg: IPC_CREAT | WR permissions, IPC_PRIVATE
- Returns:On Success: shmid On failure: -1


Attaching Shared Memory:
void * shmat(int shmid, void * shmaddr, int shmflg)
– Shmid: returned by shmget
– Shmaddr: shared memory segment address (normally NULL)
– Shmflg : SHM_RDONLY, SHM_RND
- Returns: on success: attached address, on failure: (void*)-1


Detaching Shared Memory:
int shmdt (void *shmaddr)
– Shmaddr: address returned by shmat
- Returns: on success: 0 on failure: -1


Removing Shared Memory:
Shmctl(int shm_id, int cmd, struct shmid_ds *buf)
- shm_id: returned by shmget
- cmd: command to control shared memory ex: for remove IPC_RMID
- Returns: on success:0 On failure:-1


/* Shared Memory implementation */


/* FileName: SMServer.c */

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>

#define MAXSIZE  100

int main()
{
    char c;
    int shmid;
    key_t key;
    char *shm, *s;

    key = 1234;

     // Creating shared memory  
     if ((shmid = shmget(key, MAXSIZE, IPC_CREAT | 0666)) < 0)
        {
           printf("Error in creating shared memory \n");
           exit(0);
        }
     else
         printf("Shared Memory Created with id %d\n", shmid);
    // Attaching shared memory to this process

    if ((shm = shmat(shmid, NULL, 0)) == (char *) -1)
        {
           printf("Error in attaching shared memory \n");
        }
     else
        printf("Shared memory attached \n");

    s = shm;

   // Writing data on shared memory
   printf("\nEnter a message to add to message queue: ");
   scanf("%[^\n]s",s);
   getchar();
   printf("Entered message now available on Shared memory \n");

   // Deleting shared memory
   //if(shmctl(shmid, IPC_RMID, 0)==0)
     //printf("Shared memory deleted\n");

    exit(0);
}

To Run: gcc  SMServer.c
              ./a.out




/* FileName: SMClient.c */


#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>

#define MAXSIZE  100

int main()
{
    int shmid;
    key_t key;
    char *shm, *s;

    key = 1234;

    if ((shmid = shmget(key, MAXSIZE, 0666)) < 0)
        {
           printf("Error in accessing shared memory \n");
           exit(0);
        }
        else
        {
           printf("Accessing shared memory od id %d\n", shmid);
        }

    if ((shm = shmat(shmid, NULL, 0)) == (char *) -1)
        {
           printf("Error in attaching shared memory\n");
        }
    else
        {
           printf("Shared Memory Attached \n");
        }

    //Now read what the server put in the memory.
    for (s = shm; *s != '\0'; s++)
        putchar(*s);
        putchar('\n');

   if(shmdt(shm)==0)
     {
         printf("Shared memory detached\n"); 
        
     }
    exit(0);
}

To Run: gcc  SMClient.c
              ./a.out


Mapping & Unmapping a XWindow

XMapWindow(Display*, Window) - is used to map(visible) a Xwindow on top of all window.

XUnmapWindow(Display*, Window) - is used to unmap(hime) a Xwindow.

/* CPP program to map & unmap a Xwindow */
/* FileName: MapUnMap.cpp */


#include<X11/Xlib.h>
#include<assert.h> 
#include<unistd.h>
#include<iostream>
#include<stdio.h>
#define NIL (0)

int main()
{

      Display *dpy = XOpenDisplay(NIL);
      assert(dpy);

      int blackColor = BlackPixel(dpy, DefaultScreen(dpy));
      int whiteColor = WhitePixel(dpy, DefaultScreen(dpy));


      Window w = XCreateSimpleWindow(dpy, DefaultRootWindow(dpy), 0, 0,
                     200, 100, 0, blackColor, blackColor);

      XSelectInput(dpy, w, StructureNotifyMask);

      XMapWindow(dpy, w);
      sleep(2);
      printf( "Mapping : : 0x%x\n", (unsigned int)w);
      int count=1;
           
      GC gc = XCreateGC(dpy, w, 0, NIL);
      XSetForeground(dpy, gc, whiteColor);

      XEvent event;

      while ( 1 ) {
        XNextEvent( dpy, &event );
        if ( event.type == MapNotify ) {
            XMapEvent *mapevent = (XMapEvent *)&event;
            printf( "UnMapping    : 0x%x\n", (unsigned int)(mapevent->window) );
            ++count;
            XUnmapWindow(dpy, w);
            sleep(2);
        }

    if ( event.type == UnmapNotify ) {
            XUnmapEvent *unmapwindowevent = (XUnmapEvent *)&event;
            printf( "Mapping : 0x%x\n", (unsigned int)(unmapwindowevent->window) );
            ++count;
            XMapWindow(dpy, w);
            sleep(2);
        }
           if(count==10)
              break;
    }

      XFlush(dpy);
      sleep(3);
      return 0;
}



To Run: g++ MapUnMap.cpp -lX11

               ./a.out

Tuesday, July 2, 2013

Scanf Search Sets in C Programming

         Search sets are sets of characters, which are enclosed in square braces []. These search sets are generally parts of some format specifier. For example, the format specifier %[/-] tells scanf to match any sequence of characters consisting of / and -. All these characters are assigned to the corresponding argument. This argument must be the name of the string. Lets us see how these search sets are used.

// Program Name: Scan_Sets.c

#include <stdio.h>

void main()
{
 
 int date, month, year;
 char separator[2];
 printf("\n Input your date of birth:");
 scanf("%d%[-/]%d%[-/]%d", &date,separator,&month,separator,&year);
 printf("\n Date: %d", date);
 printf("\n Month: %d", month);
 printf("\n Year: %d", year);

}

To Run: gcc Scan_Sets.c
             ./a.out
Input:  Input your date of birth: 12-12/2012
Output: Date: 12
               Month: 12
               Year: 2012

           While scanning the input, scanf will put the hyphen(-) after the date into the separator and after scanning the month, it will place the slash(/) into separator again. Though the program works as expected, we are having the string separator without actually using it for any purpose, other than temporarily storing the separator characters.  

         To avoid this temporary storing we can use assignment suppressing character(*). Using an assignment suppression character tells the scanf that the input field should only be scanned and not assigned to any argument. Let us modify the above program using  assignment suppression character so that we can avoid separator.

// Program Name: Scan_Sets_Sup.c

#include <stdio.h>

void main()
{
 
 int date, month, year;
 char separator[2];
 printf("\n Input your date of birth:");
 scanf("%d%*[-/]%d%*[-/]%d", &date,&month,&year);
 printf("\n Date: %d", date);
 printf("\n Month: %d", month);
 printf("\n Year: %d", year);

}

To Run: gcc Scan_Sets_Sup.c
             ./a.out
Input:  Input your date of birth: 12/12/2012
Output: Date: 12
               Month: 12
               Year: 2012

Friday, June 28, 2013

SANGRAH - Knowledge Repository for FOSS in Education

          We are announcing the release of our portal Sangrah - Knowledge Repository for FOSS in Education http://nrcfoss.cdacmumbai.in/sangrah. The portal contains resources about different categories like Learning Management System, Content Management System, etc. It also contains user experiences for these categories, comparative analysis of various tools from these categories, specialised search, and collaboration facility for community supported content updates.



           The portal is maintained with least manual intervention as most of the tasks including, resource collection, categorization, user experience identification, comparative analysis, etc are largely automated.

           The portal is intended for academic institutions, entrepreneurs, among others to help them to adopt Free and Open Source Softwares (FOSS). The portal is still evolving, so kindly provide your feedback, improvement suggestions through the feedback section on portal.

  Kindly visit and register on the portal at - http://nrcfoss.cdacmumbai.in/sangrah

Regards
sangram Team.

Monday, June 17, 2013

PGDST Course Details of CDAC Kharghar

Hello,

C-DAC Mumbai is offering 1-year full-time Post Graduate Diploma in Software Technology (PG-DST) for the past several years with excellent placement records. The course provides a systematic blend of theory and hands-on, foundational and advanced concepts, and includes current trends and technologies.

Admission is now open for the next batch of PG-DST commencing on 27th August 2013, and its admission test (CST) will be held on 14th July 2013.

Course Synopsis

The 1-year full-time PG-DST course offers a carefully defined blend of theory and hands-on, foundational and advanced concepts, and includes current trends and technologies. The overall objective of the course is to build usable technical skills for practical application development over web and mobiles, using state-of-the-art technologies and frameworks. The course lays emphasis on the ability to move effectively from problem statements to working programs.

While learning programming languages, one often tends to focus on the intricacies of the language, rather than looking at it as a tool for problem solving. Keeping this in mind, the whole course is built around the notion of “from problems to programs”. All relevant software engineering practices are given emphasis from the beginning, including bug tracking, version control, project management, and so on. PG-DST has practical assignments or mini-projects in every module that provide exposure to a number of state-
of-the-art software tools and environments.

The course exposes the candidates to a variety of tools and frameworks, and expects proficiency in them. The list includes programming languages (C, C++ and Java), database systems (MySQL, Oracle, Hibernate, NoSQL), development frameworks (Spring, HTML-5, PHP, JavaScript), tools in software engineering (Redmine, Git), Operating systems (Gnu/Linux, Windows, Android), etc.

PG-DST Syllabus
  • Programming & Problem Solving - Procedural programming, Object oriented programming, Data structures, Algorithm design and analysis, File handling, Multi-threaded programming.
  • Operating System Concepts & Networking - Resource & CPU scheduling, Concurrency control, Memory management, Networking protocols, OSI layers & functions, Network security.
  • Database Technologies - SQL & query optimization, Database design, Relational databases, Object oriented databases, ORM technologies, Unstructured data.
  • Web Application Development - Client-server/Multi-tier architecture, JavaScript, HTML5, GUI design, Server side programming with PHP, Web development framework, Web services and SOA.
  • Software Engineering - Requirement gathering, Analysis & design, Software development life cycle including agile, Bug tracking, Version control, Software architecture including design patterns.
  • Advanced Topics - Machine Learning, Data mining, Mobile computing, Cloud computing, etc.
  • Soft Skills - Communication, Presentation, Time management, Team handling, etc.
  • Live Project - Complete development project covering the entire SDLC.
Salient Features
  • Excellent placement record.
  • Over 30 years of history in training software professionals.
  • Practical assignments or mini-projects in every module.
  • Complete development project covering the entire SDLC as course project including use of version control and bug-tracking.
  • Exposure to a number of state-of-the-art software tools and environments.
  • Systematic blend of foundational concepts and practical skills.
  • Use of technology enhanced education for improved learning and assessment.
  • Some universities consider PG-DST as equivalent to the first year of their MSc programme.
  • Hostel facility available on a first-come-first-served basis.

PG-DST Centre: C-DAC Kharghar
Course Commencement: 27th August 2013
Fees: Rs 79,000/-
Eligibility Criteria: Graduate in any subject
Admission Test: Competence in Software Technology (CST) Exam
General Aptitude (1 hour)
Logical reasoning, Quantitative reasoning, Visual-spatial reasoning, High school mathematics, Vocabulary, English comprehension & Verbal ability
Computer Concepts (1 hour)
Computer basics, Data representation, Binary arithmetic, Foundations, Computer architecture, Computer languages, Operating System basics, Basic programming using C
CST Exam Date: 14 July 2013
CST Exam Venues: Bengaluru, Mumbai, Noida & Patna
Last Date of Submitting CST Application Form: 3 July 2013
CST Application Fee: Rs 500/- (to be paid as DD or cash at C-DAC Kharghar)
Announcement of CST Results: 24 July 2013
For more information: entrance-mumbai@cdac.in

With best regards,

PG-DST Coordinator
C-DAC, Near Kharghar Rly Stn, Navi Mumbai (Tel 022-27565303)
C-DAC, Gulmohar Crossroad No. 9, Juhu, Mumbai (Tel 022-26703251)

Thursday, June 13, 2013

Changing Properties of Terminal / Console using termios

         Linux Devices are designed for interactive use, that means devices used both for input and for output. All the devices have a similar interface derived from the serial TeleType paper-display terminals and thus dubbed the tty interface. tty(TeleType) is a interface which is used to access serial terminals, consoles, xterms, network logins and many more.

        All tty manipulation can be done using termios structure and several functions which all are defined in <termios.h> header file. struct termios as follows.

struct termios
{
   tcflag_t c_iflag;         /* input mode flags */
   tcflag_t c_oflag;        /* output mode flags */
   tcflag_t c_cflag;         /* control mode flags */
   tcflag_t c_lflag;          /* local mode flags */
   cc_t c_line;                 /* line discipline */
   cc_t     c_cc[NCCS];   /* special characters */
}

c_iflag - determines how received characters are interpreted & processed
c_oflag - determines how your process writes to the tty are interpreted & processed
c_cflag - determines serial protocol characteristics of the devices
c_lflag - determines how characters are collected & processed before they are sent to output processing

The main two functions which are used to manipulate tty are
tcgetattr() - to get a device's current settings, modify those settings
tcsetattr() - to make the modify settings active

Now lets write a small program, where we can change the properties of our terminal / console pro-grammatically so that we can read a password without echoing it in console / terminal. To understand the code do not forget to read comments in the code.

// File Name: termios.c

 #include <stdio.h>
 #include <termios.h>
 #include <unistd.h>

 void main()
 {
    struct termios termios_temp, termios_orig;
    char pwdbuffer[1024];

    // getting and saving current termios settings
    tcgetattr(STDIN_FILENO, &termios_temp);
    termios_orig = termios_temp;

    // changing current termios settings, so that entered password can't be echoed
    termios_temp.c_lflag &= ~ECHO;
    termios_temp.c_lflag |=ECHONL;
    tcsetattr(STDIN_FILENO, TCSAFLUSH, &termios_temp);
    printf("NOTE: termios settings changed, so entered pwd can't be echoed :-)\n");

    // checking that the settings took effect or not
    tcgetattr(STDIN_FILENO, &termios_temp);
    if(termios_temp.c_lflag & ECHO)
    {
        fprintf(stderr, "failed to turn off echo");
        // setting original termios settings
        tcsetattr(STDIN_FILENO, TCSANOW, &termios_orig);
    }
  
    // getting pasword and printing the password
    printf("Enter Password:");
    fflush(stdout);
    fgets(pwdbuffer, 1024, stdin);
    printf("Your Entered Password is: %s", pwdbuffer);
  
    // setting original termios settings
    tcsetattr(STDIN_FILENO, TCSANOW, &termios_orig);
    printf("NOTE: termios settings changed to original:-)\n");
}

To Run: gcc termios.c
              ./a.out

Sunday, June 2, 2013

Adding / Injecting Audio Track to Video Without Audio

Suppose you have a video file and that video has no sound. You have a separate audio Mp3 file which is of same length (same play time) as video file and you want to inject / add that audio file to video file. How it can be done?

It can be done by using mencoder, is a encoder for popular MPlayer.

To Add / inject audio file into video file, please following the following instructions.

Step-1: Install mencoder using following command
             $sudo apt-get install mencoder.

Step-2: Move audio file and video without audio file into same folder
             $mv myAudio.mp3 /home/myhome/InjectAudo/
             $mv myVideo.avi /home/myhome/InjectAudo/

Step-3: Run following commands to add/ inject audio into video
             $cd /home/myhome/InjectAudo/
             $mencoder -ovc copy -audiofile myAudio.mp3 -oac copy myVideo.avi -o OutPutAVFile.avi

Step-4: Play OutPutAVFile.avi file.


Saturday, May 25, 2013

One Day Workshop on Parikshak - An Online Program Grading System

                             Computer Programming is an important aspect of any computer-science/information-technology course. This is among the most difficult to teach, since being a good programmer is a skill to be acquired coupled with knowledge of many different aspects such as abstraction, analysis, structured programming, debugging, etc. Usually computer programming is taught through a combination of theory classes on concepts and languages, and lab classes on specific languages. Assignments are given, which are manually graded by the instructor. Manual grading of programs is very tedious and time consuming. While evaluating student assignments the teacher has to act as a compiler/interpreter and inspect each line in program and judge whether the overall program would work correctly. While this grading approach works fine for a small number of simple assignments, it gets unwieldy as the complexity and number of the assignment increases. This, in turn, results in inadequate attention to the practical programming skills of students.
                   Parikshak is a web based system which offers a solution to this. A tool like Parikshak, which facilitates automated evaluation of software programs can significantly reduce the load of the faculty, give direct feedback to student, thereby leading to efficient handling of programming assignments/exams. Parikshak allows teachers to define programming assignments systematically, allows registered students to attempt solving them online, and automatically assesses the solution. The feedback is available to the students and the faculty, for follow up and record. Using Parikshak to manage your programming component, clearly offers many advantages.
                    During the workshop, we will demonstrate the system, discussing various ways in which tool can be used in the academic setting, and provide hands-on for faculty. Since we have limited number of seats, we request you to confirm participation from your colleges latest by June 12, 2013, by email or phone call. Teachers from the CS/IT departments are preferred, though others with some programming experience/interest are welcome.



Contact Information
Details of workshop
Phone: 022-27565303, Extn 301
Contact Person: Ms. Mercy Sobhan
Date & Timing: Sat, 15 June, 2013
10:00 AM – 5:00 PM
Venue: CDAC Kharghar
Registration Fees: Rs 600/-
Tea and Lunch will be provided to all participants

Registration fee has to be paid by Demand Draft / Cheque (local or at par) drawn in favour of CDAC payable at Mumbai. Please mention your name, organization and contact no. on the back side of the Demand Draft / Cheque.

Looking forward to your support and participation

Thanking you,


Monday, May 20, 2013

Plotting / Creating Graphs in C / C++

Graph (Chart): A graph is a diagram / picture which is showing a relation between two variable quantities.

In this post,  I am going to show you, how to create or plot a graph(chart) in C / C++ program using gnuplot tool. GNUPLOT is a command line tool to generate 2D and 3D graphs. 

Lets write a small program to create a graph as shown below using C / C++ program with gnuplot tool.

Note: Before running following program make sure you have installed gnuplot. (sudo apt-get install gnuplot)


// File Name: GraphPlotting.c
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#define NO_OF_POINTS 11
#define NO_OF_COMMANDS 4

void main()
{
    // X, Y Co-ordinate values
    double X_Values[NO_OF_POINTS] = {0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0};
    double Y_Values[NO_OF_POINTS] = {0.0 ,0.5, 0.0, 1.0, 0.0, 1.5, 0.0, 1.0, 0.0, 0.5, 0.0};
    register int i=0;
    // Creating & Opening Co-ordicates.txt file in Write mode
    FILE * CO_Ordinates_FILE = fopen("Co-ordicates.txt", "w");
    // Writing Co-Ordinates into Co-ordicates.txt file
    for (i=0; i  <  NO_OF_POINTS;  i++)
    fprintf(CO_Ordinates_FILE, "%lf %lf \n", X_Values[i], Y_Values[i]);
    // List of commannds to run on gnuplot
    char * CMDsFOR_GNUPLOT[] = {"set title \"RENI V/S SAM\"",
                                "set xlabel \"----RENI--->\"",
                                "set ylabel \"----SAM--->\"",
                                "plot \"Co-ordicates.txt\" using 1:2 with lines"
                               };
    // Opening gnuplot using pipe IPC
    FILE * GNUPLOT_Pipe = popen ("gnuplot -persist", "w");
    // Executing gnuplot commands one by one
    for (i=0; i  <  NO_OF_COMMANDS;  i++)
    fprintf(GNUPLOT_Pipe, "%s \n", CMDsFOR_GNUPLOT[i]);
}

To Run: gcc GraphPlotting.c
              ./a.out

Friday, May 10, 2013

Listing Input devices in C / C++

         Without  input devices we can't do anything with our computer / system. Here Input device may be Mouse, Keyboard, Touch screen, External touch pad, Pen tablet, Mic, camera etc.

         When we are programatically dealing with input devices, It is unavoidable to List / scan all input devices to get information about those devices. For this purpose we can use a X function called XListInputDevices.

Syntax:
XDeviceInfo * XListInputDevices(Display *display, int *ndevices)
where
Display *display Specifies the connection to the X server.
int *ndevices Specifies the address of a variable into which the server can return the number of input devices available to the X server.

XListInputDevices allows a client to determine which devices are available for X input and information about those devices. An array of XDeviceInfo structures is returned, with one element in the array for each device. The number of devices is returned in the ndevices argument. The X pointer device and X keyboard device are reported, as well as all available extension input devices. The use member of the XDeviceInfo structure specifies the current use of the device.

Lets write a small C program to list All Xinput devices using XListInputDevices.

//File Name: ListInputDevices.c
#include <stdio.h>
#include <X11/Xutil.h>
#include <X11/extensions/XTest.h>
#include <X11/extensions/XInput.h>

void main()
{
        int n, i=0;
        XDeviceInfo *devList, *curDev;
        // Connecting to XServer
        Display *dpy = XOpenDisplay(0);
        // Getting Input Device list
        devList = XListInputDevices(dpy, &n);
        // Checking for more then 0 devices
       if (!devList)
        printf("\n No Input devices to List");
        // Listing devices ID and NAME
        while(i < n)
        {
                curDev = devList + i;
                printf(" DEVICE ID: %d ",curDev->id);
                printf(" DEVICE NAME: %s \n",curDev->name);
                i++;             
    }
}
To Run: gcc ListInputDevices.c -lX11 -lXi
             ./a.out

Out Put: Your All Xinput Devices


Monday, May 6, 2013

Drawing With Mouse - An Example for Event Handling in X Window System (X11) Programming

What is X Window System?

The X Window System is client/server system for managing a windowed graphical user interface in a distributed network. In general, such systems are known as windowing system.

Event handling in X Window System Programming:

Most applications simply are event loops. They wait for an event, decide what to do with it, execute some amount of code that results in changes to the display, and then wait for the next event. X window system also provides large amount of support for event handling. Here I am going to show you how to draw with mouse as shown in this video, using X window System or X11 events. Watch Video Here: http://www.youtube.com/watch?v=dPVpKHGdi6A
  Screen shot:

// File Name: XEventHandling.c
#include <stdio.h>
#include <X11/Xutil.h>
#include <X11/cursorfont.h>
#include <X11/extensions/XTest.h>
#include <X11/extensions/XInput.h>
struct Point{
              int x;
              int y;
             }p1,p2;
void main()
{
 Display *dpy = XOpenDisplay(0);
 char *window_name = (char*)"Drawing window";
 int whiteColor = WhitePixel(dpy, DefaultScreen(dpy));
 Window parent = XCreateSimpleWindow(dpy, RootWindow(dpy, DefaultScreen(dpy)), 0, 0,
                     230, 150, 0, whiteColor, whiteColor);
 XStoreName(dpy, parent, window_name);
 XMapWindow(dpy, parent);
 XSelectInput(dpy, parent, ButtonPressMask| PointerMotionMask| LeaveWindowMask| EnterWindowMask| ButtonReleaseMask );
 Drawable d = parent;
 XGCValues values;
 values.line_width = 4;
 values.line_style = LineSolid;
 GC gc = XCreateGC(dpy, d, GCLineWidth, &values);
 int flag = 0;
 for(;;) {
   XEvent e;
   XNextEvent(dpy, &e);
   if(e.xany.window == parent)
     {
       switch(e.type)
        {
         case EnterNotify: printf("\n POINTER Entered in Window");
                           break;
         case LeaveNotify: printf("\n POINTER Left Window");
                           break;     
         case ButtonPress:if(flag == 0 && e.xbutton.button==1)
                          {
                          printf("\n Button %d Pressed at (%d, %d)", e.xbutton.button, e.xbutton.x, e.xbutton.y);
                          p1.x = e.xbutton.x;
                          p1.y = e.xbutton.y;
                          flag =1;
                          }
                          break;
         case ButtonRelease:if(flag == 1 && e.xbutton.button == 3)
                          {
                           printf("\n Button %d Pressed at (%d, %d)", e.xbutton.button, e.xbutton.x, e.xbutton.y);
                           flag =0;
                           XUnmapWindow(dpy, parent);
                           XMapRaised(dpy, parent);
                           XMoveWindow(dpy, parent, 0, 100);
                          }
                          break;
        case MotionNotify: if(flag ==1)
                          {
                           printf("\n Motion Notified at (%d, %d)", e.xbutton.button, e.xbutton.x, e.xbutton.y);
                           p2.x = e.xbutton.x;
                           p2.y = e.xbutton.y;
                           XDrawLine(dpy, parent, gc, p1.x, p1.y, p2.x, p2.y);
                           p1.x = p2.x;
                           p1.y = p2.y;
                           }                                        
                           break;                     
               }
          }
  }
}

To Run: gcc -lX11 XEventHandling.c 

              ./a.out
Out Put:  To Start drawing Click & release mouse button-1 in Drawing window
                 Move mouse pointer
                 To end drawing Click & release mouse button-3 in Drawing window
              

Thursday, May 2, 2013

Program To Create SVG Icon For A Software

Scalable Vector Graphics (SVG) is an XML-based vector image format. The SVG specification is developed by the World Wide Web Consortium since 1999.

Advantages of using SVG over other image formats (like JPEG and GIF) are:
  • SVG images can be created and edited with any text editor
  • SVG images can be searched, indexed, scripted, and compressed
  • SVG images are scalable
  • SVG images can be printed with high quality at any resolution
  • SVG images are zoomable (and the image can be zoomed without degradation)
  • SVG is an open standard
  • SVG files are pure XML
SVG images are zoomable, without degradation of quality, That's why most of the people use SVG images as their software icon. In this post i am going to show you, how to create SVG icon / image as shown below, for your software using C and Cairo graphics library.
NOTE: Before running the following program, plz make sure that you have already installed cairo library. (sudo apt-get install libcairo2-dev)

To Know How to create PDF files in C programming Click HERE.

 // File Name: SVGCreate.c

 #include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <cairo/cairo.h>
#include <cairo/cairo-svg.h>

void main() {
    // Declaring Variables
    cairo_t *cr;
    cairo_surface_t *surface;
    double x=25.6,  y=128.0;
    double x1=102.4, y1=230.4, x2=153.6, y2=25.6, x3=230.4, y3=128.0;
    surface = (cairo_surface_t *)cairo_svg_surface_create("R.E.N.I.svg", 250.0, 250.0);
    cr = cairo_create(surface);
    // Creating required graphics in SVG file
    cairo_move_to (cr, x, y);
    cairo_curve_to (cr, x1, y1, x2, y2, x3, y3);
    cairo_set_line_width (cr, 10.0);
    cairo_stroke (cr);
    cairo_set_source_rgba (cr, 1, 0.2, 0.2, 0.6);
    cairo_set_line_width (cr, 6.0);
    cairo_move_to (cr,x,y);   cairo_line_to (cr,x1,y1);
    cairo_move_to (cr,x2,y2); cairo_line_to (cr,x3,y3);
    cairo_stroke (cr);
    // Typing text in SVG file
    cairo_set_font_size (cr, 15);
    cairo_select_font_face (cr, "Georgia", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_BOLD);
    cairo_set_source_rgb (cr, 0, 0, 0);
    cairo_move_to(cr, 140, 150);
    cairo_show_text(cr, "R.E.N.I");
    // Destroying context and surface
    cairo_destroy (cr);
    cairo_surface_destroy (surface);
}

To Run: gcc -lcairo SVGCreate.c
              ./a.out
Out Put: It will create R.E.N.I.svg file in your current directory

Tuesday, April 30, 2013

Programming A Simple Kernel Program / Module

What is kernel?

A kernel is an important part of operating system, which acts as a bridge between user level applications and computer hardware. Kernel allows user level applications, to use system resources such as CPU, Memory, I/O Devices etc.

Why / When to write kernel Programs / Modules?

We know that there are two levels of programming. 1). User space level 2). Kernel level. We already writing so many user space level programs using C, C++, Java, D ...etc. Then why to write a kernel level programs/modules? The reasons are as follows

1). If your program / module excessively using low-level resources.
2). If you are defining a new interface / driver for hardware, which can not build on user level.
3). If you are developing something that is used by kernel subsystems.

Writing a Kernel Program / Module

Create a folder some where in your home directory and name that folder to USB_Module. Now create a C source file called usb_driver.c in that folder with the following source code.

// File Name: usb_driver.c
 #include <linux/kernel.h>
 #include <linux/module.h>
 #include <linux/init.h>

static int usb_driver_module_load(void)
{
     printk(KERN_INFO "USB-Driver Module Loaded...!!!\n");
     return 0;
}
static void usb_driver_module_unload(void)
{
     printk(KERN_INFO "USB-Driver Module UnLoaded...!!!\n");
}

module_init(usb_driver_module_load);
module_exit(usb_driver_module_unload);

MODULE_AUTHOR("Reniguntla Sambaiah http://umencs.blogspot.in");
MODULE_DESCRIPTION("Kernel module to load USB Driver");
MODULE_LICENSE("GPL");
// code end


Now create a Makefile in the same folder with the following code.

ifeq ($(KERNELRELEASE),)

KERNELDIR ?= /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)

.PHONY: build clean

build:
         $(MAKE) -C $(KERNELDIR) M=$(PWD) modules

clean:
         rm -rf *.o *~ core .depend .*.cmd *.ko *.mod.c
else

$(info Building with KERNELRELEASE = ${KERNELRELEASE})
obj-m :=    usb_driver.o

endif


Note: Becareful that Makefiles require indentation. So, use Tab character, not a multiple spaces below build and clean options.

Compiling Kernel Program / Module

If you created above two files, then compile the kernel module using following Command.
>make
Once you execute the above command it will create a bunch of files in USB_Module folder. In that bunch of files you can find usb_driver.ko which is a kernel module.

Loading Kernel Module / Program

To load usb_driver.ko kernel module use following command
>sudo insmod usb_driver.ko

 Now you must be thinking why printk in usb_driver.c didn't print "USB-Driver Module Loaded...!!!" on console. Because you are looking at wrong location. It is a Kernel level programming, you can find "USB-Driver Module Loaded...!!!" in syslog. To see this message run following command.
>dmesg | tail

 UnLoading Kernel Module / Program

To unload usb_driver.ko kernel module use following command
>sudo rmmod usb_driver.ko

To see "USB-Driver Module UnLoaded...!!!" message use following command
>dmesg | tail

Getting Kernel Module / Program details

use following command to know the details of any kernel module
>/sbin/modinfo usb_driver.ko




Saturday, April 27, 2013

Programming a Virtual / Online Key Board

Virtual / online key board is software program, which allows users to enter characters. This virtual / online key board can be operated by various input devices like Mouse, touch pad, external touch tablet etc. Virtual / Online key boards provides different input mechanisms to disability persons also.

Here I am going to share a java code, which was developed and used to create a Hindi virtual / online key board for application level.

You can download an application level Hindi Virtual / Online Key Board DOWNLOAD HERE.

The GUI of this Hindi online / virtual keyboard looks like as follows


Here you can Analyze the java code to create  Hindi Online / Virtual Key board.

// File Name:  HindiKeyBoard.java

import java.awt.*;
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.*;
import javax.swing.*;

public class HindiKeyBoard {
    public static void main(String args[])
    {
        Hindi_KeyBoard_Main J = new Hindi_KeyBoard_Main();
        J.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        J.set_TextArea_prop();
        J.set_menu();
        J.Hindi_KeyBoard_Main_();
        J.setSize(500, 600);
        J.setVisible(true);   
    }
}
class Hindi_App_Level_Key_Board extends JDialog{
       private static final long serialVersionUID = 1L;
       protected JTextArea textArea;
        HindiStateBuffer stateBuffer=new HindiStateBuffer();
        String hindi[]={"अ","आ","इ","ई‌","उ","ऊ","ऋ","ए","ऐ","ओ","औ","अं","अः","क्","ख्","ग्","घ्","ङ्","च्","छ्","ज्","झ्","ञ्","ट्","ठ्","ड्","ढ्","ण्","त्","थ्","द्","ध्","न्","प्","फ्","ब्","भ्","म्","य्","र्","ल्","व्","श्","ष्","स्","ह्"};
        String hindiMatraSet[]={"","ा","ि","ी","ु","ू","ृ","े","ै","ो","ौ","ं","ः"};
        public Hindi_App_Level_Key_Board(Hindi_KeyBoard_Main aui){
            super(aui,"हिन्दी",false);
            JButton button[]=new JButton[63];
            textArea=aui.textArea;
            for(int i=0; i<63 br="" i="">                button[i]= new JButton("");
            }
            Container contPane = getContentPane();
            JPanel panel =new JPanel();
            JPanel flowPanel= new JPanel();
            flowPanel.setLayout(new GridLayout(9,7));
           
            for(int j=0; j<7 br="" j="">                button[j].setText(hindi[j]);
                flowPanel.add(button[j]);
                button[j].addActionListener(new ActionListener()
                {
                    public void actionPerformed(ActionEvent e) {
                        int caretposition= textArea.getCaretPosition();
                        Object btnObj= e.getSource();;
                        JButton btn=(JButton) btnObj;
                        if(stateBuffer.commit==false){
                            stateBuffer.precomposedString=stateBuffer.precomposedString.substring(0, stateBuffer.precomposedString.length()-1);
                            for(int lo=0; lo<7 br="" lo="">                                if(btn.getText().equals(hindi[lo])){
                                    stateBuffer.precomposedString=stateBuffer.precomposedString+hindiMatraSet[lo];
                                }
                            }
                           
                        }else{
                            stateBuffer.precomposedString=btn.getText();
                        }
                        textArea.select(caretposition, caretposition+stateBuffer.precomposedString.length());
                        textArea.replaceSelection(stateBuffer.precomposedString);
                        stateBuffer.reset();
                    }
                });
            }       
            int k=7;
            for(int j=7; j<14 br="" j="">                button[j].setText(hindi[k++]);
                flowPanel.add(button[j]);
                button[j].addActionListener(new ActionListener()
                {

                    public void actionPerformed(ActionEvent e) {
                        int caretposition= textArea.getCaretPosition();
                        Object btnObj= e.getSource();;
                        JButton btn=(JButton) btnObj;
                        if(stateBuffer.commit==false){
                            stateBuffer.precomposedString=stateBuffer.precomposedString.substring(0, stateBuffer.precomposedString.length()-1);
                            for(int lo=7; lo<14 br="" lo="">                                if(btn.getText().equals(hindi[lo])){
                                    stateBuffer.precomposedString=stateBuffer.precomposedString+hindiMatraSet[lo];
                                }
                            }   
                            if(btn.getText().equals("‌्")){
                                stateBuffer.precomposedString=stateBuffer.precomposedString+"\u094d";
                            }
                        }else{
                            stateBuffer.precomposedString=btn.getText();
                        }
                        textArea.select(caretposition, caretposition+stateBuffer.precomposedString.length());
                        textArea.replaceSelection(stateBuffer.precomposedString);
                        stateBuffer.reset();
                    }
                });
            }
            button[12].setText("‌्");
            button[13].setText(hindiMatraSet[11]);
            k=13;
            for(int set=15; set<=19; set++){
                button[set].setText(hindi[k++]);
            }
            for(int j=14; j<21 br="" j="">                flowPanel.add(button[j]);
                button[j].addActionListener(new ActionListener()
                {
                    public void actionPerformed(ActionEvent e) {
                        int caretposition= textArea.getCaretPosition();
                        Object btnObj= e.getSource();
                        JButton btn=(JButton) btnObj;
                        if(stateBuffer.commit==false && !stateBuffer.precomposedString.equals("")){
                            stateBuffer.precomposedString=stateBuffer.precomposedString.substring(0, stateBuffer.precomposedString.length()-1);
                            textArea.select(caretposition, caretposition+stateBuffer.precomposedString.length());
                            textArea.replaceSelection(stateBuffer.precomposedString);
                            stateBuffer.precomposedString=btn.getText();
                        }else{
                            stateBuffer.precomposedString=btn.getText();
                       }
                        stateBuffer.commit=false;                               
                    }
                });
            }
            k=18;
            for(int set=22; set<=26; set++){
                button[set].setText(hindi[k++]);
            }
            for(int j=21; j<28 br="" j="">                flowPanel.add(button[j]);
                button[j].addActionListener(new ActionListener()
                {
                    public void actionPerformed(ActionEvent e) {
                        int caretposition= textArea.getCaretPosition();
                        Object btnObj= e.getSource();
                        JButton btn=(JButton) btnObj;
                        if(stateBuffer.commit==false && !stateBuffer.precomposedString.equals("")){
                            stateBuffer.precomposedString=stateBuffer.precomposedString.substring(0, stateBuffer.precomposedString.length()-1);
                            textArea.select(caretposition, caretposition+stateBuffer.precomposedString.length());
                            textArea.replaceSelection(stateBuffer.precomposedString);
                            stateBuffer.precomposedString=btn.getText();
                        }else{
                            stateBuffer.precomposedString=btn.getText();
                               }
                        stateBuffer.commit=false;                               
                    }
                });
            }   
            k=23;
            for(int set=29; set<=33; set++){
                button[set].setText(hindi[k++]);
            }
            for(int j=28; j<35 br="" j="">                flowPanel.add(button[j]);
                button[j].addActionListener(new ActionListener()
                {
                    public void actionPerformed(ActionEvent e) {
                        int caretposition= textArea.getCaretPosition();
                        Object btnObj= e.getSource();
                        JButton btn=(JButton) btnObj;
                        if(stateBuffer.commit==false && !stateBuffer.precomposedString.equals("")){
                            stateBuffer.precomposedString=stateBuffer.precomposedString.substring(0, stateBuffer.precomposedString.length()-1);
                            textArea.select(caretposition, caretposition+stateBuffer.precomposedString.length());
                            textArea.replaceSelection(stateBuffer.precomposedString);
                            stateBuffer.precomposedString=btn.getText();
                        }else{
                            stateBuffer.precomposedString=btn.getText();
                            }
                        stateBuffer.commit=false;                               
                    }
                });
            }
            k=28;
            for(int set=36; set<=40; set++){
                button[set].setText(hindi[k++]);
            }
            for(int j=35; j<42 br="" j="">                flowPanel.add(button[j]);
                button[j].addActionListener(new ActionListener()
                {

                    public void actionPerformed(ActionEvent e) {
                        int caretposition= textArea.getCaretPosition();
                        Object btnObj= e.getSource();
                        JButton btn=(JButton) btnObj;
                        if(stateBuffer.commit==false && !stateBuffer.precomposedString.equals("")){
                            stateBuffer.precomposedString=stateBuffer.precomposedString.substring(0, stateBuffer.precomposedString.length()-1);
                            textArea.select(caretposition, caretposition+stateBuffer.precomposedString.length());
                            textArea.replaceSelection(stateBuffer.precomposedString);
                            stateBuffer.precomposedString=btn.getText();
                        }else{
                            stateBuffer.precomposedString=btn.getText();
                            }
                        stateBuffer.commit=false;                               
                    }
                });
            }
            k=33;
            for(int set=43; set<=47; set++){
                button[set].setText(hindi[k++]);
            }
            for(int j=42; j<49 br="" j="">                flowPanel.add(button[j]);
                button[j].addActionListener(new ActionListener()
                {

                    public void actionPerformed(ActionEvent e) {
                        int caretposition= textArea.getCaretPosition();
                        Object btnObj= e.getSource();
                        JButton btn=(JButton) btnObj;
                        if(stateBuffer.commit==false && !stateBuffer.precomposedString.equals("")){
                            stateBuffer.precomposedString=stateBuffer.precomposedString.substring(0, stateBuffer.precomposedString.length()-1);
                            textArea.select(caretposition, caretposition+stateBuffer.precomposedString.length());
                            textArea.replaceSelection(stateBuffer.precomposedString);
                            stateBuffer.precomposedString=btn.getText();
                        }else{
                            stateBuffer.precomposedString=btn.getText();
                            }
                        stateBuffer.commit=false;                               
                    }
                });
            }   
             k=38;
            for(int j=49; j<56 br="" j="">                button[j].setText(hindi[k++]);
                flowPanel.add(button[j]);
                button[j].addActionListener(new ActionListener()
                {
                    public void actionPerformed(ActionEvent e) {
                        int caretposition= textArea.getCaretPosition();
                        Object btnObj= e.getSource();
                        JButton btn=(JButton) btnObj;
                        if(stateBuffer.commit==false && !stateBuffer.precomposedString.equals("")){
                            stateBuffer.precomposedString=stateBuffer.precomposedString.substring(0, stateBuffer.precomposedString.length()-1);
                            textArea.select(caretposition, caretposition+stateBuffer.precomposedString.length());
                            textArea.replaceSelection(stateBuffer.precomposedString);
                            stateBuffer.precomposedString=btn.getText();
                        }else{
                            stateBuffer.precomposedString=btn.getText();
                            }
                        stateBuffer.commit=false;                               
                    }
                });
            }
            button[56].setText(hindi[45]);
            for(int j=56; j<57 br="" j="">                flowPanel.add(button[j]);
                button[j].addActionListener(new ActionListener()
                {
                    public void actionPerformed(ActionEvent e) {
                        int caretposition= textArea.getCaretPosition();
                        Object btnObj= e.getSource();
                        JButton btn=(JButton) btnObj;
                        if(stateBuffer.commit==false && !stateBuffer.precomposedString.equals("")){
                            stateBuffer.precomposedString=stateBuffer.precomposedString.substring(0, stateBuffer.precomposedString.length()-1);
                            textArea.select(caretposition, caretposition+stateBuffer.precomposedString.length());
                            textArea.replaceSelection(stateBuffer.precomposedString);
                            stateBuffer.precomposedString=btn.getText();
                        }else{
                            stateBuffer.precomposedString=btn.getText();
                        }
                        stateBuffer.commit=false;                               
                    }
                });
            }
           
            for(int j=57; j<63 br="" j="">                flowPanel.add(button[j]);
            }
            button[57].setText("space");
            button[57].addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent e) {
                    int caretposition= textArea.getCaretPosition();
                    String space="\u0020";
                        if(stateBuffer.commit==false){
                        stateBuffer.precomposedString=stateBuffer.precomposedString.substring(0, stateBuffer.precomposedString.length()-1);
                        textArea.select(caretposition, caretposition+stateBuffer.precomposedString.length());
                        textArea.replaceSelection(stateBuffer.precomposedString);
                    }
                    stateBuffer.precomposedString=space;
                    textArea.replaceSelection(stateBuffer.precomposedString);
                    stateBuffer.reset();
                }
            });
           
            button[58].setText("clear");
            button[58].addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent e) {
                    if(stateBuffer.precomposedString.equals("\u0020")){
                        stateBuffer.commit=false;
                    }else{
                    stateBuffer.reset();
                    }
                }
            });
           
            flowPanel.setVisible(true);
            panel.add(flowPanel);
            panel.setVisible(true);
            contPane.setLayout(new BoxLayout(contPane,BoxLayout.Y_AXIS));
            contPane.add(panel);
            contPane.setVisible(true);
            setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
            pack();
            this.setVisible(true);   
        }
    }
    class HindiStateBuffer{
        public boolean commit =true;
        public String precomposedString;
        HindiStateBuffer(){
            commit=true;
            precomposedString="";
        }
        public void reset(){
            commit=true;
            precomposedString="";
        }
}

class Hindi_KeyBoard_Main extends JFrame{
   
    private static final long serialVersionUID = 1L;
    protected JTextArea textArea = new JTextArea();   
    protected JScrollPane textAreaScrollPane = new JScrollPane(textArea, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
    protected int textAreaRows = 10;
    protected JFileChooser fileChooser=new JFileChooser();
    Hindi_KeyBoard_Main thisreference =this;
    Hindi_App_Level_Key_Board halkb;
   
    public void Hindi_KeyBoard_Main_()
    {
        halkb = new Hindi_App_Level_Key_Board(thisreference);
    }
    public void set_TextArea_prop()
    {
    Container contPane = getContentPane();
    contPane.setLayout(new BorderLayout());
    textArea.setRows(textAreaRows);
    textArea.setLineWrap(true);
    textArea.setWrapStyleWord(true);
    textArea.setBorder(BorderFactory.createLineBorder(Color.black));
    textArea.setSize(500, 600);
    Font font = new Font("TimesRoman",Font.BOLD,15);
    textArea.setFont(font);
    contPane.add(textAreaScrollPane, BorderLayout.WEST);
    }
   
    public void set_menu()
    {
        JMenuBar menu = new JMenuBar();
        JMenu menuTool = new JMenu("File");
        menuTool.setMnemonic('F');
        JMenuItem menuToolOpenText = new JMenuItem("Open File...");
        menuToolOpenText.setMnemonic('O');
        JMenuItem menuToolSaveToText = new JMenuItem("Save as Text...");
        menuToolSaveToText.setMnemonic('S');
        JMenuItem menuToolExit = new JMenuItem("Exit...");
        menuToolSaveToText.setMnemonic('E');
        menuTool.add(menuToolOpenText);
        menuTool.add(menuToolSaveToText);
        menuTool.add(menuToolExit);
        menu.add(menuTool);
        setJMenuBar(menu);
       
        menuToolSaveToText.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent ae){
                int returnVal = fileChooser.showSaveDialog(thisreference);
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    File file = fileChooser.getSelectedFile();
                   
                    try {
                        String taString=textArea.getText();
                        FileOutputStream fosr=new FileOutputStream(file);
                        fosr.write(taString.getBytes());

                        fosr.close();

                        System.out.println(taString+"");
                    } catch (IOException ioe) {
                        System.out.println("Some error occurred while creating " + file + " : " + ioe);
                    }               
                    System.out.println("Saving: " + file.getName());
                } else {
                    System.out.println("Save command cancelled by user.");
                }
                textArea.setCaretPosition(textArea.getDocument().getLength());
            }           
        });
       
        menuToolOpenText.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent ae){
                int returnVal = fileChooser.showOpenDialog(thisreference);

                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    File file = fileChooser.getSelectedFile();
                        try {
                            Reader r = new BufferedReader(new FileReader(file));
                            int ch;
                            String nav="";
                            while ((ch = r.read()) != -1){
                                char chr=(char)ch;
                                nav=nav+chr;
                            }
                           
                            textArea.setText(nav);
                            r.close();
                        } catch (IOException ioe) {
                            System.out.println("Some error occurred while creating " + file + " : " + ioe);
                        }               
                                    }           
                textArea.setCaretPosition(textArea.getDocument().getLength());
            }
        });
        menuToolExit.addActionListener(new ActionListener()
        {
                public void actionPerformed(ActionEvent ae){
                    dispose();
                    System.exit(0);   
                }
        });
    }

}