Friday, May 29, 2009

SWING JApplet with multimedia

Play Audio in JApplet
When playing music, AudioClip object is needed, which play *.au and *.wav files.
There are three methods on AudioClip objects:
• play(): it plays the audio file once and stop.
• loop(): it plays the audio file repeatedly until the stop method is called.
• stop(): it stops a loop play of an audio clip.

To test the code, get any wav files, rename them to shutter.wav and tuner2.wav, then copy them to your DocumentBase directory (just uncomment //System.out.println("DocumentBase="+getDocumentBase()); to find out).

Show Code   Hide Code



Play Video in JApplet
When playing video a Manager class and a player object are needed.
There are there control methods on the player object:
player.start()
player.stop()
player.close()

Java Media Framework (JMF) API is needed for import javax.media.*;
You need to download JMF library for compiling the code.

To test the code, get any mpg file, rename it to phantom.mpg, then copy it to your DocumentBase directory (just uncomment //System.out.println("DocumentBase="+getDocumentBase()); to find out).

Show Code   Hide Code


download the supporting files and code from here.

Model fighter game UI with Swing - Part 1

tutorial reference:
Swing with Netbeans

In this session, we will create a fighter selection user interface. If you ever played console game such as "Street Fighters" and "Iron Fists", you already know what the UI feels like.

In part 1, our objective is to create the UI frame showing the fighter's information.

At the application level, once the User opens the game, a panel will list all available fighters with their thumbnail pictures. Once user selects a fighter, we entered this information frame, which show the details about the fighter. There will be two buttons "Back" and "Fight". "Back" button brings user to the thumbnail frame, while "Fight" button brings user to the fighting arena frame. Optionally, user can click to view the fighter's story, watch the fighter's fighting movie's etc.
At the function level, this frame have upperArea and lowerArea. The upperArea shows the fighters name, style, birthday, hometown and many control buttons. The lowerArea shows the fighter's picture, fighter's power, speed, energy etc. There are many interactive features. For example, the user is able to adjust the fighter's power, speed, energy etc. with sliders and save the data to hard disk. There are prev and next button to iterate through all the fighters. The frame embeds many special effects, such as the 3D shadowing of the text, button pressing sounds and the background music for each fighter.
At the implementation level, there are two classes, SelectPanel.java and Afighter.java. SelectPanel provide the view and control. The Afighter.java is the model of a fighter, with fields and getters/setters. The persistant layer is provided by harddisk files.

SelectPanel.java

/*SelectPanel.java*/
package FighterSelect;

import java.applet.AudioClip;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.AffineTransform;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Properties;
import java.util.Vector;

import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class SelectPanel extends JFrame implements ActionListener{
JPanel content;
JPanel upperArea;
JPanel controlBar;
JButton prevButton;
JButton nextButton;
JLabel infoLabel;
JLabel photoLabel;
JLabel descLabel;
JSlider slider1;
JSlider slider2;
JSlider slider3;
JSlider slider4;
JSlider slider5;
MusicButton musicBtn;
DrawingPanel drawingPanel;

Vector fighters;
String[] ids = {"010","030","022"};
Afighter afighter;
private int current = 0;
public static void main(String[] args) {
new SelectPanel("Fighter NameCard");
}

public SelectPanel(String name) {
super(name);
super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
super.setSize(800,600);
super.setLocationRelativeTo(null);
fighters = parseParameters();
afighter = (Afighter)fighters.firstElement();

try {
// UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
// UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch(Exception e) {
System.out.println("Error setting Motif LAF: " + e);
}

content = (JPanel)getContentPane();
content.setBackground(Color.GRAY);
Font font = new Font("Serif", Font.PLAIN, 30);
content.setFont(font);

ImageIcon lefticon = new ImageIcon("images/left.gif");
ImageIcon righticon = new ImageIcon("images/right.gif");
prevButton = new JButton("Prev",lefticon);
prevButton.setEnabled(false);
prevButton.addActionListener( new ButtonClicked());
prevButton.addActionListener(this);
nextButton = new JButton("Next",righticon);
nextButton.addActionListener(this);
nextButton.addActionListener( new ButtonClicked());
nextButton.setHorizontalTextPosition(SwingConstants.LEFT);
infoLabel =
new JLabel("labelText", JLabel.CENTER);
infoLabel.setBorder
(BorderFactory.createTitledBorder("Information"));
drawingPanel = new DrawingPanel(afighter.getName());
try {
URL u = new URL("file:audio/"+afighter.getMusic());
AudioClip audio = JApplet.newAudioClip(u);
musicBtn = new MusicButton(audio);
} catch (MalformedURLException e) {
e.printStackTrace();
}
JButton backBtn = new JButton("Back");
backBtn.addActionListener(new ButtonClicked());
JButton saveBtn = new JButton("Save Data");
saveBtn.addActionListener(new ButtonClicked());
JButton fightBtn = new JButton("Fight");
fightBtn.addActionListener(new ButtonClicked());
JButton storyBtn = new JButton("Story");
storyBtn.addActionListener(new ButtonClicked());
JButton videoBtn = new JButton("Video");
videoBtn.addActionListener(new ButtonClicked());
controlBar = new JPanel(new GridLayout(1,5));
controlBar.setBackground(Color.GRAY);
controlBar.add(saveBtn);
controlBar.add(backBtn);
// controlBar.add(storyBtn);
// controlBar.add(videoBtn);
controlBar.add(fightBtn);
controlBar.add(musicBtn);

upperArea = new JPanel(new BorderLayout());
upperArea.setBackground(Color.GRAY);
upperArea.add(infoLabel, BorderLayout.NORTH);
upperArea.add(drawingPanel, BorderLayout.CENTER);
upperArea.add(prevButton, BorderLayout.WEST);
upperArea.add(nextButton, BorderLayout.EAST);
upperArea.add(controlBar, BorderLayout.SOUTH);
content.add(upperArea,BorderLayout.NORTH);

slider1 = new JSlider();
slider1.addChangeListener(new sliderDragged(1));
slider1.setBackground(Color.GRAY);
slider2 = new JSlider();
slider2.setBackground(Color.GRAY);
slider2.addChangeListener(new sliderDragged(2));
slider3 = new JSlider();
slider3.setBackground(Color.GRAY);
slider3.addChangeListener(new sliderDragged(3));
slider4 = new JSlider();
slider4.setBackground(Color.GRAY);
slider4.addChangeListener(new sliderDragged(4));
slider5 = new JSlider();
slider5.setBackground(Color.GRAY);
slider5.addChangeListener(new sliderDragged(5));

photoLabel =
new JLabel("",
new ImageIcon("images/street_fighter_"+afighter.getId()+".gif"),
JLabel.CENTER);
descLabel = new JLabel("labelText");

JPanel controlArea = new JPanel(new GridLayout(6,1));
// controlArea.setPreferredSize(new Dimension(400, 0));
controlArea.setBackground(Color.GRAY);
controlArea.add(descLabel);
controlArea.add(slider1);
controlArea.add(slider2);
controlArea.add(slider3);
controlArea.add(slider4);
controlArea.add(slider5);

JPanel LowerArea = new JPanel(new BorderLayout());
LowerArea.setBackground(Color.GRAY);
LowerArea.add(photoLabel,BorderLayout.WEST);
LowerArea.add(controlArea, BorderLayout.EAST);
content.add(LowerArea, BorderLayout.SOUTH);

this.init();
super.setVisible(true);
}

void init() {
String labelText =
"<html>" +
"<FONT COLOR=rgb(200,200,200)>Style: </FONT> " +
"<FONT COLOR=WHITE>"+afighter.getStyle()+"</FONT> " +
"<FONT COLOR=rgb(200,200,200)> Birthday: </FONT> " +
"<FONT COLOR=WHITE>"+afighter.getBd()+"</FONT> " +
"<FONT COLOR=rgb(200,200,200)>HomeTown: </FONT> " +
"<FONT COLOR=WHITE>"+afighter.getHometown()+"</FONT> " +
"</html>";
infoLabel.setText(labelText);

labelText =
"<html>" +
"<div width='250px' padding='10px' margin='0px'>" +
"<I>" + afighter.getDescription() + "</I>" +
"</div>" +
"</html>";
descLabel.setText(labelText);

photoLabel.setIcon(new ImageIcon("images/street_fighter_"+afighter.getId()+".gif"));
slider1.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEmptyBorder(),"Power "+afighter.getPower()));
slider1.setValue((int) afighter.getPower());
slider2.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEmptyBorder(),"Speed "+afighter.getSpeed()));
slider2.setValue((int) afighter.getSpeed());
slider3.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEmptyBorder(),"Flexibility "+afighter.getFlexibility()));
slider3.setValue((int) afighter.getFlexibility());
slider4.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEmptyBorder(),"Energy "+afighter.getEnergy()));
slider4.setValue((int) afighter.getEnergy());
slider5.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEmptyBorder(),"Endurance "+afighter.getEndurance()));
slider5.setValue((int) afighter.getEndurance());

