Showing posts with label snippet. Show all posts
Showing posts with label snippet. Show all posts

Friday, 27 May 2011

AJAX and JSON

I recently had to develop a kind of "widget" that interrogates a remote server by means of an asynchronous javascript call. The response was a javascript object defined with JSON syntax. Question was: how do I process it? I found many tutorials that use JSONP techniques (weird yet powerful for cross-site execution) but I don't have control on the remote service. Others suggest an external framework (like jQuery) but I don't like it, I want my own wheel.

So, here come my snippets. First, you make your async call:


xmlhttp = window.XMLHttpRequest?
   new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = parse_function;
xmlhttp.open("GET", service_url );
xmlhttp.send(null);


Then, you handle the response (inside parse_function):


if ( xmlhttp.readyState == 4 && xmlhttp.status == 200) {
   json_data = eval( "(" + xmlhttp.responseText + ")" );
}


This way you get an object filled with usable stuff (json_data). Notice js' eval function and the brackets - those do the trick.

Saturday, 21 May 2011

CUDA, random numbers inside kernels

Evolutive algorithms have an intrinsic stochastic nature, therefore they make large use of random numbers generators, for instance the C/C++ rand() function. Anyway, when GPGPU comes into play, using random numbers could be tricky.

The naive solution of create and pour them into GPU's global memory is a bad idea, because of the huge bandwidth that would be wasted. Therefore, it takes a device-bound generator. Nvidia's CURAND library makes it easy to generate random numbers directly inside CUDA kernels.

A bit of theory...

Obviously, it is impossible to generate really random numbers on a deterministic machine. Any random function just applies some kind of transformation on another number, determining a succession that looks like a random one. Anyway, two successions starting from the same number (the seed) will be completely identical. If our kernels start from the same seed, regardless the algorithm, they will produce the same results. They must be different. Moreover, you have to store the previous numbers (let's call them global states) in order to produce the next ones during the following execution of each kernel. Fortunately, CUDA allows the storage and update of our partials directly inside GPU's memory.

...and some sample code
I post the example code - comments will follow.

__global__ void setup_kernel ( curandState * state, unsigned long seed )
{
    int id = threadIdx.x;
    curand_init ( seed, id, 0, &state[id] );
} 

__global__ void generate( curandState* globalState ) 
{
    int ind = threadIdx.x;
    curandState localState = globalState[ind];
    float RANDOM = curand_uniform( &localState );
    globalState[ind] = localState; 
}

int main( int argc, char** argv) 
{
    dim3 tpb(N,1,1);
    curandState* devStates;
    cudaMalloc ( &devStates, N*sizeof( curandState ) );
    
    // setup seeds
    setup_kernel <<< 1, tpb >>> ( devStates, time(NULL) );

    // generate random numbers
    generate <<< 1, tpb >>> ( devStates );

    return 0;
}


Obviously, you have to include not only CUDA's includes and libraries, but CURAND kernel's as well (curand_kernel.h). Let's see what happens in the code, starting from main.

First, we create a curandState pointer, that will point to our global states.

Kernel setup_kernel will invoke curand_init(), that takes some seeds (I used the seconds since the Epoch, but it's free to the user) and sets the global states.

Generate() kernel creates N threads. Each thread will have its own random floating point number, by using a local copy of its global state. In this case, the random number it's sampled from (0,1) with a uniform probability, but CURAND gives the possibility to sample from a standard normal distribution as well.

Finally, we store the new seed into the global memory, and return.

Monday, 28 June 2010

Aho-Corasick (multiple pattern match) in PHP

When I started programming Mergifier, my "RSS feeds dispenser", I knew I was going to need some kind of terms filtering. It's useless to take into account the most common words, for they don't bring any information.

My initial solution was to split the text into an array of substrings and use array_diff to remove those in my blacklist array. I don't know the asymptotic cost of array_diff algorythm, but using it with plenty of items (featuring long titles, summaries and descriptions) soon appeared a bit too expensive.

Recently I studied a lot of pattern matching algorythms, including the well known "Aho-Corasick" which checks occourrences of multiple patterns "at once" inside a text of length n in O(M+n), being M the total number of characters composing the patterns. Useful for virus signature detection and bioinformatics, I did not find its implementation anywhere, so I did my own!



Download the code



As you could see inside the code, this algorythm is cool because one can precalculate delta/phi transition tables and cache them, brutally speeding up computations on many different texts made of many terms.

If you find this code useful, or if you have any kind of suggestion to improve it, please let me know. :)

Tuesday, 27 April 2010

Just for fun: obfuscated hello world, in C

main(int argc,char*argv[]){memset(&argc,0,1);char*s[11]={0,-3,4,4,7,-40,15,7,10,4,-4};while(argc<11)printf("%c",s[argc++]+0x48);}

What could this code do? =)

The reason behind this code is here.

Monday, 18 January 2010

Deleting stuff with javascript

Would you like to clean house with js without messing around with hidden stuff? Piece of cake:

document.getElementById("thing_to_delete").parentNode.removeChild(document.getElementById("thing_to_delete"));

Yes, it's kinda weird, just like referring to myself as "the son of my father", but it actualy works.

Tuesday, 7 October 2008

One query, many records, one result


Sometimes you need to serialize the results of one simple db query. Instead of fetching any single row and appending it to a string, I thought it could be nice (and faster) to delegate the string creation to the database server.

I found out there's no explicit way to do it in MySQL, but I created a nice workaround using the group_concat clause:

SELECT GROUP_CONCAT (field)
FROM table
WHERE index IN (...)
GROUP BY null



Usually, group_concat is used to concatenate the results grouped as specified. Instead, I want to concatenate all the results. Passing null we achieve this result: everything is appended to a single record, and we can fetch a single comma separated string with a single query.

Keep in mind the possibility of issues with the size of the result.

Monday, 8 September 2008

"Cool and quiet" search box

It's cool (and a bit web2.0) to have a search box which works as soon as we cease typing, and displays new contents in the very page we're navigating.

The concept of "typing ceased" is tricky anyway; it's not cool (and not quiet!) to have the page refreshed soon after the onKeyUp event, because maybe we're still typing the whole word.

So, it takes a bit of javascripting:


function lookupStuff(flag) {
if (flag) {
do_things();
} else {
clearTimeout(timerid);
timerid = setTimeout("lookupStuff(true)", 1000);
}
}


If we bind this to the onKeyUp event of an text input form, we have do_things() called after 1 second, which is enough for typing anything; clearing the timer is useful for "jittered" key pressing.

This snippet has been tested successfully on every browser, and appears pretty usable.

Friday, 5 September 2008

Reinventing the wheel

Matrix multiplication is fundamental in computer graphics, expecially when you're dealing with shadow maps and texture projections.

Unfortunately, there are no standard functions for matrix multiplication, so it was time for DIY. Here comes my snippet:



float* matrixProduct(float* A, float* B) {

// we have to allocate space for a 4x4 floats matrix
float* pointer= (float *) calloc(sizeof(float), 16);

// in order to compute the resulting matrix, we have to use two nested fors
for (int r=0; r<4; r++) {
for (int c=0; c<4; c++) {

// actual multiplications
for (int i=0; i<4; i++) {
pointer[r*4+c] = pointer[r*4+c] + A[r*4+i]*B[c+i*4];
}
}
}

return
pointer;

}


This simple function returns a pointer to an handful 4x4 array of floats, without memory flaws. Maybe this snippet will be helpful for someone in the future.

Thursday, 1 March 2007

OpenAL hello world!


OpenAL are for audio what OpenGL are for video: a cross-platform, and open source, set of API useful for creating a realistic tridimensional audio environment.

Exactly like OpenGL, they're easy to learn and well documented. They don't handle MIDI yet, therefore I used them only to play samples, triggered by the numerical pad on the wrist of powerglove.

I quit using playsound() Windows primitive for it is too cheap: no multibuffering, no pitch control, no positioning... just playing. Instead, I wanna play several alien-related noise at a time, launch drum loops and so on.

So, let's see how to play something. First, you have to download OpenAL SDK, libraries and documentations from the official site. Once installed, link libraries to your project and put the headers in your code (al.h, alc.h, alut.h).

Then, simply:

alutInit(NULL, NULL);

to erase any pending AL process. Now, we have to open a sound device and, for any device, we must define a "context" to place the sounds in. We can make this by coding:

ALCdevice* device;
ALCcontext* context;
device = alcOpenDevice(NULL);
context = alcCreateContext(device, NULL);
alcMakeContextCurrent(context);
alGetError();

alGetError() returns AL_NO_ERROR if opening procedure went ok. If it happened, we have correctly initialized OpenAL. Done this, it's time to place a listener (imagine Doom - it's the spacemarine!); listener has 3 important features: a position, a velocity and an orientation. Every parameters help OpenAL to render sounds, as it happens in OpenGL environment. They're very similar as approach.

ALfloat ListenerPos[] = { 0.0, 0.0, 0.0 };
ALfloat ListenerVel[] = { 0.0, 0.0, 0.0 };
ALfloat ListenerOri[] = { 0.0, 0.0, -1.0, 0.0, 0.0, 0.0 };

alListenerfv(AL_POSITION, ListenerPos);
alListenerfv(AL_VELOCITY, ListenerVel);
alListenerfv(AL_ORIENTATION, ListenerOri);

Check out documentation for the meaning of every floating-point value. Now it's time to load a wave file in memory, decant it into a buffer to be used by OpenAL routines and launch it.

ALuint Buffer;

ALenum formato;
ALsizei dimensione;
ALvoid* dati;
ALsizei frequenza;
ALboolean loop;

alGenBuffers(1, &Buffer);
alutLoadWAVFile(percorso, &formato, &dati, &dimensione, &frequenza, &loop);
alBufferData(Buffer, formato, dati, dimensione, frequenza);
alutUnloadWAV(formato, dati, dimensione, frequenza);

It's very clear what happens: we generate a buffer, load the wave into the buffer catching informations, load the wave into the generated buffer, and unload wave from memory.

Finally, we have to bind the buffer to a source and play it:

/* generate source */
alGenSources(1, &Source);

/* place it */
ALfloat SourcePos[] = { 0.0, 0.0, 0.0 };
ALfloat SourceVel[] = { 0.0, 0.0, 0.0 };

/* options */
alSourcei (Source, AL_BUFFER, Buffer );
alSourcef (Source, AL_PITCH, 1.0f );
alSourcef (Source, AL_GAIN, 1.0f );
alSourcefv(Source, AL_POSITION, SourcePos);
alSourcefv(Source, AL_VELOCITY, SourceVel);
alSourcei (Source, AL_LOOPING,
loop);

/* riproduco sorgente */
alSourcePlay(Source);

You're done. It's really that simple. Amazing!