• Menu 1
  • Menu 2
  • Menu 3
  • Menu 4

Gravatar


Soy César Olea, programador desktop, Web y de sistemas embebidos. Originario de Ciudad Obregón, Sonora, México.

Actualmente he terminado mi maestría en Ciencias de la Computación y me dedico dar mantenimiento, administrar y programar el sitio aVeralCine.com, escribir en Geek&Roll, el Web-comic geeksofacto y distintos proyectos de programación. Mi trabajo oficial (o sea, el que paga las cuentas) es en Tiempo Development como Senior Software Engineer. Si eres un buen programador, hablas Inglés y te interesa trabajar en una empresa con excelente ambiente laboral y projectos interesantes, estamos buscando gente como tu.

Para contactarme puedes enviarme un mensaje si estoy conectado a gTalk.

Geek&Roll es el blog donde escribo sobre programación, cracking, cultura geek, Software Libre, Internet, y más. En conjunto con Axel y Rafyta mantenemos un blog de contenido (casi todo) original.

Últimas entradas

Estamos de vuelta!
Por: Cesar

Debido a que ocurrió un overflow cuando intentamos pagar el dominio, GoDaddy no permitió el acceso a este blog por medio de nuestro dominio. Los detalles no los se, solo que el BigInt que utilizan para guardar la cantidad del pago no alcanzó, y por tanto el overflow, causando todo tipo de problemas.

Gracias por su paciencia. Estamos de vuelta, keep on Geek&Rolling!

Cuidado con cambiar de BlackBerry en Telcel
Por: Cesar

Hace poco decidí cambiar de modelo de BlackBerry, de la viejita 8110 a la un poquito más moderna 8520. Al ir a Telcel me dijeron que con mi plan era imposible cambiar al equipo que yo quería, aún cuando quisiera pagar el costo total del mismo.

Como en Telcel me la hicieron difícil, compré el equipo aparte y le cambié el chip. Hasta ahí todo bien, sin embargo al llegar la factura veo que me cobran la conexión de datos, aún cuando mi plan incluye datos ilimitados. En la factura me cobran el plan (con datos ilimitados incluidos) más los datos consumidos. Obviamente algo andaba mal. Después de dos visitas al centro de “atención” al cliente – que de atención no tiene nada – no me pudieron resolver mi problema. Las dos personas que me atendieron coincidían en que “que raro!?!?” y levantaron un reporte.

Gracias a que tengo a una persona conocida que trabaja en el corporativo, después de unos cuantos SMS’s el problema quedó aclarado y resuelto. Bueno, resuelto a medias porque voy a tener que pagar el cargo excesivo.

El problema, y lo que nunca me pudieron explicar en el centro de pseudo-atención, fue que al cambiar de equipo si tienes un plan de datos ilimitados, esto no se te respeta. En ningún lugar te lo indican, tampoco te lo advierten en Telcel. Y lo que es peor, nunca me lo superion resolver. Tuve que usar “palancas” del corporativo para que me resolvieran, ya que los asesores del centro de atención se limitaron a rascarse la cabeza. Nunca me preguntaron ¿No cambió su equipo señor?

Así que si tienen una BlackBerry y deciden cambiar de equipo, antes de meter su chip en el equipo nuevo, vayan a su centro de atención y pidan que les hagan el cambio para evitar cargos excesivos. Esta información la deberían de proporcionar de primera mano en Telcel, pero como siempre con prácticas poco éticas para sacar hasta el último centavo.

No iba a proporcionar información, pero por el coraje que me hicieron pasar les muestro una captura de pantalla de lo que será Everlasting Flame 2.0. Descárguenlo y eviten pagarle más de la cuenta a Telcel.

ELF2

El PS3 ha sido hackeado
Por: Cesar

Finalmente lo inevitable sucedió. George Hotz ha superado las barreras impuestas por el hypervisor del PS3, teniendo acceso total a la memoria del sistema y al CPU. Este es el anuncio oficial:

I have read/write access to the entire system memory, and HV level access to the processor. In other words, I have hacked the PS3.

Lo que sigue es esperar a la implementación de un exploit y ver cómo se desarrolla la comunidad del homebrew alrededor de esta consola.

Tiempo total de hackeo: 5 semanas. Can’t wait.

Crackeando el PS3: El estado actual
Por: Cesar

El PS3. Esta consola de séptima generación, y el tercer miembro de la familia PlayStation. Desde su lanzamiento en Noviembre del 2006 muchos crackers se han dado a la tarea de romper las barreras impuestas por el hypervisor y abrir la posibilidad de ejecutar código de terceros en esta máquina.

Primero que nada, ¿Qué es un Hypervisor? Según la Wikipedia, es un monitor de hardware o software que permite la ejecución de varios sistemas operativos en el mismo hardware. Existen dos tipos: Tipo 1 o nativo son los que corren directamente en el hardware. Tipo 2 son los que corren como cualquier otra aplicación del sistema operativo (como VirtualBox o VMWare)

Una visita a los foros de PS3-Scene revela poca actividad alrededor de la escena del PS3. Hace ya lo que parecen siglos Paradox, uno de los grupos más respetados en el mundo del cracking, anunciaba que tenía un iso loader listo para el PS3. Algo así como el santo grial, que nunca llegó.

