JDK Division Bug

November 25, 2013

I have read and heard that java language has some cons. Today, to my surprise, I discovered one loophole by myself in such a simple operation that I didn’t expect in. The flaw I found was when two double values are divided and the result is also double, java compiler always doesn’t yield correct result. For instsance,

0.3d/12.0d = 0.024999999999999998

while any normal calculator or compiler like C++ gives 0.025. My conjecture about why it happens is – java probably just reads the raw underlying values in bits from registers and displays after directly converting to decimal value while other compilers like C++ does intelligent conversion from bits to decimal format before displaying.

Whatever the cause is, in order to meet my purpose, I fixed it (with my conjecture above in mind)  by multiplying both dividend and divisor by a number containing max decimal precision allowed in the context I was working in. The result came out correctly.

(1000000 * 0.3d)/(1000000 * 12.0d) = 0.025. //max precision allowed = 6

However, this mayn’t yield precise result for all cases.

Another easier solution is to use BigDecimal class :

BigDecimal bd = new BigDecimal((0.3d/12.0d), new MathContext(2, RoundingMode.HALF_UP));
System.out.println(bd); // 0.025

I hope, future version of jdk will come out with a fix for this bug.


Chair Survivor Problem

January 30, 2013

This solution to the problem in question makes use of BitSet class of jdk which I found very useful and easy. Besides, this solution works for any number of chairs in the problem.

/**
* PROBLEM:
* You are in a room with a circle of 100 occupied chairs. The chairs are numbered sequentially from 1 to 100.
At some point in time, the person in chair #1 will be asked to leave.
The person in chair #2 will be skipped, and the person in chair #3 will be asked to leave.
This pattern of skipping one person and asking the next to leave will keep going around the circle until there is one person left: the survivor.
Write a program to determine which chair the survivor is sitting in.
*/

import java.io.IOException;
import java.util.BitSet;
import java.util.Scanner;

public class ChairSurvivor {
public static void main(String... args) {
System.out.print("How many chairs? ");
final int numOfChairs = new Scanner(System.in).nextInt();
if(numOfChairs < 1){
System.out.println("Invalid");
System.exit(0);
}
if(numOfChairs == 1){
System.out.println("Assuming that at least one has to survive, #1 is the survivor");
System.exit(0);
}

BitSet chairs = new BitSet(numOfChairs);
chairs.set(0, numOfChairs, true);

int i = -1, j = -1;
while(!chairs.isEmpty()){
j = chairs.nextSetBit((i+1)%numOfChairs);
if(j == -1){
j = chairs.nextSetBit(0);
}

if(i == j){
break;
}
chairs.clear(j);

i = chairs.nextSetBit(j);
if(i == -1){
i = chairs.nextSetBit(0);
}
}

System.out.println("Survivor is #" + ++j);
}
}


Post on Unpublished Facebook Page

April 7, 2012

You need to have at least 25 fans of a fb page to get a public url of the page. And without public url, you can’t post status on the page directly from a java program. But I have a kinda hacked it to get access to the unpublished page (the page with no url). The idea is to use id of the page instead of human readable url. The following java code which uses restfb library to post status onto the unpublished page.

NOTE:  Other detail steps are available aplenty on net.

FacebookClient facebookClient = new DefaultFacebookClient(page_access_token);
String connection = “<page_id>/feed”;
FacebookType publishMessageResponse = facebookClient.publish(connection, FacebookType.class,      Parameter.with(“message”, “<status>”));


Playing with RedHat Linux

September 25, 2011
When I was a junior student of computer engineering program in 2003, 
I used to play with redhat linux 7 at spare time. While doing so, I would
run into various problems like not being able to boot system after 
installation/uninstallation of linux on my xp box. I had learnt 
few things as I went on fixing them. Besides, I would do other stuffs, 
some of which I have mentioned below.

1. To run redhat linux directly from ms dos, I would keep 2 files - 
loadlin.exe & vmlinuz in C:\linux folder and would run the command from dos:
	c:\linux>loadlin vmlinux root=/dev/hda7 ro

2. In order to install grub, I'd insert grub boot disk, go to /boot and 
type grub which would take me to the grub prompt.And then following 
commands -
grub> find /boot/grub/stage1 -- use this cmd if you don't know partion name
grub> root (hd0, 7) -- specify root
grub> setup (hd0) -- install grub at MBR
or
grub> setup (hd0, 0)   --install grub at boot sector instead of MBR, 

3.After redhat linux uninstallation, system wouldn't boot to windows and 
would get stuck at 'grub>' prompt. In this case, to boot to windows,
grub> root ( hd0, 0) // neglect o/p
grub> chainloader +1
grub> boot

4. Some interesting files I jot down were:
$HOME/.login
$HOME/.profile   -- contains history of commands, can be seen by 
  typing 'history'
/etc/passwd  -- password related
/etc/shadow  -- password related
/boot/grub/grub.conf
/var/adm/syslog  -- currently logged in users
/var/log/faillog  -- to see failed logins
/var/log/lastlog  -- to see last logins
/etc/hosts.deny --- to disallow host
login.access  -- to check if password has been changed by others

5. Some summarized commnads:
tty -- display terminal & teletypes
file related :
  date
  touch
  cat
ls -l --color
less /string -- search backward
command related:
  cmd1; cmd2  -- in subshell
  cmd& -- run in bkgnd
  nuhup cmd -- no hnag
  cron cmd --- to run at specific time
  bg --- run suspended process in background
user related:
  who -u/-q
  sync
  finger user
  login - to switch user
  su user
  passwd  -- change pwd
  useradd/userdel/usermod/groupadd
