Raequel, scraping en la web de la rae con app engine

Written by javaguirre on May 14, 2012 Categories: Python Tags: , , ,

La semana pasada me enteré de que DuckDuckGo te permitía implementar plugins que luego ellos testean e introducen en la plataforma (DuckDuckHack), me pareció que podía ser muy divertido. :-)

Tras pensar varias cosas y ver cómo se podía implementar el plugin, estuve investigando por ahí y me pareció buena idea hacer un plugin que buscase en la RAE la palabra buscada y devolviese las acepciones de ésta.

En Github encontré a una persona que había hecho scraping sobre la web de la RAE y con el SDK de Python para Google App Engine había creado una API, este fue mi punto de partida. :-)

Leyendo el código y probándolo me di cuenta de que necesitaba por el momento un par de cosas por implementar, una era que la API debía ser JSONP, y otra que las peticiones debían responder más rápido.

La primera solución fue muy sencilla, simplemente añadir un par de cabeceras:

self.response.headers['Access-Control-Allow-Origin'] = '*'
self.response.headers['Access-Control-Allow-Methods'] = 'GET'

La segunda también resultó muy sencilla, ya que el SDK de Google App Engine dispone de una biblioteca para memcache, bastó añadir esa funcionalidad a la petición JSON/JSONP y listo.

Ahora toca la parte de DuckDuckGo, hará falta tiempo para ello, el proyecto está en Github.

No Comments

Using Aspen

Written by javaguirre on May 10, 2012 Categories: Development, Python Tags: , ,

Aspen is a python web framework based in the filesystem, mixing controller and view in the same archive, it’s called a Simplate.

We had some static html files in production, but months later we needed to add some server logic to this ones, without changing any url and having it integrated fast in our actual environment. These conditions make us think in this framework, it is perfect for this kind of situation, we hadn’t to change our actual filesystem for our html files and we could have easily integrated this new logic inside them. :-)

Our main problem using aspen is the lack of documentation, in my opinion is really poor and it could explain more and better basic things, such as requests handling. Anyway, I like to explore the code but sometimes you don’t want to spend some time in it when you have to get things done.

I have been using Django and Flask and I could say I found basics less intuitive in aspen than the others. I will try to explain what I meant in a later post when I get deeper in it.

No Comments

Evolución

Written by javaguirre on May 8, 2012 Categories: Development Tags: ,

En la última reunión de python-madrid argumenté por qué me parecía que el Software libre, o mejor dicho su comunidad es una evolución en la vida del desarrollador corriente.

No hablaba de evolución con respecto al software propietario sino con respecto a uno mismo, en mi caso hablaba de mi experiencia. Son unos cuantos años los que llevo dedicando a mi pasión, que es el desarrollo de software y es un camino muy fácil pero a a la vez muy complejo.

¿Por qué? En ocasiones somos los reyes del mundo o Neo en Matrix, creo que siempre que se empieza a ser productivo en el desarrollo te sientes un poco orgulloso, hasta que cada día te das cuenta que hay mucha gente mejor que tú en muchas cosas pero que tu contribución es importante porque somos un equipo, y que la humildad te hace más fuerte.

He estado intentando sacar proyectos personales, software libre, pero proyectos que al final quedan en la cuneta por la simple cuestión de que no hay comunidad y de que vuelvo a inventar la rueda, sino del todo, sí en gran parte.

Hace muy poco decidí no centrarme en éstos, sino en los que me interesan, dedicando tiempo a proyectos que habían resuelto alguno de los problemas que yo quería volver a resolver, y comenzar contribuyendo en éstos. Lo sé, sonará a tontería ya que de esto va el Software Libre, pero hasta este momento no había visto la luz y la verdad es que ahora todo es mucho más divertido.

Ese abrirse más al mundo es para mí el Software Libre, y Github facilita las cosas muchísimo, he decidido pasar a ser un Doer. :-)

No Comments

Lua Highlighter for Rainbow

Written by javaguirre on April 29, 2012 Categories: Development, Javascript Tags: , , , ,

I’ve been studying an Udacity course to build your own web browser(CS262), it’s a great way to learn some things quicker and funnier than expected, and time is gold in this world of ours. :-)

These first chapters were easier, we were practising regexp a lot, so I decided to contribute to rainbow.js project, adding some highlight patterns for lua language.

You can look for this awesome js plugin in its webpage and at github.

No Comments

Usando Subsonic y MiniSub

Written by javaguirre on April 22, 2012 Categories: Java, Javascript, Music Tags: , ,

Tras una semana para probar Subsonic tengo que decir que estoy encantado, facilita sobremanera el control de la música en mi casa y pronto desde fuera. :-)

