Recent blog entries for ebf

TEDx Amazônia

Como já disse no post anterior, o TEDx Amazônia foi um evento indescritível. A qualidade dos palestrantes, da organização, do publico e da estrutura ajudaram a este developer, entrar numa fase de profunda reflexão e análise pessoal.

Após duas semanas do evento, as idéias continuam a germinar. E agora já sinto mais a vontade para compartilhar minhas impressões “pós-evento”. Vou falar um pouco do que mais me tocou e como foi a experiência lá.

Esse foi meu primeiro evento TED e gostei muito do formato. O fato de que os palestrantes e platéia se misturam completamente foi algo que eu deveria estar melhor preparado!

Encontramos o Michael Braungart no barco rumo ao evento. Fico muito triste de não ter puxado uma conversa com ele lá, pois a apresentação dele foi genial. Redefiniu, para mim, o que é ser sustentável ou “estúpido”. Um dos melhores trechos de sua apresentação:

Sustentável? Isso é bom? Já pensaram alguém perguntar “Como vai seu relacionamento?” e responderem: “Sustentável”. Isso é estúpido!

Nas palavras dele, aprendi que devemos ter uma pegada positiva com a Natureza e não negativa, ou “zerada”. Fazer menos mal, não. Fazer o bem, o certo pela Natureza. Uma curiosidade interessante (obrigado @AlineMary!): O livro dele Cradle to Cradle: Remaking the Way We Make Things, é feito de um papel sintético facilmente reciclável, sem utilizar árvores. Isso sim é um cara que segue o que diz.

Durante uma das refeições no evento, um senhor pede licença para entrar na fila. É estranho como gigantes do pensamento podem ser tão simples! Esse senhor era “apenas” Enrique Leff. A nova racionalidade proposta por ele até agora está fazendo minha cabeça girar. E ainda ele é um cara super simples e acessível! Sua frase inicial “A humanidade errou o caminho de construção da civilidade” já bateu forte. @AlineMary e eu estamos debatendo e planejando estudar muito, além dos 15 minutos que ele falou. Edgar Morin, nos vemos em breve! :)

Ver, por exemplo, Bernardo Toro brincar de dançar Thriller durante a apresentação do Magnólio foi surreal. Falando em Bernardo Toro, seu ”Saber Cuidar” calou fundo. Hoje somos máquinas produtoras de trabalho e esquecemos de cuidar. Cuidar da mente, do espírito, do corpo. Das pessoas próximas, dos conhecidos e dos desconhecidos. Isso cai como uma luva para nossa civilização, tão individualista e egoísta.

A palestra de Zach Lieberman foi libertadora. Para mim tecnologia sempre foi sinônimo de ganho financeiro. Uma boa idéia para ganhar muito dinheiro. Zach mostrou que tecnologia é dar poder para as pessoas. E pode, também, ajudar pessoas. No caso do grafiteiro Temptone, que pôde voltar a fazer sua paixão graças ao trabalho dele. Veja no vídeo abaixo:

Mais informações sobre o projeto em http://www.eyewriter.org

A apresentação do Sérgio Laus, o surfista de pororoca, foi interessantíssima. O impacto do esporte nas comunidades ribeirinhas é positivíssimo, apesar de que nunca pegaria uma onda num tsunami de água doce… :)

Aaron Koblin mostou que a arte pode nascer do trabalho coletivo. Achei incrível como utilizou o Turk da Amazon para trabalhos impressionantes de arte coletiva.

Joan Roughgarden fez um contraponto forte a Darwin em sua apresentação. Mostrou como a sexualidade aproxima bandos de diversas espécies, independente do sexo/gênero. Destruiu o conceito da fêmea tímida e do macho promíscuo. Iluminador e esclarecedor, principalmente na nossa sociedade sexista e preconceituosa.

Thiago de Mello me deu calafrios. Com sua voz suave e as palavras fortes, declamando uma nova versão de seu famoso “Estatutos do Homem”… incrível.