controlBar.remove(musicBtn);
musicBtn.a.stop();
try {
URL u = new URL("file:audio/"+afighter.getMusic());
AudioClip audio = JApplet.newAudioClip(u);
musicBtn = new MusicButton(audio);
} catch (MalformedURLException e) {
e.printStackTrace();
}
controlBar.add(musicBtn);

upperArea.remove(drawingPanel);
drawingPanel = new DrawingPanel(afighter.getName());
upperArea.add(drawingPanel, BorderLayout.CENTER);

super.pack();
}

//Load all fighter characters
protected Vector parseParameters() {
Vector pix = new Vector(10); //start with 10, grows if necessary
for (int j = 0; j < ids.length; j++) {
pix.addElement(FighterFactory(ids[j]));
}
return pix;
}

protected Afighter getAfighter() {
return this.afighter;
}

//initiate Afighter object with persistant data (we can also use JDBC)
protected Afighter FighterFactory(String id){
Afighter fighter = new Afighter();
Properties props = new Properties();
try {
props.load(new FileInputStream("DataBase/"+id));
fighter.setId(props.getProperty("id"));
fighter.setMusic(props.getProperty("music"));
fighter.setPower(new Integer(props.getProperty("power")));
fighter.setSpeed(new Integer(props.getProperty("speed")));
fighter.setFlexibility(new Integer(props.getProperty("flexibility")));
fighter.setEnergy(new Integer(props.getProperty("energy")));
fighter.setEndurance(new Integer(props.getProperty("endurance")));
fighter.setName(props.getProperty("name"));
fighter.setBd(props.getProperty("bd"));
fighter.setHometown(props.getProperty("hometown"));
fighter.setStyle(props.getProperty("style"));
fighter.setDescription(props.getProperty("description"));
}catch(IOException e){
e.printStackTrace();
}
return fighter;
}

