Wednesday 18 June 2014

Oracle Linux 5.8 Server DVD 64-bit link for Torrent download.

Torrent File Link

Magnetic Link

File List.

1. OracleLinux-R5-U8-Server-x86_64-dvd.iso    Size : 3.61 GB

Tracker :

udp://tracker.openbittorrent.com:80

udp://tracker.publicbt.com:80

udp://tracker.istole.it:80/announce

udp://open.demonii.com:1337

Seeders    : 1
Leechers : 3

Oracle Linux 6.0 link for torrent download.

Torrent Link

Magetic Link

Hash Code : 948D63227E488D718A1E34DFE783D7258F32EF59

Total Size : 10.1 GB

List of Files available :
 File Name                                                                             Size (in GB)
1. OracleLinux-R6-U0-Server-i386-dvd.iso                          2.63
2. OracleLinux-R6-U0-Server-x86_64-dvd.iso                     3.16
3. OracleLinux-R6-U0-src-dvd1.iso                                      3.00
4. OracleLinux-R6-U0-src-dvd2.iso                                      1.38

Trackers

udp://tracker.openbittorrent.com:80/announce

udp://open.demonii.com:1337


How to run 16 bit program in 64 bit Windows OS

Generally you will not be able to run old widows 16 bit program in Windows 64 bit OS.
But it is possible after installing a software known as DOSBox. This is basically an emulator
which helps you to run your 16 bit programs.
Just follow this link given below from where you can download DOSBox.

DOSBox Download link

Wait... After installing when you open the program you will get a DOS based interface.
Now suppose you want to run Turbo C which is in you D:\TC . You need to mount this folder as
as virtual drive i.e. d, for that write this command mount d d:\tc. If succeeded it will display a
message : Drive D is mounted as Local Directory D:\TC.

It's all done. Just type D: ad press enter on the prompt and it will change the drive to virtual drive
as D:>. Now you have to imagine your current directory as d:\tc, not d: ad you can do all work you
need to to on this current directory.

Sunday 15 June 2014

Wolf 3D versio 1.0 cheats

Start the game from the command line with the goobers option:

wolf3d -goobers

After doing this, press Left Alt, Left Shift, and Backspace simultaneously during gameplay. You should see a message, "Debugging keys are now available!" You can now use the following cheat codes:

    Tab + C - Show statistics
    Tab + E - Instantly ends current level
    Tab + F - Show current coordinates
    Tab + G - God mode
    Tab + H - Player takes damage
    Tab + I - Same effect as the LIM cheat
    Tab + S - Slow motion
    Tab + T - Show all game sprites
    Tab + W - Warp to any map in current Episode (prompt)
    Tab + N - No clipping (disabled on later game versions)

Wednesday 4 June 2014

How to use rm command in linux


    Command is - rm filename.extensionname
     rm file1.txt

     rm does not remove directory but you can remove list of files in a directory by this command
     rm -r directoryname.  (-r recursive method)
     rm -r Music.  This command will remove all the files in the directory Music.

     You cannot remove files with rm if you do not have write permission on the files.

Few functionalities of ls command in Linux


Lists the contents of the current working directory
(pwd - "Print Working Directory" To see the current working directory)

ls -a
List all files including the files with Dot prefix

ls -l

List name of files with details like permission,date time (created/modified)

Commands can be combined
Say you want to list all files with details you type
ls -a -l or ls -al
This joining can be only done for Short options
for long options like -all you cannot join to options
(example ls -al)

Long and short options can be mixed.
ls --all -l

Monday 26 May 2014

How to swap 2 numbers using pointers.

#iclude"stdio.h"
#include"conio.h"
void main()
{
int a=4,b=8;
void swap(int *,int *); // Prototype  for the function
clrscr();
printf("\nNumbers before swap : a = % d, b = %d",a,b); // print variable value before swap
swap(&a,&b);
printf("\nNumbers after swap : a = % d, b = %d",a,b); / print variable value after swap
getch();
 }