André Abujamra, como sempre, foi ímpar. Apesar dos deslizes no começo da apresentação por parte da produção, começou sua música a cappella e deixou todo mundo boquiaberto.

Sempre fui muito competitivo e o tal do “próximo”, seja ele uma pessoa ou a natureza, sempre foi algo muito abstrato e intangível. Esse evento mudou essa realidade pra mim, mudou minha escala de prioridades. Vivemos num mundo tão consumista que não vemos o que isso está causando ao “próximo”.

Mal posso esperar a começar a agir.

Hotel Amazon Jungle Palace, sede do TEDx Amazônia
Minha Credencial - sim, erraram o nome da A&D :)
Enrique Leff
Almoço. Servidos? :)
Platéia TEDx
Aaron Koblin - Fenomenal
Suely Carvalho
Suely Carvalho mostrando o valor das parteiras e da dignidade, beleza e naturalidade do parto normal.
André Abujamra detonando
Diana Whitten - \
André Abujamra detonando
Paul Bennett, da Ideo
Edgard Gouveia Jr - \
Lama Samten
Paulo Arruda
Zach Lieberman - Essa apresentação mudou minha visão
Michael Braungart - Palestra Brilhante
Filipe Milanez denunciando genocídio dos Índios Kawahiva
Bernardo Toro
Lucas Santtana
Lucas Santtana
Poste de Luz
Leito seco do Rio Negro
José R. Fonseca
Nosso pequeno transfer.
Alexandre Siqueira
O gigante Thiago de Mello

#TEDxAmazonia – Indescritível

Indescritível.

É assim, com esse chavão, com essa palavra tão usada, que defino o primeiro dia do TEDx Amazônia.

Nunca fui tão agraciado com idéias, com experiências tão diferentes e plurais. Desde a maravilhosa dança inicial, os pensamentos do Lama Santen, a dança das chuvas, o trabalho fenomenal com o genoma de Paulo Arruda (obrigado pelo café!), Enrique Leff (obrigado pelo autógrafo!), a consciência de Leinad Carbogim (obrigado pelo abraço!), Bernardo Toro, ao poder dado pela tecnologia de Zach Lieberman, a luta de Zé Claudio Ribeiro, a visão e visualização tecnológica de Aaron Koblin…

Cheguei até a desmaiar no relato de Deise Nishimura (sangue + Eduardo = blackout)!

E muitos outros que, por mais que tente, meu cérebro castigado (no bom sentido) não consegue associar seus nomes as suas excelentes palestras.

É impossível descrever a sensação de estar imerso num ambiente tão rico – e no meio do mais rico ecossistema do mundo: A Floresta Amazônica.

O que eu não esperava é que o TED tem um efeito colateral inesperado e não divulgado: A reflexão.

As idéias ainda estão fervilhando em minha mente e sei que vão trazer mudanças significativas no modo que me vejo inserido na minha comunidade, no meu país e no mundo.

E tentarei espalhar essas mesmas idéias com a mesma paixão e vontade mostrada pelos palestrantes.

Adendo: Ficamos encalhados no meio do Rio Negro após uma manobra pouco ortodoxa de nosso barqueiro. Fizemos novos amigos e rimos muito. Até nisso o TEDx Amazônia está sendo único e transformador! :)

#TEDxAM – Estamos aqui!



Já chegamos em Manaus para um dos eventos mais esperados do ano (pelo menos por nós da @aedtech): TEDx Amazônia!

Eu e a @AlineMary tentaremos postar diariamente fotos e impressões das 50 apresentações interessantíssimas que veremos aqui nos próximos dias.

27 Oct 2010 (updated 30 Oct 2010 at 19:22 UTC) »

CherryPy – WebApps with a great stuffing

I’m an old-fashioned kind of guy. I started developing web apps when Perl was something really new and revolutionary, Guido van Rossum wasn’t dealing with snakes yet and Netscape Enterprise Server was the fastest server ever. Yeah right.

In order to create apps that would interact with the web browser, you only had one option. CGI. And the so called Common Gateway Interface always worked. Personally, I still used it until quite recently. Last week recently, BTW ;)

