Joaquin Sorianello: Up things
Así nació Up things (no pregunten el porque del nombre ), un repositorio en github donde voy poniendo las cosas que se me ocurren.
El primer proyecto es el lanzador de partículas. Les dejo unos screenshots:
As asked by an Italian friend that posted a review on his blog (link). I’ve implemented Drag&Drop decoding support for QR Codes images directly from a website in QtQR.
You can see this in action in the following video:
You can expect this feature to be available in the daily PPA or wait for the stable release.
EDIT: Just if you don’t know, you can drag&drop to a QtQR dekstop launcher like showed in the next video, in this manner you don’t even have to open QtQR previusly to decode a file.
Any thoughts, bugs or feature request are more than welcome!
class Map(object):
def __init__(self, x, y, cell_size):
self.x = x
self.y = y
self.cell_size = cell_size
def locate(self, x, y):
cell = ""
middle_x, middle_y = self.x / 2, self.y / 2
size = max(self.x, self.y)
while size > self.cell_size:
left, right = int(x > middle_x), int(y > middle_y)
cell += ("QW", "AS")[left][right]
middle_x *= 0.5 + left * 0.25
middle_y *= 0.5 + right * 0.25
size /= 2
return cell
m = Map(100, 100, 10)
print m.locate(2, 32)
class Map(Map):El costo de calcular el vecino es relativo a la precisión, pero en la mayoría de los casos requiere sólo un par de cambios. Con estas funciones sólo resta calcular el viewport, para lo cual calculamos los cuatro extremos de nuestra caja y generamos a partir de ellos el resto:
...
@staticmethod
def right(cell):
if cell[-1] == "Q":
return cell[:-1] + "W"
elif cell[-1] == "A":
return cell[:-1] + "S"
elif cell[-1] == "W":
return Map.right(cell[:-1]) + "Q"
elif cell[-1] == "S":
return Map.right(cell[:-1]) + "A"
@staticmethod
def down(cell):
if cell[-1] == "Q":
return cell[:-1] + "A"
elif cell[-1] == "W":
return cell[:-1] + "S"
elif cell[-1] == "A":
return Map.down(cell[:-1]) + "Q"
elif cell[-1] == "S":
return Map.down(cell[:-1]) + "W"
class Map(Map):
...
@classmethod
def row(cls, cell, limit):
yield cell
while cell != limit:
cell = cls.right(cell)
yield cell
@classmethod
def col(cls, cell, limit):
yield cell
while cell != limit:
cell = cls.down(cell)
yield cell
def viewport(self, n, e, s, w):
left_col = self.col(self.locate(n, e), self.locate(s, e))
right_col = self.col(self.locate(n, w), self.locate(s, w))
for start, stop in zip(left_col, right_col):
for cell in self.row(start, stop):
yield cell
Para nuestro mapa, el uso sería:
for cell in m.viewport(0, 0, 20, 20):
print cell
QtQR 1.0/1.1/1.2 has the following dependecies:
yum install pyqt4 qrencode python-imaging
Once you got them installed you can go on installing python-zbar using easy_install:
easy_install zbar
If you get an “error: Setup script exited with error: command ‘gcc’ failed with exit status 1″ error, you need to install the zbar-devel package first, like this:
yum install zbar-devel
And there you go.. now you can download the sourcecode from Launchpad, decompress and run QtQR with the following command:
cd <dir of qtqr sourcecode> python qtqr.py
In summary, this are the commands you need to run (as root) to get QtQR working:
su (enter root password) yum install pyqt4 qrencode python-imaging zbar-devel easy_install zbar
Tested in Fedora 15, but if you find any difficulties please let me know in the comments.. happy hacking! :-)
Tercer conferencia internacional sobre el lenguaje de programación python.
Cuánto hace que no actualizo este blog!! Hoy estuve jugando un poco con Python y me puse a hacer un pequeño script que supongo que a otros les podrá servir como base para hacer algo más interesante. Precisamente, tengo planes para hacer algo más interesante, pero como recién están en veremos, les voy pasando esta pequeña base a ver si alguien me gana de mano
Como muchos sabrán, Apache (y otros web servers) tiene un módulo llamado mod_status que nos permite ver en tiempo real el estado del servidor (los requests que se están procesando, el uso del CPU, el estado de las conexiones, etc.). Esta información puede ser muy útil para hacer diagnósticos cuando está habiendo algún tipo de problema, para hacer monitoreo, etc. El módulo nos muestra una página web con la información y tiene dos interfaces: una está pensada para ser vista por seres humanos y otra para ser consultada por scripts (para ver esta segunda sólo hace falta pasarle el parámetro “?auto” en la URL). El problema es que esta segunda interfaz no nos muestra a qué dominios (virtual hosts) están dirigidos los requests que se están procesando (o si hay forma de que lo muestre yo no la encontré). Entonces me puse a hacer un sencillo script en Python para parsear la página “para seres humanos”.
Por suerte Python nos ofrece muchas herramientas muy útiles para este tipo de cosas, así que no me tuve que esforzar demasiado. En este caso utilicé urllib2 para acceder a la página de mod_status y BeautifulSoup para parsear el HTML. Por si no lo conocen, BeautifulSoup es un muy poderoso parser para XML/HTML hecho en Python. No viene con el código fuente sino que hay que instalarlo, pero hacerlo es muy fácil:
En Debian/Ubuntu:
apt-get install python-beautifulsoup
En CentOS/RedHat:
yum install python-BeautifulSoup
Con easy_install:
easy_install BeautifulSoup
El código tiene una clase Status que es la que hace la magia y una función main() que utiliza la clase para parsear una URL e imprimir algunos datos a modo de ejemplo.
class Status (object):
_url = None
def __init__ (self, url):
self._url = url
def fetch (self):
return urllib2.urlopen(self._url).read()
def parse (self):
html = self.fetch()
soup = BeautifulSoup(html)
status = {}
status[‘server_info’] = [i.string.strip() for i in soup.findAll(‘dt’)]
status[‘requests’] = []
requests = soup.find(‘table’).findAll(‘tr’)
keys = [i.string for i in requests.pop(0)]
for tr in requests:
req = {}
for n, td in enumerate(tr):
req[keys[n]] = td.string
status[‘requests’].append(req)
return status
def main (argv):
if len(argv) < 2:
print "Usage %s "%argv[0]
return 1
status = Status(argv[1])
data = status.parse()
print "SERVER INFORMATION"
print "=================="
for v in data[‘server_info’]:
print v
print "REQUESTS BY VHOST"
print "================="
entries = [i[‘VHost’] for i in data[‘requests’]]
requests = sorted([(entries.count(i), i) for i in list(set(entries))], reverse=True)
print "\n".join(["%d: %s"%(a,b) for a,b in requests])
if __name__ == "__main__":
sys.exit(main(sys.argv))
La forma de uso es:
python status.py "http://localhost/server-status"
Y en este caso la salida del script es algo así:
SERVER INFORMATION ================== Server Version: Apache/2.2.19 (Unix) mod_ssl/2.2.19 OpenSSL/0.9.8e-fips-rhel5 DAV/2 Server Built: May 26 2011 15:14:47 Current Time: Sunday, 31-Jul-2011 00:53:59 ART Restart Time: Saturday, 30-Jul-2011 12:07:12 ART Parent Server Generation: 0 Server uptime: 12 hours 46 minutes 47 seconds Total accesses: 407813 - Total Traffic: 3.7 GB CPU Usage: u2.05 s3.23 cu52 cs0 - .125% CPU load 8.86 requests/sec - 85.0 kB/second - 9.6 kB/request 10 requests currently being processed, 8 idle workers REQUESTS BY VHOST ================= 9: www.tail-f.com.ar 5: www.otro-dominio.com.ar 4: www.not-a-domain.com.ar 3: www.algunlado.com.ar 2: subdominio.dominio.com.ar 1: www.pepe.com.ar 1: www.no-votes-a-macri.com.ar 1: www.asd.com.ar 1: localhost
Obviamente esto no es una aplicación funcional, sino un ejemplo que espero que les sirva para hacer algo más copado. Yo seguiré jugando y si hago algo un poco más interesante, ya se los mostraré.