//Back and Next Buttons' sound effect
private class ButtonClicked implements ActionListener {
ButtonClicked() {}
public void actionPerformed (ActionEvent e) {
try {
URL u;
if(e.getActionCommand() == "Fight") {
u = new URL("file:audio/aah.wav");
}else if(e.getActionCommand() == "Back"){
u = new URL("file:audio/attack.wav");
}else if(e.getActionCommand() == "Save Data"){
u = new URL("file:audio/shutter.wav");
saveData();
}else{
u = new URL("file:audio/shutter.wav");
}
AudioClip music = JApplet.newAudioClip(u);
music.play();
} catch (MalformedURLException ex) {
ex.printStackTrace();
}
}
}

//save data to the file system (we can also use JDBC here)
private void saveData(){
Properties pro = new Properties();
try {
pro.load(new FileInputStream("DataBase/"+afighter.getId()));
} catch (Exception e1) {
e1.printStackTrace();
}
pro.setProperty("power", afighter.getPower().toString());
pro.setProperty("speed", afighter.getSpeed().toString());
pro.setProperty("flexibility", afighter.getFlexibility().toString());
pro.setProperty("energy", afighter.getEnergy().toString());
pro.setProperty("endurance", afighter.getEndurance().toString());
try {
pro.store(new FileOutputStream("DataBase/"+afighter.getId()),null);
} catch (Exception e) {
e.printStackTrace();
}
}

//Update slider title and the Afighter object.
private class sliderDragged implements ChangeListener {
private int id;
sliderDragged(int id) {
this.id = id;
}
public void stateChanged(ChangeEvent arg0) {
JSlider a = (JSlider)arg0.getSource();
switch(id) {
case 1:
getAfighter().setPower(a.getValue());
a.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEmptyBorder(),"Power "+afighter.getPower()));
break;
case 2:
getAfighter().setSpeed(a.getValue());
a.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEmptyBorder(),"Speed "+afighter.getSpeed()));
break;
case 3:
getAfighter().setFlexibility(a.getValue());
a.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEmptyBorder(),"Flexibility "+afighter.getFlexibility()));
break;
case 4:
getAfighter().setEnergy(a.getValue());
a.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEmptyBorder(),"Power "+afighter.getEnergy()));
break;
case 5:
getAfighter().setEndurance(a.getValue());
a.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEmptyBorder(),"Power "+afighter.getEndurance()));
}
}
}

//Play background music
private class MusicButton extends JButton implements Runnable, ActionListener {
Thread runner;
AudioClip a;
MusicButton(AudioClip audio) {
super("Play Music");
addActionListener(this);
a = audio;
}
public void actionPerformed(ActionEvent event) {
String command = event.getActionCommand();
if (command == "Play Music")
startMusic();
if (command == "Stop Music")
stopMusic();
}
void startMusic() {
if (runner == null) {
runner = new Thread(this);
runner.start();
setText("Stop Music");
}
}
void stopMusic() {
a.stop();
runner = null;
setText("Play Music");
}
public void run() {
a.loop();
}
}

//Drawing the name with shadowing effects
private class DrawingPanel extends JPanel {
private int fontSize = 20;
private String message = "Java 2D";
private int messageWidth;

public DrawingPanel(String message) {
this.message = message;
setBackground(Color.GRAY);
Font font = new Font("Serif", Font.PLAIN, fontSize);
setFont(font);
FontMetrics metrics = getFontMetrics(font);
messageWidth = metrics.stringWidth(message);
int height = fontSize*3;
setPreferredSize(new Dimension(0, height));
}

public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
int x = (super.getWidth()-messageWidth)/2;
int y = fontSize*5/2;
g2d.translate(x, y);
g2d.setPaint(Color.lightGray);
AffineTransform origTransform = g2d.getTransform();
g2d.shear(-0.95, 0);
g2d.scale(1, 3);
g2d.drawString(message, 0, 0);
g2d.setTransform(origTransform);
g2d.setPaint(Color.black);
g2d.drawString(message, 0, 0);
}
}