Después vino IronPeter, un hacker de Rusia que logró tener acceso a algunos de los registros del RSX (la tarjeta de video del PS3) y con eso permitir la aceleración 2D para aplicaciones que se ejecutan desde OtherOS (GNU/Linux), lo que en teoría significa poder tener juegos y otras aplicaciones como Boxee o XBMC corriendo en el PS3 bajo GNU/Linux. La discusión técnica se encuentra en los foros de PS2Dev. Desgraciadamente la manera para aprovecharse de este bug es por medio de OtherOS, es decir la capacidad que tenían modelos anteriores de ejecutar otro sistema operativo. Hablo en pasado ya que el nuevo PS3 Slim ha eliminado el soporte para OtherOS, cosa que no me sorprende en lo absoluto.

A la fecha no se ha abierto el PS3 al homebrew. Es el turno de Geohot (a.k.a. George Hotz, master del iPhone) de probar suerte. Ya ha creado un blog “On the PlayStation 3” al igual que sucedió con el ahora famoso “Finding JTAG on the iPhone”. Pura lectura técnica y altamente interesante. Si la escena va a reportar adelantos próximamente, este es el lugar para estar atento.

Desde el Blackberry 8520
Por: Axel

Recién bajé la aplicación de Wordpress para Blackberry y de inmediato quise probar la publicación. Es bastánte cómoda.

Lo que me parece es que si subo una foto me va a poner el tamaño por default y ya. Veamos qué sucede.

Saludos a los visitantes de este blog fantasma :)

Update: en efecto, la foto se subió un poco más grande de lo debido (640px wide), la acabo de reducir desde la PC.

Feliz Navidad
Por: Axel

Desde los headquarters (we wish) de Geek & Roll les deseamos una feliz navidad a todos nuestros comentaristas, lurkers, trolls y visitantes ocasionales. Va un abrazo.

URL’s Pípiris Nais sin Wordpress
Por: Rafyta

Si te da hueva instalar tooooodo el wordpress nomás para evitarte las extensiones .php (o las de tu religión elegida), o de plano no lo necesitas, no te pierdas de ésta fíchur. Suponiendo que vivas en el maravilloso mundo de Apache, puedes arrojar este archivito .htaccess para que te haga el paro instantáneamismamente de quitar las extensiones .php de todos tus archivos, ok ok, en realidad los redirecciona pero es la misma, no?

descargar

Si lo que quieres es ahorrarte los horrores de ?var=value&this=siht&foo=barrio y esas cosas del diablo que no le gustan a Google y sus compas, también se puede; sólo tienes que editar unas líneas del archivo para alcanzar la felicidad instantánea. El archivo está así por default:

Options +FollowSymLinks
Options +Indexes
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d

# RewriteRule ^folder/(.*)/$ /file.php?image=$1
# RewriteRule ^kind$ /category.php?cat=kind

RewriteRule ^([^\.]+)$ $1.php [NC,L]