With the arrival of new web technologies (Rails, Django, and etc…), I studied and learned those new “formats” (BTW, I love MVC). But I always felt “restrained”. CGI is obsolete and old (most of the time), but you can do whatever you want.

We needed a new technology for one of our internal projects at @aedtech. Something that could ease the development and still be flexible, and mainly fast. After Googling a lot, I found a great solution: CherryPy.

CherryPy is a very “pythonic” HTTP framework. What really got me excited is the simplicity, the sane use of OOP and how mature the project is. The easiest way to describe how simple and nice CherryPy is, is by showing some code. Below is a little snippet from the project’s website:

import cherrypy

class HelloWorld(object):
    def index(self):
        return "Hello World!"
    index.exposed = True

cherrypy.quickstart(HelloWorld())

Easy, hum? My crazy-scientist-tests starts today, mixing this with mongoDB, Memcached and some secret sauce :)

CherryPy – WebApps com recheio

Sou um cara das “antigas”. Comecei a programar para web na época que Perl era algo novíssimo e revolucionário, Guido van Rossum ainda não estava envolvido com cobras e o Netscape Enterprise Server era o que havia de mais rápido. Pois é.

Para criar programas que rodavam no browser, você tinha uma opção. CGI. E o tal do Common Gateway Interface sempre funcionou. E pessoalmente, usava ele até pouco tempo atrás. Semana passada na verdade :) .

Com o advento das novas tecnologias web (Rails, Django, e etc…), me atualizei e comecei a trabalhar com elas também. Mas sempre me sentia “preso”. CGI é obsoleto e lento (na maioria das vezes), mas você tem uma flexibilidade incomparável.

Montando um projeto interno da @aedtech, comecei a procurar um ambiente mais… neutro. Algo que pudesse ter a flexibilidade dos CGIs, mas num ambiente mais rápido, eficiente e inteligente. Depois de pesquisar bastante, achei a solução: CherryPy.

CherryPy é um framework HTTP, bem “pythonico”. O que me empolgou é a facilidade, o uso correto e sensato de classes e como o projeto está maduro. A forma mais fácil de descrever como o gostoso de trabalhar com esse framework é mostrar um pouco de código. E segue um snippet direto do site do projeto:

import cherrypy

class HelloWorld(object):
    def index(self):
        return "Hello World!"
    index.exposed = True

cherrypy.quickstart(HelloWorld())

Simples né? Os testes de cientista louco começam hoje, misturando isso com mongoDB, Memcached e outras coisinhas mais :)

19 Oct 2010 (updated 25 Oct 2010 at 23:12 UTC) »

HOWTO: Delete all of your tweets in a few steps

@AlineMary and I decided to change our course with Twitter. Our profiles used to be private, restricted to a few known acquaintances. For personal reasons, we decided to use Twitter in a different way, more public and focused on our projects.

But (always a but) we wouldn’t like to lose our followers or to stop following the interesting people we already followed, so deleting and recreating our accounts was out of league. Manually deleting all tweets, well, was too nightmarish (I had ~ 9800 tweets and @AlineMary ~ 600).

I Googled several mass delete services and found a handful – some, well recommended. There was only one minor problem: none of them worked ;)

Always witty and wise, @AlineMary told me: “You used to be a programmer, right?”. Point taken, my dear :-D .

After googling for some simple-to-use APIs (with OAuth support), I found Jeff Miller’s - “Twitter from the command line in Python using OAuth”, in which he demonstrated the very easy-to-use Tweepy library.

After a quick grok at the documentation, and following Jeff’s footsteps, I managed to assemble a very bare-bones app to mass delete all Tweets. Best of all: It worked :)

So, let’s proceed to the HowTo. You will need to follow Jeff’s steps for the OAuth authentication first:

Step 1: Download Tweepy

Tweepy is an awesome Twitter library for Python. Much of this post is based on information I found in the Tweepy documentation.

Download Tweepy from GitHub and install it on your system.

Step 2: Register a new client app with Twitter