//User clicked either the next or the back button.
public void actionPerformed(ActionEvent e) {
//Compute index of fighter to view.
if (e.getActionCommand().equals("Next")) {
current += 1;
if (!prevButton.isEnabled())
prevButton.setEnabled(true);
if (current == fighters.size() - 1)
nextButton.setEnabled(false);
} else {
current -= 1;
if (!nextButton.isEnabled())
nextButton.setEnabled(true);
if (current == 0)
prevButton.setEnabled(false);
}
//Get the Afighter object.
afighter = (Afighter)fighters.elementAt(current);
init();
}
}


Afighter.java

/*Afighter.java*/
package FighterSelect;

public class Afighter {
private String id = "030";
private String music = "030.wav";
private Integer power = 98;
private Integer speed = 87;
private Integer flexibility = 80;
private Integer energy = 100;
private Integer endurance = 100;
private String secretskill = "?";
private String name = "Phil Jackson";
private String bd = "02/14/1989";
private String hometown = "New York City, USA";
private String style = "Boxer/Out-fighter";
private String description =
"A classic boxer who seeks to maintain distance between himself " +
"and his opponent, fighting with faster, longer range punches, " +
"most notably the jab, and gradually wearing his opponent down.";

public Afighter() {}

public void setId(String id) {
this.id = id;
}

public String getId() {
return this.id;
}

public void setMusic(String music) {
this.music = music;
}

public String getMusic() {
return this.music;
}

public void setPower(Integer power){
this.power = power;
}

public Integer getPower(){
return this.power;
}

public void setEnergy(Integer energy){
this.energy = energy;
}

public Integer getEnergy(){
return this.energy;
}

public void setSpeed(Integer speed){
this.speed = speed;
}

public Integer getSpeed(){
return this.speed;
}

public void setFlexibility(Integer flexibility){
this.flexibility = flexibility;
}

public Integer getFlexibility(){
return this.flexibility;
}

public void setEndurance(Integer endurance){
this.endurance = endurance;
}

public Integer getEndurance(){
return this.endurance;
}

public void setSecreteskill(String secretskill){
this.secretskill = secretskill;
}

public String getSecreteskill(){
return this.secretskill;
}

public void setName(String name){
this.name = name;
}

public String getName(){
return this.name;
}
public void setBd(String bd){
this.bd = bd;
}

public String getBd(){
return this.bd;
}

public void setHometown(String hometown){
this.hometown = hometown;
}

public String getHometown(){
return this.hometown;
}

public void setStyle(String style){
this.style = style;
}

public String getStyle(){
return this.style;
}

public void setDescription(String description){
this.description = description;
}

public String getDescription(){
return this.description;
}

}

Thursday, May 28, 2009

Blog Tricks, how to remove the navigation bar in your post in 10 seconds?







Press Customize tab, press Edit HTML. Copy paste the following line into the css code.
#navbar-iframe{display:none!important;}

In the future, if blogger updates the template, the id "navbar-iframe" may change, you need to view your page's source code (how?), and find the corresponding id.

Notice removing the navigation bar is violating the agreement when you signed up to blogger, so I still keep it there.

Wednesday, May 27, 2009

Model a fighter academy with Factory Method and Abstract Factory design pattern

In my previous posts, I have modeled a fighter and a fighter's body conditions, now I will model the academy which trains the fighters.

Below you will find abstract classes and concrete classes for a fighter training system. You will find classes for regional fighter academies along with classes for fighters a academy can train. Each regional academy can decide how they will train the fighters.

First of all, a fighter academy is just an abstract brand, such as ShaoLin Temple, Karate Institute or Aikido Dojo... A fighter get trained under ShaoLin temple only told us it should have some characters and qualities, but did not restrict how they should get trained. In another words, the detailed training plan is the decision of a specific regional ShaoLin Temple, no matter it's ShongShan mountain ShaoLin Temple or New York City ShaoLin Temple. We model this with factory method design pattern. While abstract class FighterAcademy guaranteed to return a qualified fighter, the concrete class NYCShaoLinTemple make it happen by making the actual training plan in the method trainFighter().

As a common challenge all brands face, we need a quality control mechanism. For example, Jack wants to open an ObjvillKarateInstitute today, he can't claim his institute to be a qualified fighter academy until he hires a licensed fighter. Only through the licensed fighter, we can call method TrainSpeed(), TrainPower(), TrainFlexibility(), TrainReflection(), TrainStagama(). Here the abstract factory come into play.

Tuesday, May 26, 2009

Adjust display settings to protect your eys

Feel your display uncomfortable for the eyes?

Sometimes it's because your monitor's brightness or contract were set too high. You can find several bottons on your monitor which allow you to adjust display settings.