Las dos líneas que empiezan con el gato (#) son las que pueden habilitar esa onda, por ejemplo en el primer caso, puedes tener el url original:

http://sitio.com/fotos.php?src=verano.jpg&w=300&h=200&zc=1

y con unos cambios hacerlo así: http://sitio.com/fotos/verano especialmente útil si usas TimThumb o algo así.

El segundo caso considera el ejemplo una tienda en línea, o cualquier tipo de sitio que use una base de datos para clasificar varios elementos (o records) en categorías y haga una lista. Por ejemplo, puedes tener: http://mitiendita.com/articulos.php?tipo=jeans
y pasar a: http://mitiendita.com/jeans.

Hay más cosas que se pueden hacer con éste simple código, pero éstas son las más frecuentes. Si se te ocurre alguna otra posibilidad, déjala en los comentarios.

Instalación:

  • Descomprime el .zip
  • Edita el .htaccess si es necesario (con notepad o cualquier editor de texto)
  • Sube el .htaccess al web root de tu sitio

Busca en google desde la barra de direcciones de Firefox
Por: Axel

Si alguna vez has usado Google Chrome y lo dejaste para volver a firefox, probablemente tengas el mismo problema que yo tuve: extrañas hacer búsquedas en Google directamente desde la barra de dirección.

De hecho, Firefox hace *casi* lo mismo, sólo que en lugar de llevarte a los resultados de búsqueda este te lleva directamente al primer resultado, o al “I’m feeling lucky”, lo que es mucho menos útil, porque seamos sinceros: una cosa es que te sientas suertudo y otra cosa muy distinta es que encuentres lo que buscas a la primera. Pero bueno, esto es muy sencillo de cambiar:

  1. Escribe about:config en la barra de direcciones de Firefox. Esto te lleva a la configuración.
  2. Firefox te advierte que estás a punto de violar tu garantía. Siéntete h4×0r y dale aceptar.
  3. En el campo “filtro” escribe “keyworld.url”. No, asi no, sin las comillas. Ándale, asi.
  4. Dale doble click a la única línea que quedó, y en el campo de texto que aparece, sustituye el valor por “http://www.google.com/search?btnG=Google+Search&q=”
  5. Presiona “Aceptar”.

Listo, ahora puedes buscar desde la barra de direcciones de firefox. Y ya puedes quitar la barra de búsqueda que está a la derecha.

De nada.

iPod – iTunes en Windows
Por: Cesar

Foobar2000 main window
iTunes me desespera, nunca he sido fan del programa. Para mi gusto es un programa demasiado restrictivo en cuanto a manejar un iPod se refiere. Supongo que lo hacen así para evitar la piratería, trabajar con DRMs y darle gusto a masoquistas. Cuando quiero reproducir música en Windows, mi gallo es Foobar2000.

Para el que no lo conozca, Foobar2000 es un reproductor minimalista creado por un ex-desarrollador de Nullsoft (los de Winamp). Foobar2000 tiene un SDK para que terceros puedan crear plugins y extender sus capacidades con cosas como visualizador de portadas, espectogramas, convertidores, entre otras cosas. Si buscas un reproductor ligero en recursos con una interfaz minimalista y altamente configurable, definitivamente tienes que probarlo.

Ahora bien, a lo que nos concierne. Además de no gustarme, iTunes es un tabú en la oficina así que mi iPod nano de nosequegeneración no sirve de mucho. No solo eso, sino que aún con iTunes, este se niega a reproducir la música guardada en el iPod. No se a ciencia cierta, pero sospecho que es elitismo de parte de iTunes porque todos los mp3 que tengo fueron puestos ahí por gtkpod. ¿Será que a iTunes no le agrada gtkpod?

Foobar2000 al rescate. Gracias a su SDK, alguien se dio a la tarea de crear un plugin para administrar iPods lo que le permite a Foobar2000 reproducir la música contenida sin preocuparte por borrarla accidentalmente al sincronizarse y, lo que es más importante, sin elitismos. Foobar2000 con el iPod manager plugin reproduce toda mi música, los mismos archivos que iTunes no pudo, sin importar su procedencia.

Lo mejor de todo: la instalación. Descomprime Foobar2000 en cualquier folder. Después descomprime el plugin iPod manager en el folder de components dentro del folder principal de Foobar2000. En Foobar2000 ve a File | iPod | Load library y el resto espero no tener que explicarlo.

iPod – iTunes en Windows = Bliss

Otro Mundo Nos Vigila
Por: Boynas

Que titulo tan mas pendejo y tan mas viejo. Pero bueno, se trata de que un buen amigo me paso este enlace esta mañana. No pude dejar de interesarme ya que me encantan las teorías de conspiración y más cuando se tratan del gobierno cargándonos la mano! Yeah!

Bueno, para resumir, el enlace habla de que estamos en contacto con vida extraterrestre, al menos de una manera oficial. “The Telegraph” (ni me pregunten quienes son) publico que una entidad gubernamental búlgara (me imagino que científica) oficialmente acepto que estamos en contacto con ETs.

Otro enlace, dice que este es el plan maestro del gobierno gringo, y que Obama, cuando le entreguen su premio nobel de la paz en Oslo el próximo 10 de diciembre, tiene preparado un discurso donde dará la noticia mundial de que queremos lazos con los ETs y que exhortara a todas las naciones a desarmarse para crear un ambiente de paz global. Esto con el fin ultimo de, si, adivinaron, crear un gobierno global y único. Claro seremos cochis con etiquetas en un socialismo asqueroso.

Todo esto como lectura esta al chingazo, y la verdad tengo curiosidad por que sea 10 de diciembre y saber si Obama realmente hablara de esto. Claro que seria emocionante vivir el tiempo en el que la civilización humana de un cambio colectivo global. Porque no hay metas claramente establecidas. Si, tenemos el fenómeno del niño y el fenómeno invernadero y las iniciativas “green” que nos traen las “macs”… ¿Pero realmente a donde llegamos con eso? A ninguna parte. La humanidad sigue de cabeza y sigue habiendo muchas cosas descompuestas.

A lo que voy es a que seria bonito tener una esperanza de que este pedo se va a arreglar y de que algún día llegué un cometa que nos obligue a mandar a una flota de perforadores vestidos de anaranjado que caminen en camara lenta (entre ellos Bruce Willis), y que gracias a eso, todas las personas puedan escuchar en la tele y en la radio mientras ven una explosión en el cielo de victoria. No nos vamos a morir, vamos a sobrevivir, pero tenemos que dejarnos de pendejadas.

Esta muy cabrón pedir un cometa, pero que tal decirle a Obama que cree el caos global y que truene las religiones (como las conocemos) con una noticia de UFOs!!! Seria como otro 911. Nos ayudaría a unirnos para una meta común, global y con metas claramente trazadas!

Ya en serio, en este post no pretendo discutir si estas noticias son ciertas o son solamente delirios de hippies que viven en tiendas de campaña y que queman monos gigantes. Sino compartir lo que no pude evitar pensar a lo largo del día.

Imagine que era completamente aceptado que venían seres de otra civilización. Obviamente mas avanzados que nosotros, porque ni modo que los saquemos de los hormigueros. Hasta los viajes a la luna los quieren privatizar por que odiamos el socialismo. E imagine que teníamos que darles la bienvenida y desde ahorita se los digo, yo no quiero ser el embajador intergalactico que les tenga que explicar las siguientes cosas:

  • Esto es un carro, funciona con un motor que se invento hace mas de 150 años… Ajajajaaa! pero no nos crean tan pendejos, nosotros tenemos otro tipo de motores muchísimo mas eficientes, pero no me preguntes porque todavía utilizamos gasolina y llantas hechas a base de petroleo.
  • Tenemos sistemas perfectos de trafico, no obstante, hay embotellamientos diariamente, debido a nuestra naturaleza humana de ser gandallitas y de creer que merecemos llegar primero que los demás.
  • Tenemos que trabajar para obtener cosas tan básicas como: Comida, agua, energía.
  • Escuchamos música, pero incluso canciones tan bonitas de Lennon, que sugieren erradicar fronteras, religiones y posesiones y que exhortan a la gente a vivir en paz, están cerradas con unas leyes de derechos de autor que ni siquiera nosotros las entendemos.
  • No solo la musica cuesta, los libros cuestan. La educación cuesta.
  • Ella se llama gloria trevi, y ha cometido muchísimos crímenes, la mayoría en contra de menores de edad. Porque la celebramos? Bienvenido a la tierra amigo.
  • Esto es una corporación…
  • Existen un poco mas de 6,000 millones de personas en el mundo, de las cuales mas de 1,000 millones viven en pobreza extrema (viven con menos de 1 dolar diario) y 1,800 no tienen acceso a agua potable. Por cierto visitantes, ¿Les he dicho que nosotros los seres humanos necesitamos tomar agua para sobrevivir? En este mismo mundo, existen personas que compran bolsas fendis y carros bentils, por decir algunas barateces.
  • Este continente grandote que ven aquí… Se llama África, mmmmh, nop, no quieren ir ahi, mejor los llevo a Paris, es muy bonito en Paris. En África la gente se muere de enfermedades de las que en otras partes del mundo nos reimos. Niños, se mueren.
  • El mejor golfista del mundo es negro y el mejor rapero del mundo es blanco. ** (ver nota)

En serio, puedo hacer esto todo el dia.

Ahora les pregunto a ustedes. ¿Que serian capaces de dar a cambio de que no existieran todas estas cosas sin sentido? En serio… Yo se que la mayoría no tienen bentlis de esos… Pero no los necesitan. ¿Que tal sacrificar el agua caliente y el aire acondicionado con tal de que el resto del mundo tuviera lo mismo que tu?

Pinche botón de reset… Donde chingados estas!

believe

Los dejo con esta foto para hacerles la barba a los ETs y a Obama, uno nunca sabe lo que pueda pasar!

** Nota: El chiste de estereotipos raciales fue incluido para restarle seriedad al escrito y para poder decir que el post entero es broma en caso de que Obama no diga nada el dia 10 de Diciembre… Que quemadoooon!

Proyectos locales

  • Everlasting Flame. Termina llamadas automáticamente (auto hangup) en tu BlackBerry.

Actividad en Github

Push
HEAD is eb02f912cdfaf9f233c37d70410f2cb864433b28
  • cesarolea committed eb02f912:
    Added status bar buttons and started the PIM screen.
  • cesarolea committed 024bb071:
    setCurrentTime and getCurrentTime methods added to TimePanel
  • cesarolea committed fd69e856:
    Implemented TimePanel and started on the final Config Screen.
When: 21 January 2010, 9:01 pm
Create
New branch is at cesarolea/Everlasting-Flame/tree/gui
When: 12 January 2010, 11:14 pm
Push
HEAD is 1e94dfbf5c7599990e0dc0babda1768a1202f74a
  • cesarolea committed 1e94dfbf:
    Fixed bug with init code. Selected notification method was not initialized correctly.
When: 5 January 2010, 10:55 pm
Push
HEAD is 3f41f4fa9b08f9020041321e8d15c57b36a8fd76
  • cesarolea committed 3f41f4fa:
    Fixed Notification combo. Selected option is now persisted.
When: 5 January 2010, 9:06 pm
java-mateview's description:
A TextMate syntax compatible source editing widget. Current adapters are for SWT.
When: 30 November 2009, 12:16 pm
Create
New branch is at cesarolea/Everlasting-Flame/tree/notifications
When: 3 November 2009, 4:57 pm
Create
New branch is at cesarolea/Everlasting-Flame/tree/master
When: 3 November 2009, 4:47 pm
Create
New repository is at cesarolea/Everlasting-Flame
When: 3 November 2009, 1:42 pm
Push
HEAD is b2342b9ea541191be1978b0912abdfcebf1e6f2c
  • cesarolea committed b2342b9e:
    Modified inventory handling and removed the global inventory
When: 3 November 2009, 1:31 pm
Push
HEAD is 57c68c176604d5037558973c966d0f2d9e327b49
  • cesarolea committed 57c68c17:
    Modified the gitignore to include the dist directory
When: 22 October 2009, 5:02 pm
Push
HEAD is c0cfffe5233db3b874a720d02f8673b03744f148
  • cesarolea committed c0cfffe5:
    Inventory add product initial implementation
When: 28 September 2009, 6:53 pm

Stack Overflow Flair

Actividad reciente en Stack Overflow

StackOverflow

An AJAX request contains the same request/response information as a traditional HTTP request. You can set cookies on the client once the async callback is executed, etc.

Permalink
When: 7 February 2010, 7:02 pm
StackOverflow
Agree, this is an easy question to answer by means of a Google search, but it is a programming related question so we should try to answer it. That's my opinion anyways.
Permalink
When: 7 February 2010, 12:41 pm
StackOverflow

REST stands for Representational State Transfer, and it was proposed in a doctorate dissertation (see here). It uses the four HTTP methods GET, POST, PUT and DELETE to execute different operations. This in contrast to SOAP for example, which creates new arbitrary commands (verbs) like getAccounts() or applyDiscount()

A REST API is a set of operations that can be invoked by means of any the four verbs, using the actual URI as parameters for your operations. For example you may have a method to query all your accounts which can be called from /accounts/all/ this invokes a HTTP GET and the 'all' parameter tells your application that it shall return all accounts.

Permalink
When: 7 February 2010, 12:36 pm
StackOverflow

If you want to create your own borderless window, instead of using a Frame/JFrame use a Window/JWindow. Frame/JFrame are extensions to Window/JWindow that provide borders and the maximize, minimize and close buttons. Usually those widgets are provided by the OS, but you can override them.

Permalink
When: 6 February 2010, 4:03 pm
StackOverflow

When you compile something in Java, the compiler generates bytecode. This is native code for the Java Virtual Machine. The JVM then translates the bytecode to native code for your processor/architecture, this is where the JIT happens. Without JIT, the JVM would translate the program one instruction at a time, which is very slow.

Permalink
When: 4 February 2010, 3:19 pm
StackOverflow

While XPath is a great choice, I would recommend JDom if your XML document is not huge, since it loads the entire document in memory.

Using JDom:

try {
    SAXBuilder builder = new SAXBuilder();
    Document firstDocument = builder.build(firstFile);
    Document secondDocument = builder.build(secondFile);

    Element firstRoot = firstDocument.getRootElement();
    Element secondRoot = secondDocument.getRootElement();

    List<Element> sourceListPost = secondRoot.getChild("listPost");
    firstRoot.addContent(sourceListPost);

    Document merged = new Document(firstRoot);
} catch(JDOMException e) {
    e.printStackTrace();
} catch(IOException e) {
    e.printStackTrace();
}

Now merged contains the merged Document. You can serialize it to a file with XMLOutputter.

Permalink
When: 3 February 2010, 12:24 pm
StackOverflow

You don't need an applet, from a grails controller you may use any Java library. Use the Java printing services available to the runtime in javax.print. This is assuming that the printer is installed where the grails runtime is running.

Permalink
When: 3 February 2010, 8:36 am
StackOverflow
It's very important to point out that Object Oriented Programming is language independent, so it stays the same when moving from language to language.
Permalink
When: 1 February 2010, 9:34 pm
StackOverflow
URLDecoder.decode(url);

See related question http://stackoverflow.com/questions/623861/how-do-you-unescape-urls-in-java

Permalink
When: 29 January 2010, 5:42 pm
StackOverflow

I think you would benefit greatly with a build tool, such as ant or maven. You can have a target to compile only one class without building the whole code, or any other related task.

Permalink
When: 28 January 2010, 10:14 pm
StackOverflow
I would recommend to first grasp the compile process, packages, the classpath and all that works. Then familiarize with an IDE and then take on a tool like ant or maven.
Permalink
When: 28 January 2010, 9:59 pm
StackOverflow

There's nothing wrong with the way you are compiling, it's just cumbersome but certainly not wrong.

That being said, create a src directory to store your .java files, keeping your directory structure coherent with the package structure of your classes. In this case you would have src directory and inside it, directory A and directory B. Inside A put Test1.java and inside B put Test2.java

Then:

javac B/Test2.java

Why Test2.java? Because it depends on A, then the compiler is smart enough to first compile A/Test1.java and then B/Test2.java. At this point you have each .class files inside A and B

To run it:

java B.Test2
Permalink
When: 28 January 2010, 9:23 pm
StackOverflow

My only advise would be don't go that way. As Bill K already said, most implementations would be significantly faster and more complete. Even more important is that there are excellent resources to achieve what you are trying to do: OSGi for example which has Eclipse and Glassfish v3 under its belt.

Personally I implemented something similar to your description, loading plugins at runtime without needing to restart the container. It was a nightmare to maintain and debug. And more important, while it was relatively easy for me to implement new modules (after all, I designed the thing), it was very difficult to program to. I ended up learning a lot about classloaders, but that was it.

Permalink
When: 28 January 2010, 4:38 pm
StackOverflow

If you fix the scaleMod and initialDistance to powers of 2 you could use shifts for faster multiplication and division.

See here for reference.

Permalink
When: 27 January 2010, 1:54 pm
StackOverflow

Check out Web Harvest. It's both a library you can use and a data extraction tool, which sounds to me that's exactly what you want to do. You create XML script files to instruct the scraper how to extract the information you need and from where. The provided GUI is very useful to quickly test the scripts.

Check out the project's samples page to see if it's a good fit for what you are trying to do.

Permalink
When: 24 January 2010, 6:16 pm
StackOverflow

JComboBox constructor can take a ComboBoxModel as argument. DefaultComboBoxModel is a concrete implementation of the ComboBoxModel interface.

So, if you have a Personel class:

class Personel{
    String personelName;
    int personelId;
    //getters, setters

    //This will be your display member
    @Override
    public String toString(){
        return this.personelName;
    }
}

And supposing you obtained all personel via JDBC and have it stored in a new Vector, you can do:

DefaultComboBoxModel comboModel = new DefaultComboBoxModel(personel);
JComboBox myCombo = new JComboBox(comboModel);

At runtime, you can getModel and setModel to access the JComboBox model. The display member will be Personel's toString() method. The value member will be the actual object stored in the DefaultComboBoxModel vector, in this case a Personel instance.

I suggest you take a look at the API documentation for ComboBoxModel and DefaultComboBoxModel.

Permalink
When: 24 January 2010, 5:32 pm
StackOverflow
You should post the problematic code.
Permalink
When: 22 January 2010, 3:15 pm
StackOverflow

You would use a regular expression to search for @username and then turn that to the corresponding link.

I use the following for the @ in PHP:

$ret = preg_replace("#(^|[\n ])@([^ \"\t\n\r<]*)#ise", 
                    "'\\1<a href=\"http://www.twitter.com/\\2\" >@\\2</a>'", 
                    $ret);
Permalink
When: 9 January 2010, 1:17 pm
StackOverflow
You need to define the action using the "action" attribute on the actionSubmit tag, otherwise it's derived from the value itself. Also, you don't need to define an action in the form itself (it's discouraged) and you can use regular forms or uploadForms.
Permalink
When: 8 January 2010, 2:37 pm
StackOverflow

With an actionSubmit:

Purpose

Creates a submit button that maps to a specific action, which allows you to have multiple submit buttons in a single form. Javascript event handlers can be added using the same parameter names as in HTML.

From the Grails reference docs.

Permalink
When: 8 January 2010, 12:45 pm
StackOverflow
I've used RXTX in the past for serial communication with no problems. Maybe if your question was on getting RXTX to work?
Permalink
When: 8 January 2010, 8:41 am
StackOverflow
You are right, in that case explicit jar loading is better. When you have a group of independent jars to load using wildcards is a good solution. Even better to have an ant script as duffymo suggested.
Permalink
When: 6 January 2010, 11:34 pm
StackOverflow

Since you are using JDK6, you can use classpath wildcards: CLASSPATH=".:/home/phoenies/jdk1.6.0_17/lib/*" will match all JARS inside lib/

Check out http://java.sun.com/javase/6/docs/technotes/tools/windows/classpath.html there's a section called "Understanding class path wildcards"

Permalink
When: 6 January 2010, 8:35 pm
StackOverflow

For it to work, the phpBB code would have to be looking for POSTed login credentials, which may not be the case. phpBB would need to specifically look for a post variable named user_name and user_pass which again may not be the case.

The example you are following is more a tutorial for using the POST method in HTTP from Java. If you want to see the results try it with the page they posted in the article located at http://www.1your.com/drupal/sample%5Flogin.php

As a suggestion, you could use something like Firebug to analyze the request/response HTTP transaction and from there you know what phpBB is expecting at the server side.

Permalink
When: 22 December 2009, 1:48 pm
StackOverflow
It's working now. No console errors. The problem was that I was using RootPanel instead of RootLayoutPanel.
Permalink
When: 22 December 2009, 9:51 am
StackOverflow
I wasn't aware of RootLayoutPanel existance. Once I changed to using it instead of RootPanel, everything works as expected.
Permalink
When: 22 December 2009, 8:52 am
StackOverflow
Thanks for trying it out. If you inspect the code that is sent to the client you can see the other elements are there. I believe it's the CSS layout that is incorrect, but I don't know enough CSS to debug it.
Permalink
When: 21 December 2009, 8:12 am
StackOverflow

I'm trying to get a simple layout working under GWT 2.0 using UiBinder. The layout I'm trying to get is one that mimic Java's BorderLayout in where you can specify different panels in the north, south, east, west and center directions; for that I'm using DockLayoutPanel. I would like to get a header and footer, both with fixed width. The remaining viewport space would be occupied by the widget assigned to the DockLayoutPanel center slot.

The current .ui.xml file I've got is:

<g:DockLayoutPanel unit='EM'>
    <g:north size='2'>
        <g:HTML>HEADER</g:HTML> 
    </g:north>

    <g:south size='2'>
        <g:HTML>FOOTER</g:HTML> 
    </g:south>

    <g:center>
        <g:HTML>
            <div id='loginform'>Hello!</div>
        </g:HTML>
    </g:center>
</g:DockLayoutPanel>

The browser only renders HEADER at the top left corner. How can I achieve the layout I'm looking for? It seems that there's more CSS you've got to know before you can use GWT layout panels, but that kind of defeats the purpose of creating the UI with it.

Permalink
When: 20 December 2009, 10:09 pm
StackOverflow
The basic idea is to build your query using the URL path, for example: myapp.com/houses/california/ This would yield all houses available for sale in California. You can do this manually by looking at $_SERVER['REQUEST_URI'] in any PHP script or let a framework such as Code Igniter handle this for your.
Permalink
When: 16 December 2009, 10:50 am
StackOverflow

You can convert a MySQL result set to JSON easily: http://phpclasses.nlared.com/browse/package/3195.html

For a RESTful interface, basically any hosted PHP script can function as a REST interface for your application.

Permalink
When: 15 December 2009, 10:55 pm
StackOverflow
I'm using 1.1.1 and also get lowerCamelCase URLs. Here's my UrlMappings.groovy file. class UrlMappings { static mappings = { "/$controller/$action?/$id?"{ constraints { // apply constraints here } } "/"(view:"/index") "500"(view:'/error') } }
Permalink
When: 1 October 2009, 8:20 pm
StackOverflow

A background worker is a class that works in a separate thread, but it provides additional functionality that you don't get with a simple Thread (like task progress report handling).

If you don't need the additional features given by a background worker - and it seems you don't - then a Thread would be more appropriate.

Permalink
When: 1 October 2009, 5:34 pm
StackOverflow
Tried it, and it works. Thanks! But before that I tried with optionKey="${it?.id}" and it gave me the same results as before. I'm not sure I understand how the g:select knows to get the id from each product, instead of trying to get the id from the list itself.
Permalink
When: 28 September 2009, 6:49 pm
StackOverflow

I have a g:select in my view that displays a list of products:

<g:form name="addproductform" action="saveProductToInventory" method="post">
    <g:select from="${products}" name="product" value="${it?.id}" />
    <g:hiddenField name="inventory.id" value="${inventoryInstance.id}" />
    <input class="save" type="submit" value="Save product" />
</g:form>

${products} is a list of all products. If I print the params variable that is passed to the controller, I get this:

[product:Test Product, inventory:[id:1], inventory.id:1, action:saveProductToInventory, controller:inventory]

The product key contains the name, and not the ID which I thought it would contain when I added value="${it?.id}" to the g:select tag.

How do I need to declare the g:select tag to render the product's name as it is right now, but pass the product's id as value?

Permalink
When: 28 September 2009, 1:49 pm
StackOverflow

Check the answers to these other questions:

  • What's the Java equivalent to LINQ
  • LINQ to Java?
  • Linq for Java

This is a fairly popular question.

Permalink
When: 25 September 2009, 5:52 pm
StackOverflow
Most likely you don't have your mergetool configured. Use git config --global mergetool.[tool].cmd = [command-line call] You can use many diff tools like kdiff3, tkdiff, xxdiff or many others. See gitguru.com/2009/02/22/…
Permalink
When: 16 September 2009, 6:12 pm
StackOverflow

Another option would be IKVM. It's a Java implementation for .NET. Please take a look at this related question, the answers there might help you.

Permalink
When: 15 September 2009, 2:51 pm
StackOverflow

You can push a branch to a remote server, say github. You would first have to do the initial project setup, then clone your project and:

git push <remote repo> <your branch>
Permalink
When: 9 September 2009, 5:14 pm
StackOverflow

The Unsatisfied Link Error can mean many things went wrong. I would use

System.loadLibrary("HelloWorld");

Instead of

System.load();

As TwentyMiles suggested.

Also, when invoking your program you need to (assuming your DLL is on the same directory as your class files:

java -Djava.library.path=. HelloWorld

Here's a simple demo I made that calls a Win32 API function (MessageBox)

Java class

class CallApi{
    private native String showMessageBox(String msg);
    private native double getRandomDouble();

    static{
        try{
            System.loadLibrary("CallApi");
            System.out.println("Loaded CallApi");
        }catch(UnsatisfiedLinkError e){
            //nothing to do
            System.out.println("Couldn't load CallApi");
            System.out.println(e.getMessage());
        }
    }

    public static void main(String args[]){
        CallApi api = new CallApi();
        double randomNumber = api.getRandomDouble();
        String retval = api.showMessageBox("Hello from Java!\n"+
            "The native random number: "+randomNumber);
            System.out.println("The native string: "+retval);
    }
}

Generated header file

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class CallApi */

#ifndef _Included_CallApi
#define _Included_CallApi
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     CallApi
 * Method:    showMessageBox
 * Signature: (Ljava/lang/String;)Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL Java_CallApi_showMessageBox
  (JNIEnv *, jobject, jstring);

/*
 * Class:     CallApi
 * Method:    getRandomDouble
 * Signature: ()D
 */
JNIEXPORT jdouble JNICALL Java_CallApi_getRandomDouble
  (JNIEnv *, jobject);

#ifdef __cplusplus
}
#endif
#endif

The C DLL code

#include "CallApi.h"
#include <windows.h>
#include <stdlib.h>
#include <time.h>

#pragma comment(lib,"user32.lib")

JNIEXPORT jstring JNICALL Java_CallApi_showMessageBox
  (JNIEnv *env, jobject thisObject, jstring js)
{
    //first convert jstring to const char for use in MessageBox
    const jbyte* argvv = (*env)->GetStringUTFChars(env, js, NULL);
    char* argv =(char *) argvv;

    //Call MessageBoxA
    MessageBox(NULL, argv, "Called from Java!", MB_ICONEXCLAMATION | MB_OK);
    return js;
}

JNIEXPORT jdouble JNICALL Java_CallApi_getRandomDouble
  (JNIEnv *env, jobject thisObject)
{
    double num1;
    srand((unsigned)(time(0)));
    num1 = ((double)rand()/(double)RAND_MAX);

    return num1;
}

Compile instructions

I compile with the Visual C++ express 2008 cl, removing the -ML flag since it causes an exception when the Java code tries to call the native code:

cl /I"c:\Program Files\Java\jdk1.6.0_10\include" /I"c:\Program Files\Java\jdk1.6.0_10\include\win32" -LD CallApi.c -FeCallApi.dll

Then, to run the code:

java -Djava.library.path=. CallApi

Permalink
When: 9 September 2009, 2:42 pm
StackOverflow

I have an application that takes some input and generates configuration files as output. Since the exact input or output format could change over time, I defined two interfaces: Importer and Exporter.

Each concrete importer or exporter could have different parameters that need to be initialized to work. For example, if the import data is coming from a CSV file you only need the path of the file, but if the data is coming from a database then you need a connection string, username, password, etc. Same thing for exporters.

My implementation currently is:

public interface Importer {
    public void setup(Map<String,String> params);
    public List<ConfigEntry> getList();
}

public interface Exporter {
    public void setup(Map<String,String> params);
    public void writeDocument(List<ConfigEntry> entries) throws IOException;
}

The setup method needs to be called before getList() or writeDocument() can be called. I use a Map to keep parameters because each child class can have different parameters.

Is using JavaBean style parameter initialization a preferred way? That means, adding setConnnectionString(), setCSVFilePath(), setX() to each child class.

What are the advantages, disadvantages of these approaches?

Permalink
When: 27 August 2009, 6:07 pm
StackOverflow

For what is worth, I finally nailed it.

The exception I got when trying to save a car was

not-null property references a null or transient value

It was obvious that the engine was null when trying to save, but why? Turns out you have to do:

def car = new Car(params)
car.engine = new Engine(name: "Default Engine")
car.engine.save()

Since engine doesn't belongs to a Car, you don't get cascade save/update/delete which is fine in my case. The solution is to manually save the engine and then save the car.

Permalink
When: 25 June 2009, 10:03 pm
StackOverflow

I'm struggling to get association right on Grails. Let's say I have two domain classes:

class Engine {
    String name
    int numberOfCylinders = 4
    static constraints = {
        name(blank:false, nullable:false)
        numberOfCylinders(range:4..8)
    }
}

class Car {
    int year
    String brand
    Engine engine = new Engine(name:"Default Engine")
    static constraints = {
        engine(nullable:false)
        brand(blank:false, nullable:false)
        year(nullable:false)
    }
}

The idea is that users can create cars without creating an engine first, and those cars get a default engine. In the CarController I have:

def save = {
    def car = new Car(params)
    if(!car.hasErrors() && car.save()){
        flash.message = "Car saved"
        redirect(action:index)
    }else{
        render(view:'create', model:[car:car])
    }
}

When trying to save, I get a null value exception on the Car.engine field, so obviously the default engine is not created and saved. I tried to manually create the engine:

def save = {
    def car = new Car(params)
    car.engine = new Engine(name: "Default Engine")
    if(!car.hasErrors() && car.save()){
        flash.message = "Car saved"
        redirect(action:index)
    }else{
        render(view:'create', model:[car:car])
    }
}

Didn't work either. Is Grails not able to save associated classes? How could I implement such feature?

Permalink
When: 24 June 2009, 10:14 pm
StackOverflow

You've clearly narrowed it down to two options. Between those two I would recommend to stick to the one with a larger community, since it's easier to get support that way. You already experienced that here, where Grails is familiar territory for many, but that's not the case for Aribaweb.

Also I've found that it really helps to try and do a simple but complete example project in both tools. Come up with a general design, and see how much time and effort it takes you to implement it in both frameworks. You can look for the following symptoms:

  • Do I get stuck very often?
  • Do I have to go hunt for an answer every time I get stuck, or can I get past it by reading at documentation?
  • Is the framework built to support what I'm trying to do, or do I have to invest significant effort to get it to play nice?
  • Do I feel like I get it after using it for a while?

Personally, that framework would be Grails.

Permalink
When: 23 June 2009, 6:21 pm
StackOverflow
I'm not at home so I can't try it, but I always thought that when passing a model to the view (via the model map), the key is how the view will access the value, and the value is the domain class? But now I see that the value must be the instance itself.
Permalink
When: 22 June 2009, 9:12 am
StackOverflow

I'm having a hard time figuring this validation problem. I have one parent domain class defined as follows:

class Person {
    String fullName
    List telephones = []

    static hasMany = [telephones : Telephone]

    static constraints = {
        fullName(size:3..50, blank:false, nullable:false)
    }
}

Then a sublcass:

class SalesAdvisor extends Person{
    Float comission //In percentage
    Portfolio customerPortfolio
    Inventory inventory

    static constraints = {
        comission(range:0..100, scale:2, nullable:false)
        customerPortfolio(nullable:false) 
        inventory(nullable:false)
    }
}

In the SalesAdvisorController I save SalesAdvisor instances:

def save = {
    def portfolio = new Portfolio()
    def inventory = new Inventory(name:'${params.fullName}Inventory', description:"${params.fullName}'s Inventory")
    params.customerPortfolio = portfolio
    params.inventory = inventory
    def salesAdvisor = new SalesAdvisor(params)

    if(!salesAdvisor.hasErrors() && salesAdvisor.save()){
        log.info("New instance of SalesAdvisor saved.")
        redirect(action:show, id:salesAdvisor.id)
    }else{
        log.error("There was an error saving the sales advisor.")
        salesAdvisor.errors.allErrors.each{
        println it.code
    }
    render(view:'create', model:[salesAdvisor:SalesAdvisor])
  }
}

In order to display any errors, in the 'create' view I have:

<g:hasErrors bean="${salesAdvisor}">
    <div class="errors">
        <g:renderErrors bean="${salesAdvisor}" as="list" />
    </div>
</g:hasErrors>

Validation seems to be working fine. However if I submit a string instead of a float for the comission field, in logs I can see "typeMismatch" but the view renders nothing! The message.properties file has a default entry for typeMismatch. Same thing for the fullName field, in logs I can see "nullable" and "blank" errors, but the view renders nothing.

I'm guessing it's more the view's fault than the controller or the domain, since unit tests behave like they should.

Permalink
When: 21 June 2009, 9:11 pm
@cesarolea
Escuchando @rockofonia como todos los Lunes! He's a woman, She's a man tiene un buen cover por parte de Helloween, para la emision pendiente
8 hours, 1 minute ago
@cesarolea
@anabel Zombieland kicks ass! Dile hola a Woody Harrelson de mi parte.
18 hours, 40 minutes ago
@cesarolea
@boynas pasaste por hermosillo y no te reportaste! Que mala onda morro.
20 hours, 57 minutes ago
@cesarolea
Orale me encontre a la Marla en Liverpool.
2 days, 1 hour ago
@cesarolea
@carloslaso yo estoy igual. Pero puro apoyo moral para mis compas de la #shdhobson
2 days, 2 hours ago
@cesarolea
@anhell1402 ya le llame a la señora para que venga por mi.
3 days, 22 hours ago
@cesarolea
@bobbher ve este bato! No hay nada como mi editor de texto favorito: http://www.geekandroll.com/2008/02/mi-editor-html-favorito/
3 days, 22 hours ago
@cesarolea
El control de la alarma de mi carro no quiso agarrar. Aqui me tiene afuera del trabajo.
3 days, 22 hours ago
@cesarolea
@bobbher antes, con JScript, se podia mandar a imprimir sin interaccion del usuario. Lo hicimos con el cajero del itson. No te da miedo?
4 days, 6 hours ago
@cesarolea
Que miedo el anuncio de Alan Cox en StackOverflow.
4 days, 18 hours ago