top
free
nice
fstool - control panel to set /etc/fstab
fdisk /MBR -- from dos, reinstall mbr
xv -- capture screen
message related:
  talk, talkd, mail, email, mesg, motd, write, wall, echo
  echo hello > /dev/tty3
SuperProbe -- to scan sys h/w info
xf86Config -- to configure XFree86
  tail -3 -- display last 3 lines
  tail +3  -- display from first 3rd line
  head -3 --- display first 3 lines

Java Security Features & Holes

September 19, 2011

Thinking that my one class presentation on java security features & holes carried out from the perspective of network security may be useful, I have blogged on it with the mere purpose of sharing.  Here are the links to them:

Presenation slides:

http://www.slideboom.com/presentations/160812/java-security-featurse-%26-holes

PDF Report:

http://www.seminarprojects.com/Thread-java-security-features-holes



Richfaces Captcha

July 8, 2010

I used richfaces web framework for an academic project. When I first had to create a captcha on this framework, I rarely found any help on google. Then I came up with an idea and used richfaces’ paint2d component to create it. Here it shows how to have one –

Also available on http://snippets.dzone.com/posts/show/7466

I created a captcha using richfaces paint2d component as follows:
On your .jsp page, put

<h:form id="registerForm">
		<rich:paint2D id="painter" width="300" height="120"
			data="#{paintData}" format="png" paint="#{capBean.paint}" />

		<h:inputText id="secureText" value="#{capBean.secureText}"
			required="true">
			<f:validator validatorId="capValidator" />
		</h:inputText>
		<h:message for="secureText" />

		<h:commandLink action="#{capBean.submit}">
			<h:outputText value="Submit" />
		</h:commandLink>
       </h:form>

Now, have an object of PaintData class like –

public class PaintData implements Serializable{
    String text;
    int color;
    float scale;

    public int getColor() {
        return color;
    }
    public void setColor(int color) {
        this.color = color;
    }
    public float getScale() {
        return scale;
    }
    public void setScale(float scale) {
        this.scale = scale;
    }

    public String getText() {
        return text;
    }
    public void setText(String text) {
        this.text = text;
    }
}
Have a backing bean -
public class CapBean implements Serializable {
	private String secureText;

	public String getSecureText() {
		return secureText;
	}

	public void setSecureText(String secureText) {
		this.secureText = secureText;
	}

	/** Generates Random Text for displaying on the image */
	public String getRandomString() {
		String str=new  String("QAa0bcLdUK2eHfJgTP8XhiFj61DOklNm9nBoI5pGqYVrs3CtSuMZvwWx4yE7zR");
	 	StringBuffer sb=new StringBuffer();
	 	Random r = new Random();
	 	int te=0;
	 	for(int i=1;i<=6;i++){
	 		te=r.nextInt(62);
	 		sb.append(str.charAt(te));
	 	}
	 	System.out.println(sb.toString());
         //todo: save this string in session
	 	return sb.toString();
	}

	public void paint(Graphics2D g2d, Object obj) {

        PaintData data = (PaintData) obj;
        data.text = getRandomString();
        data.color = 11;
        data.scale = 1.5f;

        int testLenght = data.text.length();
        int fontSize = testLenght < 8? 40 : 40 - (testLenght - 8);
         if (fontSize < 12)fontSize = 12;
         Font font = new Font("Serif", Font.HANGING_BASELINE, fontSize);
         g2d.setFont(font);

         int x = 10;
         int y = fontSize*5/2;
         g2d.translate(x, y);
         Color color = new Color(data.color );

         g2d.setPaint(new Color(color.getRed(),color.getGreen(), color.getBlue(), 30));
         AffineTransform origTransform = g2d.getTransform();
         g2d.shear(-0.5*data.scale, 0);
         g2d.scale(1, data.scale);
         g2d.drawString(data.text, 0, 0);

         g2d.setTransform(origTransform);
         g2d.setPaint(color);
         g2d.drawString(data.text, 0, 0);
    }

	public void submit(){
	}
}
Have a validator like
public class CaptchaValidator implements Validator {

	public static final char[] 	INVALID_CHARS 					= new char[] {'*',     '@', '/', '\\'};
	public static final int		MAX_NAME_LENGTH 				= 50;

	public static final String 	VALUEREQUIRED_ERROR_MESSAGE 	= "Value is required.";
	public static final String 	TEXTNOTNATCH_ERROR_MESSAGE 		= "Text not match text on image";

	public void validate(FacesContext context, UIComponent component,
			Object value) throws ValidatorException {
		String val = ((String)value).trim();
		if (val.isEmpty()) {
			throw new ValidatorException(
				new FacesMessage(VALUEREQUIRED_ERROR_MESSAGE, VALUEREQUIRED_ERROR_MESSAGE)
			);
		}

		//todo:
// generatedValueFromSession = saved value in session generated by capBean.generateRandomString()
//		if (!generatedValueFromSession != val)) {
//			throw new ValidatorException(
//				new FacesMessage(TEXTNOTNATCH_ERROR_MESSAGE, TEXTNOTNATCH_ERROR_MESSAGE));
//		}
	}
}

Your faces-config.xml should have -
<managed-bean>
		<managed-bean-name>capBean</managed-bean-name>
		<managed-bean-class>test.CapBean</managed-bean-class>
		<managed-bean-scope>request</managed-bean-scope>
	</managed-bean>
	<managed-bean>
		<managed-bean-name>paintData</managed-bean-name>
		<managed-bean-class>test.PaintData</managed-bean-class>
		<managed-bean-scope>request</managed-bean-scope>
	</managed-bean>
       <validator>
		<validator-id>capValidator</validator-id>
		<validator-class>test.CaptchaValidator</validator-class>
	</validator>

That’s it. Don’t forget to do your action if user enters correct captcha.


Follow

Get every new post delivered to your Inbox.