If your monitor is CRT, try to change the refresh rate to the highest one.
For LCD monitor, refresh rates have no effect. To adjust refresh rate:
1. Right-click on a blank area of your desktop
2. Select Properties from the context menu
3. Select the settings tab
4. Press the Advanced button
5. Select the Monitor tab
6. Select highest refresh rate from the drop down box.
7. Click OK until the boxes are closed out

If you use winXP, you can re-rerender fonts to make them easier on the eyes by turning on "ClearType".
To turn on ClearType:
1. Right-click on a blank area of your desktop
2. Select Properties from the context menu
3. Select the Appearance tab
4. Press the Effects button
5. Select the check box before Use the following method to smooth edges of screen fonts
6. Select ClearType from the drop down box.
7. Click OK until the boxes are closed out

Friday, May 22, 2009

Turn you PC into HD TV with 20 bucks

Most cities in the US broadcast free TV over the air in HD (High Definition). To receive this signal an HD tuner is required. (Does this remind you of ancient radio broadcast? Yes, they are almost the same!) Televisions have an HD tuner built in. BUT, you can buy a usb plug-in TV tunner and enjoy free HDTV on your computer.

Step 1, Get a usb tv tunner with $15 to $50 bucks.
Search "usb tv tunner" on http://www.newegg.com/, I picked a cheap one, which works fine. Usb tv tunner is simply a usb adapter plus an antenna. The antenna receive microwave from air, usb adapter convert the microwave to digital signal your PC understand. Don't spend too much time on this, these products won't be too different. The only thing you need to worry about is the operation system the driver requires. Some driver only work on winxp and vista.


If you have hooked the usb tv tunner up, you may be enjoying many free HDTV channel on you PC right now. Depending on your city, you may have different channels available. The experience is similar to watching video on youtube, except the TV is really High Definition even with full screen. Also you don't need network connection, because signal is from your antenna which collect HDTV broadcast from air like radio does.

Step 2, Get a powerful antenna.
Want more channels? No problem, go ahead and buy a $100+ commercial antenna, or make a better antenna with less than 5 bucks and 30 minutes by yourself.
The link have detailed instructions. The key here is, HDTV is electromagnetic waves, to strengthen the signal, we need to form standing-wave in the antenna. Therefore, we need to pay attention to the wire's size, other things are just not so important details. Have fun and enjoy cool cyber stuff!

Thursday, May 21, 2009

Model a fighter's conditions with OBSERVER design pattern

Below you will find classes and interfaces for the conditions of a fighter during combat. You will find classes for events along with classes for conditions the fighters may have during a combat. Each event can cause many conditions to change, while each condition can be changed by many events during a combat.

Here we see one-to-many relationship. For example, an event of "get hit" can cause energy, power, speed, looking and other conditions to change; energy condition can be changed by events such as "get hit", "get inspired", "get rest". The thing that varies are the state of the events and the number and type of the conditions that get effected by a specific event. The thing that stay constant is a subject-observer relationship in the picture, therefore we abstract them into two interfaces: Observable and Observer.
Show   Hide

Wednesday, May 20, 2009

Model a fighter with STRATEGY design pattern

Below you will find classes and interfaces for a martial artist. You will find classes for individual fighters along with classes for movements the fighters can take during a combat. Each fighter can make only one movement at a time, but can change movement at any time during a combat.

First All, Fighter is an abstract concept. He/She can be Gracie Jiu-Jitsu, Capoeira, American Kenpo, Jeet Kune Do, Shaolin fighters... or mixed style fighter. He/She may have unique looking, nationality, age etc. During combat, fighters have something in common, their movement can be classified into attack and defense.

There are many attack strategies such as punch, tick, elbow, knees, joint knock; as many defense strategies as well -- block, trap, lock, duck, roll, footsweep... The problem is, you never know how many strategies a fighter has learned, and a fighter could invent a new strategy today!

The strategy design pattern resolve this by defining a family of movements, encapsulates each one, and make them interchangable by extending the same interfaces (attack or defense), as a result, new movement classes can be added without modifying other parts of the system.


Show   Hide

Cyber Jedi

Have you ever think of adding them together? Reverse Engineer hardware engineer Stanford CS107 computer scientist Fight Science martial artist 

Top 10 websites Blogger should know

1. Digg
2. Twitter
3. FriendFeed
4. Reddit
5. Hacker News
6. Facebook
7. MySpace
8. LinkedIn
9. Flixster
10. Flickr

Monday, May 18, 2009

Debugging tools in major browsers:

Firefox:
firebug

Safari:
WebKit
It's easier on mac os -- open a terminal, run command:
% defaults write com.apple.Safari IncludeDebugMenu 1
restart safari,
now "Develop" menu is show up in the menu bar, also "inspect element" shows up when right clicking.

IE:
IETester

DIY your wireless antena



The idea is simple, microwave get reflected from the metal surface, thus condensed at a specific direction. 

Blog Tricks, how to embed an online dictionary in your post in 10 seconds?


Word Lookup:




---------------------------
To achieve the above effect, copy paste the following code into your blog's Html. Done.

