Validating file path in Java

Import File class

import java.io.File;

Create a new File Instance by giving full pathname String of file/folder

File file = new File("Full-path-to-file-or-folder");

 

  • Checking if File/Folder exists
		if (file.exists()) {
			// File Exists
		} else {
			// File does not exist
		}
  • Check if path specified is a Directory
		if (file.isDirectory()) {
			// Directory
		}
  • Check if application can read/write to file/folder at specified path
		if (file.canRead()) {
			// Application can read File/Folder
		}
		if (file.canWrite()) {
			// Application can write File /Folder
		}
		if (file.canExecute()) {
			// Application can execute file
		}

There may be problems in using canWrite() method in Windows and may not give correct results. Here is a workaround-

Define a method which takes file as input.

Use file.createNewFile() and file.delete() in try block and return true.

If these methods fail then return false in catch block

 

public boolean checkWritable(File file) {
		try {
			file.createNewFile();
			file.delete();
			return true;
		} catch (Exception e) {
			return false;
		}
	}

You can also try opening the file with FileOutputStream and then catch the exceptions.

Connect Four Game Coding Puzzle Algorithm in Java

Puzzle Description:

Connect Four (also known as Plot Four, Find Four, Four in a Row, and Four Up) is a two-player game where players select a color, then take turns dropping their colored discs from the top into a vertically suspended grid. The pieces fall straight down, occupying the next available space within the column. The object of the game is to get four of the same colored discs next to each other vertically, horizontally, or diagonally before one’s opponent can do so. You can find more details about the game from Wikipedia.

Write a program that takes an input as a single argument on the command line. This argument must be a file name, which contains the state of a Four in a Line game. The program must determine if the game has ended and if one of the two players has won. Note that the game ends if either side wins or if the board has no empty slots left, which is a draw.

Input specifications

Your submission will be tested against an input file that contains ASCII characters. Each row of text is terminated by a single new-line character. Each row contains a comma separated list of numbers. Each row will have the same length and all the rows together will describe the grid.

An example of the input file can be:

0,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0
0,0,0,0,1,0,0,0
0,2,1,2,1,2,0,1
2,1,1,2,1,2,1,1
1,2,2,1,1,2,2,2

Where each cell is associated to a number:

  • 0 means that the cell is still empty
  • 1 means that the cell contains a disk put by player 1
  • 2 means that the cell contains a disk put by player 2

Output specifications

The expected output must be one of the following strings, terminated by a new line character:

  • 1 if the game ended and player 1 won
  • 2 if the game ended and player 2 won
  • draw if the game ended with no winner
  • play if the game did not ended yet

Expected output based on the example above:

1

[hr]
Algorithm :

  • Make 2D array representing the Connect Four Grid
  • Initial Array with values 1,0,-1 (using -1 for player 2)
  • If at least one ‘0’ in array then return ‘play’ else return ‘draw’
  • We start checking from Bottom to speed up the code
  • Check row,columns,diagonals by adding the values
  • If sum is ‘4’ then Player1 wins and if ‘-4’ then Player2 wins