Navigate to http://twitter.com/oauth_clients and click on Register a new application. You might have to log in to the Twitter site first, if you’re not already.

Fill in the registration fields as follows:

When finished on the registration page, click Save.

Next page:

Keep this browser window open. We’ll need the information in the next step.

Step 3: Connect the app to your Twitter account

Next, the app needs to be authorized to connect to your account so it can send tweets under your name.

We’ll create a one-off utility script to do this. Save the following Python code as a script on your local system.

#!/usr/bin/env python

import tweepy

CONSUMER_KEY = 'paste your Consumer Key here'
CONSUMER_SECRET = 'paste your Consumer Secret here'

auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth_url = auth.get_authorization_url()
print 'Please authorize: ' + auth_url
verifier = raw_input('PIN: ').strip()
auth.get_access_token(verifier)
print "ACCESS_KEY = '%s'" % auth.access_token.key
print "ACCESS_SECRET = '%s'" % auth.access_token.secret

Paste the Consumer Key and Consumer Secret from the end of step 2 into this script, replacing the CONSUMER_KEY and CONSUMER_SECRET constants. Then save and run on your system.

You should see a prompt like this:

Please authorize: <URL>
PIN:

Open that URL in your browser. You should see the standard OAuth Twitter connection screen:

Click Allow.

Twitter will then provide you with a PIN code that authenticates the connection between the client app and your Twitter account.

Enter this PIN into the prompt from the Python registration script:

PIN: 2781961

The script will then print out another key/secret pair:

ACCESS_KEY = '124242RCyi3g0cZ4r5BWL047rsh0S0yv5VxAGwTKCOsHAb'
ACCESS_SECRET = 'kaTXiC489qo8y6haTBSlwOqR1syG83tzPG2StdQ'

But the values will be different each time.

Keep this information on your screen because we’ll need it in the next step.

Ok! Thanks Jeff :) . Now, to the destructive part of this post. Muahuahua*.

We will create a very simple Python script that will iterate over your tweets and… well, delete them :)

#!/usr/bin/env python
import sys
import tweepy
import time

CONSUMER_KEY = 'xxxxxxxx'
CONSUMER_SECRET = 'xxxxxxxx'
ACCESS_KEY = 'xxxxxxxxx'
ACCESS_SECRET = 'xxxxxxxxxxxx'

auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth)

pag  = 1
status  = []

while (1):
	try:
		status  = api.user_timeline(page=pag)
		for update in status:
			print update.id
			print update.text
			api.destroy_status(update.id)
			print "--"
			pag  = pag + 1
	except:
		print "Failure... sleeping for 10 minutes."
		time.sleep(600) # Sleep for 10 minutes and try again.

And that’s it. Execute this Python script (don’t forget to fill your Keys and Secrets, the one you got with Jeff’s steps) and… wait. This app takes a long time to run (mine is still running). But it works 100% :)

Doubts? Comment!

* Sheldon Cooper. :)
19 Oct 2010 (updated 25 Oct 2010 at 23:12 UTC) »

Como apagar seus tweets em poucos passos.

Eu e a @AlineMary decidimos mudar o rumo no Twitter. Antes, tínhamos um perfil privado, restrito a alguns conhecidos. Por motivos pessoais, resolvemos que vamos utilizar o Twitter de forma mais publica e mais voltada a nossos projetos.

Só um porém: não gostaríamos de perder nossos seguidores e aqueles os quais seguíamos, portanto deletar e recriar a conta era algo impraticável. Deletar manualmente os tweets, também (eu tinha ~ 9800 tweets e ela ~ 600).

Procurei vários serviços de mass delete na web e achamos alguns muito bem recomendados. O problema é que eles simplesmente não funcionaram :)

Sempre unida de uma sabedoria cativante, @AlineMary falou: “Você não é um programador?”. Point taken, my dear :)

Após efetuar algumas buscas na web por uma API simples de usar (e com suporte a OAuth), achei o artigo do Jeff Miller – “Twitter from the command line in Python using OAuth”, o qual demonstrava o uso muito simples da API Tweepy.

