Calling Python from Java, a quick way to implement a rule engine

This is a robot that my son made with some parts I was using to assemble a crib.
It is amazing what you can build with small simple parts!

I have the following situation at work: One of our applications gets data from a proprietary data source and the rules on how to filter the data change very often; On top of that the traders are the ones who know what is the best criteria so hard-coding this rules into Java is tedious, error prone and takes more time than it should.

I’ve been using Jython for a while and I must say I’m in love with the project. I have the flexibility of a scripting language with the ability to use all the Java libraries and also our application classes, which is something that is priceless as the majority of the code is tested and I can reuse a lot of it.

So, what about calling Python from Java? It would be great it I can let the traders implement their own business rules (we will work together but they can prototype stuff faster that way). Also the traders I work with are very technical savvy 🙂

After checking the chapter ‘Jython and Java integration‘ from the Jython book I decided to experiment myself.

For the sake of the example, I want to have a simple Python class where I receive a Map and a String and print some values:

from com.kodegeek.blog.jython import HelperInt;

class Helper(HelperInt):

        def doSomething(self, data, name):

                if name == None:
                        raise Exception("Name is missing!")

                if data == None:
                        raise Exception("No data was provided!")

                print "Hello, my name is: %s" % name
                if data.containsKey('age'):
                        age = data.get('age')
                        if age > 21:
                                print "%s, you can also have a beer!" % name
                        else:
                                print "%s, it is time for your milshake :-)" % name

So far is good, but who is the class ‘HelperInt’? Is an interface and that will help us to glue our Python class into the Java world:

package com.kodegeek.blog.jython;

import java.util.Map;

public interface HelperInt {

        public void doSomething(Map data, String name);

}

Nothing weird so far, uh?. Now the most complicated part is to bring the Jython implementation back into the Java world. The book give us a really nice Singleton Factory class that I used as is (the code is below, but I strongly suggest you read the book explanation on how it works. It seems there are many ways to skin this cat):

package com.kodegeek.blog.jython;

import org.python.core.Py;
import org.python.core.PyObject;
import org.python.core.PySystemState;

/**
 * Jython Object Factory using PySystemState
 */
public class JythonObjectFactory {

 private final Class interfaceType;
 private final PyObject klass;

 // Constructor obtains a reference to the importer, module, and the class name
 public JythonObjectFactory(PySystemState state, Class interfaceType, String moduleName, String className) {
     this.interfaceType = interfaceType;
     PyObject importer = state.getBuiltins().__getitem__(Py.newString("__import__"));
     PyObject module = importer.__call__(Py.newString(moduleName));
     klass = module.__getattr__(className);
     System.err.println("module=" + module + ",class=" + klass);
 }

 // This constructor passes through to the other constructor
 public JythonObjectFactory(Class interfaceType, String moduleName, String className) {
     this(new PySystemState(), interfaceType, moduleName, className);
 }

 // All of the followng methods return
 // a coerced Jython object based upon the pieces of information
 // that were passed into the factory. The differences are
 // between them are the number of arguments that can be passed
 // in as arguents to the object.

 public Object createObject() {
     return klass.__call__().__tojava__(interfaceType);
 }


 public Object createObject(Object arg1) {
     return klass.__call__(Py.java2py(arg1)).__tojava__(interfaceType);
 }

 public Object createObject(Object arg1, Object arg2) {
     return klass.__call__(Py.java2py(arg1), Py.java2py(arg2)).__tojava__(interfaceType);
 }

 public Object createObject(Object arg1, Object arg2, Object arg3)
 {
     return klass.__call__(Py.java2py(arg1), Py.java2py(arg2),
         Py.java2py(arg3)).__tojava__(interfaceType);
 }

 public Object createObject(Object args[], String keywords[]) {
     PyObject convertedArgs[] = new PyObject[args.length];
     for (int i = 0; i < args.length; i++) {
         convertedArgs[i] = Py.java2py(args[i]);
     }

     return klass.__call__(convertedArgs, keywords).__tojava__(interfaceType);
 }

 public Object createObject(Object... args) {
     return createObject(args, Py.NoKeywords);
 }

The last piece of the puzzle is our application, which calls the factory and then the Python object from Java:

package com.kodegeek.blog.app;

import java.util.Map;
import java.util.HashMap;

import com.kodegeek.blog.jython.HelperInt;
import com.kodegeek.blog.jython.JythonObjectFactory;

public final class Caller {