Source: (Note: There may be more optimised /simple code available)
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class fourinaline {
	static int ROWS;
	static int COLUMNS;
	public static void main(String args[]) throws IOException {

		String filename = args[0];
		FileReader fr = new FileReader(filename);
		BufferedReader bfr = new BufferedReader(fr);

		int count = 0;
		String str;
		str = bfr.readLine();
		String[] temp = str.split(",");
		COLUMNS = temp.length;
		bfr.close();
		FileReader fr1 = new FileReader(filename);
		BufferedReader bfr1 = new BufferedReader(fr1);

		while ((str = bfr1.readLine()) != null) {
			if (str.length() > 3) { // To remove rows with characters like \n
				count++;
			}
		}

		ROWS = count;
		// Array
		int[][] Array = new int[ROWS][COLUMNS];
		FileReader fr2 = new FileReader(filename);
		BufferedReader bfr2 = new BufferedReader(fr2);

		// Initializing Array
		int rx = 0;
		while (rx < ROWS) {
			str = bfr2.readLine();
			String[] temp1 = str.split(",");
			for (int j = 0; j < COLUMNS; j++) {
				if (temp1[j].equals("0")) {
					Array[rx][j] = 0;
				}
				if (temp1[j].equals("1")) {
					Array[rx][j] = 1;
				}
				if (temp1[j].equals("2")) {
					Array[rx][j] = -1;
				}
			}
			rx++;
		}
		int f = checkBoard(Array);
		if (f != 0) {
			System.out.println(f);
			System.exit(1);
		}
		System.out.println(checkDraw(Array));
	}

	private static String checkDraw(int[][] array) {
		for (int j = 0; j < COLUMNS; j++) {
			if (array[0][j] == 0) {
				return "play";
			}
		}
		return "draw";
	}

	private static int checkBoard(int[][] Array) {
		// Row Wise
		for (int r = ROWS - 1; r >= 0; r--) {
			int total;
			for (int c = 0; c < COLUMNS - 3; c++) {
				total = Array[r][c] + Array[r][c + 1] + Array[r][c + 2]
						+ Array[r][c + 3];
				if (total == 4) {
					return 1;
				}
				if (total == -4) {
					return 2;
				}
			}
		}
		// Column Wise

		for (int c = 0; c < COLUMNS - 1; c++) {
			int total;
			for (int r = ROWS - 1 - 3; r >= 0; r--) {
				total = Array[r][c] + Array[r + 1][c] + Array[r + 2][c]
						+ Array[r + 3][c];
				if (total == 4) {
					return 1;
				}
				if (total == -4) {
					return 2;
				}
			}
		}
		// Diagonals
		for (int r = ROWS - 1 - 3; r >= 3; r--) {
			int total;
			for (int c = 0; c < COLUMNS - 1 - 3; c++) {
				total = Array[r][c] + Array[r + 1][c + 1] + Array[r + 2][c + 2]
						+ Array[r + 3][c + 3];
				if (total == 4) {
					return 1;
				}
				if (total == -4) {
					return 2;
				}
			}
		}
		for (int r = ROWS - 1 - 3; r >= 3; r--) {
			int total;
			for (int c = 3; c < COLUMNS - 1; c++) {
				total = Array[r][c] + Array[r - 1][c - 1] + Array[r - 2][c - 2]
						+ Array[r - 3][c - 3];
				if (total == 4) {
					return 1;
				}
				if (total == -4) {
					return 2;
				}
			}
		}
		for (int r = ROWS - 1 - 3; r >= 3; r--) {
			int total;
			for (int c = 0; c < COLUMNS - 3; c++) {
				total = Array[r][c] + Array[r - 1][c + 1] + Array[r - 2][c + 2]
						+ Array[r - 3][c + 3];
				if (total == 4) {
					return 1;
				}
				if (total == -4) {
					return 2;
				}
			}
		}
		for (int r = ROWS - 1 - 3; r >= 3; r--) {
			int total;
			for (int c = 3; c < COLUMNS - 3; c++) {
				total = Array[r][c] + Array[r + 1][c - 1] + Array[r + 2][c - 2]
						+ Array[r + 3][c - 3];
				if (total == 4) {
					return 1;
				}
				if (total == -4) {
					return 2;
				}
			}
		}
		return 0;
	}
}

 

Download Test Cases,Source code

Read-only Textbox without Cursor

Read Only Text boxes can be used to prevent editing by User.

Making Textbox read-only by HTML readonly attribute

Example:

Source:

No value is needed for ‘readonly’ attribute but readonly=”readonly” will also work where attribute minimization is not allowed.

There is also a disabled attribute which disables a field . The field cannot be changed but you cannot get any data from that field when form is submitted.

Read-only is the best way to make an interactive field uneditable while still being able to get data from the field.