void swap(int *p,int *q)
{
int t; // Temporary variable to store the value before swapping
t=*p;
*p=*q;
*q=t;
}

How to copy string using pointer in C Programming

#include"stdio.h"
#include"conio.h"
void main(int argc,char *argv[])
{
void stringcopy(char *,char *);
char target[10];
clrscr();
fflush(stdout);
if(argc<2)
{
printf("\nWrong number of argument parameter");
exit(0);
}
stringcopy(target,argv[1]); // target, &target[0]
printf("\nSource string %s, Target String %s",argv[1],target);
getch();
}
void stringcopy(char *trg,char *source)
{
while(*trg++=*source++);
//Alternative way pretty adhoc process
/*while(*source)
{
*trg = *source;
trg++;
source++;
}
*trg=*source;*/
}

Monday 12 May 2014

How to create a view in Oracle

A view is a sql statement which can be stored in Oracle database as SQL statement. It never stored as data but as a sql statement.

Syntax to create a view

CREATE OR REPLACE VIEW VIEW_NAME AS
SELECT * FROM TABLE_NAME;

Syntax to see a view content

DESC VIEW_NAME

Syntax to delete a view

DROP VIEW VIEW_NAME

You can use a view as a table i.e. add where clause in view or use it in an inline view.

SELECT * FROM VIEW_NAME WHERE COLUMN_NAME = FIELD_VALUE

Example

Suppose you have a sql based on 2 table employee having 2 columns ecode, ename
and salary having 2 columns month_year, net_pay. Now the sql is to get ecode, ename,month_year
and sum of ney_pay. sql statement is given below.

select ee.ecode, ee.ename,sl.month_year, sum(sl.ney_pay) tot_net_pay
from employee ee,salary sl
where sl.emp_id = ee.emp_id
group by ee.ecode, ee.ename,sl.month_year,
order by 1,3

sl is the alias for table salary, ee is the alias for table employee, emp_id is primary key in employee
and reference key in salary. order by clause uses index of columns in select clause.

Now to create the view we write

CREATE OR REPLACE VIEW EMP_SAL_VIEW AS
select ee.ecode, ee.ename,sl.month_year, sum(sl.ney_pay) tot_net_pay
from employee ee,salary sl
where sl.emp_id = ee.emp_id
group by ee.ecode, ee.ename,sl.month_year,
order by 1,3

Now if you write a select query on this view it will be

SELECT ECODE,ENAME,MONTH_YEAR,NET_PAY FROM EMP_SAL_VIEW;

You can also use where clause in this view.

SELECT ECODE,ENAME,MONTH_YEAR,NET_PAY FROM EMP_SAL_VIEW
WHERE NET_PAY<=1000;

Sunday 11 May 2014

How to shutdown a Windows machine from command line.

Open command prompt.

1. To simply shutdown type
     shutdown -s

2.  To forcefully shutdown the machine (Close all application forcefully before shutdown)
     shutdown -f -s

3. To restart type
    shutdown -r

4. To forcefully restart the machine (Close all application forcefully before restart)
    shutdown -f -r

5.  To set countdown before shutting down your machine.
   
     shutdown -s -t 60  (60 is value in seconds if you want to shutdown after 1 hour value will be 3600)