Mi servidor subsonic es un ArchLinux, hay un buen tutorial para empezar en la wiki de Arch para no lanzar subsonic como root aunque hay un par de cosas a tener en cuenta para sacar todo de este servidor de música.

Es necesario instalar lame y ffmpeg, ya que subsonic los usa por debajo.

pacman -S lame ffmpeg

Posteriormente necesitamos hacer un enlace simbólico al directorio /var/subsonic/transcode para que subsonic los pille.

cd /var/subsonic/transcode
ln -s /usr/bin/lame
ln -s /usr/bin/ffmpeg

Subsonic tiene además una API para construir tu propio cliente, aunque echo de menos a primera vista la posibilidad de gestionar los llamados players.

Hay algún cliente para Subsonic por ahí en construcción, uno de ellos es MiniSub, hecho en javascript usando la API de subsonic vía JSONP, le falta un poco de estabilidad y de organización en el código, pero tiene buena pinta.

No Comments

M2Crypto from pip in old GNU/Linux OS

Written by javaguirre on April 19, 2012 Categories: Development, Python Tags: , , ,

We had a problem today with M2Crypto package from pip repository in a CentOS server.

... Error: Unable to find 'opensslconf-x86_64.h'

The actual version in pip repositories is 0.21.1, but the setup.py file doesn’t search for the correct headers in this version of CentOS 5.5 (It’s old, I know :-) ).

There’s an easy workaround to get it working, I found it in a Zenoss community thread, you can just add a new path to search for files to self.swig_opts list.

First, we can download it from pip, and modify the setup.py file.

pip install -d . M2Crypto==0.21.1
untar M2Crypto-0.21.1.tar.gz

BEFORE

#LINE 58
self.swig_opts = ['-I%s' % i for i in self.include_dirs + \                                                                                  
                 [opensslIncludeDir]]
self.swig_opts.append('-includeall')

AFTER

self.swig_opts = ['-I%s' % i for i in self.include_dirs + \                                                                                  
                 [opensslIncludeDir]]
self.swig_opts.append('-includeall')
self.swig_opts.append('-I/usr/include/openssl')

Then running python setup.py install might do the trick.

No Comments

Installing BrowserQuest

Written by javaguirre on April 18, 2012 Categories: Development, Javascript Tags: , , , , ,

It’s been a while since Mozilla released BrowserQuest, a game built on nodejs with WebSockets. I love this retro style given to the game, I’ve always wanted to do that kind of game and now is a good chance to hack a popular game project and have some fun with it! :-)

Mozilla released the code in Github, but there are some cool stuff they couldn’t release yet, I hope they do it soon to create some new worlds easily.

I followed this two excellent sources from Dirk Krause to get it running in local or anywhere, but I think some novice people are still a bit confused about how to do it, so I will try to clarify just a couple things, you will need the instructions from Dirk anyway.

Getting the code from Github, the easiest way to get the client running is copying the shared directory inside the client one, executing it with http-server as explained before.

$ cd client
$ cp -r ../shared .
$ http-server
 
Starting up http-server, serving ./ on port: 8080
Hit CTRL-C to stop the server

Now you can go to your browser to see it running.

If you click play nothing happens, we need to start the server.

$ node server/js/main.js
 
[Wed Apr 18 2012 20:52:46 GMT+0200 (CEST)] INFO Starting BrowserQuest game server...
[Wed Apr 18 2012 20:52:46 GMT+0200 (CEST)] INFO world1 created (capacity: 200 players).
[Wed Apr 18 2012 20:52:46 GMT+0200 (CEST)] INFO Server is listening on port 8000

You could modify client and server ports in the config_local.json file, inside both directories (client and server), but using this approach (http-server module) is not neccessary to change client’s port.

Server will search for config in two places:

var defaultConfigPath = './server/config.json',                                                                                                 
    customConfigPath = './server/config_local.json';

There is a config.json by default, binding the server to port 8000, so if you don’t care about ports by now there’s nothing to worry about.

That’s it, have fun!

No Comments

From WordPress to Obtvse, rake task

Written by javaguirre on April 17, 2012 Categories: Development, Ruby Tags: , , ,

Obtvse is a minimalist blog, made simple and built on Rails. I like minimalism, so I wanted to test and do something with it. I worked in a rake task to just migrate my actual posts to this new platform.

To make it work there’s only a few steps needed.

In your Gemfile you need to put…

gem "mysql"

Then add an environment to your config/database.yml

wordpress:
  adapter: mysql
  encoding: utf8
  database: obtvse_example
  username: my_user
  password: my_pass
  host: localhost

Finally you could call it from the command line…

rake wordpress:migrate_wordpress[source_db, destiny_db]