Only problem with above code is that Cursor/Caret/Pointer is still visible on selecting field .

 

Removing Cursor/Blinking Caret from field when Selected

You can easily remove  cursor by using simple Javascript : onfocus=”this.blur()”

This will prevent your field from getting focused and thus remove the Cursor.

Example:

 

Source:

GQL(Google Query Language) Examples

GQL is Query Language used in Google App Engine for getting entries/keys from Datastore.

  • GQL syntax is similar to that of SQL.
  • A GQL query cannot perform a SQL-like “join” query
  • GQL does not have an OR operator. However, it does have an IN operator, which provides a limited form of OR.
  • A maximum of 30 datastore queries are allowed for any single GQL query.
  • SELECT __key__ queries are faster  than SELECT * queries.
GQL Syntax General Form->

 

 SELECT [* | __key__] FROM <kind>
    [WHERE <condition> [AND <condition> ...]]
    [ORDER BY <property> [ASC | DESC] [, <property> [ASC | DESC] ...]]
    [LIMIT [<offset>,]<count>]
    [OFFSET <offset>]

  <condition> := <property> {< | <= | > | >= | = | != } <value>
  <condition> := <property> IN <list>
  <condition> := ANCESTOR IS <entity or key>

 

Using Datastore Viewer /Admin

Let us take an Example Table :   Laptop ( Defined with following fields in laptop.java class)

  • Fields –  brand , memory ,processor,cost
1. Login to AppEngine Dashboard of your application.
2. Select Datastore Viewer from menu on the left and Click on Query Tab.
3. In Query Tab click on options to get textbox for entering GQL Queries on your Datastore entries
Example Queries:

 

  • Select Complete Data in Datastore

 

SELECT * FROM Laptop

 

  • Select an Entry with Key

With Encoded Key (Like ag9zfnNhbXBsZS1hc………)

 

SELECT * FROM Laptop WHERE __key__ = KEY('ag9zfnNhbXBsZS1hc.......')

 
With Decoded Key (Like Laptop: name=9000)

 

SELECT * FROM Laptop WHERE __key__ = KEY('Laptop', '9000')

 

  • Select Entries with some Conditions

 

Select all Laptops in Datastore which are from “DELL”  brand

 

SELECT * FROM Laptop WHERE brand='DELL'

 

Select all Laptops in Datastore which are from “DELL”  brand and Order then with Ascending Cost

 

SELECT * FROM Laptop WHERE brand='DELL' ORDER BY cost ASC

 

Select all Laptops in Datastore where all fields are NULL
SELECT * FROM Laptop WHERE brand=NULL AND cost=NULL AND memory=NULL AND processor=NULL

 

GQL Reference on Google Code

Change default Logon Screen Windows 7

Windows 7 default logon screen background can be changed to any image of your choice.

You can change logon screen background manually by editing registry but it is not recommended for beginners ,takes more time and you can always get it wrong.

Using Tools

  • Windows 7 Logon Background Changer   


Windows 7 Logon Background Changer is a free open source software that let you change the wallpaper of the Windows 7 logon screen.It automatically creates JPEG files based on the image  for the Windows 7 logon screen, applies the appropriate cropping and sizing and saves them using the best compression quality possible.
  1. Download Windows 7 Logon Background Changer .
  2. Extract the downloaded file and run Win7LogonBackgroundChanger.exe (as Administrator)
  3. Click “Choose a Folder” and select a folder containing image that you want to set as background.
  4. Select image and click “Apply”.

  • Tweaks.com Logon Changer for Windows 7


The Tweaks.com Logon Changer for Windows 7 provides an easy way to customize the logon screen background.
  1. Download  Tweaks.com Logon Changer for Windows 7
  2. Extract the downloaded file and run TweaksLogon.exe
  3. Click  “Change Logon Screen” and select the image you want to set as Background ( It will automatically resize if size exceeds the limit)

 

Logon Screen Rotator is a free application that will change the logon background image to an image of your choosing and also at a time you select