6. To shutdown a machine remotely from another computer.

    shutdown -s -m \\computer name or ipaddress (Be sure the machine has permission to shutdown
    remotely.

Some useful shortcut key in Windows 7 and 8

1. To open, hide or show run dialog Press Windows key + R together.

2. To select any of the taksbar pinned program Press [Window + program position in taskbar] together.
    Say your Firefox is in 4th position from the left then press Window key + 4. If the program is running and
    in minimized state or not an active window then pressing this buttons will make it active window or
   maximized if it is minimized.

3. To open search window on a particular folder. Select the folder from the explorer and press
    Windows key + F.

4. To minimize all window press Window key + D.

5. I hope you know about the second screen window, it is used if you want to extend your monitor to a
    projector,  or make a duplicate screen to another monitor etc. To open the second screen window, press
    Window key + P.

6. To minimize all screen Press Window key + M.

7. To open the explorer window press Window key + E.

8. To open the start menu press Window key, or press Control key + Escape key.


How to add Quick Launch toolbar in Windows 8

Right click on empty space in task bar.

Go to Toolbar.
Select new toolbar from Toolbar submenu.
Set this path into select folder dialog

C:\Users\[You user folder]\AppData\Roaming\Microsoft\Internet Explorer\Quick Launch
Click on Select Folder
You are all done.

Quick launch toolbar will be visible on right corner of the taskbar just left to the datatime.

How to start and stop Oracle database service in Linux.

You can do this task from both server and client.

1. If you do it from server then

  i. Make sure you are logged in as oracle user i.e. user which Oracle is installed and user who has all the
     rights.
 ii. Open terminal
iii. type sqlplus / as sysdba
iv. You will be logged in sql prompt. In the sql prompt just type startup. This will start your Oracle database
     service.
v.  type exit to exit from sql prompt.
vi. Now type service start lsnrctl. This will start your listener service.

You are all done.

2. If you are in  a client / remote machine then you need to have putty ssh client. Log in to oracle user
    through putty and do the same steps as mentioned above.

How to start and stop Oracle database service in Windows.

Suppose your instance name of Oracle is ORA.

You will be having 2 services which need to be started.

Step 1:
You can configure Windows service to start this service at startup, if it is not started.

  i. Press window key + R to open run dialog. type services.msc and press enter.
 ii. Search for service OracleServiceOra.
iii. Right click on it and click on properties from popup menu.
iv.From the startup type select Automatic if you want to start the service when windows start, or select
   manual if you want to start the service manually, this will save you windows loading time and save memory
  also.
v. Click on start button if you want to start the service now.
vi. Click on apply.
vii/ Search for Oracle[OracleHomeName]TNSListener (Oracle home name is your oracle installed path).
viii. Do the same process as you have done with OracleServiceORA.

Step 2.

If you have set your service as mentioned above to be started manually then you can use command prompt
to start your service.

  i.  Create a batch file named say StartOracleService.bat
 ii.  In the batch file add these following line.
      @echo off
       net start OracleServiceOra
       net start Oracle[OracleHomeName]TNSListener
       REM OracleHomeName is you Oracle installed path
       exit
iii.   To stop the service create a batch file named say StopOracleService.bat
       In the file add these following line.
      @echo off
       net stop OracleServiceOra
       net stop Oracle[OracleHomeName]TNSListener
       REM OracleHomeName is you Oracle installed path
       exit


Monday 7 April 2014

Check for prime number in Objective-C

#import <Foundation/Foundation.h>

int isPrime(int n)
{
int i;
if(n==1||n==2)
return 0;
for(i=3;i<=n/2;i++)
if(n%i==0)
return 0;
return 1;
}

int main (int argc, const char * argv[])
{
   NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
   int i;
   for(i=1;i<=100;i++)
   {
   if(isPrime(i)==1)
    NSLog (@"%d is Prime number,",i);
   else
    NSLog (@"%d is not Prime number,",i);
   }
 [pool drain];
   return 0;
}

How to print Fibonacci series in Objective-C

#import <Foundation/Foundation.h>

int fibonacci(int n)
{
if(n<=2)
return(1);
return fibonacci(n-1) + fibonacci(n-2);
}

int main (int argc, const char * argv[])
{
   NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
   int i;
   for(i=1;i<=8;i++)
   {
   int fib=fibonacci(i);
   NSLog (@"%d,",fib);
   }
 [pool drain];
   return 0;
}

Find Factorial of a number recursively in Objective-C

#import <Foundation/Foundation.h>

float factorial(int n)
{
if(n<=1)
return(1);
return n*factorial(n-1);
}

int main (int argc, const char * argv[])
{
   NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
   long fact=factorial(8);
   NSLog (@"Factorial of 8 is %ld",fact);
 [pool drain];
   return 0;
}

Sunday 6 April 2014

How to format Date using SimpleDateFormat in JSP

<%@ page import="java.io.*,java.util.*" %>
<%@ page import="javax.servlet.*,java.text.*" %>
<html>
<head>
<title>Current Date & Time</title>
</head>
<body>
<center>
<h1>Display Current Date & Time</h1>
</center>
<%
   Date currDt = new Date( );
   SimpleDateFormat sdf =  new SimpleDateFormat ("dd/MM/yyyy hh:mm:ss");
   out.print( "<h1 align=\"center\">" + sdf.format(currDt) + "</h1>");
%>
</body>
</html>

How to open last edited file in Linux

Suppose you have edited last three following files using vi
user1@localhost$ vi file1.txt
user1@localhost$ vi file2.txt
user1@localhost$ vi file3.txt

Now to open the last edited file command is

user1@localhost$ vi ls -t | head -1

Here ls -t sort the file in order of last modified file and head -1 picks up the first file.

So here the output of the command executed above will be file1.txt file will be opened in vi for editing.

How to connect to Oracle 11g using PYTHON

import cx_Oracle
con = cx_Oracle.connect('username/password@[ipaddress or hostname]/SID')
# for example con = cx_Oracle.connect('scott/tiger@127.0.0.1/orcl')
               
ver = con.version.split(".")
print ver
             
con.close()

Manipulating string variable in Python

#!/usr/local/bin/python2.7
   
#Concatenate string
a="This "
b="Python "
c="program "
d="is "
e="about "
f="variable "
resultstr=a+b+c+d+e+f
print(resultstr)

#Repeat string n number of times
str="I will not stop.." * 4
print("\n" + str)
#This is the output : I will not stop..I will not stop..I will not stop..I will not stop..

#Concatenation of Number and string

n=4
m=4.5

s="We can repeat string " + repr(n) + " times but not " + repr(m) + " times"

Different methods used in array in PYTHON

#!/usr/local/bin/python2.7
# pleases follow the indention as it is most important in python. python don't use begin/end, if/end if or loop/
#end loop so python identify statement by indention.

from array import *
my_array = array('i', [1,2,3,4,5,6,7,8,9])

#inserting in nth position .insert(position,value)
my_array.insert(0,12)

#appending value to to the last position
my_array.append(10)

#extending python array using extend method

my_extnd_array = array('i', [7,8,9,10])
my_array.extend(my_extnd_array) # extend(array object)

#add item from list into array using fromlist
lst = [13,14,15]
my_array.fromlist(lst)

#check the number of occurance of an element in array
print('\n9 occured %d times'%my_array.count(9))

#convert any array element to list using tolist() method
c=my_array.tolist()

#remove element from the list from any position
my_array.remove(4) # remove element from 4th position

#reverse elements in a python array using reverse method
my_array.reverse()

#remove element from the last position using pop method
my_array.pop()

#Search any element by index using index method
print('\nElement in 6th position is %d'%my_array.index(6))

#print array list
for i in my_array:
  print(i)

How to check prime number in using Python.

#!/usr/local/bin/python2.7
# pleases follow the indention as it is most important in python. python don't use begin/end, if/end if or loop/
#end loop so python identify statement by indention.

def PrimeNumber(n):
  if n==1 or n==2:
    return 0
  for i in range(3,n/2+1):
    if n%i == 0:
      return 0
  return 1

n = input ('Enter the number to check prime: ')
if PrimeNumber(n)==1:
  print('\n%d is Prime Number'%n)
else:
  print('\n%d is not Prime Number'%n)

How to find factorial of a number using Python in both iteration and recursive method

#!/usr/local/bin/python2.7
# pleases follow the indention as it is most important in python. python don't use begin/end, if/end if or loop/
#end loop so python identify statement by indention.

def Factorial(n):
    fact=1
    for i in range(1,n+1):
       fact=fact*i

    return fact


def FactorialRecursive(n):
  if n <=1:
    return 1
  return n*FactorialRecursive(n-1)

n = input ('Enter the number to find factorial: ')
print('\nFactorial of a number %d is %d'%(n,Factorial(n)))

print('Factorial (recursive) of a number %d is %d'%(n,FactorialRecursive(n)))

Saturday 5 April 2014

How to read a file from script using PERL

#!/usr/bin/perl
use strict;
use warnings;

use Path::Class;
use autodie; # die if error in reading file

my $dir = dir("/tmp"); # /tmp

my $file = $dir->file("sample_file.txt");

# Read in the whole contents of the file 
 
my $stuff = $file->slurp();

# openr() returns an IO::File object to read from 
 
my $file_handle = $file->openr();

# Read one line at a time
 
 while( my $line = $file_handle->getline() ) {
print $line;
}

How to write to a file using PERL script

#!/usr/bin/perl
use strict;
use warnings;

use Path::Class;
use autodie; # die if writing a file fails

my $dir = dir("/tmp"); # /tmp

my $file = $dir->file("file.txt"); # /tmp/file.txt

# Get a File Handle (IO::File object) you can write to
my $file_handle = $file->openw();

my @arr = ('This', 'is', 'my', 'first',"Perl","Program");

foreach my $line ( @arr ) {
    # Add the line to the file
    $file_handle->print($line . "\n");

Using JDBC thin client to connect to Oracle - A sample JSP.

<!--This is a program written in HTML JSP embedded. This program use JDBC thin client to connect to Oracle 11g. Page gives user to select from 2 checkbox options and uses post method  two create criteria for SQL query. A single file is used for both post and get method, two separate form is used for post and get method.-->

<html>
<head>
  <title>Employee</title>
</head>
<body>
  <h1>Employee Details</h1>
  <h3>Choose Grade(s):</h3>
  <form method="get">
    <input type="checkbox" name="grade" value="Worker">Worker
    <input type="checkbox" name="grade" value="Staff">Staff
    <input type="submit" value="Query">
  </form>

  <%@ page import = "java.sql.*" %>
  <%
    Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@[ipaddress or hostname]:portnumber:sid","username","password";
    Statement stmt = conn.createStatement();
    String sql="select emp_code,emp_name,date_of_birth,emp_sex from employee_master";
    String[] grade = request.getParameterValues("grade");
if (grade != null)
    {
    if(grade.length>0)
        {
        sql+=" where emp_grade in (";
        int i;
        for (i = 0; i < grade.length; ++i)
        {
        sql+="'" + grade[i].charAt(0) + "'";
        if(i<grade.length-1)
        sql+=",";
        }
        sql+=")";
        sql+=" and status='A' order by emp_name";
        %>
        <hr>
        <form method="get" action="dbconn.jsp">
        <tr> <%
            try
            { %>
              <table border=1 cellpadding=5><tr><td> Emp Code</td><td>Emp Name</td><td>DOB</td><td>Sex</td><td><%=sql%></td></tr>
            <%  ResultSet rs = stmt.executeQuery(sql);
              while (rs.next()) {
          %>
                  <tr>
                    <td><%= rs.getString("emp_code") %></td>
                    <td><%= rs.getString("emp_name") %></td>
                    <td>$<%= rs.getString("date_of_birth") %></td>
                    <td><%= rs.getString("emp_sex") %></td>
                  </tr>
          <%
              }
          %>
                </table></form>
              <a href="<%= request.getRequestURI() %>"><h3>Back</h3></a>
          <%
              rs.close();
            }
            catch(SQLException e)
            {
                e.printStackTrace();
            }
        }
    }
      stmt.close();
      conn.close();
  %>
</body>
</html>

Python programing basic examples

#!/usr/local/bin/python2.7

# printing a string
print "Hello, World!"

#defining and invoking function
def hello (what):
 text = "Hello, " + what + "!"
 print text

hello("Dave")

#---------------------------------------------
# functions returning multiple values.
str = "foo"; lst = ["abra", 2038, "cadabra"]
for char in str:
  print char

def squareandcube (x):
 return x*x, x*x*x

a, b = squareandcube(3)
print a
print b

#---------------------------------------------
# functions used as an iterable object creating its own object runtime.
def cubeseries ():
 for i in range(5):
   yield (i*i*i)

for j in cubeseries():
 print j

How to echo HTML request parameters

<html>
<head>
  <title>HTML Request Parameters</title>
</head>
<body>
  <h2>Choose an Actor:</h2>
  <form method="get">
    <input type="checkbox" name="actor" value="Shahrukh Khan">Shahrukh Khan
    <input type="checkbox" name="actor" value="Amir Khan">Amir Khan
    <input type="checkbox" name="actor" value="Salman Khan">Salman Khan
    <input type="submit" value="Query">
  </form>

  <%
  String[] actors = request.getParameterValues("actor");
  if (actors != null) {
  %>
    <h3>You have selected actor(s):</h3>
    <ul>
  <%
      for (int cnt = 0; cnt < actors.length; cnt++) {
  %>  
        <li><%= actors[cnt] %></li>
  <%
      }
  %>
    </ul>
    <a href="<%= request.getRequestURI() %>">Go Home</a>
  <%
  }
  %>
</body>
</html>

A simple JSP script

<html>
<body>
<% if(1>2) {%>
<h2>You are hell pathetic </h2>
<%} else {%>
<h2>I think you are sensible </h2>
<%}%>
</body>
</html>

How to Shutdown from Terminal in Red Hat Linux 6.0

Suppose you are logged in as a normal user say:

user1@localhost ~]$

Now you need to switch to root user using switch user command
The command is

su -

Shell prompt you to enter rot user password like this

user1@localhost ~]$ su -
password:

Type your password and press enter.

Now you are switched to root user.

root@localhost ~]$ 

Type this command

 root@localhost ~]$  init 0

Thats all done.

Friday 4 April 2014

How to read a file using Java Applet

import java.applet.*;
import java.awt.*;
import java.io.*;
import java.net.*;
import javax.swing.JScrollPane;
import javax.swing.JApplet;
public class readFileApplet extends Applet {
    String fileToRead="OracleCon.java";
    StringBuffer strBuff;
    TextArea txtArea;
    Graphics g;
    public void init()
    {
        txtArea = new TextArea(100,100);
        txtArea.setEditable(true);
        JScrollPane sp=new JScrollPane(txtArea);
        add(txtArea,"center");
        String prHtml = this.getParameter("fileToRead");
        if(prHtml!=null) fileToRead = new String(prHtml);
        readFile();
        add(sp);
    }
    public void readFile()
    {
        String line;
        URL url=null;
        try
        {
            url = new URL(getCodeBase(),fileToRead);
        }
        catch(MalformedURLException e){}
        try
        {
            InputStream in = url.openStream();
            BufferedReader bf = new BufferedReader(new InputStreamReader(in));
            strBuff = new StringBuffer();
            while((line=bf.readLine())!=null)
            strBuff.append(line + "\n");
            txtArea.append("File Name : " + fileToRead + "\n");
            txtArea.append(strBuff.toString());
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
    }
}

Understandng Arrays in Java

import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.text.SimpleDateFormat;
public class array1
{
public static void main(String[] args)
{
Integer array[]={6,32,9,1,-4,76,-23,5,8,2,-4,-11};
Arrays.sort(array);
printArray("Sorted Array : ",array);
int index=Arrays.binarySearch(array,-6);
System.out.print("\nFound 2 @ " + index);
}
public static void printArray(String message,Integer array[])
{
System.out.print("\n" + message + ": [Length : " + array.length + "]  ");
for(int i=0;i<array.length;i++)
System.out.print(array[i] + ",");
printMaxMin(array);
printTime();
}
public static void printMaxMin(Integer[] arr)
{
//System.out.print("\nMaximum in the array : " + (int)Collections.max(Arrays.asList(array)) +
//                 "\nMinimum in the array : " + (int)Collections.min(Arrays.asList(array)));
      int min = (int) Collections.min(Arrays.asList(arr));
      int max = (int) Collections.max(Arrays.asList(arr));
      System.out.print("\nMin number: " + min);
      System.out.print("\nMax number: " + max);
}
public static void printTime()
{
Date date = new Date();
String strDateFormat = "hh:mm:ss a";
SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
System.out.print("\nCurrent Time is : " + sdf.format(date));
}
}

How to create a Form using Java applet

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.applet.Applet.*;
import java.lang.*;
public class loginForm extends Frame implements ActionListener
{
Label lblUname
;
Label lblPass;
Label lblblnk;
TextField usrTxt;
TextField pwdTxt;
Button btn;
public loginForm()
{
lblUname = new Label("user name");
lblPass  = new Label("password");
lblblnk  = new Label(" ");
usrTxt = new TextField();
pwdTxt = new TextField();
btn = new Button("button");
add(lblUname);
add(lblPass);
add(usrTxt);
add(pwdTxt);
add(btn);
add(lblblnk);
lblUname.setBounds(0,10,100,40);
lblPass.setBounds(0,50,100,90);
usrTxt.setBounds(110,10,210,40);
pwdTxt.setBounds(110,50,210,90);
btn.setBounds(150,110,210,130);
lblblnk.setBounds(0,130,200,150);
btn.addActionListener(this);
pwdTxt.setEchoChar('*');
addWindowListener(new mwa());
}
public void actionPerformed(ActionEvent e)
{
lblblnk.setText("Welcome " + usrTxt.getText());
}
public static void main(String[] args)
{
loginForm l = new loginForm();
l.setSize(new Dimension(600,600));
l.setTitle("Login");
l.setVisible(true);
}
}
class mwa extends WindowAdapter
{
public mwa() {}
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}

How to calculate factorial of a number using recursive methods in Java


import java.io.*;
class factorial
{
public static long getfactorial(int n)
{
if(n<=0)
return 1;
return n * getfactorial(n-1);
}
public static void main(String[] args) throws IOException
{
BufferedReader rd = new BufferedReader(new InputStreamReader(System.in));
System.out.print("\nEnter number : ");
int n=Integer.parseInt(rd.readLine());
System.out.print("\nFactorial of " + n + " = " + getfactorial(n));
}
}

How to print the nth number of a Fibonacci series by recursive method

//How to print the nth number of a Fibonacci series by recursive method

//                                                            fibo(5)         
//                               fibo(4)                      +                    f ibo(3)
//           fibo(3)             +         f ibo(2)      +        fibo(2)        +     fibo(1)
//fibo(2)   +   fibo(1)     +              1           +             1            +        1
//   1         +       1          +              1           +             1            +        1         =  5

import java.io.*;
class factorial
{
public static long getfactorial(int n)
{
if(n<=0)
return 1;
return n * getfactorial(n-1);
}
public static void main(String[] args) throws IOException
{
BufferedReader rd = new BufferedReader(new InputStreamReader(System.in));
System.out.print("\nEnter number : ");
int n=Integer.parseInt(rd.readLine());
System.out.print("\nFactorial of " + n + " = " + getfactorial(n));
}
}

How to connect to Oracle using JDBC thin client

// Hello this is a java program to connect to oracle database connection string and sql query  is //customize you have to set your own value.
//after you compile this code run in the command line with following sysntax
// you can ignore lpad and rpad function it is only given to print data in well tabed format
// java -cp "path\jdbcjarfilename" classfilename
//  i am giving the ojdbc5.jar link here : ojdbc5.jar

import java.sql.*;
import java.io.*;
class OracleCon
{

public static void main(String[] args)
{
ConnectToDB();
}
public static void ConnectToDB()
{
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch(ClassNotFoundException e)
{
System.out.println("\nOracle JDBC driver not found");
e.printStackTrace();
return;
}
System.out.print("\nOracle JDBC Driver Registered");
Connection connection=null;
Statement stmt=null;
try
{
connection = DriverManager.getConnection("jdbc:oracle:thin:@192.168.171.166:1521:orcl","payroll",
             "payroll");
stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("select emp_code,emp_name,date_of_birth from employee_master");
File file = new File("/sub/aaa.csv");
if(!file.exists())
file.createNewFile();
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
System.out.print("\n" + lpad("Emp Code",10) + "|" + lpad("Emp Name",50) + "|" + lpad("Date of Birth",20));
while(rs.next())
{
System.out.print("\n" + lpad(rs.getString("emp_code"),10) + "|" + lpad(rs.getString("emp_name"),50) + "|" + lpad(rs.getString("date_of_birth"),20));
bw.write("\n" + lpad(rs.getString("emp_code"),10) + "|" + lpad(rs.getString("emp_name"),50) + "|" + lpad(rs.getString("date_of_birth"),20));
}bw.close();
rs.close();
connection.close();
}
catch(SQLException e)
{
System.out.print("\nConnection Failed! Check output console");
e.printStackTrace();
return;
}
catch(IOException e)
{
e.printStackTrace();
return;
}
if(connection!=null)
System.out.print("\nSuccess");
else
{
System.out.print("\nFailed");
return;
}
}
public static String lpad(String s,int l)
{
String gap="";
for(int i=s.length();i<=l;i++)
gap+=" ";
return gap + s;
}

public static String rpad(String s,int l)
{
String gap="";
for(int i=s.length();i<=l;i++)
gap+=" ";
return s + gap;
}
}

Sunday 30 March 2014

How to find set of Prime Numbers by C programming.

How to find all the prime numbers within a given range in C Programming

Prime numbers are numbers which is divisible by 1 and by itself. This is a simple program which takes the range as input from user and find out all the possible prime numbers within the range.

#include"stdio.h" // Standard input output library
#include"conio.h" //console base input output library

// isPrime is a function returning 1 if n is a prime number otherwise return 0
int isPrime(int n)
{
if(n==1||n==2) // Check whether input is 1 or 2 if so exits returning 0
return 0;
for(int i=3;i<=n/2;i++) //start of for loop from 3 to half of the range number
{
if(n%i==0)  //   if n is divisible by i then number is not prime i.e. remainder returned is zero
return 0;
} // end of for loop
return 1;
}
void main()
{
int n;
clrscr();
printf("\nEnter number range : "); // Program asks for input  from user
scanf("%d",&n);  // input taken in integer variable
for(int i=1;i<=n;i++)
// iteration takes place from 1 to n i.e. the range, user gives only the upper  range
{
if(isPrime(i)) // check what function isPrime returns
printf("\n%d is a prime number",i); // if it returns 1 then print the number.
}
getch(); // Halt the console screen when finished until user press a key, this is not required in run time
}

Wednesday 5 February 2014

How to use bulk collect to optimize PL/SQL performance

BULK COLLECT is used to retrieve chunk of records from disk to memory instead of retrieving records one by one. It's vary useful when you are reading from a table consisting of huge number of records.
Here is an example script how to use BULK COLLECT.
We are using a table employee_master and we will print value from 2 columns emp_code and emp_name.

--------------------------------------------------------------------------------------------------------------
declare
-------declaring the cursor emp_rec  which retrieves all columns from employee_master----
cursor emp_rec is select * from employee_master;
------  declare avariable of type employee_master record type ---------
rec_emp employee_master%rowtype;
------- declare a type TABLE consisting of employee_master record type.
type tbl_rec is TABLE of rec_emp;
------declare a variable of TABLE type---------
var_rec tbl_rec;

i            PLS_INTEGER;

begin
------Open the cursor -----------
open emp_rec;
loop

--------fetch record chunk into var_rec --------
fetch emp_rec BULK COLLECT into var_rec;

  for i in 1..var_rec.COUNT loop
       --------Set buffer size for dbms_output ------------
      dbms_output.enable(500);
     
     dbms_output.put_line(var_rec(i).emp_code||'   ,    '||var_rec(i).emp_name);     
  end loop;
end loop;
end;
/