Share on TwitterDigg This

Coming from a Java background, javascript syntax is not really friendly sometimes.

For instance I was creating some animations with SVG and using the very common setInterval function. This function is determined as:

setInterval ( expression, interval );
so I had this object I've created : Scene, which had a draw method. I think you can figure out the picture now.
So I ran this piece of code:

setTimeout(scene.draw,20);
 
self.draw = function(f) { .... }

The idea of the draw function was to have the current frame to be passed as an argument.
If none is defined, it then uses an internal memory to render the scene.
On Chrome that works fine, but it turns that when you call the setinterval with that syntax on firefox, it also passes as the first argument some sort of elapsed time to the called function.

Now, my function went crazy since it got some really high values being used as the f argument.

To fix it, use:

setTimeout("scene.draw()",20);

That does the trick for both Chrome/Safari and Firefox

Strange things from a strange language.

Share on TwitterDigg This




Gosh it has been a long time. From the last time I wrote something I’ve moved from Brazil to Ireland and I now work at LMI Ericsson Athlone. I’m still a java Engineer, but lately I’m having lots of fun in my spare time with Javascript, JQuery, HTML5 and other languages. After all, Oracle acquired Sun, and I belive it is time to move on …

So, I’m facing some visualization challenges at work, which made me find Raphael which is the best SVG library I could ever find.

After lots of fun, the docs are really easy to understand, I’ve started a few projects of my own. So for the introduction of Raphael, I wanna show a really useful function I’ve created.

The idea is to draw any regular polygon with it. Raphael uses the SVG Path notation, which gives lots of flexibility, but for a normal human being would be hard to code.

Remembering my trigonometry lessons from high school, I recall that one of my math teachers used to draw perfect shapes using a choke attached to a string. After creating a circle he would put points on it and connect through lines, and voilá, perfect triangles, hexagons, octagons and etc…

And that was the inspiration for my function :) . Given that I have a center (x,y), a radius, and the number of points, I could find any of the points, and them reconnect them using Raphael simple path function.

The path function takes a SVG path string. Looking like this:

“M x y  L a b”

This basically says: Move to x,y and draw a line to a,b. Simple huh?

Now, our function to draw the polygon relies on a simple triangle principle to find the a,b points for every single point entered:

a = x + (radius * cos(angle))

b = y + (radius * sin(angle));

All we have to do is vary the angle according to the number of faces, so angle would be:

angle = startAngle + (i * (1 / faces) * 2 * Math.PI);

So, if we start at angle 0 for a triangle (3 faces) we would create points at 0,120,360. You’ll see that to rotate the triangle with this function all you have to do is change the start angle of it.

This function takes a data argument that has:
data.x: X center of your circle
data.y: Y center of your circle
data.r: radius of circle
data.n: number of faces of the polygon
data.s: start angle

It also relies on 2 global vars:
points: Array
paper: Raphael instance

 function shape(data) {
 
            for (var i = 0; i < data.n; i++) {
                var point = new Object;
                var angle = data.s + (i * (1 / data.n) * 2 * Math.PI);
                point.x = Math.round(data.x + (data.r * Math.cos(angle)));
                point.y = Math.round(data.y + (data.r * Math.sin(angle)));
                points.push(point);
            }
            var strp = "M" + points[0].x + " " + points[0].y;
            for (var i = 1; i < data.n; i++) {
                strp += "L" + points[i].x + " " + points[i].y;
            }
            strp += "L" + points[0].x + " " + points[0].y;
            var comb = paper.path(strp).attr({fill:"rgb(255,255,193)"});
            comb.mouseover(function(event){
                this.attr({fill:"rgb(255,128,64)"});
            });
            comb.mouseout(function(event){
                this.animate({fill:"rgb(255,255,193)"},500);
            });
 
            points = new Array();
        }

You can play around with the function with the code bellow, just provide x,y,r, and faces to draw your shape. Mark draw inner circle if you want to see the shape inside the original circle.

Have fun:

x: y: radius:
faces: draw inner circle:
Share on TwitterDigg This

In my first english blog entry, I could not find a more appropriate topic. I’m still looking for a way to provide both Portuguese and English content on this blog.

Meanwhile, english readers can check my blog entries using the google translate. Google’s Language API is the reason of this post.

Lucene, is probably one of my favorites frameworks of all times, and I love everything related to it: Hadoop, Nutch, Solr and Hibernate Search.

I use Lucene whenever I can :) And one of the things we did within it was a Federated Search for JBoss Portal. We indexed all kind of documents uploaded to the CMS portal using interceptors. One of the problems we faced, was automatic language detection. Because Lucene needs an analyzer to proper index the document, we needed a specific analyzer for each language. Well, at the time we miserably failed on that. It was a restriction we did not gave much attention since we were only indexing portuguese documents.

This week started with this restriction on my mind. At first I thought that I could find an open source api for this. Only found a few desktop apps, all closed source.

What if I use some kind of classifier, for instance a Naive-Bayes classifier, to classify my documents? I could download a few hundred of documents from wikipedia, all from different languages, train it, and then use it. Wow! That seemed cool, but would require some effort (and I’m feeling lazy this week).

So I was checking GWT extensions (because GWT is the coolest thing ever happened to the presentation layer), and I found the translation API , which BTW have an method to detect the language. Now my problems are really solved. The API relies on REST and JSON which makes it really simple to use. I started to use it by extracting random pieces of text from the documents and asking google to classify it. I’ve used this approach to avoid hitting some quotes or an abstract in a paper, which could led to a wrong idiom detection. Once we have the correct language we can instantiate the appropriate Analyzer.

The code bellow uses JSONSimple to parse the JSON response from google.

try {
	String s = URLEncoder.encode("Há tantos burros mandando em homens de inteligência, que, às vezes, fico pensando que a burrice é uma Ciência", "UTF-8");
	URL url = new URL("http://ajax.googleapis.com/ajax/services/language/detect?v=1.0&q="+s);
	 BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        String str;
        StringBuilder  buffer = new StringBuilder();
        while ((str = in.readLine()) != null) {
            buffer.append(str);
        }
        in.close();
        JSONObject obj = (JSONObject) ((JSONObject)JSONValue.parse(buffer.toString())).get("responseData");
        System.out.println(obj.get("language"));
        System.out.println(obj.get("confidence"));
 
 
} catch (UnsupportedEncodingException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
} catch (MalformedURLException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
} catch (IOException e) {
	// TODO Auto-generated catch block
		e.printStackTrace();
	}
}

The API not only provides the correct language, but also a confidence value.

Happy coding, and hope you enjoy this API as much as I did :)