Where source_db is your WordPress db in the database.yml file, and destiny_db is the Obtvse one.

The code is not a big deal, just a few lines. I know It could be a better implementation, but is my first rake task, I would like some feedback. :-)

# -*- coding:utf-8 -*-                                                                                                                              
# Usage rake wordpress:migrate_wordpress[:src, :dst]
# You will need gem "mysql" in your Gemfile
namespace :wordpress do
    task :migrate_wordpress, [:src, :dst] => :environment do |cmd, args|
        args.with_defaults(:src => "wordpress", :dst => "development")
        config = Rails.configuration.database_configuration
        src_db = config[args[:src]]
        dst_db = config[args[:dst]]
 
        conn = ActiveRecord::Base.establish_connection src_db
        posts = conn.connection.execute "SELECT * FROM wp_posts where post_status='draft' or post_status='publish'"
 
        conn = ActiveRecord::Base.establish_connection dst_db
 
        posts.each do |post|
            title = post[5].force_encoding 'utf-8'
            content = post[4].force_encoding 'utf-8'
            created_at = post[2]
            updated_at = post[14]
            draft = post[7]
 
            if draft.end_with? "draft"
                draft_flag = true
            elsif draft.end_with? "publish"
                draft_flag = false
            end
 
            p = Post.create! :title => title, :content => content, :slug => Post.acts_as_url(:title, :url_attribute => :slug),
                             :created_at => created_at, :updated_at => updated_at, :draft => draft_flag
        end
    end
end

More in my Obtvse fork. Obtvse Demo.

No Comments

Servidor de música con Subsonic

Written by javaguirre on April 16, 2012 Categories: Music, Software Libre Tags: , ,

Un servidor para todo, para tener música en tu Android por streaming, para tener en casa en cualquier portátil, y para poder manejar la música en el servidor remoto como si fuese nuestra “minicadena” (qué antiguo soy :-P), todo eso lo tenemos con Subsonic, un proyecto de Software Libre hecho en Java.

Subsonic nos provee de un servicio web desde el cual podemos gestionar la música de un servidor, gestión de usuarios y distintos players por usuario. Los players son los distintos dispositivos de un usuario, un player podría ser un móvil android, otro podría ser el portátil, y otro podría ser cambiar música remotamente en el propio servidor.

Este fin de semana he estado instalándolo en casa y estoy encantado, a falta de tunear mi router, que me está dando algunos problemas, estoy contento por lo rápido que funciona y todas las posibilidades que te da, entre ellas el poder subir nueva música al servidor muy fácilmente y unas cuantas cosillas más.

También comentar que tiene aplicación nativa para Android, y que funciona muy bien, aunque me falta la posibilidad de conexión a un player remoto, algo que se puede hacer accediendo vía navegador.

En un siguiente artículo explicaré cómo lo monté, aunque creo que es bastante sencillo para cualquiera que estudie un poquito.

No Comments

Ducksboard Python module

Written by javaguirre on April 1, 2012 Categories: Python Tags: ,

I’ve done a very simple package to wrap Ducksboard API and uploaded it to Python Packages, it’s my first Python package there so I’m excited. :-)

There are some things to improve in it, but it does everything you can do right now with this API.

Here is an example of code that makes succeeded requests.

#!/usr/bin/python                                                                                                                                    
 
from ducksboard.ducksboard import Ducksboard                                                                                                         
import time                                                                                                                                          
 
 
MYAPIKEY = 'MYAPIKEY'                                                                                                                                        
ENDPOINT = 'gauge1'                                                                                                                                        
 
d = Ducksboard(MYAPIKEY, ENDPOINT)                                                                                                                   
 
#Updates a Gauge                                                                                                                                                     
d.gauge(0.22)                                                                                                                                        
 
#Updates the counter                                                                                                                                                     
d.endpoint = 12317                                                                                                                                   
d.counter(22)                                                                                                                                        
 
#Graph                                                                                                                                                     
d.endpoint = 334                                                                                                                                      
d.graph([{"timestamp": 1299854684, "value": 10 },
         {"timestamp": 1299855600, "value": 40}])                                                           
 
 
d.endpoint = 1123                                                                                                                                    
d.image(image="https://dashboard.ducksboard.com/static/img/timeline/red.gif",
        caption="content")                                                                   
 
d.endpoint = 1236                                                                                                                                
d.timeline(title="Bye", content="world",
           image="https://dashboard.ducksboard.com/static/img/timeline/red.gif",
           link="http://ducksboard.com")

I have to improve documentation and upload the example with the package, one step at a time. :-)

If you want to improve the library, found a bug or you just have an idea, you can contact me here or check for the code in Github.

No Comments

Switch to our mobile site