<form>
Word Lookup:
<input id="words_lookup" type="text" />
<button type="button" onclick="var uri = 'http://www.merriam-webster.com/dictionary/'+document.getElementById('words_lookup').value; window.open(uri);">Search</button>
</form>


---------------------------
ps:
'http://www.merriam-webster.com/dictionary/' is the webster online dictionary, you can change it to your favorite online dictionary such as 'http://www.answers.com/'.

Blogger.com seems disabled <script> tag in the post, so I hacked this with inline javascript.

Sunday, May 17, 2009

23 Design Patterns

Reference book: Head First Design Patterns.
Reference Wiki article: Design Pattern (Computer Science)

Abstraction:

In an object-oriented software system,objects are entities used to represent or model a particular piece of the system.

A class is a template or recipe for the creation of a particular type of object. That is, one can use a class to create ("instantiate") objects of the type described by the class.

new is a keyword in Java. It is an example of what is called a class operator. It operates on a class and creates an instance (also called object) of the given class.


People have identified and separated the variant and invariant pieces of a systems and defined abstract representations whenever needed, for example

  1. Abstract Structure -- abstract classes, interfaces
  2. Abstract Behavior -- abstract methods, strategies, visitors.
  3. Abstract Construction -- factories
  4. Abstract Environments -- anonymous inner classes, closures

Inheritance and Polymorphism:


"Is-a" or "inheritance" (sometimes also called "generalization") relationships capture a hierarchal relationship between classes of objects.

We can never truly know what an object truly is, only how it acts. Java has a the keyword implements which is used to show generalization of a pure behavioral abstraction called an interface. An interface has a similar syntax to a class, but only specifies behaviors in terms of the "signatures" (the input and output types) of the methods.


Inheritance and polymorphism are really just two ways of looking at the same class relationship.

Inheritance is looking at the class hierarchy from the bottom up. A subclass inherits behaviors and attributes from its superclass. A subclass automatically possesses certain behaviors and/or attributes simply because it is classified as being a subclass of an entity that possesses those behaviors and/or attributes.


Polymorphism, on the other hand, is looking at the class hierarchy from the top down. Any subclass can be used anywhere the superclass is needed because the subclasses are all abstractly equivalent to the superclass. Different behaviors may arise because the subclasses may all have different implementations of the abstract behaviors defined in the superclass.


Inheritance and Composition:

An OO system has two distinct mechanisms to express relationship notions between objects: "is-a" which is technically referred to as "inheritance" and "has-a" which is technically referred to as "composition".

"Has-a" or "composition" (sometimes referred to as an "associative") relationships capture the notion that one object has a distinct and persistant communication relationship with another object. for instance, we can say a car "has-a" motor.


23 Design Patterns

In the book Design Patterns: Elements of Reusable Object-Oriented Software published in 1994 (Gamma et al.), there are 23 design patterns.

Creational patterns:

1 Abstract factory

2 Factory method

3 Builder

4 Prototype

5 Singleton


Structural patterns:

6 Adapter

7 Bridge

8 Composite

9 Decorator

10 Facade

11 Flyweight

12 Proxy


Behavioral Patterns:

13 Chain of responsibility

14 Command

15 Interpreter

16 Iterator

17 Mediator

18 Memento

19 Observer

Defines a one-to-many dependency between objects, so that when one object changes state, all its dependents are notified and updated automatically.

Example

20 State

21 Strategy

Defines a family of algorithms, encapsulates each one, and make them interchangable. Strategy lets the algorithm change independently from clients that use it.

Example

22 Template method

23 Visitor

Softwares for youtube publishing

For basic movie making,
1. windows Movie Maker. (Windows)
2. iMovie. (Mac)

If you want to make a movie from what is displayed on the screen,
3. Camtasia (windows)
4. SnapzPro site1, site2(Mac)

Sometimes your video file is huge, so you want to compress them.
I recommand "divx fast motion" compressor,
5. "ace"

Monday, May 11, 2009

Reading list (google book is cool)


Word Lookup:


?

Youth - Samuel Ullman

Three Days To See - Helen Keller

Oxford Revisited - James Anthony Froude

Beautiful Smile And Love - Mother Teresa

Thank You For Correcting Me,Sister! - Sister Helen P.Mrosia

Wonderful…Lousy…… - Budd Schulberg

Ⅵ,11at l Have Lived For - Bertrand Russell

The LiUle Boat That Sailed Through Time - Arnold Berwick

Integrity - Marjorie Kinnan Rawlings

Love Never Come Back - J.K.Jerome

The Giving Tree - Shel Silverstein

Dads Help Kids Walk On The Ceilings - nPhhie Fnrmer

lf I Had My Life To Live Over - Erma Bombeck

Music - WaIt Whitman



The Gift Of Magi - O.Henry

Appointment With Love - Garcia Marquez

The Gnod Old Times - Charles lamb

Tolerance - Hendrik Willem Van Loon

El Dorado - Robert Louis Stevenson

