<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
  <title>Weekend Codes</title>
  <subtitle>Codes and random stuff I am up to share with you</subtitle>
  <link href="http://feeds.feedburner.com/weekendcodes" rel="self"/>
  <link href="http://stockrt.github.com"/>
  <updated>2011-03-15T01:49:55-03:00</updated>
  <id>http://stockrt.github.com/</id>

  
    
      <author>
        <name>Rogério Carvalho Schneider</name>
        
          <email>stockrt@gmail.com</email>
        
      </author>
    
  

  
    <entry>
      <title>Django Admin on Google App Engine</title>
      <link href="http://stockrt.github.com/p/django-admin-on-google-app-engine"/>
      <updated>2011-03-14T00:00:00-03:00</updated>
      <id>http://stockrt.github.com/p/django-admin-on-google-app-engine</id>
      <content type="html">&lt;h2&gt;Django Admin on &lt;span class=&quot;caps&quot;&gt;GAE&lt;/span&gt;&lt;/h2&gt;
&lt;p&gt;Did you ever wanted to run Django&amp;#8217;s Admin interface on Google&amp;#8217;s App Engine?&lt;br /&gt;
Now you can and we have made a live sample so you can clone, try and use it.&lt;/p&gt;
&lt;h2&gt;Here is what you want to know&lt;/h2&gt;
&lt;p&gt;This is running thanks to the projects listed below:&lt;br /&gt;
&lt;a href=&quot;http://www.allbuttonspressed.com/projects/djangoappengine&quot;&gt;djangoappengine&lt;/a&gt;&lt;br /&gt;
&lt;a href=&quot;http://www.allbuttonspressed.com/projects/django-nonrel&quot;&gt;django-nonrel&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;The real thing, a live sample&lt;/h2&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/stockrt/djangoadminongae&quot;&gt;https://github.com/stockrt/djangoadminongae&lt;/a&gt;&lt;br /&gt;
&lt;a href=&quot;http://djangoadminongae.appspot.com/admin&quot;&gt;http://djangoadminongae.appspot.com/admin&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;Starting your fresh project&lt;/h2&gt;
&lt;p&gt;Here you can find a &lt;a href=&quot;https://github.com/stockrt/djangoappengine_bootstrap&quot;&gt;djangoappengine bootstrap script&lt;/a&gt; to start a fresh&lt;br /&gt;
project like this one but with the newest possible versions of all deps. The&lt;br /&gt;
same script was used to create this sample project.&lt;/p&gt;



</content>
    </entry>
  
    <entry>
      <title>Traduzindo com pytranslate diretamente do Google</title>
      <link href="http://stockrt.github.com/p/traduzindo-com-pytranslate-diretamente-do-google"/>
      <updated>2010-01-06T00:00:00-02:00</updated>
      <id>http://stockrt.github.com/p/traduzindo-com-pytranslate-diretamente-do-google</id>
      <content type="html">&lt;p&gt;Resolvi traduzir alguns textos em lote, e para isso utilizei esse módulo chamado pytranslate.&lt;/p&gt;

&lt;p&gt;Ele é um wrapper para o Google Translate e permite que você traduza textos com facilidade. O retorno dele sempre será a sentença completa (frase) traduzida.&lt;/p&gt;

&lt;h3 id='utilizao'&gt;Utilização:&lt;/h3&gt;

&lt;pre&gt;&lt;code&gt;import pytranslate