Dando uma olhada rápida na documentação e seguindo o exemplo do Jeff, montei um programa bem bare bones para remoção em massa dos tweets. E não é que deu certo? :)

Vamos aos passos. Iniciamente você terá de seguir as etapas do post do Jeff para efetuar a autenticação OAuth no Twitter.

Step 1: Download Tweepy

Tweepy is an awesome Twitter library for Python. Much of this post is based on information I found in the Tweepy documentation.

Download Tweepy from GitHub and install it on your system.

Step 2: Register a new client app with Twitter

Navigate to http://twitter.com/oauth_clients and click on Register a new application. You might have to log in to the Twitter site first, if you’re not already.

Fill in the registration fields as follows:

When finished on the registration page, click Save.

Next page:

Keep this browser window open. We’ll need the information in the next step.

Step 3: Connect the app to your Twitter account

Next, the app needs to be authorized to connect to your account so it can send tweets under your name.

We’ll create a one-off utility script to do this. Save the following Python code as a script on your local system.

#!/usr/bin/env python

import tweepy

CONSUMER_KEY = 'paste your Consumer Key here'
CONSUMER_SECRET = 'paste your Consumer Secret here'

auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth_url = auth.get_authorization_url()
print 'Please authorize: ' + auth_url
verifier = raw_input('PIN: ').strip()
auth.get_access_token(verifier)
print "ACCESS_KEY = '%s'" % auth.access_token.key
print "ACCESS_SECRET = '%s'" % auth.access_token.secret

Paste the Consumer Key and Consumer Secret from the end of step 2 into this script, replacing the CONSUMER_KEY and CONSUMER_SECRET constants. Then save and run on your system.

You should see a prompt like this:

Please authorize: <URL>
PIN:

Open that URL in your browser. You should see the standard OAuth Twitter connection screen:

Click Allow.

Twitter will then provide you with a PIN code that authenticates the connection between the client app and your Twitter account.

Enter this PIN into the prompt from the Python registration script:

PIN: 2781961

The script will then print out another key/secret pair:

ACCESS_KEY = '124242RCyi3g0cZ4r5BWL047rsh0S0yv5VxAGwTKCOsHAb'
ACCESS_SECRET = 'kaTXiC489qo8y6haTBSlwOqR1syG83tzPG2StdQ'

But the values will be different each time.

Keep this information on your screen because we’ll need it in the next step.

Ok! Obrigado Jeff :) Agora, vamos a parte destruidora do Post. Muahuahua*.

Vamos criar um script simples que vai iterar pelos posts já efetuados pelo seu usuário e… bem, deletá-los :)

#!/usr/bin/env python
import sys
import tweepy
import time

CONSUMER_KEY = 'xxxxxxxx'
CONSUMER_SECRET = 'xxxxxxxx'
ACCESS_KEY = 'xxxxxxxxx'
ACCESS_SECRET = 'xxxxxxxxxxxx'

auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth)

pag  = 1
status  = []

while (1):
	try:
		status  = api.user_timeline(page=pag)
		for update in status:
			print update.id
			print update.text
			api.destroy_status(update.id)
			print "--"
			pag  = pag + 1
	except:
		print "Failure... sleeping for 10 minutes."
		time.sleep(600) # Sleep for 10 minutes and try again.

E é isso. Execute esse script Python informando as Keys e Secrets obtidas em cima com o Jeff e… aguarde. O script demora um bocado (o meu ainda está rodando). Mas funciona 100% :)

Dúvidas? Comment!

* Frase atribuída a Sheldon Cooper. :)
16 Oct 2010 (updated 25 Oct 2010 at 23:12 UTC) »

Notes on GridFS and MongoDB

Today we made several tests with MongoDB’s GridFS. And, as simple as it is, we had a hard time trying to find detailed documentation and samples on C++ of this monster (on a good way ;) ).

After brushing some bits, groking headers and a very thorough analysis of the C++ driver source code, we got a simple code snippet that stores an arbitrary file on GridFS, and changes its metadata. This is the sample that worked – if you have any suggestions, please comment! :)