The Rose - Logan Pearsall Smith

I Will Greet This Day With Love In My Heart
Og Mandino

The Edge 0f The Sea - Rachel Carson

The Old Man And The Sea
Emest Hemingway


The Smile - Antoine De Saint—Exupery

A Walk In The Woods - Bill Bryson

Youth,Return! - John Ruskin

On Friendship - Kahlil Gibran

The Crescent Moon - Rabindranath Tagore

Poems

Poems are like songs, whose beauty can only be fully appreciated by listening the voice of a good reader.

Sonnets of William Shakespeare


Sonnet no 2: By William Shakespeare


Sonnet no 33: By William Shakespeare



Sonnet no 18: By William Shakespeare


Ode To A Nightingale-John Keats,read by Robert Donat


William Wordsworth - Daffodils (Read by Jeremy Irons)


The Road not Taken - Robert Frost (by Alan Bates)


Invictus - William Ernest Henley (by Alan Bates)


It's all in a State of Mind (spoken by Harvey Keitel)

Sunday, May 10, 2009

Blog Tricks, how to boxing your text in your post in 10 seconds?


This is my Text!!! Bla bla bla bla bla bla ...



To Achieve the above effect, in Edit Html, substitute
"This is my Text!!! Bla bla bla bla bla bla ..."
with the following code. Done.

<table width=300 border=1 frame=box cellspacing=0 cellpadding=10><tr><td bgcolor=white>
This is my Text!!! Bla bla bla bla bla bla ...
</td></tr></table>

The Real Blogger Status: Making A Website From Your Blog

The Real Blogger Status: Making A Website From Your Blog

Zen Garden

Find a very beautify personal web page:


http://www.rosefu.net/projects.php



From there, I find the Zen Garden.


http://www.csszengarden.com/?cssfile=194/194.css

Let's share

Yes, there is free lunch in the world.
We plant seeds, they grow into forests, because sunshine, air and water is free.
Share is free, so why not?

Free Online multiplayer game:
Shaiya

Free Online Music:
site1
Free Textbooks
Electronics

Free Online courses:
UC berkeley
MIT Open Courses

Free Online Drama
BBC Radio arts and Drama

Free Site Hosting
Google Site