        public static void main(final String [] args) throws Exception {

                JythonObjectFactory factory = new JythonObjectFactory(HelperInt.class, "JHelper", "Helper");
                HelperInt helper = (HelperInt) factory.createObject();
                Map data = new HashMap();
                data.put("age", 39);
                String name = "Jose Vicente";
                helper.doSomething(data, name);
        }

}

Time to compile and run the stuff. As usual, make sure you have Jython on the Classpath:

Macintosh:jython josevnz$ javac -classpath /users/Shared/jython2.5.2/jython.jar:. -d . *.java
Macintosh:jython josevnz$ 
Macintosh:jython josevnz$ java -classpath /users/Shared/jython2.5.2/jython.jar:. com.kodegeek.blog.app.Caller
*sys-package-mgr*: processing new jar, '/Library/Java/JavaVirtualMachines/1.7.0.jdk/Contents/Home/jre/lib/resources.jar'
*sys-package-mgr*: processing new jar, '/Library/Java/JavaVirtualMachines/1.7.0.jdk/Contents/Home/jre/lib/ext/zipfs.jar'
module=,class=
Hello, my name is: Jose Vicente
Jose Vicente, you can also have a beer!

Success!. Let’s see how far I can get with this on a real application 🙂

Nike+ SportWatch GPS: 1 year later, ready to go to the garbage can

Nike+ SportWatch GPS = No repair after 1 year of warranty
Good bye watch, one year is so little time for a gadget to last…

How I fell in love with my watch

I ran my first race with the Nike GPS watch on Aug 17, 2011 at 6:50 pm; It was a 3.1 mile run, at a pace of 8’43 / mile. It was nothing stellar yet I was excited because I was kicking the tires of my new watch with GPS and I had no need to use an IPhone or an Android to see how much farther away I ran (before that I was using my Nike+ Ipod nano).

Yes, I was so excited about the new watch, so simple to use, that I even played hacking my data from the NikeRunning website.

NikeSupport on tweeter
Nike support on Tweeter. Very slow, lack of answers

But today, almost one year later, my watch stopped talking with my computer. The software doesn’t recognize the watch anymore so I decided to contact Nike on tweeter first to figure out if the latest software upgrade on their Nike+ Connect software had a bug.

So I wrote and after waiting 3 hours with no further reply from their support I decided to give them a phone call (I actually used the callback service).

The called within a minute and asked me to try several options (restart your watch, re-install the software, reboot the machine, install on a different machine) and nothing worked. So looks like is a hardware problem and if I have the purchase receipt AND if the warranty is still under one year I can get a replacement, no questions asked.

So my watch is barely a year old and no receipt. Here are the bad news: Nike doesn’t re-furbish their watches, they don’t offer to repair it and there is no option to buy a new watch at discount. You have to buy a brand new watch, with a warranty of only one year.

While $160 won’t exactly break your bank account it also true that you expect a Nike watch to last more than a year; Now my data is trapped inside the watch with no way to recover it. To make things worst I also purchased the Polar Band to capture my heart beat while running, so that is another device that I cannot use now.

The aftermath

So the watch is busted. Looking through Google I found http://nikewatchrepair.com/. They charge you $12 just to receive your watch and later they tell you how much the full repair will cost, but before I asked them if they support my model and they never got back to me.

Repair is also not possible. Now I have a powerful watch that can capture heartbeats and distance using the GPS and yet cannot export the data.

So what went wrong here?

There is nothing wrong on Nike offering only one year of warranty for the watch, that seems to be the standard; Also it is my fault that I did not keep the receipt after the purchase which limits greatly my options.

But Nike dropped the ball here on the following:

  • No way to repair the watch, even if is out of warranty? Seriously Nike? Look how Garmin does it and learn!
  • Nike doesn’t care much about their users. I spoke with 2 different support people over the phone and also had a long (and fruitless) session over Twitter. I wasn’t expecting a free new watch but a discount while purchasing a new one or a way to repair it. Looks like Garmin love their users more

So what it is in the future for Nike+

I plan to buy a new watch to replace the damaged one … but it won’t be Nike. My experience with the quality of the watch and their support is negative. On top of that the fact than I cannot export the data from the NikeRunning website (effectively locking my data with the vendor) droves me even further away from purchasing any other Nike products in the future.

I know than Nike won’t notice this (I’m not expecting it either) and they won’t change their ways either. But if you are reading this and thinking about buying a GPS watch for your runs you may learn one or two things from this post. Specially about keeping the receipts or asking for the extended warranty if any.

UPDATE:

At the end Nike gave me a replacement watch after my story got published in the website ‘the consumerist‘. While it is a nice gesture from then it still doesn’t cover the issue of no repair for existing watches, even with a third party provider.

UAE Healthy Kidney 10K

UAE Healthy Kidney 10KMi mejor 10K hasta la fecha: 49:15, lo cual me pone en el 57.2% de los corredores de mi edad.

Otra carrera más a beneficio de las personas con problemas renales, esta vez un 10K en Central Park. Este fué difícil ya que esta vez hicimos el recorrido completo al parque, el cual incluye unas subidas y bajadas difíciles.

Sin embargo con tenacidad, y aguantando un dolor en el costado en los últimos 200 metros, logré hacer mi mejor 10K hasta la fecha, sin embargo aún no logró entrar en el 60% lo cual es mi meta inmediata.

¿Como logré bajar los tiempos? Bueno, además de hacer mis carreras largas ahora estoy haciendo también intervalos de 3 millas (3 veces correr una milla con descanso de 400 metros o 2 minutos) al menos una vez a la semana.

Ya vienen más carreras en el mes de Junio, 2 en concreto, las cuales me acercan más y más a y meta del maratón de Nueva York del 2013.

¡A seguir empujando!

De voluntario en ‘Run as One’

Yup, I earned my T-shirt :-D
Hoy hice el voluntariado (9+1) para el Maratón de Nueva York

Hoy hice el voluntariado, parte de lo que se llama el 9 + 1 del club NYRR para tener entrada garantizada en el maratón de Nueva York del 2013.

Wearing my best and about to take my place on the race.
¡Listo para ir a mi puesto!

Muy organizado todo, pero hubo pocos voluntarios. Con todo y eso todo marcho sobre ruedas.

Les dejo el conjunto de fotos completa para que las disfruten. Si lo desean se pueden poner en contacto conmigo para saber como funciona la parte del voluntariado. También para aquellos que quieran prepararse para un maratón como el de Nueva York, les recomiendo esta guía de entrenamiento.

–José

Terminado el entrenamiento para un medio maraton, con Hal Higdon

Colon Cancer last push

Parte del entrenamiento consistió en una carrera. En este caso yo hice 9.1 millas (Colon Cancer Challenge) en 1:12:47, http://web2.nyrrc.org/cgi-bin/htmlos.cgi/4430.1.4176275331617241034

La semana pasada terminé mi entrenamiento para un medio maratón (13.1 millas), usando el paquete para novicios de Hal Higdon. Debo decir que el programa funciona muy bien, no tengo lesiones y mi desempeño en distancias largas ha mejorado, hasta el punto de poder mantener 7’52” / milla de manera constante, lo cual me da esperanzas de poder terminar una carrera de medio maratón en menos de 1:47:52 el cual es el tiempo no oficial de mi primera carrera.

DTag on Vibram
Hasta ahora los Vibram me han servido bien. Ese fué el otro cambio que incluí en mi entrenamiento

Me decidí a bajar la aplicación del sitio de Apple.com y seguí el programa combinándolo con ejercicio de resistencia los días en los cuales correr no era obligatorio. En un principio pensé que iba a ser demasiado pero al la final pude manejar la carga, sin ningún efecto colateral.

First Half Marathon!
Mi ritmo fué consistente. La aplicación también fué consistente, yo comparé los números con el sitio nikerunning.com y los tiempos y distancias fueron muy cercanos. Tengo dudas de quien es más preciso (yo medí los resultados de Nike usando el Nike watch + GPS).

Mi única crítica no tienen que ver con el programa sino con la aplicación misma. Tiene un par de cucarachas las cuales si bien no son severas hacen que la aplicación no esté a la par de NikeRunning.com por ejemplo.

Ahora ya tengo un plan concreto para atacar el próximo medio maratón; Por ahora pienso ponerle empeño para mejorar mi velocidad usando ‘Speed workouts’, ‘hills’ y por supuesto la famosa carrera larga de los fines de semana (10 millas).

Finally done with the Half Marathon program.
¿Y ahora que viene?

Lo que viene: Me estoy preparando para mejorar mis tiempos en 5K y para hacer un medio maratón en un tiempo decente. Las cosas que vienen:

  • JP Morgan Corporate Challenge: Esta me tiene muy emocionado, ya que son apenas 3.5 millas en Central Park en la cual van a correr muchos de mis amigos, de varias compañias. ¿Quien dijo miedo? 🙂
  • ING Hartford Half Marathon:Esta carrera se ve mundial y para ese entonces debo estar super listo para rendir al máximo

Aún no tengo listas mis 9 carreras + voluntariado para el Maratón de Nueva York en el 2013; Sin embargo queda tiempo y me toca ponerle empeño 😉

Mi primer 10K: Joe Kleinerman 10K

Before the race
Mi primer 10K, no estuvo nada mal

Hoy corrí mi primer 10K; Decidí probar una estrategia dado que la distancia a batir es el doble de lo que yo estoy acostumbrado a correr; Comencé lento las 2 primeras millas, un poco más rápido las 2 siguiente y las 2 últimas con todo.

Central Park 6.2 mile loop
Recorrido alrededor de Central Park, 6.2 millas

Sin contar con una ida obligatoria al baño en la cual gaste por lo menos 40 segundos (el baño estaba ocupado) creo que salió bien 🙂

Los resultados oficiales:

Last Name

First Name

Sex/
Age

Bib

Team

City

State

Country

Overall
Place
Gender
Place
Age
Place
Net
Time
Pace/
Mile
AG
Time
AG
Gender
Place

AG %

Nunez Zuleta Jose V M38 5735 0 DARIEN CT USA 2416 1701 316 0:55:05 08:54 0:52:51 1843 50.82
 Resultados oficiales

Esta es una de las carreras del 9+1 para tener una entrada garantizada el maratón de NYC, sólo me faltan 8 más 🙂

First Night Danbury 5K, adiós al 2011, ¿que viene para el 2012?

After the race
¡Vestido para la ocasión!. corrí esta última carrera del 2011, con la mejor compañía posible: Mi Esposa Verónica y mi hijo Sebastian

¡Feliz año nuevo 2012! Con estas palabras arranco un nuevo año en este blog; Comienzo escribiendo sobre la última carrera del 2011, un 5K en Danbury, CT que hice el 31 de Diciembre a las 3:00 P.M: First Night Danbury.


¡La última carrera del 2011 comienza!

La carrera fué sencilla, sin grandes pretensiones. Con niños, ancianos, gente de todas las edades corriendo y disfrutando el momento. Por ser Danbury una comunidad pequeña, pude apreciar como sus miembros se conocen y se aprecian, más de uno felicitaba a los otros (con nombre y apellido) mientras corrían.

Jose llegando a la meta
No fué mi mejor carrera, comencé muy rápido y al final no pude hacer un ‘negative split’. Mala estrategia

No fué mi mejor carrera (aunque no fué la peor). Dos días atrás me lancé con un entrenamiento fuerte de piernas (no estaba completamente recuperado), pero lo que realmente me mató fué que comencé la primera milla muy rápido.

Es una clara indicación de lo mucho que todavía tengo por aprender:

La meta este año es hacer el 9 + 1 para correr en el Maratón de Nueva York en el 2013; Esto implica que deberé correr carreras de distancias más larga como 10K y medio maratones si quiero cumplir los requerimientos.

En pocas palabras, el año pasado fué bueno como introducción pero este año va a marcar la diferencia en cuanto al entrenamiento y fuerza de voluntad; Abajo los números que debo mejorar este año 2012 con respecto al 2011:

  • 165 salidas a correr (incluyendo carreras)
  • 310 millas recorridas
  • Velocidad promedio: 09’15” millas por minuto
  • Calorías quemadas: 36598
  • Tiempo total corriendo: 47:46:34
  • Distancia más larga recorrida: 8.06 millas
  • Milla más rápida: 6’08” minutos / milla
  • 5K más rápido: 22’01” minutos / milla
  • 10K más rápido: 54’15” minutos / milla

Como pueden ver queda mucho por hacer. Pero logré correr sin interrupciones desde Mayo hasta Diciembre (8 meses), así que ahora sólo tengo que ser constante con el entrenamiento y aspirar metas más complicadas.

Asi que, ¡Nos vemos pisando el asfalto este 2012!

–José

Clases de velocidad con NYRR

Same guy after running 5 miles at a pace of 8'10 at Central Park in 40 minutes. Yeah, it was worth it!
Las clases siempre se llevan a cabo, no importa las condiciones del tiempo (5 millas a un ritmo de 8’10 en Central Park en 40 minutos, con fuerte lluvia)

Me inscribí en las clases de velocidad del grupo NYRR en la ciudad de Nueva York; la idea es que con cierto tipo de rutinas al correr y consejos sobre la forma de correr se puede mejorar los tiempos en una carrera, todo eso en Central Park con todas las ventajas que esto ofrece.

Para entrar, sólo hace falta saber la velocidad (pace) de la última carrera de 5 kilómetros ya que te ponen a correr con gente de tu misma velocidad por una hora; Si eres muy rápido o muy lento entonces te obligan a cambiarte de grupo para asegurarse que el entrenamiento de cada banda no se vea afectado. Yo al final terminé en el nivel ‘competitivo, #6’

¿Y funciona el entrenamiento? Bueno, en menos de 10 semanas (yo tomé el curso de una clase por semana) no sólo logre reducir mis mejores tiempos en casi dos minutos, sino que además ahora puedo correr a una velocidad constante por 6 millas, antes simplemente comenzaba rápido para luego terminar muerto en las últimas 2 millas.

El precio me parece bueno por la calidad de las clases, lo preparado de los instructores y sobre todo porque los resultados si se aprecian en corto plazo. Además de eso, conocí mucha gente amigable y el espíritu de sana competencia del grupo hizo que la experiencia fuera muy agradable ya que todo el mundo estaba haciendo un esfuerzo (mi grupo era muy variado entre edades y mezcla de mujeres y hombres).

Estoy seguro que lo repetiré el año que viene en preparación a las nuevas carreras.

Euforia antes del maratón de NYC, ‘Dash to the Finish Line’

BIB3215
Escribo estas lineas antes de que mi memoria me falle y olvide detalles importantes.

Hoy fué un día super especial; Tuve la oportunidad de correr la primera carrera de 5 kilómetros del club NYRR (‘Dashto the Finish Line’), un día antes del famoso maratón de la ciudad de Nueva York. Lo mejor fué que lo hice con mis amigos, uno de ellos el cual estaba celebrando su cumpleaños justo el día de hoy mientras que el otro corría su primera carrera.

"NYRR Dash to the Finish line - Map
¿Como fué el recorrido de esta carrera?

Todo esto compartiendo con mi familia, ¿qué más se puede pedir?

El tramo inicial de la carrera, cerca del edificio de las naciones unidas y luego pasando al frente de la estación de trenes de Grand Central, fué lento y tortuoso; con todo y que mi posición inicial no era de las últimas me tocó maniobrar mucho para esquivar a los corredores lentos en la primera milla. Sin embargo en la segunda milla, subiendo por la sexta avenida, paralela a Times Square, comencé a moverme más rápido e hice el mejor tramo de la carrera.

Lo que más me llamó la atención de la segunda milla fué la ausencia de ruido de los espectadores; en vez de eso, el único sonido que se escuchaba era las pisadas constante de los corredores, muchos tratando de mantener el paso, otros acelerando la marcha.

Al llegar a Central Park, comenzó el último pedazo rumbo a la milla # 3. El terreno se hizo mas irregular con algunas pendientes suaves y curvas en el camino, además de que habia algunos corredores ¡viniendo en sentido contrario por donde corríamos nosotros!. El cansancio comenzó a hacerse latente pero al mirar el reloj pude ver que venia haciendo buen tiempo, al menos para mis capacidades.

Junto a la bandera de Venezuela
Junto a la bandera de Venezuela, después de darme cuenta que allí estaba

Los letreros del marcaje de las millas comenzaron a aparecer más seguido: 3 millas, 800 metros, 400 metros. Al llegar al letrero de los 200 metros ni me fijé en la bandera de Venezuela que allí estaba. Sólo seguía empujando.

No pude correr más rápido al final pero si logré mantener un buen paso, para así obtener una pequeña victoria personal de 23 minutos con 36 segundos. Mis sueños de hacer 20 minutos vendrán en otra carrera:


Race Name, Date
Finisher
Name
Gender/
Age
Gun
Time
Net
Time
Pace/
Mile
Overall
Place
Gender
Place
Age
Place
Age-
Graded %
NYRR Dash to the Finish Line (5K)
November 5, 2011
Nunez, Jose V M38 03.1 0:23:36 07:37 578 459 90 56.99

Una vez llegado a la meta comenzó la tarea de buscar a la familia y de esperar por mis amigos, los cuales tuvieron una muy buena carrera también (sin lugar a duda vamos a repetir la aventura, así que tomen nota :-))

Venezuela representada en el 5K
Venezuela representada en el 5K

Muchos Venezolanos en la carrera; Momentos muy amenos con la familia y amigos, sobre todo con el inmenso apoyo de estos. ¡No veo la hora de que repitamos esta experiencia!

¿Que viene para el futuro? No estoy seguro, pero les dejo una pista de lo que en algún momento me propongo a lograr:

Milla 26
¿Algún día no muy lejano?