Enjoy!

<br />
...<br />
#include "mongo/client/dbclient.h"<br />
#include "mongo/client/gridfs.h"</p>
<p>using namespace mongo;</p>
<p>...<br />
// The file's full path<br />
m_NomeArquivo = ...;<br />
QFileInfo   info(m_NomeArquivo);</p>
<p>...<br />
DBClientConnection  c;<br />
// local connection to MongoDB.<br />
c.connect("localhost");</p>
<p>// Here we "map" GridFS with the prefix we desire<br />
GridFS      gfs     = GridFS(c, "gridfs", "myfiles");<br />
BSONObj  ret    = gfs.storeFile(m_NomeArquivo.toStdString(), info.fileName().toStdString());<br />
BSONObjBuilder  b;<br />
b.appendElements(ret);<br />
// Here we can add any additional information we want<br />
b.append("fileInserted", "0001");<br />
BSONObj o   = b.obj();</p>
<p>// And now we update the document on MongoDB.<br />
c.update("gridfs.myfiles.files", BSON("filename" << retorno.getField("filename")), o, false, false);<br />
16 Oct 2010 (updated 25 Oct 2010 at 23:12 UTC) »

Notas sobre GridFS e MongoDB

Durante o dia de hoje efetuamos vários testes com o GridFS do MongoDB. E, por mais simples que seja, achar documentação e exemplos desse monstro em C++ foi bem complicado.

Depois de escovar bits, analisar headers e analisar o código fonte do driver C++ do MongoDB, chegamos a um exemplo simples de armazenamento de arquivos genéricos no GridFS, alterando o Metadata do arquivo em questão. Esse é o exemplo que deu certo – se tiver alguma sugestão, comment! :)

Aproveitem!

...
#include "mongo/client/dbclient.h"
#include "mongo/client/gridfs.h"

using namespace mongo;

...
// pega o caminho completo do arquivo a ser salvo
m_NomeArquivo = ...;
QFileInfo   info(m_NomeArquivo);

...
DBClientConnection  c;
// conexão com o MongoDB, local.
c.connect("localhost");

// Mapeamos o GridFS com o prefixo que queremos
GridFS      gfs     = GridFS(c, "gridfs", "arquivos");
BSONObj  retorno    = gfs.storeFile(m_NomeArquivo.toStdString(), info.fileName().toStdString());
BSONObjBuilder  b;
b.appendElements(retorno);
// Aqui incluímos qualquer informação que quisermos
b.append("arquivoInserido", "0001");
BSONObj o   = b.obj();

// E atualizamos o registro do metadata no MongoDB
c.update("gridfs.arquivos.files", BSON("filename" << retorno.getField("filename")), o, false, false);
14 Oct 2010 (updated 16 Oct 2010 at 00:13 UTC) »

Back to subversion…

Almost a month ago, I started an experiment here at A&D. We use Subversion (svn) for 5 years already and never thought about switching to something else. But reading so much on the web about git, I decided that we should test it and feel the advantages in person.

As everyone around me knows, my tests usually involve a “deep dive” inside the solution. :) So, we migrated all of our code repository from svn to git. My conclusion: git is great! A formidable tool that helps the developer rethink the work cicle.

But (always a but!), its distributed nature has caused some problems for us, mainly when someone (err, me!) forgets to issue a git push. That’s why we are starting a painfully migration back to subversion.

This does mean we are stopping using git, right? Wrong. With git-svn, we can have the best from both worlds, using git for a local management, and svn for our main repository.

Oh… I really recommend Redmine. I think it’s much better than Trac for project coordination.

Syndicated 2010-10-14 14:25:05 (Updated 2010-10-16 00:09:53) from #include "ebf.h"

34 older entries...

New Advogato Features

New HTML Parser: The long-awaited libxml2 based HTML parser code is live. It needs further work but already handles most markup better than the original parser.

Keep up with the latest Advogato features by reading the Advogato status blog.

If you're a C programmer with some spare time, take a look at the mod_virgule project page and help us with one of the tasks on the ToDo list!