Free online compilers
Java/Applet
multiple Languages online compiler (C/C++/Java/VB/C#)

Free web design library
Free CSS Navigation memue
embedable photo slider
flash clock
summary at blogbuster
flash game

Free web TV/movie
youtube
hulu
msnTV
abc.com
cbs.com

Free domain name
http://www.no-ip.com/services/managed_dns/free_dynamic_dns.html

Free online dictionary
Learn Chinse

Free Who'is database
The main whois database for the top-level domains ".com", ".net", and ".org" can be searched through any of the following sites:
The InterNIC Whois Search *
Domain registrars -- each with their own whois database
BetterWhois.com
AllWhois.com
SWITCH Whois Gateway
Google - Domain Name Search
Yahoo Whois Directory
The following Whois databases can be searched for information on other areas of the Internet, including Asian, Caribbean, European, and Latin American countries, and the ".mil" and ".gov" domains:
American Registry for Internet Numbers Whois
Asia Pacific IP Address Allocations Whois
European IP Address Allocations Whois
Latin American and Caribbean Internet Addresses Registry
US Military Whois - requires authorization to access
US Government Whois
Matt Power's Whois Servers List provides a long list of searchable world wide whois database servers.

An accurate and informational ip geo location  lookup

On mother's day











Blog Tricks, how to embed flash music in your post in 10 seconds?



Super easy. Just go to any website with embed music
(e.g.http://www.4shared.com/network/search.jsp?searchmode=3&searchExtention=category%3A1)

Select a music, copy the content in the textbox labeled "embed", paste into you Html code.
Done.

Blog Tricks, how to embed music in your post in 10 seconds?


...bug found...audio player removed...

I later find that autostart="false" is ignored by safari.
Not to annoy you (if you are a mac user), I removed the audio player... If you know how to resolve this cross-browser issue, please kindly let me know.


-----------------------------

(For IE users) Super easy, just paste the following code into you Html, change src="whatever your music link", done.

<embed src="http://myblogtalk.com/uploads/billu.mp3" width="144" height="62" type="text/html; charset=UTF-8" autostart="false" loop="false" controls="console"></embed>

Blog Tricks, how to embed youtube in your post in 10 seconds?

It is super easy. On the top-right hand of youtube page, there is a textbox labeled "embed".
Just copy the content in the textbox, paste it into your Html. Done!

Saturday, May 9, 2009

Bridgewater Associates, Inc. interview Questions (software developer).

I recently had a phone interview with Bridgewater Associates, Inc.

They called me at 4:00pm. There are three interviewers. The interview includes 10 minutes on my previous projects, 20 minutes on standard interview questions, 20 minutes about the job position and their team. When asking questions, they like to ask a simple question first, then trace down to the detail untill your head began to spin. They will give hints and lead you to the answer ... then... you know what? they ask a harder aditional question.

The followings are some of the interview questions:
1. If I dip a 10x10x10 Rubik's Cube into red int, how many of the 1000 cells will have red faces.
2. a bad king has a cellar of 1000 bottles of delightful and very expensive wine. a neighbouring queen plots to kill the bad king and sends a servant to poison the wine. (un)fortunately the bad king's guards catch the servant after he has only poisoned one bottle. alas, the guards don't know which bottle but know that the poison is so strong that even if diluted 1,000,000 times it would still kill the king. furthermore, it takes one month to have an effect. the bad king decides he will get some of the prisoners in his vast dungeons to drink the wine. being a clever bad king he knows he needs to murder no more than 10 prisoners - believing he can fob off such a low death rate - and will still be able to drink the rest of the wine at his anniversary party in 5 weeks time.
3. additional question: to increase your chance of living, which prisoner would you want to be?
4. What's the difference between Java and C#?
5. additional question: Why C++ have multi inheritance but Java don't have?
6. What's the difference between interface and abstract methods?
7. additional question: In what conditions you prefer abstract methods instead of interface?
8. additional question: What can interface do but abstract methods can't?
9. Given two arrays A and B. Array A is sorted with n empty elements at the end; while array B has total n unsorted elements. How can you merge A and B into a sorted array.
10. additional question: What's the Big Os of Selection sort, insertion sort, bucket sort?
11. A linked list has a loop in it, how can you find it?
12. additional question: suppose the linked list is super long, how can you find it the loop quickly?
13. Explain left join in sql.
14. Additional question: What's the difference between left join, right join, inner join, outer join and full join?
14. Additional question: How can join effect the query performance?

Cool youtube videos

Reverse Engineer



Stanford CS107
Programming Paradigms (CS107) introduces several programming languages, including C, Assembly, C++, Concurrent Programming, Scheme, and Python. The class aims to teach students how to write code for each of these individual languages and to understand the programming paradigms behind these languages.





Fight Science


Diablo 2 End Cinematic


Starcraft II

Blog Tricks, How to toggle text in your post?

Show   Hide



---------------------------------------------------------------------------
I figured out how to toggle text using inline javascript. Here is the code:


<a href="javascript:var a = document.getElementById('Link1').style.display='block'">Show</a> &nbsp <a href="javascript:var b = document.getElementById('Link1').style.display='none'">Hide</a>

<div id="Link1" style="DISPLAY: none">
Here is the text you would like to show
</div>


Please kindly let me know if you have found other ways of doing this.

Tuesday, May 5, 2009

Windows multi-threading examples

Free Web Counter

Free Counter


These examples are based on the stanford CS107 lecture 15 - lecture 20.

youtube playlist


Since C++ multi-threading library is operation system dependent, the codes listed here are tested on Visual C++ 2008 Express Edition.

Windows Multithreading Helloworld
Several Agents are selling some amount of tickets in parallel, their access to the global parameter numTicketsp are synchronized by a Mutex.
-------------------------------
The following code is tested on Visual C++ 2008 Express Edition.
Show Code   Hide Code
--------------------------------


Simple Semaphor Example
A simple network server :
writer() grab data from network connection, then write characters to buffer, at the mean-time reader() constantly read character from the same buffer.
Two semaphors "emptyBuffer" and "fullBuffer" are used here to make sure reader() and writer() won't step onto each other.

-------------------------------
The following code is tested on Visual C++ 2008 Express Edition.
Show Code   Hide Code
--------------------------------



A little bit advanced Semaphor Example

Classic Five philosophers problem:
There are 5 philosophers who sit around a table. There is a folk between each neighboring philosopher. Each philosopher must grab two folks to be able to eat. Once a philosopher finished eating, he will put the forks back and waiting for the next chance to eat. The objective is to write a multi-threading program to simulate the situation.

The trick is -- suppose each philosopher is holding a folk at his/her left hand, and waiting for the philosopher at his right hand side to give up a fork. The philosopher at the right hand will not gonna to give up his fork, because he/she is also waiting for a fork from the right side...A dead-lock condition is thus created, nobody will be able to eat and they will be waiting forever.

To resolve the dead-lock, we only allow at most 4 philosophers to grab forks at any given moment, the rest philosophers have to wait.

The pseudocode is as follows:

Semaphore forks[]={1,1,1,1,1};
Semaphore numAllowedToEat(4);
void philosophor(int id)
{
for(int i=0; i<3; i++){
think();
SW(umAllowedToEat);
SW(forks[id]);
SW(forks[(id+1)%5]);
eat();
SS(forks[id]);
SS(forks[(id+1)%5]);
SS(numAllowedToEat);
}
-------------------------------
The following code is tested on Visual C++ 2008 Express Edition.
Show Code   Hide Code
--------------------------------

meta.ai impression

Meta.ai is released by meta yesterday, it is super fast you can generate image while typing! You can ask meta.ai to draw a cat with curvy fu...