print pytranslate.translate(&amp;#39;hello&amp;#39;, sl=&amp;#39;english&amp;#39;, tl=&amp;#39;portuguese&amp;#39;)
print pytranslate.translate(&amp;#39;hello&amp;#39;, sl=&amp;#39;auto&amp;#39;, tl=&amp;#39;portuguese&amp;#39;)
print pytranslate.translate(&amp;#39;hallo&amp;#39;, sl=&amp;#39;auto&amp;#39;, tl=&amp;#39;portuguese&amp;#39;)
print pytranslate.translate(&amp;#39;hallo&amp;#39;, sl=&amp;#39;auto&amp;#39;, tl=&amp;#39;french&amp;#39;)
print pytranslate.translate(&amp;#39;Bonjour&amp;#39;, sl=&amp;#39;auto&amp;#39;, tl=&amp;#39;dutch&amp;#39;)&lt;/code&gt;&lt;/pre&gt;

&lt;h3 id='a_instalao__simples'&gt;A instalação é simples:&lt;/h3&gt;

&lt;pre&gt;&lt;code&gt;wget --no-check-certificate https://github.com/stockrt/pytranslate/tarball/master -O pytranslate.tar.gz
tar xzvf pytranslate.tar.gz
cd stockrt-pytranslate*
./setup.py install&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Você pode obter o código do &lt;a href='http://github.com/stockrt/pytranslate'&gt;pytranslate aqui&lt;/a&gt;&lt;/p&gt;</content>
    </entry>
  
    <entry>
      <title>Navegando com segurança e sem tarifação em cafés e hotéis</title>
      <link href="http://stockrt.github.com/p/navegando-com-seguran%C3%A7a-e-sem-tarifa%C3%A7%C3%A3o-em-caf%C3%A9s-e-hot%C3%A9is"/>
      <updated>2009-09-20T00:00:00-03:00</updated>
      <id>http://stockrt.github.com/p/navegando-com-segurança-e-sem-tarifação-em-cafés-e-hotéis</id>
      <content type="html">&lt;p&gt;Quando estiver pensando em se hospedar em um hotel, ou utilizar redes de cafés, pergunte primeiro o quanto custa o minuto ou diária de acesso à internet.&lt;/p&gt;

&lt;p&gt;Normalmente o custo é alto. Se este for o caso, opte pela conexão tarifada por minuto, e use o seguinte truque para economizar alguns trocados:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Logue no sistema do hotel normalmente, optanto pela menor tarifa para pouco tempo de utilização;&lt;/li&gt;

&lt;li&gt;Execute um dos comandos abaixo, ssh ou putty;&lt;/li&gt;

&lt;li&gt;Faça logoff do sistema de tarifação;&lt;/li&gt;

&lt;li&gt;Configure seu browser e demais aplicativos para usar proxy SOCKS na porta local escolhida.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3 id='usando_linux'&gt;Usando linux&lt;/h3&gt;

&lt;p&gt;Se estiver usando linux no seu notebook, você poderá fazer o seguinte:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;ssh -D 9999 user@servidor&lt;/code&gt;&lt;/pre&gt;

&lt;h3 id='usando_windows'&gt;Usando windows&lt;/h3&gt;

&lt;p&gt;Se estiver no windows, utilize o putty:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;putty.exe -D 9999 user@servidor&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Nota: Você precisa, claro, ter um &amp;#8220;servidor&amp;#8221; rodando um sshd e uma conta nele :) Talvez o seu linux que fica rodando no desktop, em casa? Ou aquele servidor da faculdade/trabalho?&lt;/p&gt;

&lt;p&gt;Outra dica é configurar o putty para manter a sessão sempre aberta, com keepalive (Category / Connection / Seconds between keepalives / 5) ou manter a sessão ativa deixando um comando qualquer rodando no shell, que gere tráfego no terminal:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;while true; do date; sleep 5; done&lt;/code&gt;&lt;/pre&gt;

&lt;h3 id='depois_de_criado_o_proxy_dinmico'&gt;Depois de criado o proxy dinâmico&lt;/h3&gt;

&lt;p&gt;Agora você pode fazer logoff do sistema de internet tarifado e então apontar o firefox, ou qualquer outra aplicação (uma nova sessão de ssh, por exemplo), para o proxy dinâmico local, que agora ouve na porta local 9999.&lt;/p&gt;

&lt;p&gt;&lt;a href='http://vectrosecurity.com/content/view/67/26'&gt;Outros&lt;/a&gt; &lt;a href='http://www.nardol.org/2009/3/9/maceio-took-some-days-off'&gt;posts&lt;/a&gt; também descrevem essa técnica.&lt;/p&gt;

&lt;p&gt;Com essas medidas você pode economizar no acesso, além de garantir uma navegação muito mais segura na internet, pois tudo será tunelado e codificado pelo ssh.&lt;/p&gt;

&lt;p&gt;Enjoy the hacking.&lt;/p&gt;</content>
    </entry>
  
    <entry>
      <title>handling html forms with python mechanize and BeautifulSoup</title>
      <link href="http://stockrt.github.com/p/handling-html-forms-with-python-mechanize-and-BeautifulSoup"/>
      <updated>2009-09-14T00:00:00-03:00</updated>
      <id>http://stockrt.github.com/p/handling-html-forms-with-python-mechanize-and-BeautifulSoup</id>
      <content type="html">&lt;p&gt;In the post about &lt;a href='http://stockrt.github.com/p/emulating-a-browser-in-python-with-mechanize'&gt;emulating a browser in python with mechanize&lt;/a&gt; I have showed you how to make some basic tricks in the web with python, but I have not showed how to login a site and how to handle a session, with html forms, links and cookies.&lt;/p&gt;

&lt;p&gt;Here I will show it all for you, let&amp;#8217;s see it.&lt;/p&gt;

&lt;p&gt;First, you must install some dependecies:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;easy_install BeautifulSoup
easy_install html2text&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Then, let the code speak:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;import mechanize
import cookielib
from BeautifulSoup import BeautifulSoup
import html2text

# Browser
br = mechanize.Browser()

# Cookie Jar
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)

# Browser options
br.set_handle_equiv(True)
br.set_handle_gzip(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)

# Follows refresh 0 but not hangs on refresh &amp;gt; 0
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)

# User-Agent (this is cheating, ok?)
br.addheaders = [(&amp;#39;User-agent&amp;#39;, &amp;#39;Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1&amp;#39;)]

# The site we will navigate into, handling it&amp;#39;s session
br.open(&amp;#39;http://gmail.com&amp;#39;)

# Select the first (index zero) form
br.select_form(nr=0)

# User credentials
br.form[&amp;#39;Email&amp;#39;] = &amp;#39;user&amp;#39;
br.form[&amp;#39;Passwd&amp;#39;] = &amp;#39;password&amp;#39;

# Login
br.submit()

# Filter all links to mail messages in the inbox
all_msg_links = [l for l in br.links(url_regex=&amp;#39;\?v=c&amp;amp;th=&amp;#39;)]
# Select the first 3 messages
for msg_link in all_msg_links[0:3]:
    print msg_link
    # Open each message
    br.follow_link(msg_link)
    html = br.response().read()
    soup = BeautifulSoup(html)
    # Filter html to only show the message content
    msg = str(soup.findAll(&amp;#39;div&amp;#39;, attrs={&amp;#39;class&amp;#39;: &amp;#39;msg&amp;#39;})[0])
    # Show raw message content
    print msg
    # Convert html to text, easier to read but can fail if you have intl
    # chars
#   print html2text.html2text(msg)
    print
    # Go back to the Inbox
    br.follow_link(text=&amp;#39;Inbox&amp;#39;)

# Logout
br.follow_link(text=&amp;#39;Sign out&amp;#39;)&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The basic flow is:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Open the site and login;&lt;/li&gt;

&lt;li&gt;Session is handled by cookiejar, automatically;&lt;/li&gt;

&lt;li&gt;We list the first 3 mail messages;&lt;/li&gt;

&lt;li&gt;For each mail message, we open it and read it&amp;#8217;s contents;&lt;/li&gt;

&lt;li&gt;We go back to the Inbox and to the next mail message;&lt;/li&gt;

&lt;li&gt;All done, we can logoff;&lt;/li&gt;

&lt;li&gt;The first 3 mail messages will have it&amp;#8217;s status changed to &amp;#8220;read&amp;#8221; if you look at it in the gmail web interface.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;You may ask, how do I know the name of the form fields to fill?&lt;/p&gt;

&lt;p&gt;We can inspect it, before filling:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;# Open the site
br.open(&amp;#39;http://gmail.com&amp;#39;)

# Forms
for f in br.forms():
    print f&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The output contains the fields to fill in the form:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;...
&amp;lt;TextControl(Email=)&amp;gt;
&amp;lt;PasswordControl(Passwd=)&amp;gt;
...&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And the rest you already know.&lt;/p&gt;

&lt;p&gt;Why gmail? It was only an example. I know we have &lt;a href='http://libgmail.sourceforge.net'&gt;libgmail&lt;/a&gt; , but again, it was only an example, with login forms and a session to handle :)&lt;/p&gt;</content>
    </entry>
  
    <entry>
      <title>git branch in your shell prompt</title>
      <link href="http://stockrt.github.com/p/git-branch-in-your-shell-prompt"/>
      <updated>2009-08-31T00:00:00-03:00</updated>
      <id>http://stockrt.github.com/p/git-branch-in-your-shell-prompt</id>
      <content type="html">&lt;p&gt;Every time (every few minutes?) I was looking at my git versioned projects (all my projects?) I encounter myself in doubt:&lt;/p&gt;

&lt;p&gt;Am I at the branch I think I am?&lt;/p&gt;

&lt;p&gt;And there was I, issuing a &amp;#8220;git branch&amp;#8221; command to check it&amp;#8230;&lt;/p&gt;

&lt;p&gt;That is enough! I said.&lt;/p&gt;

&lt;p&gt;Looking at the &lt;a href='http://github.com/guides'&gt;github guides&lt;/a&gt; I found &lt;a href='http://github.com/guides/put-your-git-branch-name-in-your-shell-prompt'&gt;this tip&lt;/a&gt; very interesting, so I decided to bettered it, and to publish as a tip here.&lt;/p&gt;

&lt;p&gt;It will show in your prompt which is your current branch, when your current work directory is a git initialized one.&lt;/p&gt;

&lt;p&gt;To use it, just place this line inside your ~/.bashrc or into /etc/profile.d/git-branch.sh or /etc/bashrc or even /etc/profile, the choice is yours:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;# git branch
parse_git_branch() {
    git branch 2&amp;gt; /dev/null | sed -e &amp;#39;/^[^*]/d&amp;#39; -e &amp;#39;s/* \(.*\)/(\1) /&amp;#39;
}
PS1=&amp;quot;\$(parse_git_branch)$PS1&amp;quot;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This will give you a prompt like this one:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;stockrt@jackbauer ~ $ cd Dropbox/stockrt/git/stockrt.github.com
(master) stockrt@jackbauer ~/Dropbox/stockrt/git/stockrt.github.com $&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here you can see a &amp;#8220;normal&amp;#8221; prompt and then, when I enter one of my git versioned directories, a &amp;#8220;git branchned&amp;#8221; prompt.&lt;/p&gt;

&lt;p&gt;Way cool.&lt;/p&gt;</content>
    </entry>
  
    <entry>
      <title>Browser cache invalidation with Javascript and querystring</title>
      <link href="http://stockrt.github.com/p/browser-cache-invalidation-with-javascript-and-querystring"/>
      <updated>2009-08-30T00:00:00-03:00</updated>
      <id>http://stockrt.github.com/p/browser-cache-invalidation-with-javascript-and-querystring</id>
      <content type="html">&lt;p&gt;Some time ago I started my blog here at github and noticed that new posts didn&amp;#8217;t come live right way I published them.&lt;/p&gt;

&lt;p&gt;Quickly I spot the problem: They are sending &lt;a href='http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.21'&gt;HTTP Cache Headers&lt;/a&gt; for the index.html and all pages served by github, a 24 hour cache.&lt;/p&gt;

&lt;h3 id='the_problem'&gt;The problem&lt;/h3&gt;

&lt;pre&gt;&lt;code&gt;$ curl -I http://stockrt.github.com

HTTP/1.1 200 OK
Server: nginx/0.6.31
Date: Sat, 22 Aug 2009 01:36:49 GMT
Content-Type: text/html
Content-Length: 66829
Last-Modified: Sat, 22 Aug 2009 01:12:50 GMT
Connection: keep-alive
Expires: Sun, 23 Aug 2009 01:36:49 GMT
Cache-Control: max-age=86400
Accept-Ranges: bytes&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;So, to overcome this &amp;#8220;problem&amp;#8221; I made this tiny trick, and published it to others to take advantage of it, in case your are hosting your pages behind an web server with &lt;a href='http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.21'&gt;Expires&lt;/a&gt; configured.&lt;/p&gt;

&lt;h3 id='the_trick'&gt;The trick&lt;/h3&gt;

&lt;p&gt;Go and clone &lt;a href='http://github.com/stockrt/cache_invalidation'&gt;cache_invalidation&lt;/a&gt; and start using the provided javascripts in your site, this way:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;html&amp;gt;

&amp;lt;head&amp;gt;
 &amp;lt;script src=&amp;quot;http://your_site/javascripts/querystring.js&amp;quot; type=&amp;quot;text/javascript&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;
 &amp;lt;script src=&amp;quot;http://your_site/javascripts/cache_invalidation.js&amp;quot; type=&amp;quot;text/javascript&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;/head&amp;gt;

&amp;lt;body&amp;gt;
&amp;lt;/body&amp;gt;

&amp;lt;/html&amp;gt;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Set the desired TTL inside de cache_invalidation.js file:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;// TTL: set your cache threshold here
var ttl = 300;  // seconds&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And it is all set.&lt;/p&gt;

&lt;h3 id='but_why_does_it_happen_and_how_it_works'&gt;But, why does it happen, and how it works?&lt;/h3&gt;

&lt;p&gt;It does happen because their web server (&lt;a href='http://nginx.net/'&gt;the great nginx&lt;/a&gt;) is configured with what we used to call &lt;a href='http://httpd.apache.org/docs/2.2/mod/mod_expires.html'&gt;mod_expires&lt;/a&gt; in &lt;a href='http://httpd.apache.org'&gt;Apache&lt;/a&gt;. This module activates the &lt;a href='http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.21'&gt;Expires&lt;/a&gt; &lt;a href='http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.21'&gt;HTTP Cache Header&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;If you look at the response headers I got before, you would see:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Date: Sat, 22 Aug 2009 01:36:49 GMT
Expires: Sun, 23 Aug 2009 01:36:49 GMT&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;and:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Cache-Control: max-age=86400&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Notice that:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;$ bc &amp;lt;&amp;lt;&amp;lt; 86400/3600
24&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;They are saying to my browser that it should use the local copy, for the next 24 hours, when accessing this site. More precisely, when accessing index.html of this site.&lt;/p&gt;

&lt;p&gt;I think that, for a blog, this is a pretty big time to update the user&amp;#8217;s cache. This cache header means that if a reader accessed you site just before your posted something, and returned to your site after you posted, he would not see any difference. He would only notice your new post the next day.&lt;/p&gt;

&lt;p&gt;But, you can bypass that, just passing any query string within the site&amp;#8217;s address to the navigation bar in your browser.&lt;/p&gt;

&lt;p&gt;This tricks the browser to go in the source and to fetch the page, instead of using a local copy. It would only use a local copy if you have no query string or if you have already cached that url with that query string (say, in a second time you visit the same query string).&lt;/p&gt;

&lt;p&gt;Just because the browser would cache the same query string in a second access, I made the script to vary it on each access, and also it forces a refresh when accessing a querystring that is TTL seconds older than the current time, even if it is already cached from a previous access, say, when clicking a bookmark.&lt;/p&gt;

&lt;p&gt;As a front end engineer I am, I only pray to my web developer colleagues don&amp;#8217;t find this post, ever :)&lt;/p&gt;</content>
    </entry>
  
    <entry>
      <title>Finding the next prime number from a given number</title>
      <link href="http://stockrt.github.com/p/finding-the-next-prime-number-from-a-given-number"/>
      <updated>2009-08-29T00:00:00-03:00</updated>
      <id>http://stockrt.github.com/p/finding-the-next-prime-number-from-a-given-number</id>
      <content type="html">&lt;p&gt;Finding the next prime number online is useful if you do not have time to calculate it but need a good seed for your hash.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;export start_number=250000
curl -s &amp;quot;http://www.numberempire.com/primenumbers.php?action=next&amp;amp;number=${start_number}&amp;quot; | sed -n -e &amp;#39;s#.*The smallest prime greater than.*&amp;lt;font color=.*&amp;gt;\(.*\)&amp;lt;/font&amp;gt;&amp;lt;/div&amp;gt;&amp;lt;/td&amp;gt;&amp;lt;/tr&amp;gt;&amp;lt;tr&amp;gt;.*#\1#p&amp;#39;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This can be good the help you finding which number to use when &lt;a href='http://varnish.projects.linpro.no/wiki/Performance'&gt;tuning&lt;/a&gt; &lt;a href='http://varnish.projects.linpro.no'&gt;Varnish&lt;/a&gt; for better &lt;a href='http://varnish.projects.linpro.no/wiki/Performance'&gt;performance&lt;/a&gt; with the classic hash algorithm, avoiding bucket collision when having a big number of objects, making hash lookups faster.&lt;/p&gt;</content>
    </entry>
  
    <entry>
      <title>sed quick tips</title>
      <link href="http://stockrt.github.com/p/sed-quick-tips"/>
      <updated>2009-08-28T00:00:00-03:00</updated>
      <id>http://stockrt.github.com/p/sed-quick-tips</id>
      <content type="html">&lt;p&gt;A little collection of sed tips.&lt;/p&gt;

&lt;h3 id='the_basic_one_substitution'&gt;The basic one, substitution&lt;/h3&gt;

&lt;p&gt;You already know this one:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;sed -i &amp;#39;s/old text/new text/g&amp;#39; file.txt&lt;/code&gt;&lt;/pre&gt;

&lt;h3 id='deleting_all_lines_containing_an_specific_text'&gt;Deleting all lines containing an specific text&lt;/h3&gt;

&lt;pre&gt;&lt;code&gt;sed -i -e &amp;#39;/this line will disapear/d&amp;#39; file.txt&lt;/code&gt;&lt;/pre&gt;

&lt;h3 id='deleting_blank_lines'&gt;Deleting blank lines&lt;/h3&gt;

&lt;pre&gt;&lt;code&gt;sed -i -e &amp;#39;/^$/d&amp;#39; file.txt&lt;/code&gt;&lt;/pre&gt;

&lt;h3 id='filtering_text_between_delimiters'&gt;Filtering text between delimiters&lt;/h3&gt;

&lt;p&gt;All matching text into the first defined group &amp;#8220;()&amp;#8221; will be printed:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;curl -s -L http://www.terra.com.br | sed -n -e &amp;#39;s#.*\(http://.*\.\(js\|css\)\).*#\1#p&amp;#39;&lt;/code&gt;&lt;/pre&gt;

&lt;h3 id='printing_only_from_a_given_line_number_to_another'&gt;Printing only from a given line number to another&lt;/h3&gt;

&lt;p&gt;Prints from line 20 to line 30:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;sed -n 20,30p file.txt&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;More tips can be found &lt;a href='http://sed.sourceforge.net/sed1line.txt'&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Do you know some trick that is worth sharing? Please post it as a comment!&lt;/p&gt;</content>
    </entry>
  
    <entry>
      <title>Sunset in Porto Alegre</title>
      <link href="http://stockrt.github.com/p/sunset-in-porto-alegre"/>
      <updated>2009-08-16T00:00:00-03:00</updated>
      <id>http://stockrt.github.com/p/sunset-in-porto-alegre</id>
      <content type="html">&lt;p&gt;Beautiful sunset in the capital city of Rio Grande do Sul, Brazil.&lt;/p&gt;

&lt;p&gt;&lt;img src='http://stockrt.github.com/images/misc/pordosolnoguaiba.jpg' alt='' /&gt;&lt;/p&gt;

&lt;p&gt;My wife and I decided to take some of our spare time to appreciate that.&lt;/p&gt;

&lt;p&gt;Do you think it was worth?&lt;/p&gt;</content>
    </entry>
  
    <entry>
      <title>Emulating a Browser in Python with mechanize</title>
      <link href="http://stockrt.github.com/p/emulating-a-browser-in-python-with-mechanize"/>
      <updated>2009-08-16T00:00:00-03:00</updated>
      <id>http://stockrt.github.com/p/emulating-a-browser-in-python-with-mechanize</id>
      <content type="html">&lt;p&gt;It is always useful to know how to quickly instantiate a browser in the command line or inside your python scripts.&lt;/p&gt;

&lt;p&gt;Every time I need to automate any task regarding web systems I do use this recipe to emulate a browser in python:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;import mechanize
import cookielib

# Browser
br = mechanize.Browser()

# Cookie Jar
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)

# Browser options
br.set_handle_equiv(True)
br.set_handle_gzip(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)

# Follows refresh 0 but not hangs on refresh &amp;gt; 0
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)

# Want debugging messages?
#br.set_debug_http(True)
#br.set_debug_redirects(True)
#br.set_debug_responses(True)

# User-Agent (this is cheating, ok?)
br.addheaders = [(&amp;#39;User-agent&amp;#39;, &amp;#39;Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1&amp;#39;)]&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now you have this &lt;em&gt;br&lt;/em&gt; object, this is your browser instance. With this its possible to open a page, to inspect or to interact with:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;# Open some site, let&amp;#39;s pick a random one, the first that pops in mind:
r = br.open(&amp;#39;http://google.com&amp;#39;)
html = r.read()

# Show the source
print html
# or
print br.response().read()

# Show the html title
print br.title()

# Show the response headers
print r.info()
# or
print br.response().info()

# Show the available forms
for f in br.forms():
    print f

# Select the first (index zero) form
br.select_form(nr=0)

# Let&amp;#39;s search
br.form[&amp;#39;q&amp;#39;]=&amp;#39;weekend codes&amp;#39;
br.submit()
print br.response().read()

# Looking at some results in link format
for l in br.links(url_regex=&amp;#39;stockrt&amp;#39;):
    print l&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If you are about to access a password protected site (http basic auth):&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;# If the protected site didn&amp;#39;t receive the authentication data you would
# end up with a 410 error in your face
br.add_password(&amp;#39;http://safe-site.domain&amp;#39;, &amp;#39;username&amp;#39;, &amp;#39;password&amp;#39;)
br.open(&amp;#39;http://safe-site.domain&amp;#39;)&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Thanks to the Cookie Jar we&amp;#8217;ve added before, you do not have to bother about session handling for authenticated sites, as in when you are accessing a service that requires a POST (form submit) of user and password. Usually they ask your browser to store a session cookie and expects your browser to contain that same cookie when re-accessing the page. All this, storing and re-sending the session cookies, is done by the Cookie Jar, neat!&lt;/p&gt;

&lt;p&gt;You can also manage with browsing history:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;# Testing presence of link (if the link is not found you would have to
# handle a LinkNotFoundError exception)
br.find_link(text=&amp;#39;Weekend codes&amp;#39;)

# Actually clicking the link
req = br.click_link(text=&amp;#39;Weekend codes&amp;#39;)
br.open(req)
print br.response().read()
print br.geturl()

# Back
br.back()
print br.response().read()
print br.geturl()&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Downloading a file:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;# Download
f = br.retrieve(&amp;#39;http://www.google.com.br/intl/pt-BR_br/images/logo.gif&amp;#39;)[0]
print f
fh = open(f)&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Setting a proxy for your http navigation:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;# Proxy and user/password
br.set_proxies({&amp;quot;http&amp;quot;: &amp;quot;joe:password@myproxy.example.com:3128&amp;quot;})

# Proxy
br.set_proxies({&amp;quot;http&amp;quot;: &amp;quot;myproxy.example.com:3128&amp;quot;})
# Proxy password
br.add_proxy_password(&amp;quot;joe&amp;quot;, &amp;quot;password&amp;quot;)&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;But, if you just want to quickly open an webpage, without the fancy features above, just issue that:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;# Simple open?
import urllib2
print urllib2.urlopen(&amp;#39;http://stockrt.github.com&amp;#39;).read()

# With password?
import urllib
opener = urllib.FancyURLopener()
print opener.open(&amp;#39;http://user:password@stockrt.github.com&amp;#39;).read()&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;See more in &lt;a href='http://wwwsearch.sourceforge.net/mechanize'&gt;Python mechanize site&lt;/a&gt; , &lt;a href='http://wwwsearch.sourceforge.net/mechanize/doc.html'&gt;mechanize docs&lt;/a&gt; and &lt;a href='http://wwwsearch.sourceforge.net/ClientForm'&gt;ClientForm docs&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Also, I have made this post to elucidate how to &lt;a href='http://stockrt.github.com/p/handling-html-forms-with-python-mechanize-and-BeautifulSoup'&gt;handle html forms and sessions with python mechanize and BeautifulSoup&lt;/a&gt;&lt;/p&gt;</content>
    </entry>
  
    <entry>
      <title>Listing GitHub projects in your blog</title>
      <link href="http://stockrt.github.com/p/listing-github-projects-in-your-blog"/>
      <updated>2009-08-15T00:00:00-03:00</updated>
      <id>http://stockrt.github.com/p/listing-github-projects-in-your-blog</id>
      <content type="html">&lt;p&gt;I needed to list my GitHub projects in a fancy way inside my blog, in the sidebar, all dynamically done. So, I searched a little around and found how.&lt;/p&gt;

&lt;p&gt;There are two major badges to do it, here I will describe them:&lt;/p&gt;

&lt;h3 id='dr_nics_githubbadges'&gt;Dr Nic&amp;#8217;s github-badges&lt;/h3&gt;

&lt;p&gt;This is my choice. &lt;a href='http://drnic.github.com/github-badges'&gt;drnic&amp;#8217;s github-badges&lt;/a&gt; is flexible on configuration and also have some code of myself in it.&lt;/p&gt;

&lt;p&gt;Here is how to configure it:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;div id=&amp;quot;github-badge&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;
&amp;lt;script type=&amp;quot;text/javascript&amp;quot; charset=&amp;quot;utf-8&amp;quot;&amp;gt;
  GITHUB_USERNAME=&amp;quot;stockrt&amp;quot;;
&amp;lt;/script&amp;gt;
&amp;lt;script src=&amp;quot;http://drnic.github.com/github-badges/dist/github-badge-launcher.js&amp;quot; type=&amp;quot;text/javascript&amp;quot;&amp;gt;&amp;lt;/script&amp;gt;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is the complete list of options available:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;GITHUB_USERNAME = &amp;quot;stockrt&amp;quot;;
GITHUB_LIST_LENGTH = 10;
GITHUB_HEAD = &amp;quot;div&amp;quot;; // e.g. change to &amp;quot;h2&amp;quot; for wordpress sidebars
GITHUB_THEME = &amp;quot;white&amp;quot;; // try &amp;#39;black&amp;#39;
GITHUB_TITLE = &amp;quot;My projects&amp;quot;;
GITHUB_SHOW_ALL = &amp;quot;Show all&amp;quot;;
GITHUB_SHOW_FORK = 1;&lt;/code&gt;&lt;/pre&gt;

&lt;h3 id='subtlegradients_mootoolsgithubbadge'&gt;subtleGradient&amp;#8217;s mootools-github-badge:&lt;/h3&gt;

&lt;p&gt;This is also pretty neat, &lt;a href='http://github.com/subtleGradient/mootools-github-badge'&gt;subtleGradient&amp;#8217;s mootools-github-badge&lt;/a&gt; has a great visual effect when it is building the project&amp;#8217;s list, using a delayed composal. See this &lt;a href='http://subtlegradient.github.com/mootools-github-badge'&gt;running example&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Here is how to configure it:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;div id=&amp;quot;github-badge&amp;quot;&amp;gt;&amp;lt;/div&amp;gt;
&amp;lt;script src=&amp;quot;http://ajax.googleapis.com/ajax/libs/mootools/1.2.1/mootools.js&amp;quot; type=&amp;quot;text/javascript&amp;quot;&amp;gt; &amp;lt;/script&amp;gt;
&amp;lt;script src=&amp;quot;http://projects.subtlegradient.com/mootools-subtle-templates/Source/Plugins/SubtleTemplate.js&amp;quot; type=&amp;quot;text/javascript&amp;quot;&amp;gt; &amp;lt;/script&amp;gt;
&amp;lt;script src=&amp;quot;http://subtlegradient.github.com/mootools-github-badge/mootools-github-badge.js&amp;quot; type=&amp;quot;text/javascript&amp;quot;&amp;gt; &amp;lt;/script&amp;gt;
&amp;lt;script type=&amp;quot;text/javascript&amp;quot; charset=&amp;quot;utf-8&amp;quot;&amp;gt;
  new SubtleTemplate.GitHubBadge.Basic({ username:&amp;#39;stockrt&amp;#39; });
&amp;lt;/script&amp;gt;&lt;/code&gt;&lt;/pre&gt;

&lt;h3 id='using_jekyll_and_scribbish_from_stockrts_site_source'&gt;Using jekyll and scribbish from &lt;a href='http://github.com/stockrt/stockrt.github.com/tree/master/site'&gt;stockrt&amp;#8217;s site source&lt;/a&gt;&lt;/h3&gt;

&lt;p&gt;If you are using my template to generated a &lt;a href='http://stockrt.github.com/p/iniciando-um-blog-no-github'&gt;scribbish styled static site with jekyll (pt-BR)&lt;/a&gt;, all you need to do to activate the use of drnic&amp;#8217;s github-badge is to configure this parameters in config.yml:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;github_badge:
    enable: true
    username: stockrt
    length: 8
    head: div
    #head: h2
    theme: white
    #theme: black
    title: My Projects
    showall: Show all
    showfork: 0
    #showfork: 1&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;All said, I must warn you that these two badges do not really behave well on IE 6, but who still uses it today? Better upgrade to Firefox, folks!&lt;/p&gt;</content>
    </entry>
  
    <entry>
      <title>Como converter datas e timestamps no linux usando o comando date</title>
      <link href="http://stockrt.github.com/p/como-converter-datas-e-timestamps-no-linux-usando-o-comando-date"/>
      <updated>2009-08-02T00:00:00-03:00</updated>
      <id>http://stockrt.github.com/p/como-converter-datas-e-timestamps-no-linux-usando-o-comando-date</id>
      <content type="html">&lt;p&gt;Se você chegou até aqui, anote esta dica.&lt;/p&gt;

&lt;p&gt;Uma hora ou outra a gente sempre chega neste problema: Converter datas com timestamp, seja de timestamp para string ou o contrário.&lt;/p&gt;

&lt;p&gt;Pois ai vai a dica para converter datas no Linux:&lt;/p&gt;

&lt;h3 id='string_da_data_atual'&gt;String da data atual&lt;/h3&gt;

&lt;pre&gt;&lt;code&gt;$ date
Sun Aug  2 03:13:19 2009&lt;/code&gt;&lt;/pre&gt;

&lt;h3 id='timestamp_seconds_from_the_epoch_da_data_atual'&gt;Timestamp (seconds from the Epoch) da data atual&lt;/h3&gt;

&lt;pre&gt;&lt;code&gt;$ date +&amp;quot;%s&amp;quot;
1249193599&lt;/code&gt;&lt;/pre&gt;

&lt;h3 id='timestamp_de_uma_determinada_string_de_data'&gt;Timestamp de uma determinada string de data&lt;/h3&gt;

&lt;pre&gt;&lt;code&gt;$ date -d &amp;#39;2009-07-31 12:00:01&amp;#39; +&amp;quot;%s&amp;quot;
1249052401&lt;/code&gt;&lt;/pre&gt;

&lt;h3 id='string_de_data_a_partir_de_um_determinado_timestamp'&gt;String de data a partir de um determinado timestamp&lt;/h3&gt;

&lt;pre&gt;&lt;code&gt;$ python -c &amp;quot;import time; print time.ctime(1249052401)&amp;quot;
Fri Jul 31 12:00:01 2009&lt;/code&gt;&lt;/pre&gt;</content>
    </entry>
  
    <entry>
      <title>Iniciando um blog no GitHub</title>
      <link href="http://stockrt.github.com/p/iniciando-um-blog-no-github"/>
      <updated>2009-07-19T00:00:00-03:00</updated>
      <id>http://stockrt.github.com/p/iniciando-um-blog-no-github</id>
      <content type="html">&lt;p&gt;Use jekyll, facilita a sua vida.&lt;/p&gt;

&lt;p&gt;Estou usando o GitHub para hospedar meu blog/site, mas como ele não oferece nenhuma engine dinâmica de blog, tipo wordpress ou alguma outra feita em php, python, ruby&amp;#8230;, estou gerando o site estaticamente e depois faço o upload para o GitHub. Uso jekyll para gerar o site, criar as co-relações entre posts, fazer a formatação, paginação, lista de tags, links e blogroll.&lt;/p&gt;

&lt;p&gt;Jekyll é muito legal, vale a pena dar uma olhada. Com esse modelo de geração estática é possível se fazer posts com apenas alguns passos:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;cd yournickname.github.com/site
./new_post.sh &amp;quot;Nome do post&amp;quot;
vi _posts/$(date +&amp;quot;%Y-%m-%d&amp;quot;)-nome-do-post.markdown
./build.sh; cd ..
git add .
git commit -a -m &amp;#39;New blog post&amp;#39;
git push origin master&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Eu gosto dessa forma de &amp;#8220;bloggar&amp;#8221; pois assim evito de entrar em editores HTML ou páginas web lentas. Faço tudo daqui do meu shell mesmo, onde me sinto mais à vontade :)&lt;/p&gt;

&lt;p&gt;A formatação dos textos é feita usando &lt;a href='http://daringfireball.net/projects/markdown/syntax'&gt;markdown&lt;/a&gt;, bem mais fácil do que HTML para postar da forma como escolhi, pelo shell.&lt;/p&gt;

&lt;p&gt;Recomendo ler um pequeno texto que fiz informando sobre como usar o template para jekyll que eu modifiquei:&lt;/p&gt;

&lt;p&gt;&lt;a href='http://github.com/stockrt/stockrt.github.com/tree/master'&gt;http://github.com/stockrt/stockrt.github.com/tree/master&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Outra dica: No link &lt;a href='http://stockrt.github.com/projects'&gt;Projects&lt;/a&gt; ao lado você poderá encontrar algo útil. Se sim, me avisa.&lt;/p&gt;</content>
    </entry>
  
</feed>