Word Reverse Algorithm in Java

Problem :

Write a program that takes an input as a single argument on the command line. This argument must be a file name, which contains rows of text. The program should print each row of text and reverse all individual words in it, leaving the word order, punctuation and any non-alphanumeric characters unmodified. A word is a sequence of alphanumeric characters (i.e. letters and numbers).

Example :

Input :  Q: What do you call a blind pre-historic animal?

Output : Q: tahW od uoy llac a dnilb erp-cirotsih lamina?

Source Code : (Note: There may be more optimised /simple code available)
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class Reverse {
	public static void main(String args[]) throws IOException {

		String filename = args[0];

		FileReader fr = new FileReader(filename);
		BufferedReader bfr = new BufferedReader(fr);

		String str;

		while ((str = bfr.readLine()) != null) {

			StringBuffer buffer = new StringBuffer();
			char stringArray[];
			stringArray = str.toCharArray();
			for (int index = 0; index < stringArray.length; index++) {
				char c = stringArray[index];

				if (Character.isLetter(c) || Character.isDigit(c)) {
					buffer.append(c);
					if (index == (stringArray.length - 1)) {
						System.out.print(buffer.reverse().toString());
						buffer.trimToSize();
						buffer.delete(0, buffer.length());
					}
					continue;
				} else {
					System.out.print(buffer.reverse().toString());
					buffer.trimToSize();
					buffer.delete(0, buffer.length());
					System.out.print(c);
				}
			}
			System.out.print('\n');
		}
	}
}

DBScan (Density Based Clustering) in Java

DBSCAN (Density-Based Spatial Clustering of Applications with Noise) is a data clustering algorithm that finds a number of clusters starting from the estimated density distribution of corresponding nodes.
DBSCAN is one of the most common clustering algorithms and also most cited in scientific literature.
DBSCAN requires two parameters: e (eps)-threshold distance and the minimum number of points required to form a cluster (minPts).
It starts with an arbitrary starting point that has not been visited. This point’s e-neighborhood is retrieved,
and if it contains sufficiently many points, a cluster is started. Otherwise, the point is labeled as noise.
Note that this point might later be found in a sufficiently sized e-environment of a different point and hence be made part of a cluster.

If a point is found to be part of a cluster, its e-neighborhood is also part of that cluster. Hence, all points that are
found within the e-neighborhood are added, as is their own e-neighborhood. This process continues until the cluster is completely found.
Then, a new unvisited point is retrieved and processed, leading to the discovery of a further cluster or noise.

Read More at http://en.wikipedia.org/wiki/DBSCAN

 

Implementation of DBScan in java for points 

Download Source Code + DBScan GUI(.exe) on GitHub https://github.com/KanwarBhajneek/DBSCAN

Source Files ->

  • dbscan.java
  • Utility.java
  • Point.java
  • Gui.java
Standalone Executable->
  • DbScan.exe

 

 

 

Installing ant on Windows 7, Vista, Xp

ANT   is a java build tool to do various tasks like compile, assemble, test/run java applications.

Easiest way to use ant is through command -line . 

Here are the Steps to Install Ant on Windows

  • Download ant package from http://ant.apache.org/bindownload.cgi
  • Extract the downloaded file
  • Right Click “Computer” and click Properties to open System Information  or go to Control Panel\All Control Panel Items\System 

  • Click on “Advanced System Settings ”  to open System Properties window.
  • Select ” Advanced” tab and click on “Environment Variables” button at the bottom
  • Add a  “New User Variable” with Variable Name as ANT_HOME and Variable Value as path to your extracted ant folder (Folder that contains bin folder) like C:\apache-ant-1.8.2
  • Now in “System Variables” select and edit “Path”. 
  • Add the path to bin folder like C:\apache-ant-1.8.2\bin  or  %ANT_HOME%\bin . Click OK
To check if ANT has been installed , Open Command Prompt (Shift + Right Click in any folder) and type any ant command like ant -version