Planeta PythonBrasil

January 31, 2012

PUG - PE

Mailson Lira apresentando seu trabalho com OpenCv + python

Olá pessoal,

Neste último sábado (28.01.2012) realizamos o primeiro encontro do ano de 2012: O XVIII Encontro do Grupo de Usuários de Python de Pernambuco. Este foi sediado no Anfiteatro do Centro de Informática da Universidade Federal de Pernambuco com a presença moderada de vários membros e um novo público presente. Contamos com as palestras principais de Túlio Caraciolo da Manifesto Games Studio, Marcel Caraciolo da Orygens e várias palestras-relâmpago.

Algumas fotos do público presente:

Público no Encontro do PUG-PE

Público no Encontro do PUG-PE

Público no XVIII Encontro do PUG-PE

Público no XVIII Encontro do PUG-PE

Antes de começarmos o resumo do evento, gostaríamos de agradecer aos membros que ajudaram a organizar o evento, não precisarei citar nomes, então todos que ajudaram ou contribuíram, muito obrigado! Quero destacar um agradecimento especial ao membro Renato Oliveira do Departamento Acadêmico do CIN/UFPE que está fazendo um excelente trabalho divulgando as comunidades open-source em Pernambuco dentro do CIN, graças ao D.A. pudemos realizar este encontro novamente no CIN/UFPE. E por fim aos nossos patrocinadores: as empresas Idealizza (@idealizza), Orygens (@orygens) e a Hostech pelo apoio e ajuda de custos para os brindes e coffee-break! :D

A primeira palestra do dia foi ministrada por Marcel Caraciolo (@marcelcaraciolo) com a apresentação intitucional “O que é o PUG-PE”. Nesta palestra ele apresentou o grupo aos novos membros e também apresentou algumas métricas de uma enquete realizada em 2011 do perfil de desenvolvedores Python em Pernambuco. Vale a pena dar uma olhada nos slides da apresentação para entender um pouco melhor o cenário de Python em Pernambuco!

Slides

A próxima palestra foi ministrada por Túlio Caraciolo (@tuliocaraciolo ) que apresentou “Como Python auxilia na construção de jogos”.  Uma palestra muito boa, bem detalhada e inclusivo com código-fonte da palestra rs rs!  Ele apresentou em detalhes como Python auxiliou na construção de diversos jogos na sua empresa em especial nas atividades de manipulação de arquivos e de sistema operacional. Recomendo a todos a olharem com carinho sua palestra! E muitos podem entender como Python também pode ser aplicado a jogos! Destaque à construção de bots no BattleField que é em Python!!! :D :D

Slides da Palestra de Túlio

Túlio apresentando os jogos da Manifesto

Túlio apresentando os jogos da Manifesto

Python + Battlefield

Python + Battlefield

A próxima palestra foi de Marcel Caraciolo (@marcelcaraciolo) que apresentou sobre processamento de linguagem natural com a ferramenta NLTK , em especial, como pré-processar e lidar com textos em língua portuguesa brasileira. Ele comentou passo -a-passo o fluxo de mineração de textos, com exemplos em classificação de textos e por fim sua maior contribuição está na ajuda de um projeto com o grupo de línguistica computacional da UFCE liderado pelo professor Leonel onde constroem um  conjunto de ferramentas para tratamento e processamento em textos de língua portuguesa brasileira chamado Aelius Donatus, totalmente open-source!

Marcel Caraciolo apresentando sobre NLP com Português

Marcel Caraciolo apresentando sobre NLP com Português

Slides em breve.

Por fim a última parte do evento foi dedicada às palestras-relâmpago! Tivemos 5 palestras-relâmpago ao todo! A primeira foi sobre o sistema de cursos e treinamento de Python e suas aplicações à distância chamado PyCursos criado por Marcel Caraciolo e Gileno Filho. Eles fundaram este projeto como meio de ensinar e divulgar a linguagem Python por meio de uma plataforma de ensino à distância similar aos cursos on-line oferecidso nos mesmos modelos em Stanford. Nestes cursos o aluno poderá assistir video-aulas em sua casa a qualquer hora e quantas vezes quiser até o final do curso e poder discutir por meio de foruns e resolver exercicios por meio de exercicios on-line e programação! Atualmente estão acontecendo os cursos de Computação Científica com Python e Desenvolvedor Python. A idéia é lançar mais cursos durante o semestre!

Slides

A próxima palestra foi ministrada por Jonas Xavier, estudante do IFPE, que falou sobre o seu trabalho com a Wikipedia em um projeto open-source sobre mineração de dados.  Ele fala sobre seu trabalho junto à organização,  o status atual e como outros podem contribuir nesta área de mineração com textos da Wikipedia.

Jonas apresentando seu trabalho junto ao Wikipedia

Jonas apresentando seu trabalho junto ao Wikipedia

Slides

A próxima palestra relâmpago foi ministrada por Mailson Lira que apresentou como Python ajudou em um dos projetos de uma disciplina cursada por ele no seu curso focado em Realidade Aumentada. Ele apresentou o OpenCv com um trabalho muito legal onde ele simulou ações do Kinect por meio de Python que permite acessar a webcam do seu computador e manipular em tempo real as imagens capturadas por ela. O resultado foi um joguinho bem legal de estourar bolas por meio de uma câmera onde as pessoas com as mão poderiam estourar as bolinhas.

Código-fonte aqui.

Mailson Lira apresentando seu trabalho com OpenCv + python

Mailson Lira apresentando seu trabalho com OpenCv + python

A próxima palestra foi de Marcel Caraciolo sobre o PyFoursquare, que é uma biblioteca para acessar a API da rede social de localização móvel Foursquare em Python. O trabalho que foi resultado do seu trabalho de mestrado (1 deles) foi reorganizado e disponibilizado em projeto open-source para que outros desenvolvedores pudessem contribuir e usar o projeto.  Seu projeto já foi inclusive listado em uma das bibliotecas oficiais de Python para Foursquare!

Slides

A última palestra foi uma discussão entre os membros presentes sobre como será organizado o XX Encontro do Grupo de Usuários de Python de Pernambuco, que pretende comemorar os 20 encontros com um encontro especial envolvendo palestrantes de fora, sorteio de brindes, open-spaces e muitas outras atividades. Em breve estaremos informando mais detalhes em como estaremos recebendo colaborações. Recomendo acessar a nossa lista de discussão do grupo e acompanhar nossas threads para mais detalhes!

E  assim terminamos mais um encontro do PUG-PE, muito networking, muita informação e troca de conhecimento! Evento muito bem realizado e acredito ter agradado a todos!  Até o próximo XIX!

Fotos do encontro podem ser encontradas aqui.

Atenciosamente,

Marcel Caraciolo

Links para os assuntos discutidos


por marcelcaraciolo em 31 de January de 2012 às 03:06

January 24, 2012

Eventos da APyB

XVIII Encontro do Grupo de Usuários de Python PE

 Neste encontro teremos a participação das empresas Manifesto Game Studio com uma palestra sobre o uso de Python para auxiliar na construção de jogos  (para os fãs de jogos vai ser uma ótima oportunidade) por Túlio Caraciolo e  sobre processamento de linguagem natural com língua portuguesa com o uso da plataforma Python pela empresa Orygens com Marcel Caraciolo.  Teremos várias palestras relâmpago sobre temas variados englobando concorrência, software livre, frameworks web, etc.

 

Para os que não conhecem Python, eis uma excelente oportunidade de conhecer uma das linguagens de programação que mais crescem na comunidade open-source e possui várias aplicações em nichos como web, jogos, sistemas embarcados, computação científica, segurança, etc.

por Érico Andrei em 24 de January de 2012 às 11:37

January 23, 2012

Elcio Luiz Ferreira

Assalto

Na última quinta-feira, indo para casa, fui assaltado. Havia deixado o Peka e o Hugo em casa, e estávamos eu a Dani no carro. Levaram meu computador, um Mac que eu estava usando para desenvolver um projeto, meu iPad e meu celular. Da Dani levaram computador, celular, documentos e dinheiro.

Passado o susto, fui na quinta à noite mesmo comprar um computador para repor o que haviam levado. É minha ferramenta de trabalho, não posso ficar sem. Comprei um Vaio VPCSB25FB, instalei Xubuntu 11.10, a passei a sexta-feira e o domingo colocando as coisas no lugar nele e num Mac Mini que eu já tinha e vou usar no lugar do que levaram.

Algumas lições:

  1. Criptografe sua pasta pessoal: dormi mais tranquilo sabendo que a minha estava criptografada.
  2. Cloud rulez: meus contatos, agenda e e-mails estão no Google. No dia seguinte, mesmo sem meu celular, consegui conferir meus compromissos e ligar para quem eu precisei. Meus projetos estão todos no Git e os arquivos pessoais todos no Dropbox. Perdi no total uns quatro dias de trabalho, a maior parte desse tempo reconfigurando as coisas.
  3. Tenha seguro: eu não tinha seguro das minhas coisas. Quando procurei, me pareceu muito caro. Quando levaram minhas coisas, comecei a achar o seguro barato.
  4. Tenha backup: tenho uma conta Pro 100 no Dropbox. Custa 20 dólares por mês. É barato.

É isso. Passou o susto. Vamos trabalhar bastante agora, pra pagar as coisas novas.

Update: excelente post do Maudy Pedrão: Instale o PREY no Ubuntu e não perca de vista o seu notebook.


por elcio em 23 de January de 2012 às 12:51

January 22, 2012

Kodumaro

Média harmónica

Poliedro Já que falávamos de variâncias e médias, um dos cálculos mais belos de média é a média harmónica.

Vou roubar a explicação o exemplo da Wikipédia por pura preguiça… :-/

[update]
Roubar a explicação não… roubei o exemplo. Para a explicação deixei o apontador para o artigo na Wikipédia – mais preguiçoso ainda!
[/update]


Você se lembra do colégio, quando tinha de calcular a velocidade média percorrida por um carro, certo? Imagine que um carro faz uma viagem de x horas, tendo percorrido metade do tempo a 40Km/h e a outra metade a 60Km/h.

Calcular a velocidade média é bem fácil, não?

(40Km/h + 60Km/h) / 2 = 50Km/h


Então o carro percorreu a distância a uma velocidade média de 50Km/h, tornando fácil calcular, por exemplo, a distância: se o carro andou por 3h, percorreu 150Km.

Porém imagine que a proposição do problema não fosse quanto ao tempo, mas quanto à distância…

O carro percorreu metade do percurso (não do tempo) a 40Km/h e outra metade a 60Km/h. Qual a velocidade média?

Para obter esse resultado, precisamos da média harmónica:

2 / ((1 / 40Km/h) + (1 / 60Km/h)) = 48Km/h


Então é o equivalente a percorrer todo o trajeto a 48Km/h.

Isso também se aplica a diversos outros ramos, como a matemática financeira: se um investidor aplica um mesmo valor em compra de ações todos os meses, no final o preço médio das ações será a média harmónica dos preços das ações em cada mês.

Mãos à massa


Conversamos até agora sobre matemática, agora é hora de ver o código! Usarei novamente Scheme.

Vamos nos concentrar primeiro no cálculo do denominador. Novamente apelaremos para map/reduce.

O map será usado para inverter cada um dos elementos, para tanto usaremos a função lambda (λx.(1/x))xi:
(map (lambda (x) (/ 1 x)) *list*)


Feio isso, precisaremos de um somatório desses elementos, portanto usaremos reduce novamente com #'apply e #'+:
(apply +
(map (lambda (x) (/ 1 x)) *list*))


O numerador é fácil, é a quantidade de elementos, ou tamanho da lista:
(length *list*)


Basta dividirmos um pelo outro e, quase sem querer, já temos o cálculo da média harmónica!
(define harmonic-mean
(lambda (*list*)
(/
(length *list*)
(apply +
(map (lambda (x) (/ 1 x)) *list*)))))


Se quiser testar com os valores do exemplo (40Km/h e 60Km/h):
(let ((params '(40 60)))
(display (harmonic-mean params))
(newline))


[update]
Ainda esperando o pessoal do Prettify corrigir o syntax highlighting para LISP.
[/update]


[]’s
Cacilhας, La Batalema

por noreply@blogger.com (Darth Batalema) em 22 de January de 2012 às 10:02

January 21, 2012

Ivan Neto

Mudando a resolução do Windows com Python

O Python for Windows oferece suporte a várias operações no Windows usando Python. Hoje tive uma demanda de mudar a resolução “programatically”, e a solução foi o seguinte código:

import os, sys

import win32api
import win32con
import pywintypes

Primeiro é preciso importar as libs necessárias.

display_modes = {}
n = 0
while True:
  try:
    devmode = win32api.EnumDisplaySettings(None, n)
  except pywintypes.error:
    break
  else:
    key = (
      devmode.BitsPerPel,
      devmode.PelsWidth,
      devmode.PelsHeight,
      devmode.DisplayFrequency
    )
    display_modes[key] = devmode
    n += 1

No fim da execução do código acima, você tem display_modes como um dicionário contendo as possibilidades de resolução e frequência do monitor do seu sistema. Você pode imprimi-lo:

for item in display_modes.items():
    print item

O resultado é algo como:

((32L, 1024L, 768L, 60L), <PyDEVMODEA object at 0x00E03328>)
((32L, 3200L, 1200L, 60L), <PyDEVMODEA object at 0x00E03F58>)
((32L, 2560L, 1024L, 60L), <PyDEVMODEA object at 0x00E03BB0>)
((24L, 1400L, 1050L, 60L), <PyDEVMODEA object at 0x00E026F8>)
((24L, 1280L, 1024L, 60L), <PyDEVMODEA object at 0x00E025C0>)
((16L, 3200L, 1200L, 60L), <PyDEVMODEA object at 0x00E01D38>)
((24L, 6400L, 1200L, 60L), <PyDEVMODEA object at 0x00E030B8>)
((24L, 800L, 600L, 60L), <PyDEVMODEA object at 0x00E07A60>)
((8L, 1920L, 1440L, 60L), <PyDEVMODEA object at 0x00E00140>)
((4L, 800L, 600L, 1L), <PyDEVMODEA object at 0x00E04438>)
((16L, 640L, 480L, 60L), <PyDEVMODEA object at 0x00E009C8>)

Você pode testar se a resolução desejada está no dicionário, e então escolhê-la:

desired_res = (32, 800, 600, 60)
if desired_res in display_modes:
    devmode = display_modes[desired_res]
    win32api.ChangeDisplaySettings(devmode, 0)

That’s it! :)

 

Fontes: http://mail.python.org/pipermail/tutor/2006-November/051106.html, http://bytes.com/topic/python/answers/660265-how-change-display-screen-resolution-800×600

por ivan em 21 de January de 2012 às 21:21

January 17, 2012

Kodumaro

Dissecando a variância

Paradigma funcional Este artigo dá seguimento ao artigo sobre variância amostral.

A variância pode ser entendida como a média aritmética dos quadrados dos desvios de cada elemento da população.

O desvio de um elemento é a diferença entre o elemento e seu valor esperado. Quando lidamos com um conjunto, o valor esperado é a média dos elementos.

Então o desvio do elemento xi é xi - x.

A variância populacional pode ser descrita como:
σ²x=1/n Σ(xi - xm)


Na maioria dos casos, não se tem disponível todos os elementos de um conjunto, mas apenas uma amostra. Nesses casos, calculamos a variância de amostra ou variância amostral.

A diferença no cálculo é que, em vez de dividirmos pelo número total de elementos da amostra no cálculo da média, dividimos pelo número total menos um, o que aumenta o resultado do desvio padrão, compensando não conhecermos todos os elementos do conjunto.

Então o cálculo muda para:
s²x=1/(n - 1) Σ(xi - xm)


Em Erlang, para calcular o somatório dos desvios, primeiros usamos list comprehension para gerar uma lista dos quadrados desvios:
[math:pow(Xi - Xm, 2) || Xi <- List]


O que este código diz é: retorne a lista dos quadrados (math:pow/2) das diferenças entre cada elemento (Xi) da lista (Xi <- List) e sua média (Xm, calculado anteriormente).

Depois ele usa math:sum/1 para gerar um somatório e retorna a divisão do resultado do somatório pelo tamanho da lista menos um (Num / Demon).

Volte ao artigo anterior para ver como fica o código.

Em Scheme, a lógica é quase a mesma, mas em vez de list comprehension, é usado map/reduce. O #'map roda a função anónima (lambda) em cada elemento, extraindo os quadrados dos desvios.

[update]
Troquei o link para map/reduce, que apontava para um arcabouço do Google, quando as referências reais seriam encontradas no segundo parágrafo do texto referenciado.
[/update]


A função usada foi (λx.(x - x)²)xi, ou: (lambda (x) (expt (- x xm) 2)) em LISP.

Para o reduce (#'apply) é usado somatório (#'+), aplicado ao conjunto resultante.

Novalmente, volte ao artigo anterior para ver o código.

[]’s
Cacilhας, La Batalema

por noreply@blogger.com (Darth Batalema) em 17 de January de 2012 às 02:08

January 16, 2012

Gustavo Niemeyer

Bazaar, the git way

Back at the Ubuntu Platform Rally last week, I’ve pestered some of the Bazaar team with questions about co-location of branches in the same directory with Bazaar. The great news is that this seems to be really coming for the next release, with first-class integration of the feature in the command set. Unfortunately, though, it’s not quite yet ready for prime time, or even for I’m-crazy-and-want-this-feature time.

Some background on why this feature turns out to be quite important right now may be interesting, since life with Bazaar in the past years hasn’t really brought that up as a blocker. The cause for the new interest lies in some recent changes in the toolset of the Go language. The new go tool not only makes building and interacting with Go packages a breeze, but it also solves a class of problems previously existent. For the go tool to work, though, it requires the use of $GOPATH consistently, and this means that the package has to live in a well defined directory. The traditional way that Bazaar manages branches into their own directories becomes a deal breaker then.

So, last week I had the chance to exchange some ideas with Jelmer Vernooij and Vincent Ladeuil (both Bazaar hackers) on these problems, and they introduced me to the approach of using lightweight checkouts to workaround some of the limitations. Lightweight checkouts in Bazaar makes the working tree resemble a little bit the old-style VCS tools, with the working tree being bound to another location that actually has the core content. The idea is great, and given how well lightweight checkouts work with Bazaar, building a full fledged solution shouldn’t be a lot of work really.

After that conversation, I’ve put a trivial hack together that would make bzr look like git from the outside, by wrapping the command line, and did a lightning talk demo. This got a few more people interested on the concept, which was enough motivation for me to move the idea forward onto a working implementation. Now I just needed the time to do it, but it wasn’t too hard to find it either.

I happen to be part of the unlucky group that too often takes more than 24 hours to get back home from these events. This is not entirely bad, though.. I also happen to be part of the lucky group that can code while flying and riding buses as means to relieve the boredom (reading helps too). This time around, cobzr became the implementation of choice, and given ~10 hours of coding, we have a very neat and over-engineered wrapper for the bzr command.

The core of the implementation is the same as the original hack: wrap bzr and call it from outside to restructure the tree. That said, rather than being entirely lazy and hackish line parsing, it actually parses bzr’s –help output for commands to build a base of supported options, and parses the command line exactly like Bazaar itself would, validating options as it goes and distinguishing between flags with arguments from positional parameters. That enables the proxying to do much more interesting work on the intercepted arguments.

Here is a quick session that shows a branch being created with the tool. It should look fairly familiar for someone used to git:


[~]% bzr branch lp:juju
Branched 443 revisions.

[~]% cd juju
[~/juju]% bzr branch
* master

[~/juju]% bzr checkout -b new-feature
Shared repository with trees (format: 2a)
Location:
shared repository: .bzr/cobzr
Branched 443 revisions.
Branched 443 revisions.
Tree is up to date at revision 443.
Switched to branch: /home/niemeyer/juju/.bzr/cobzr/new-feature/

[~/juju]% bzr branch other-feature
Branched 443 revisions.

[~/juju]% bzr branch
  master
* new-feature
  other-feature

Note that cobzr will not reorganize the tree layout before the multiple branch support is required.

Even though the wrapping is taking place and bzr’s –help output is parsed, there’s pretty much no noticeable overhead given the use of Go for the implementation and also that the processed output of –help is cached (I said it was overengineered).

As an example, the first is the real bzr, while the second is a link to cobzr:


[~/juju]% time /usr/bin/bzr status
/usr/bin/bzr status 0.24s user 0.03s system 88% cpu 0.304 total

[~/juju]% time bzr status
bzr status 0.19s user 0.08s system 88% cpu 0.307 total

This should be more than enough for surviving comfortably until bzr itself comes along with first class support for co-located branches in the next release.

In case you’re interested in using it or are just curious about the command set or other details, please check out the web page for the project:

por Gustavo Niemeyer em 16 de January de 2012 às 04:02

January 15, 2012

Kodumaro

Variância

Glider Uma das operações mais importantes e necessárias da matemática é a variância de amostra. É usada, por exemplo, para o cálculo do desvio padrão e da regressão linear.

Usando linguagens funcionais, a implementação fica muito mais elegante.

Erlang


Em Erlang, a função para o cálculo da variância toma o seguinte formato:
variance(List) ->
Xm = mean(List),
Num = lists:sum([math:pow(Xi - Xm, 2) || Xi <- List]),
Denom = length(List) - 1,
Num / Denom.


É preciso ainda definir a função de média, mean/1:
mean(List) ->
lists:sum(List) / length(List).


LISP


Em Scheme a implementação é um pouco mais verbosa, mas ainda assim elegante.

Segue o código em R⁵RS:
(define variance
(lambda (*list*)
(let ((xm (mean *list*)))
(/
(apply +
(map (lambda (x) (expt (- x xm) 2)) *list*))
(- (length *list*) 1)))))


Também precisamos implementar a média:
(define mean
(lambda (*list*)
(/
(apply + *list*)
(length *list*))))


Paradigma imperativo


Para comparação, segue a implementação de variância em uma linguagem imperativa, C:
double variance(int length, double *list) {
double x_mean = mean(length, list);
double sum = 0;
int i;

for (i=0; i<length; ++i)
sum += pow(list[i] - x_mean, 2.);

return sum / (length - 1);
}


É preciso incluir o cabeçalho math.h. Segue a implementação da função mean():
double mean(int length, double *list) {
double sum = 0;
int i;

for (i=0; i<length; ++i)
sum += list[i];

return sum / length;
}


Perceba a mudança de estado, o que não ocorre nos códigos funcionais.

Escolhi C em vez de Python, porque Python também suporta bem o paradigma funcional, enquanto C é quase necessariamente imperativa.

[]’s
Cacilhας, La Batalema

por noreply@blogger.com (Darth Batalema) em 15 de January de 2012 às 23:06

January 12, 2012

Artificial Intelligence in Motion

The Anatomy of Product Recommendations - Infographic - Tips and Best Practices

Hi all,

I'd like to share a post that I found recently from a product's blog called LiftSuggest. It is focused on recommender engines for e-commerces and give several tips about how to design your product recommender at your website for maximum clicks and to increase your sales.

They posted a infographic about the anatomy of a product recommender engine. The tips they give are quite important when you are designing a recommender system for your e-commerce. 


Product Recommender Engine

Further information please access their blog.


Regards,

Marcel Caraciolo

por Marcel Caraciolo (noreply@blogger.com) em 12 de January de 2012 às 21:10

Machine Learning with Python: Meeting TF-IDF for Text Mining

3Hi all,

This month I was studying about information retrieval and text mining, specially how to convert the textual representation of information into a Vector Space Model (VSM).  The VSM is an algebraic model representing the importance of a term (tf-idf) or even the absence or presence (Bag of Words) of it in a document. I'd like to mention the excellent post from the researcher Christian Perone at his blog Pyevolve about Machine learning and Text Mining with TF-IDF, a great post to read.

I decided in this post to be shorter and give some examples using Python . I expect at the end of this post you feel confortamble to use tf-idf at your tasks handling with text mining.

By the way, I extremely recommend you to check the scikit.learn machine learning toolkit. There is a whole package to work with text classification, including TF-IDF with Python!


What is TF-IDF ?

Term Frequency - Inverse Document Frequency is a weighting scheme that is commonly used in information retrieval tasks. The goal is to model each document into a vector space, ignoring the exact ordering of the words in the document while retaining information about the occurrences of each word.

It is composed by two terms: one first computes the normalized Term Frequency, which is the number of times a word appears in a documnet, divided by the total number of words in that document. Then, the second term is the Inverse Document Frequency, which is computed as the logarithm of the number of the documents in the corpus divided by the number of documents where the term ti appears. Or, in symbols:



and 




The TF-IDF gives how important is a word to a document in a collection, since it takes in consideration not only the isolated term but also the term within the document collection. The intuition is that a term that occurs frequently in many documents is not a good discriminator ( why emphasize a term which is almost present in the entire corpus of your documents ?)  So it will scale down the frequent terms while scaling up the rare terms; for instance, a term that occurs 10 times more than another isn't 10 times more important thant it.

For computing the TF-IDF weights for each document in the corpus, it is required in the corpus a series of steps:  1) Tokenize the corpus  2)  Model the Vector  Space  and 3) Compute the TF-IDF weight for each document in the corpus.

Let's going through each step:


Tokenization


First we need to tokenize the text. To do this, we can use the NLTK library which is a collection of natural language processing algorithms written in Python. The process of tokenizing the documents in the corpous is a two steps:  First the text is splint into sentences, and then the sentences are split into the individual words. It is important to notice that there are several words that are not relevant, that is, terms like "the, is, at, on", etc...  aren't going to help us, so in the information extraction, we ignore them. Those words are commonly called stop words and they are present in almost all documents, so it is not relevant for us. In portuguese we also have those stop words such as (a, os , as , os, um , umas, que, etc.)

So considering our example below:


We will tokenize this collection of documents and represent them as vectors (rows) of a matrix with |D| x F shape, where |D|  is the cardinality of the document space, or how many documents we have and the F is the number of features, in our example it is represented by the vocabulary size.

So the matrix representation of our vectors above is:



As you have noticed, these matrices representing the term frequencies (tf) tend to be very sparse (lots of  zero-elements),  so you will usually see the representation of these matrices as sparse matrices. The code shown below will tokenize each document in the corpus and compute the term frequencies.



Model the Vector Space

Now that each of the documents in the corpus has been tokenized, the next step is to compute the document frequency quantity, that is, for each term, how many documents that term appears in. Before going to IDF, it is important to normalize the term-frequencies. Why ?  Imagine that we have a repeated term in document with porpuse of improving its ranking on an Information Retrieval System or even create a bias torwards long documents, making them look more important than they are just because of the high frequency of the term in the document. By normalizing the TF vector we can overcome this problem.
The code.



Compute the TF-IDF

Now that you saw how the vector normalization was applied, we will now have to compute the second term of tf-idf: the inverse document frequency. The code is provided below:




The TF-IDF is the product between the TF and IDF.  So a high weight of the tf-idf  is reached when you have a high term frequency (tf) in the given document and low document frequency of the term in the whole collection. Now let's see the tf-idf computed for each term present in the vector space.

The code.



Putting everything together, the following code will compute the TF-IDF weights for each document. And the result matrix it will be:




A row of this matrix would be:



I ommited the zero-values elements of the row.

If we would decide to check the most relevant words for this place, by using the tf-idf I could see that the place has a nice hot chocolate drink (0.420955 <= chocolate quente ótimo), the soft drink nega maluca is also delicious (0.315716 - nega maluca uma delicia),  its Cheese bun is also quite good (0.252573 - pao de queijo muito bom).

And that is how we comput  our M_{tf\mbox{-}idf} matrix.  You can take a look at this link and this one to know how to use it with GenSim and Scikit.Learn respectively.

That's all,  I hope that  you enjoyed this article and help more people to know how to implement the tf-idf weight to mine your collection of texts.  Feel free to comment and make suggestions.

The source code of this example is also available.

Regards,

Marcel Caraciolo

por Marcel Caraciolo (noreply@blogger.com) em 12 de January de 2012 às 20:39

January 11, 2012

Eventos da APyB

Plone, presente e futuro do CMS usado no Brasil.gov.br

Palestrante

Érico Andrei é sócio e CEO da Simples Consultoria, empresa especializada em soluções web para gestão de conteúdo e portais corporativos. Com 15 anos de experiência na gestão de projetos e operações de tecnologia da informação com passagens em empresas como Microsoft Brasil, Vesta Technologies e Editora Abril.

Atuante nas comunidades de Software Livre, é membro-fundador da Associação PythonBrasil, membro da Plone Foundation e core developer do Plone.

Recentemente, Érico Andrei foi eleito membro do conselho da Plone Foundation, entidade que promove e protege o software e a comunidade Plone

Local

O evento será realizado no Interlegis

  • Auditório Antônio Carlos Magalhães
  • Av. N2, Anexo E do Senado Federal - Brasília(DF)

por Érico Andrei em 11 de January de 2012 às 17:56

January 09, 2012

Noticias da APyB

Rio de Janeiro será a sede da PythonBrasil[8]

De volta ao Rio de Janeiro após 3 anos, o evento PythonBrasil será realizado entre os meses de setembro e outubro em data e local a serem anunciados em breve. A escolha da sede é um prêmio a comunidade local que é a mais atuante na divulgação de Python no Brasil.

A expectativa da APyB é que a PythonBrasil[8] conte com a participação de mais de 400 participantes entre estudantes, desenvolvedores, usuários e gestores de tecnologia da informação. Na edição de 2011, empresas como Google, Canonical, Globo.Com e Serpro mostraram como utilizam Python apresentaram casos de sucesso de Python em suas operações.

A APyB terá um membro da comunidade do local como seu representante na organização e comercialização do evento,  que nesta edição serão de responsabilidade da Associação.

Parceria com Python Argentina

Continuando a parceria iniciada com a primeira edição da PyConAr, o encontro da comunidade Python da Argentina, a APyB e a Python Argentina (PyAr) coordenarão esforços para a realização de suas conferências.

por Érico Andrei em 09 de January de 2012 às 01:01

January 05, 2012

Artificial Intelligence in Motion

Deepjewel - Social Media powering Recommendations

Hi all,

Happy new year!  My first post this year will be about an idea that I had with my friend Ricardo Caspirro about the next generation of social recommenders in commerce applications and retail stores. What excites me is that this idea came from a conversation that we had in 2009, and since that year we discussed more about what it would be the "Deepjewel".

Deepjewel is a giant knowledge base that encapsulates interesting entities and relationships of the social world in the web.  The social world in this context means all the millions and billions of tweets, Facebook messages, profiles, relationships, blog posting, YouTube videos, and more - a living organism itself, constantly evolving. 


The Deepjewel

But what motivated us to create the Deepjewel?  One of main problems that we face nowadays is the discovery of content and items of our interest.  Many times, for instance, to find a book or a movie that we like, it is required to search at several websites and social networks through the web.  There isn't a tool that allow this connection between items of many domains in a organized and structured way, even for easy access. Those objects are spread over the web, and the recommendations are placed in social networks by comments, results of machine learning techniques or by queries at several web pages or search engines.  The problem becomes worst when we don't know anything about the existence of a certain item, which it could result at never finding out that possible item that would be of our interest. 

The social media is huge and we need tools that performs a deep analysis of all this data, filter out items of my interest, specially from the historical data  (with our permission, of course)  from our presence in the web and bring items and products relevant to us without loosing the discovery process associated with the serendipity.  One of the solutions is a powerful recommender engine fed by this Social Genome.



Hybrid Social Context-Aware Recommender RecDay


This hybrid social context-aware recommender (which we call recday) is a engine composed by several modular components, which we employ a broad range of semantic analysis techniques, including information extraction and integration, natural language processing and machine learning. The main task of this recommender is to analyze information about his posts, bios and relationships/lists collected from the social genome and summarize it (all this data would represent the interests of the user) in profiles, which we could call DNA. Those profiles built by the recday would infer the possible interests of the users and would serve as basis for personalized recommendations of products and services from the retail stores/e-commerce applications.


A perfect example for this proccess, which we call the translation, is when you mentioned several times about Apple products (such as macbook, ipod, iphone, etc) at your tweets. Even you never used the word "Apple", we can use the Social Genome to detect the products and infer that you are interested in Apple products. The following figure illustrate certain kinds of entities and relationships collected in the Social Genome:


The relationships extracted from the social web data

The second step of this engine is to build the user profile. Different from another approaches which it only uses the content or the historical data from reviews or ratings from the user, the Recday would go further and would analyze the temporal context included in the interests of the user. Several reports on consumer behavior show that the user desires are influented by external factors and even the humour or feelings of the person at the certain moment. It is required to collect in a stealth way (with the user permission of course) his social data and build his personality defined by several dimensions. Those dimensions represent the current state of the user which may define what kind of suggestions he would like to receive at that particular moment. For example, if you are happy today because you got a new job and posted at your Facebook about that event or even updated your profile about this new position, it would be a valuable information for your DNA profile in order to recommend products and services to celebrate this occasion (You are happy and excited, don't you think ?).

Another important component in this proccess is the product side. We need extract more information from their products portfolio. Items must be juiced in order to get all its meta-data available. Imagine the movie Batman where we have details about the year, genre, cast, production, direction, sinoypsis, etc. All this data can be used to build the DNA Item and be expressed by a collection of dimensions that represent the item profile. With those profiles (DNA User and DNA Item) we compute the similarity between user and items in order to produce a list of top recommendations and related explanations.


The Social Architecure of the Recommender


The final result can be shown in several mediums: mobile apps, widgets, web, API's, pluggins, etc. It is important the usability and how you will present all this information for a particular user. That's why the user interface must be simple and easy to navigate and have mechanisms to collect the user's feedback for the suggestions given by the engine. This proccess is cyclic, so when you give a feedback (a like or dislike or a comment about the suggestion), this piece of information is handled and leveraged to power your DNA profile.

A particular medium of the recommendations: Ipad Demo

In order to build all these interesting technical challenges, we needed to start developing our in-house solution called Crab, which proccesses all this data and employ several analysis and filtering techniques  to deal with the percularities of this heterogeneous sources of data. The first start is the launch of the Deepjewel Labs. Deepjewel is a principle that we can mine the wealth in data, by identifying interesting entities and relationships and converting them into valuable information as input in the recommendation proccess of items and services. 

In summary, all those human and computation techniques can be used to perform a deep semantic analysis of web and social data, where the result for a commerce application or retail store is the ability to offer what the users want before they know that they really want in a personalized way. The RecDay  would be able to daily offer relevant product and services to their customers without they even know it exists. This is a new way to shop in which you don't have to go find products, service and information; the machine will help them find their way to you.

To know more about our Deepjewel labs, visit the website (currently in portuguese):  


I hope you enjoyed,

Marcel Caraciolo

por Marcel Caraciolo (noreply@blogger.com) em 05 de January de 2012 às 05:47

December 30, 2011

PUG - PE

:D

Olá pessoal,

Este post vem como um post resumido do que aconteceu com este grupo no ano de 2011. Irei ser bem breve, em especial com fazer várias menções epeciais para diversos novos membros, palestrantes e parceiros que participaram da construção do PUG-PE este ano.

Este grupo de usuários foi fundado em 2007 por alguns membros, um deles gosto sempre de citar o nosso colega e membro e fundador da célula Rodrigo Amaral (@rodrigoamaral). Embora com algumas tentativas de tentar realizar um encontro, só apenas este ano conseguimos organizar nosso primeiro encontro oficial, precisamente em fevereiro no ano de 2010. Desde então, começamos a encorpar e os encontros cada vez mais frequentes  em periodicidade mensal. Este ano de 2011 o grupo se consolidou como um dos mais ativos grupos de software livre na região Nordeste onde conseguimos consolidar com diversas atividades durante o ano. Ao total neste ano de 2011 realizamos 8 Encontros Oficiais, os quais foram distribuídos em diversas faculdades de tecnologia pernambucanas como CIN/UFPE, UFRPE, POLI e IFPE. Realizamos nosso encontro especial de aniversário na Livraria Cultura e também encontros no ITBC no Recife Antigo. Formamos 2 turmas este ano de 2011 em conjunto com o CITI da UFPE o qual novos desenvolvedores Python saíram para o mercado! E sem mencionar os diversos workshops de Python espalhados pelo Recife , interior e fora do estado!! (Fomos para Aracaju -Sergipe!). Fomos mencionados também na revista Espírito Livre, uma das mais respeitadas revistas brasileiras sobre software livre e  por fim, tivemos uma boa amostra de representantes da nossa célula no encontro Brasileiro da comunidade Python (PythonBrasil), inclusive o próprio grupo foi tema de palestra oficial dentro da trilha do encontro!

X Encontro do PUG-PE

X Encontro do PUG-PE

X Encontro do PUG-PE

XI Encontro do PUG-PE
XI Encontro do PUG-PE

XI Encontro do PUG-PE

XII Encontro do PUG-PE
XII Encontro do PUG-PE

XII Encontro do PUG-PE

XIII Encontro do PUG-PE
XIII Encontro do PUG-PE

XIII Encontro do PUG-PE

XIV Encontro do PUG-PE
XIV Encontro do PUG-PE

XIV Encontro do PUG-PE

XV Encontro do PUG-PE
XV Encontro do PUG-PE

XV Encontro do PUG-PE

XVI Encontro do PUG-PE
XVI Encontro do PUG-PE

XVI Encontro do PUG-PE

XVII  Encontro do PUG-PE
XVII Encontro do PUG-PE

XVII Encontro do PUG-PE

Não só realizamos encontros como também construimos nosso I Open-Space : O Famoso PUG-PE Summer of Code onde tivemos um dia de aprendizado e desenvolvimento com Django.  Oficinas de Python também em conjunto ao Centro de Reciclagem da Unidade Marista em Recife também foram ministradas à garotada que está aprendendo programação por lá.   O ritmo de crescimento foi também muito melhor que o ano de 2010 onde saltamos de 205 usuários para 397 usuários, um crescimento de 48% de usuários!

Histórico de Usuários no PUGPE desde 2007
Histórico do PUG-PE

Histórico do PUG-PE

Mas este é apenas um resultado parcial e fruto de um trabalho contínuo e  voluntário de pessoas com interesses afins que querem conversar e discutir sobre Python, tecnologia e software livre e cultura digital. Acredito que se somos referência no estado de Pernambuco, e até nível Nordeste/ Brasil.  Mas não paramos por aqui, temos metas maiores para o ano de 2012 e espero poder estar participando deste time sensacional que forma hoje o grupo do PUG-PE.

Tenho que agradecer em nome de todos os grupos a todos visitantes deste blog, a todos os palestrantes convidados que cederam seu tempo para palestrarem em nossos encontros, a todos os membros (não precisarei citar pois cada um sabe quem é) , designers voluntários, web-designers que tornaram estes encontros uma realidade, em diversos aspectos: infra-estrutura, logística, coffe-break, cabos, etc.

Um agradecimento especial às empresas Idealizza, Especializa, Orygens, Hostech, Fontech pelo suporte oferecido durante todo o ano em sorteios, patrocínios e apoios. Empresas que acreditam no nosso trabalho!

Agradeço a todos os visitantes deste blog e a todos que apoiam essa comunidade diretamente e indiretamente, esperamos que possamos alcançar muito mais usuários e disseminar cada vez Python em todos ambientes seja acadêmico ou profissional. Uma menção honrosa ao fundador desta célula, Rodrigo Amaral por ter mantido essa chama viva durante todo este tempo em 3 anos. E vários obrigados a todas  universidades que nos cederam o seu espaço para podermos sediar nossos encontros. Quero agradecer também o apoio de todas células irmãs Grupy-PB, Grupy-AL, Grupy-RN, PythonBrasil, APyB pelo apoio na divulgação e logística.

Vamos trabalhar forte para que no ano de 2012 possamos atingir metas maiores e chegarmos mais longe, melhorar muito ainda em nossos possíveis encontros quem sabe até ter um encontro de maior porte no cenário nordestino.

E é isso aê , que venha 2012 e muito Python na veia! :D

Atenciosamente,

Marcel Caraciolo
Membro e Moderador da Célula PUG-PE


por marcelcaraciolo em 30 de December de 2011 às 01:57

December 22, 2011

Thiago Avelino

VIM a IDE para programadores Python

Depois muito tempo sem escrever nada no meu blog, escolhi esse tema para chamar a atenção do pessoal que esta começando desenvolver em Python que sempre pergunta qual é a melhor IDE para desenvolver em Python ou qual quer programador que usa uma super IDE pesado porque tem o recurso X, Y e Z.

Com o VIM podemos ter todos os recurso avançado que temos em qual quer IDE, basta algumas configurações para que esses recursos ser ativado, para facilitar a vida de todos compartilhei o meu .vimrc e nesse post vou explicar como usar o mesmo.

"Em 2 de novembro de 1991, Bram Moolenaar publicava a primeira versão do edito vim. O vim nasceu como um clone para Amiga do editor vi criado por Bill Joy em 1976, adicionando algumas funcionalidades extras, daí seu nome (VI iMproved ou VI Melhorado). Este editor se adaptou rapidamente a outras plataformas. "

Assumindo que o vi já esta instalado no meu micro, vamos instalar as configurações que eu fiz, basta rodar os seguintes comando no seu bash (Linux ou Mac):

curl https://raw.github.com/avelino/.vimrc/master/bootstrap.sh -o - | sh

Após isso ele vai baixar o repositório na sua pasta HOME. Recomendo o uso o VIM em GUI pois podemos chegar 256 cores, ou seja, colocar temas mais agradável e assim deixando o uso do vim mais confortável para o desenvolvimento, para Linux é o gvim e para mac o macvim (Para mac o Björn Winckler fez um ótimo trabalho, na minha humilde opinião é a melhor versão do VIM via GUI).

Chega de blablabla né, vamos logo para o que realmente interessa, como o VIM ficou e como utilizar ele?

vim start

Usando o vim para navegar nas pasta de um projeto:

vim files

Buscando arquivo por nome dentro do projeto:

vim search file

Listar todas as class e def do arquivo esta esta aberto (Python)

vim list class

Lista de comandos para usar no 'vim', lembrando que esses comando foi customizado:

  • :cd /path Abrir pasta
  • tn Abrir nova aba
  • te Abrir nova aba e carregar arquivo
  • t] Proxima aba
  • t[ Voltar aba
  • Ctrl+c Adicionar todos os arquivos no cache para poder fazer busca de arquivo (recomendo fazer isso ao abrir o projeto)
  • Ctrl+f Busca arquivo e abre na mesma aba
  • Ctrl+s Busca arquivo e abre em uma nova aba
  • \b Abre arquivo que esta no buffer do vim (Arquivo abertos)
  • \d, \n ou F3 Abre navegador de arquivo
  • \f Lista todas as class e def (Python)
  • \j Vai para declaração de um metodo
  • \r Renomear todos os metodos
  • [e Move linha para cima
  • e] Move linha para baixo
  • \v ouCtrl+w + v` Divide a tela em vertical
  • \h ou Ctrl+w + s Divide a tela em horizontal
  • \w ou Ctrl+w + q Fecha a aba atual
  • Ctrl+k Abre console Python
  • Ctrl+j Roda o script Python aberto
  • \sh Abre bash (shell)
  • \p Manda o arquivo em aberto para o dpaste.com
  • \ga Git add .
  • \gc Git commit
  • \gsh Git push
  • \gs Git status
  • \gd Git diff
  • \gr Git remove
  • \S Remove todos os espaços do final
  • \c Lista controle de versao do buffer


por avelino@chierry.com (avelino) em 22 de December de 2011 às 13:58

December 21, 2011

Artificial Intelligence in Motion

Playing with Foursquare API with Python

Hi all,

I'd like to share a project that I am developing that it may be useful for anyone who wants to create datasets from mobile location networks.  Specifically, I developed a wrapper in Python for accessing the Foursquare API called PyFoursquare

For anyone who doesn't know what is Foursquare, it is a popular mobile social-location network with more 10.000.000 of users around the world. The idea is that you can share your current location with your friends and as result discover new places, find where your friends are and even check some tips and recommendations about a place and what to do when you arrive there. It is an amazing project with lots of data available for anyone who wants to develop new apps for connect or mine (data mining) its data!

Foursquare Mobile Application

This Python API is one of the results of my master degree project where I proposed a new architecture for mobile recommenders that fetches reviews from social networks to improve the explanation and the quality of the given recommendations.  I  used this library to collect tips (text reviews) from Foursquare from places at my neighborhood Recife, Brazil.  This API was a little messy, so I decided to clean it up, organize and documment it for publish for the open-source community.

One of advantages of this API is that you can handle each entity from the Foursquare data as Model object. So instead of handling with json dictionaries, I encapsulate the results in the respective models (Venue, Tips, User, etc.) and access its attributes as common object in Python!

I inspired myself at the work of Joshua at Tweepy, which is a Python library for Twitter.  In this version released 0.0.1 I only implemented some API's such as search/venues,  venue_details and venue_tips.  In future releases I pretend to add more models and support for more API methods available at Foursquare.

How can you use it at your project ?

It is simple! Just install it by downloading at the Github's home project, extract the source from the tar.gz and  at the directory of the project run the command below:

$ python setup.py install

or the easier way is to install by the command easy_install:

$ easy_install pyfoursquare


After that, you can  simple test by running the command below at your Python Shell

>>> import pyfoursquare


Now let's see how you can get started with the PyFoursquare:

First you need to create an application at Foursquare. The link is this.  There  you can also get further information about the API, another libraries and several applications using the Foursquarw API's.  

The Foursquare Developer's Settings


After creating your application, you must get the client_id and your client_secret. Those keys will be important to connect the app to the users' accounts.  Foursquare uses the secure authentication based on OAuth2.  In PyFoursquareAPI, you won't need to handle with all steps provided by OAuth2.  It already encapsulates all the steps and handshakes between your app and Foursquare servers. \m/ 

Below the  code you must write for authenticate an user to connect to your app:




After the user  authorized, you now can instantiate the PyFoursquare API.  It will give you access to the Foursquare API methods.  I implemented several methods, but feel free to add new ones! Don't forget to submit the final results as pull requests at the project's repository at Github.

In this example I fetched a venue by giving as input the latitude and longitude and querying for the place with the name 'Burburinho'.  Burburinho is a popular bar nearby where I work!

Source code




Now you can access the result and access the Venue as a Python Object. All elements of the Venue are represented as attributes of the object Venue at PyFoursquare. The goal is to make easier the life of the developer when he access the Foursquare API by parsing all the JSON (the result) and placing in the correct model for him.



I expect you enjoyed this API. Feel free to use it at your applications or research!  I'd like to thank the Foursquare team for expose their data by providing those API's!  For data mining researchers instered in mobile location data, it is a mine of gold!

Further information about PyFoursquare, you can find here.

Feel free to give sugestions, improvements and comments,

Regards,

Marcel Caraciolo

por Marcel Caraciolo (noreply@blogger.com) em 21 de December de 2011 às 21:23

Gustavo Barbieri

kmod announcement (and how to help testing it!)

introduction and motivation

At ProFUSION a common topic is how to optimze the system. Not just the speed, but also what and how it is done. Not just for our embedded systems, but also our desktops and laptops.

These discussions led us to be involved in projects that consider this goal, such as EnlightenmentConnMan, oFono and systemd. With great projects, come great people and thus enlightening discussions on how to improve things. From these discussions Lennart Poettering and Kay Sievers put together a A Plumber’s Wish List for Linux, with one of the items being of special interest for ProFUSION as it had the potential of also helping embedded systems and speeding up or boots:

* module-init-tools: provide a proper libmodprobe.so from
module-init-tools:
Early boot tools, installers, driver install disks want to
access information about available modules to optimize
bootup handling.

One of the reasons for this is that udev will search /sys/devices for all “modalias” files and call “/sbin/modprobe -bv $ALIAS“, however many of these calls evaluate to an empty list, thus an useless execution of program that will open /lib/modules/`uname -r`/modules.*, load resources, search for something that is not there and return. This could be way cheaper if done inside udev workers. [note: Lucas did measure and noticed 2.5x speedups, stay tuned for benchmarks]

kmod

Then our developer Lucas De Marchi proposed to do the libmodprobe and we funded it. After some discussions with Lennart and Kay, it was decided to rename it to kmod for shortness and good namespace. The initial goal was to achive a 1:1 replacement of module-init-tools as a library to be used by udev and systemd-modules-load and we are close to it with our second release done today! While we miss depmod tool (planned for v3), our kmod-modprobe should be fully functional and if this proves to be true, the logic will move to libkmod to be used by udev.

we need your testing!

To ensure kmod-modprobe does what it is supposed to do, we need extensive testing, there is where we need you! Try it on as many systems as possibles and let us know. To do this we recommend:

$ git clone git://git.profusion.mobi/kmod.git
$ cd kmod
$ ./autogen.sh
$ ./configure --enable-logging \
              --enable-debug --enable-tools \
              --enable-zlib # if you have module.ko.gz
$ make all
$ sudo make install
$ sudo mv /sbin/modprobe /sbin/modprobe-bkp
$ sudo ln -s /usr/bin/kmod-modprobe /sbin/modprobe
$ ls -1 /sys/module/ > ~/original-modules
$ reboot
$ ls -1 /sys/module/ > ~/kmod-modules
$ diff ~/original-modules ~/kmod-modules

current users and feedback

Being a new project in a critical area of Linux system, we expected lots of criticism and rejection by people, but interestingly enough after Lucas’ announcement and LWN article the feedback was highly positive! We even had some testers and people to help with ideas and experience.

Among the people that joined the project is the current maintainer of module-init-tools package Jon Masters, which announced that kmod replaces module-init-tools. He is helping a lot with his knowledge and cases from Red Hat Enterprise Linux, also providing modules from non-trivial platforms such as s390. Last but not least he provided insights to improve module handling on Linux, particularly replacing modules with better alternative as required in enterprise systems.

With Jon’s blessing we’ll use the same mailing list linux-modules@vger.kernel.org and our git will move to kernel.org soon.

People from ARCH and Debian were also interested and even created packages for it! These guys were extremely helpful to test cases such as gzip modules, 64bits modules with i386 user space and so on. They are: Tom Gundersen (tomegun), Dave Reisner (falconindy) and Marco d’Itri (Md).

next steps

Based on our TODO, we have the following ideas for next steps:

  • Finish libkmod-elf.c to provide information required by depmod. I’m working on this in my depmod branch;
  • tools/kmod-depmod.c: create a 1:1 compatible tool to generate /lib/modules/`uname -r`/modules.*;
  • libkmod should export parsed configuration to be used by kmod-modprobe.c –dumpconfig;
  • create kmodmock library to be LD_PRELOAD’ed to redirect some syscalls such as init_module(), delete_module() and open() of /sys and /proc. I’ve started a branch for this some time ago as “unittest” branch but stopped due lack of ELF support at the time;
  • create unittests and measure coverage. Given kernel modules are user-input they may be broken files and libkmod-elf.c needs to be extensively tested to avoid segmentation fault due out-of-boundaries access. This mean not trusting null terminated string in .strtab section and so on.
  • create optimized modules.archive that would contain optimized search index and all modules compressed independently, but in the same file. This would save file access and could provide information we don’t have today, like the uncompressed size of gzipped modules.

por Gustavo Barbieri em 21 de December de 2011 às 18:24

Elcio Luiz Ferreira

Workshop de Javascript Avançado

Javascript se tornou a linguagem mais importante no desenvolvimento web. Não importa o que você use no servidor, Ruby, PHP, Python, Java, .Net…

Com a chegada do HTML5 e suas novas APIs, Javascript vai ganhar ainda mais importância nos próximos anos.

Aprenda Javascript de Verdade


por elcio em 21 de December de 2011 às 17:05

December 17, 2011

Thiago Avelino

Google Nexus S, atualização oficial para Android 4.0 (Ice Cream Sandwich)

Dia 16/12/2011 o Google lançou oficialmente a atualização do aparelho Nexus S para Ice Cream Sandwich (Android 4.0), a noticia saiu no Twitter oficial do Google Nexus.

Para você atualizar o seu Nexus S faça o seguinte procedimento:

  • 1 - Faça download da imagem do Android 4.0 para o Nexus S no seguinte link: http://android.clients.google.com/packages/ota/google_crespo/VQ8PQk_V.zip ou http://dl.dropbox.com/u/763381/VQ8PQk_V.zip
  • 2 - Coloque o VQ8PQk_V.zip SD do seu Nexus S e você deve renomear o arquivo para update.zip
  • 3 - Desligue o seu aparelho
  • 4 - Aperte o botão do volume para cima + o botão power, seu celular vai iniciar no modulo fastboot
  • 5 - Selecione a opção recovery
  • 6 - Vai começa carregar e aparecera um triângulo com um !, nessa tela você deve aperta o botão power + volume para cima (Deve ser na sequência relatado no post)
  • 7 - Vai aparecer um menu onde você deve selecionar a seguinte opção Apply update from /sdcard
  • 8 - Após instalar você deve selecionar reboot system now
  • 9 - Pronto, Android 4.0.3 instalado no seu Nexus S

Quando o seu celular for ligar a primeira vez com Android 4.0 ele vai ficar um pouco lento pois vai refazer o dalvik cache.

Lembrando que você tem que ter a versão do Android oficial do Google instalado no seu Nexus S, caso não esteja não vai conseguir fazer os procedimentos, pois estamos atualizando para a versão oficial do Google.

O Google vai liberar aos poucos a atualização automatica para os Nexus S pois se não vai acabar com o link das operadoras, no Brasil principalmente que nosso 3G é um 2G.


por avelino@chierry.com (avelino) em 17 de December de 2011 às 17:41

December 13, 2011

PUG - PE

Última palestra do dia do Encontro

Pessoal,

Tivemos neste último sábado o nosso último encontro do ano (XVII Encontro do PUG-PE) lá no Auditório do Instituto Federal de Pernambuco (IFPE), Antigo CEFET. Um evento com excelentes palestras e muito networking. Agradecimentos especiais ao Prof. Marcos por nos ajudar a mais uma vez a sediar este evento no IFPE, nossa segunda vez  este ano! E também agradecimentos aos nossos patrocinadores as startups Orygens , Idealizza e Hostech!

Algumas fotos abaixo do evento:

XVII Encontro do Grupo de Usuários de Python de Pernambuco

XVII Encontro do Grupo de Usuários de Python de Pernambuco

A primeira palestra foi ministrada pelo Luciano Rodrigues e o Arthur Alvin (por sinal agradecimentos especiais ao Arthur que deu uma força para organização de todo o evento e nosso contato no IFPE).  Eles ministraram uma palestra rápida sobre o que é o PUG-PE e o uso de Python na comunidade.

A próxima palestra ministrada foi por Marcos Egito que é um dos educadores do Centro de Reciclagem de Computadores (CRC) da Unidade Marista. Ele falou um pouco do trabalho que ele realiza junto à instituição e como Python tem ajudado a educar jovens carentes no ensino de programação! Muito se deu graças ao trabalho conjunto com o grupo de usuários de Python de Pernambuco que em parceria realizou em meados de agosto um evento por lá! Parabéns pessoal!

Seguem os slides da palestra do Marcos:

A próxima palestra foi ministrada pelo Marcelo Lira, engenheiro do Instituto Nokia de Tecnologia, que apresentou o projeto que vem trabalhando junto ao instituto por meio de bindings de C++ com Python. Esta palestra foi ministrada na PythonBrasil deste ano e convidamos o Marcelo para apresentar em nosso evento local! O trabalho muito interessante o qual ele fala das experiências, dores de cabeça (hehe trabalhar com C++ e templates é pra quem tem colh$%oes!) . O projeto serviu como base para construir os bindings do Qt com Python , do qual derivou o atual projeto PySide !

Seguem os slides e a foto do Marcelo palestrando:

Marcelo Lira palestrando sobre bindings com Python e C++

Marcelo Lira palestrando sobre bindings com Python e C++

Seguem os slides do Marcelo Lira:

Após o coffee-break tivemos a palestra do Hugo Serrando com aplicações científicas usando Python. Hugo apresentou como ele aplicou python em seus diversos projetos, em especial um projeto bem interessante envolvendo predição de nivelamento de barragens que já foi tema de palestra relâmpago do último encontro. Várias aplicações interessantes com o uso dos pacotes numpy, Scipy e matplotlib!

Segue foto e slides do Hugo:

Hugo Serrano apresentando sobre Aplicações Científicas com Python

Hugo Serrano apresentando sobre Aplicações Científicas com Python

Por fim terminamos com algumas palestras relâmpago com os membros Brunno Gomes sobre o Mini- Framework Web Bottle , André Ericsson e outro membro do grupo recém-chegado e membro do CRC!

Seguem as fotos e as palestras-relâmpago:

Palestra Relâmpago do André

Palestra Relâmpago do André

Slides:

Foto da palestra do Brunno Gomes:

Brunno Gomes apresentando o Bottle.py

Brunno Gomes apresentando o Bottle.py

E por fim a última palestra do dia:

Última palestra do dia do Encontro

Última palestra do dia do Encontro

E assim foi mais um encontro do PUG-PE! Queremos agradecer a todos os presentes e novamente agradecer a todos que fizeram este PUG-PE crescer neste ano de 2011! Realizamos 8 encontros, mais de 4 workshops e mais de 2 cursos e várias palestras!  Um excelente 2011 e que venha 2012 com mais sucesso e mais novos pythonistas em nosso grupo mostrando seus trabalhos e compartilhando o conhecimento!

Links para os assuntos discutidos


por marcelcaraciolo em 13 de December de 2011 às 02:33

December 12, 2011

Gustavo Niemeyer

Good concurrency changes the game

A long time before I seriously got into using distributed version control systems (DVCS) such as Bazaar and Git for developing software, it was already well known to me how the mechanics of these systems worked, and why people benefited from them. That said, it wasn’t until I indeed started to use DVCS tools that I understood how much my daily workflow around code bases would be changed and improved.

This weekend, while flying home from MongoSV, I could experience that same feeling in relation to first class concurrency support in programming languages. Everybody knows how the feature may be used, but I have the feeling that until one actually experiences it in practice, it’s very hard to really understand how much the relationship with ordering while developing software may be improved.

I was having some fun working on improvements to Goetveld. This package allows Go programs to communicate with Rietveld servers to manipulate code review entries. The Rietveld API is a bit rough in a few places, and as a result some features of the package actually parse an HTML form to extract some data, before sending it back. You may have done something similar before while attempting to script a web site that wasn’t originally intended to be.

The interesting fact here is that this is an intrinsically serial procedure: load a form, change it, and send it back, right? Well, not really. As one might intuitively expect, establishing an SSL session and its underlying TCP connection are not instantaneous operations.

To give an idea, here is part of a dump of an SSL connection being initiated (that is, no HTTP data was sent yet) to codereview.appspot.com, originated from my home location:

# tcpdump -ttttt -i wlan0 'host codereview.appspot.com and port 443'
(...)
00:00:00.000000 IP (...)
00:00:00.000063 IP (...)
00:00:00.000562 IP (...)
00:00:00.341627 IP (...)
00:00:00.357009 IP (...)
00:00:00.357118 IP (...)
00:00:00.360362 IP (...)
00:00:00.360550 IP (...)
00:00:00.366011 IP (...)
00:00:00.689446 IP (...)
00:00:00.727693 IP (...)

That’s more than half a second before the application layer was even touched. So, turns out that to save that roundtrip time, we can start both the form loading and the form sending requests at the same time. By the time the form loading ends, processing the data locally is extremely fast, and we can complete the sending side by just providing the request body.

At this time you may be thinking something like “Ugh, that’s too much trouble.. why bother?”, and that highlights precisely the point I’d like to make: it is too much trouble because most people are used to languages that turn it into too much trouble, but the issue is not inherently complex. In fact, this is the entire implementation of this logic in Go:

func (r *Rietveld) UpdateIssue(issue *Issue) error {
        op := &opInfo{r: r, issue: issue}
        errs := make(chan error)
        ch := make(chan map[string]string, 1)
        go func() {
                errs - r.do(&editLoadHandler{op: op, form: ch})
                close(ch)
        }()
        go func() {
                errs - r.do(&editHandler{op: op, form: ch})
        }()
        return firstError(2, errs)
}

I'm not cheating. The procedure was being done serially before, with very similar logic. Previously it had to take the form variable itself from the first request and manually provide it to the next one. Now, instead of providing the form, it's providing a channel that will be used to send the form across. One might even argue that the channel makes the algorithm more natural, curiously.

This is the kind of procedure that becomes fun and natural to write, after having first class concurrency at hand for some time. But, as in the case of DVCS, it takes a while to get used to the idea that concurrency and simplicity are not necessarily at opposing ends.

por Gustavo Niemeyer em 12 de December de 2011 às 17:52

December 09, 2011

Elton Luís Minetto

eminetto

Hoje precisei fazer uma tarefa que acabou me levando a descobrir uma nova ferramenta. A tarefa em questão era: “exportar para uma lista os e-mails de todas as pessoas que compraram o meu e-book“. Toda venda realizada com sucesso o Pagseguro me envia um e-mail avisando da venda, e um script PHP que eu criei envia o PDF do e-book para o e-mail do comprador. Então teoricamente só precisaria exportar essa lista de e-mails enviados da minha conta do Gmail para um arquivo TXT.
Após pesquisar algumas alternativas cheguei ao Got Your Back (GYB). É um script Python que serve para fazer um backup/restore de todos os e-mails da sua conta do Gmail. Ele salva todas as mensagens em pastas separadas por ano/mes, no formato .eml, o que facilita o uso de alguma ferramenta de busca de textos como o find do MacOSX/Linux. E para facilitar ainda mais ele gera um banco de dados SQLite com os detalhes da mensagem (from, to, subject), então é só fazer uma consulta SQL e você tem acesso a todas as suas mensagens.
Achei bem útil e fácil de usar, então resolvi compartilhar.


por eminetto em 09 de December de 2011 às 17:14

December 07, 2011

Artificial Intelligence in Motion

Annoucing a Scientific Computing With Python Course !

Hi all,

I am announcing the launch of the website PyCursos. Pycursos is a online-course and training platform for anyone who wants to learn Python programming language and its related extensions. The first course is being already announced, which is the Scientific Computing Programming with Python,  with me as teacher.




The goal of the course is to teach scientific computing, specially on how to solve scientific problems in your daily routine by using the packages that Python provides for free: Scipy, Numpy and Matplotlib.

With those tools, the student will learn how to reproduce their problems into a simple and legible code and to use the helpful tools to plot graphs, write reports, mathematics optmization, matrices manipulation, linear algebra and more.

The requirement to attend the course is only the student be motivated to learn and have some experience with programming.  The course will start in 2012, January in on-line mode, where the students will apply and follow a schedule of video-classes on-line and review exercises regularly.

We have also the option of the in-company training, where the student may watch the classes in a classroom with another students. In both modes the students, at the end of the course, will receive a conclusion certificate.

It is important to tell that the course now is all  in Portuguese! Sorry for anyone for another countries!


For further information please visit our website : http://www.pycursos.com

Anyone who whant to know more about scientific computing with python, can check out those  slides of a keynote that I lectured at some institutions from here at Recife, Pernambuco, Brazil.






Regards,

Marcel Caraciolo

por Marcel Caraciolo (noreply@blogger.com) em 07 de December de 2011 às 15:55

December 06, 2011

Noticias da APyB

Aberto o período de propostas para sediar a PythonBrasil[8] em 2012 (prorrogado)

Atualização: a notícia foi atualizada para refletir as novas datas.

Está aberto o período para envio de propostas para sediar a PythonBrasil[8] que acontecerá por volta de setembro/outubro de 2012 (as candidaturas deverão listar as datas possíveis em suas propostas).

As propostas devem ser enviadas até o fim do dia 18 de Dezembro de 2011 e a escolha será divulgada até o dia 8 de Janeiro de 2012. A escolha será feita por um comitê formado pela diretoria da Associação Python Brasil mais os BigKahunas das edições anteriores do evento (responsáveis pela organização).

  • Término do prazo: até o fim do dia 18/12/2011 (essa já é a data pós-prorrogação)
  • Divulgação do resultado: 08/01/2012

 As propostas devem ser elaboradas de forma à "vender" o local do evento para esse comitê que vai avaliar os seguintes ítens (por ordem de importância):

  • Big Kahuna — Nome da pessoa que será o responsável principal pela organização do evento. O envolvimento dessa pessoa com a comunidade, disponibilidade de tempo, capacidade de mobilizar, organizar e delegar tarefas terão o maior peso na escolha do local.
  • Autonomia — A PythonBrasil é um evento da comunidade Python e é organizado pela Associação Python Brasil, ou seja, a prerrogativa de definir o conteúdo apresentado (grade de palestras, etc) pertence à comunidade.
  • Localização — Fácil acesso à cidade (passagens aéreas baratas, proximidade geográfica, etc) e mobilidade na cidade (transporte público, metrô, etc).
  • Interesse de patrocinadores — A Associação Python Brasil já tem um relacionamento de longa data com diversas empresas dispostas a patrocinar a PythonBrasil e alguns deles tem preferência por certas cidades. Os proponentes estão livres para acrescentar nomes de empresas com interesse real em patrocinar o evento.
  • Estrutura — Local onde o evento será realizado, disponibilidade de infra-estrutura de rede, energia, auditórios, salas para treinamentos, espaço para "OpenSpaces", segurança, entre outras.
  • Fornecedores — equipamentos de audio/video, filmagens, fotografia, tradução simultânea, coffee-break, entre outras.
  • "Extras" — possibilidade de transmissão do evento, a cidade apresentar alternativas "extra-evento" (pontos turísticos, restaurantes, bares, …)

Estamos avaliando a possibilidade de escolher a cidade para os próximos 2 anos (2012 e 2013) para otimizar processo de organização do evento, portanto, se houver interesse em sediar o evento por mais de um ano é importante colocar isso na proposta.

As pessoas interessadas em submeter propostas devem ler com *muita atenção* o Manual do BigKahuna. Lá você encontrará informações importantes sobre como elaborar a sua proposta e organizar o evento.

Qualquer dúvida entre em contato com a Associação Python Brasil pelo email: contato@python.org.br.

por Osvaldo Santana em 06 de December de 2011 às 21:55

PUG - PE

XVII Encontro do Grupo de Usuários de Python de Pernambuco

Olá pessoal, Segue o convite a  todos interessados em participar do nosso XVII Encontro do Grupo de Usuários de Python de Pernambuco que será realizado nesta edição nas dependências do Auditório do Instituto Federal de Pernambuco (IFPE) – Antigo CEFET em Recife no dia 10/12 (Sábado) a partir das 08:30encerrando nossos encontros no ano de 2011.

XVII Encontro do Grupo de Usuários de Python de Pernambuco

XVII Encontro do Grupo de Usuários de Python de Pernambuco

Teremos a palestra sobre Aplicações Científicas com Python por Hugo Serrano e mestre em computação pela UPE/POLI, palestra sobre integração de C++ com Python com o engenheiro de sistemas Marcelo Lira do Instituto Nokia de Tecnologia, palestra sobre sistemas de recomendação por Marcel Caraciolo, cientista chefe da startup Orygens.com e Atepassar.com e uma palestra sobre Python na Educação com Marcos Egito, um dos coordenadoras da célula de reciclagem  (CRC) da Unidade Marista e palestras relâmpago com vários assuntos Vai ser muito maneiro! Teremos à tarde a II Edição do PUG-PE summer of code para desenvolvimento de projetos django e outra tecnologias!

O encontro é gratuito, e para quem não conhece Python eis uma excelente oportunidade de conhecer a plataforma de maior crescimento em 2010 segundo o índice Tiobe [2]. É uma linguagem de programação multi-plataforma e multi-paradigma presente em diversos nichos desde computação científica, web, embarcados e até gráfica! Para mais informações ver a entrevista do Marcel, moderador do grupo sobre a plataforma Python [3]. Uma ótima oportunidade de fazer networking, aprendizado e conversar sobre software livre e desenvolvimento colaborativo! Participe da nossa lista de discussão para troca de idéias [4]. O evento está sendo patrocinado pelas startups pernambucanas Orygens, Idealizza e Hostech.

[1] http://pug.pe

[2] http://www.geeks3d.com/20110121/tiobe-index-january-2011-python-wins-the-tiobe-programming-language-award-of-2010/

[3] http://www.citi.org.br/blog/2010/12/14/python-entenda-a-tecnologia/

[4] https://groups.google.com/group/pug-pe?hl=pt

Aguardamos a presença de todos!

Atenciosamente,

Equipe PUG-PE


por marcelcaraciolo em 06 de December de 2011 às 11:57

marcelcaraciolo

Esta semana o membro do grupo Anderson Berg teve a oportunidade de ministrar uma palestra para os alunos da Farec (Faculdade do Recife) falando sobre o Python, incluindo biblioteca padrão, pacotes e frameworks úteis para todo tipo de projeto.  A seguir estão os slides:

Parabéns Anderson pelo excelente trabalho e pela divulgação da plataforma nas faculdades do Recife!
Mais informações no seu blog.
Equipe PUG-PE

por marcelcaraciolo em 06 de December de 2011 às 03:27

December 01, 2011

Artificial Intelligence in Motion

Review of the book Numpy 1.5 - Beginner's Guide

Hi all,

I'd like to share my review of the book Numpy 1.5 the Beginner's Guide by Ivan Idris, which is one of the latest books in a series of manuals covering scientific computing libraries written in Python.  This book covers the Numpy library for manipulating vectors and matrices and support for mathematical libraries.

Numpy 1.5  from Packt Publisher

Quick Review

The book is a great and useful resource for anyone who wants to explore further the Numpy scientific library since it covers almost all of the modules available at Numpy 1.5.  It comes with several examples, specially for finantial researchers and developers that work with finantial data. The author explored several modules using stocks and historical price data.  The authors explains each function or operation with code and the expected results, so the reader can follow precisely what's happening when he presents the modules. One of the values of the book is how it is organized: the step-by-step guide when he presents complex functions at Numpy, for example: add.reduceat, add.accumulate and add.reduce operators.
The part that I didn't like was about the exercises which was quite simple. I'd like to see deep exercises exploring the resources given at the book and I missed more information about NaN values. Also, I didn't  see information also about the functions squeeze, choose and about more complex structured arrays (arrays with tuples, etc.).

To sum up, I recommend this book for anyone whishing to learn about scientific computing with Python using the mathematical library Numpy which is a great alternative (and free !) for Matlab, Mathematica and other packages. I expect quite soon a book covering Scipy library also!  By the way, the finantial fans will love this book since it covers almost of the entire book with examples using finance data!

Review


The book starts with a step-by-step installation process of Numpy as also giving a litte introduction about what is Numpy, its history, etc.   I'd like to mention that even all the platforms covered at the book, Numpy is not so easy as mentioned to install at Mac OS.  The problem is that generally the developers don't use the built-in Python that comes with the Mac, since it is outdated (my Snow leopard comes with the Python 2.6.1). So when you install the new Python, that the problems come! Several compilation errors, messages that you can't understand, etc.  But if you go by using the MacPorts,  you will free of all these errors! ( After all the nightmare of the installation, I discovered the MacPorts :P).

The following chapters 2-4 presents the Numpy Fundamentals covering the array manipulations and most commonly used operations.  The books goes into a cyclic process, where each function that the author presents goes through an introduction about the problem to solve, the actions (how you with Numpy can solve), auxiliar numpy functions and operations and finally what just happened, that is, explain what he has done after showing the solution. The examples covered at book, most of them, are from finantial data and stock market values. An interesting choice since he used the same examples through the chapters in a progression and logical way.  Having each function and numpy featured described and explained made the book a good reference guide for someone using the library.  There were minor issues  related to the imports, he doesn't mention the imports in some examples,  for instance the numpy.loadtxt function when he uses the datetime module.  For a beginner that is studying Python for the first time, it may be harder to them to follow the examples, since he could not always tell where the functions or modules were coming from.

The second part of the book includes the matrices, universal functions, some scipy modules and the use of matplotlib and testing.  The chapter 5 covers the matrix module and universal functions such as add, divide, prod, sum and so on.  I missed some functions that weren't covered at this chapter such as numpy.choose or numpy.squeeze.  I believe the author didn't remember or didn't have space to mention these specific functions, but it does not prejudice at all the quality of the book. The chapter that I liked the most at the book was about testing. Several developers, special the scientific researchers are not used to test their code, so I believe it is a great chapter for anyone who wants to assure quality and avoid future bugs using Numpy testing modules.  The chapter should be more bigger and include more examples even creating test cases and tips for scientific developers.
Finally the last two chapters focus on plotting and Scipy integration. I think the plotting chapter should be at the beginning of the book, because he already uses lots of examples at the previous chapters with matplotlib and only at the end explain further about the library. The chapter is well-written and gives you sufficient content for beginning with Matplotlib. The last chapter covers the use of several scipy functions but it does not give deeper explanations about how it works as he did at the previous chapters with Numpy. However it gives several useful examples to work with integration, image processing and even optimization. Many developers will enjoy this extra-chapter covering the use of scipy+numpy.


Conclusions

 My overall impression of this book is that it could make a useful reference guide for Numpy. For finantial researchers and developers it will be a great book since it also covers lots of examples using finance data to present the numpy fundamentals.  There were minor issues related to Scipy and Matplotlib that should be more explained. For anyone who wants to start using Numpy it can a be an excellent book to begin, since it covers all the fundamentals steps with a cyclic progressive introduction of using the scientific packages in Python.

Regards,

Marcel Caraciolo

por Marcel Caraciolo (noreply@blogger.com) em 01 de December de 2011 às 07:08

November 24, 2011

Luciano Ramalho

Curso Online: Python para quem sabe Python

Este mini-curso de 12h destina-se a pessoas que já estudaram ou até já usam Python no dia-a-dia, mas querem conhecer mais profundamente como a linguagem funciona, como o Django e outros frameworks conseguem fazer certas coisas que parecem mágica, e como aproveitar recursos de Python que não existem em outras linguagens.

Tópicos


  • pérolas sub-utilizadas da biblioteca padrão
  • sobrecarga de operadores: usos benéficos
  • iteráveis e iteradores, geradores
  • comando with e gerenciadores de contexto
  • programação funcional e decoradores de funções
  • acesso, criação, remoção dinâmica de atributos
  • propridades e descritores
  • tratamento de acessos não previstos (ex. como "method_missing" de Ruby)
  • criação dinâmica de classes e monkeypatching
  • metaclasses

Formato

  • Instrutor: Luciano Ramalho
  • Curso online, com aulas interativas
  • Carga horária total: 12h
  • Preço: R$ 250
  • Vagas limitadas

Datas e Horários

Uma das opções a seguir será escolhida pela maioria dos interessados:
  • Sábados, 10h-13h (dias: novembro 26, dezembro 3, 10 e 17)
  • 2ª e 4ª-feira, 17h30-19h30 (dias: novembro 28 e 30, dezembro 5, 7, 12, 14)
  • 3ª e 5ª-feira, 21h-23h (dias: novembro 29, dezembro 1, 6, 8, 13, 15)

Para se inscrever

INSCRIÇÕES ENCERRADAS, EM 2012 TEM MAIS!
Se você tem interesse em participar deste curso, preencha o formulário cujo link aparece abaixo. Lá você terá a oportunidade de escolher o horário mais conveniente, e propor outros temas a serem tratados. Verifique com cuidado seu e-mail: eu vou entrar em contato pessoalmente com cada interessado para dar mais informações e esclarecer eventuais dúvidas.
Formulário de pré-inscrição (sem compromisso)


PS. O nome deste mini-curso foi inspirado no título de um livro de PHP do Juliano Niederauer, publicado pela editora Novatec. Mandou bem, Juliano!

por Luciano Ramalho (noreply@blogger.com) em 24 de November de 2011 às 05:44

November 21, 2011

Eventos da APyB

V Semana Acadêmica de Ciência da Computação - UFT

Semana Acadêmica de Computação é um evento que ocorre com periodicidade anual, sendo promovido pelo curso de Ciência da Computação da Fundação Universidade Federal do Tocantins (UFT) com apoio da FAPTO – Fundação de Apoio Científico e Tecnológico do Tocantins. Ao longo dos anos, esse evento científico em computação vem ganhando cada vez mais importância e respeito, agregando grande parte da comunidade regional cujo interesse em tecnologia e computação seja proveniente do meio acadêmico ou do meio empresarial e industrial.

As últimas quatro edições da Semana Acadêmica realizadas anualmente no campus de Palmas da UFT foram um sucesso superando todas as expectativas . Todas elas contaram com mais de 200 participantes e a cooperação de todos os docentes do curso, além de profissionais do mercado de trabalho e de professores de outras instituições, tornando possível a realização dos eventos com qualidade e eficácia. 

Dentre os destaques dessa edição contaremos com a presença do membro-fundador da Associação PythonBrasil, Érico Andrei (SP), que participará do evento com a palestra Linguagem, Framework, Comunidade e Conta-Bancária: Da Teoria a Prática, com o minicurso Introdução a Python e participará da mesa redonda.

Também contaremos com a presença do fundador e mantenedor da comunidade Viva e Linux, Fábio Berbert de Paula (RJ) que irá apresentar a palestra Desenvolvimento web: Conceitos e Tecnologias e o minicursoDesvendando o universo GNU/Linux.

V Semana Acadêmica de Ciência da Computação da UFT também contará com a 2ª edição da Maratona Interna de Programação.

A realização se dará nos dias 22, 23 e 24 de novembro 2011, proporcionando aos inscritos uma rica variedade de atividades como palestras de convidados de renome vindos de outras instituições, sessões técnicas, minicursos, debates e mesa redonda. 

 

por Érico Andrei em 21 de November de 2011 às 14:00

Aprenda Python

Várias versões de Python ao mesmo tempo

Estou precisando ter o Python 2.6 (padrão no Ubuntu 10.04) convivendo harmoniosamente com a versão 2.7. Ou seja, mais de uma versão no mesmo sistema operacional. Pesquisando, encontrei um repositório para Ubuntu com várias versões de Python: https://launchpad.net/~fkrull/+archive/deadsnakes Achei também uma forma de fazer com que elas não briguem e não atrapalhem o que já funciona, dentro do

por Vinicius Assef (noreply@blogger.com) em 21 de November de 2011 às 02:54

November 18, 2011

Gustavo Niemeyer

Launchpad + Rietveld == HappyCodeReviews

In the past week, I’ve finally stopped to fix something that I’ve been wishing for years: inline code reviews in Launchpad. Well, I haven’t exactly managed fix it in Launchpad, but the integration with Rietveld feels nice enough to be relatively painless.

The integration is done using the lbox tool, that was developed in Go using the lpad package for the communication with Launchpad, and a newly written rietveld package for communication with Rietveld.

If you want to join me in my happines, here are the few steps to get that working for you as well.

First, install lbox from the Launchpad PPA. Since it’s written in Go, it has no dependencies.

$ sudo add-apt-repository ppa:gophers/go
$ sudo apt-get update
$ sudo apt-get install lbox

Now, as an example of using it, let’s suppose we want to perform a change in the lbox code itself. First, we take the branch out of Launchpad.

$ mkdir hacking
$ cd hacking
$ bzr branch lp:lbox
Branched 9 revision(s).

Then, let’s create a feature branch based on the original trunk, and perform a change.

$ bzr branch lbox my-nice-feature
Branched 9 revision(s).

$ cd my-nice-feature
$ echo # Yo >> Makefile
$ bzr commit -m "Yo-ified makefile"
Committing to: /home/user/hacking/my-nice-feature/
modified Makefile
Committed revision 10.

Ok, we’re ready for the magic step, which is actually pushing that branch and proposing the merge on the original branch on both Launchpad and Rietveld. It’s harder to explain than to do it:

$ lbox propose -cr
2011/11/17 23:29:49 Looking up branch information for "."...
2011/11/17 23:29:49 Looking up branch information for "hacking/lbox"...
2011/11/17 23:29:49 Found landing target: bzr+ssh://bazaar.../lbox/
(...)

This command will ask you for a few details interactively, like your authentication details in Launchpad and in Rietveld (your Google Account, details sent over SSL to Google itself; you may have to visit Rietveld first for that to work), and also the change description.

In case something fails, feel free to simply execute the command again, as many times as you want. The command is smart enough to figure that an existing merge proposal and change in Rietveld exist and will update the existing ones with the new details you provide, rather than duplicating work.

Once the command finishes, you can visit the URL for the merge proposal in Launchpad that was printed, and you should see something like this:

Note that the change description already includes a link onto the Rietveld issue at codereview.appspot.com. The issue on Rietveld will look something like this:

Observe how the issue has the same description as the merge proposal, but it links back onto the merge proposal. At the left-hand side, there’s also an interesting detail: the original merge proposal email has been added as the reviewer of this change. This means that any changes performed in Rietveld will be mailed back onto the merge proposal for its record.

In the center you can find the meat of the whole work: the actual change set that is being reviewed. Rietveld works with patch sets, so that you can not only see a given change, but you can also review the history of proposals that the proponent has made, and any inline comments performed in them.

Click on the side-by-side link next to Makefile to get an overview of the actual change, and to make comments on it just click on the desired line:

Your comments won’t be sent immediately. Once you’re done making comments and want to deliver the review, click on the “Publish+Mail Comments” link at the top-right, which will take you onto a page that enables complementing with any heading details if desired.

Since the merge proposal is registered as the reviewer of the issue in Rietveld, publishing the review will deliver a message back onto the merge proposal itself, including context links that enable anyone to be taken to the precise review point back in Rietveld:

Then, once you do make the suggested changes and want to publish a new version of the branch, simply repeat the original command: “lbox propose -cr”. This will push the new diff onto Rietveld and create a new patch set. You’ll also be given the chance to edit the previous description, and any changes there will take place both in the merge proposal and in the Rietveld issue.

lbox also has other useful command line options, such as -bug, -new-bug, to associate Launchpad bugs with the merge proposal and put them in progress, or -bp to associate a blueprint with the branch and bug (if provided) being handled.

This should turn your code reviews in Launchpad into significantly more pleasant tasks, and maybe even save some of your precious life time for more interesting activities.

Happy reviewing!

por Gustavo Niemeyer em 18 de November de 2011 às 02:28

November 16, 2011

Christiano Anderson

Curso online de Python para quem sabe Python

 

 
  O Luciano Ramalho é uma das principais referências sobre Python no Brasil, além de ser um grande amigo. Já foi presidente da Associação Python Brasil, participa como palestrante de quase todos os eventos de software livre e suas palestras são bem didáticas, com conteúdo altamente capacitado.

O Ramalho gosta de ensinar, tem uma didática incrível uma grande experiência de mercado. Ele está lançando seu curso online de Python para quem já sabe Python e procura agregar um conhecimento ainda mais profundo sobre a linguagem, conhecendo técnicas mais avançadas e naturalmente, aprendendo com alguém que é referência no assunto.

Os principais tópicos desse mini curso são:

  • pérolas sub-utilizadas da biblioteca padrão
  • sobrecarga de operadores: usos benéficos
  • iteráveis e iteradores, geradores
  • comando with e gerenciadores de contexto
  • programação funcional e decoradores de funções
  • acesso, criação, remoção dinâmica de atributos
  • propridades e descritores
  • tratamento de acessos não previstos (ex. como “method_missing” de Ruby)
  • criação dinâmica de classes e monkeypatching
  • metaclasses
Como sei que tem muita gente querendo um treinamento mais avançado de Python, está aí uma ótima indicação.
Mais informações e como se inscrever, acesse o blog do Ramalho.

por Christiano Anderson em 16 de November de 2011 às 12:33

November 14, 2011

Artificial Intelligence in Motion

Machine Learning with Python - Logistic Regression

 Hi all,

I decided to start a new series of posts now focusing on general machine learning with several snippets for anyone to use with real problems or real datasets.  Since I am studying machine learning again with a great course online offered this semester by Stanford University, one of  the best ways to review the content learned is to write some notes about what I learned. The best part is that it will include examples with Python, Numpy and Scipy. I expect you enjoy all those posts!

The series:


In this post I will cover the Logistic Regression and Regularization.


Logistic Regression


Logistic Regression is a type of regression that predicts the probability of ocurrence of an event by fitting data to a logit function (logistic function).  Like many forms of regression analysis, it makes use of several predictor variables that may be either numerical or categorical. For instance, the probability that a person has a heart attack within a specified time period might be predicted from knowledege of the person's age, sex and body mass index. This regression is quite used in several scenarios such as prediction of customer's propensity to purchase a product or cease a subscription in marketing applications and many others. 


Visualizing the Data



Let's explain the logistic regression by example. Consider you are the administrator of a university department and you want to determine each applicant's chance of admission based on their results on two exams. You have the historical data from previous applicants that you can use as a trainning set for logistic regression.  For each training example, you have the applicant's scores on two exams and the admissions decision.   We will use logistic regression to build this model that estimates the probability of admission based the scores from those two exams.

Let's first visualize our data on a 2-dimensional plot as show below. As you can see the axes are the two exam scores, and the positive and negative examples are shown with different markers.

Sample training visualization

The code


Costing Function and Gradient



The logistic regression hypothesis is defined as:

where the function g  is the sigmoid function. It is defined as:


The sigmoid function has special properties that can result values in the range [0,1].  So you have large positive values of X, the sigmoid should be close to 1, while for large negative values,  the sigmoid should be close to 0.

Sigmoid Logistic Function 

The cost function and gradient for logistic regression is given as below:


and the gradient of the cost is a vector theta where the j element is defined as follows:



You may note that the gradient is quite similar to the linear regression gradient, the difference is actually because linear and logistic regression have different definitions of h(x).

Let's see the code:






Now to find the minimum of this cost function, we will use a scipy built-in function called fmin_bfgs.  It will find the best parameters theta for the logistic regression cost function given a fixed dataset (of X and Y values).
The parameters are:
  • The initial values of the parameters you are trying to optimize;
  • A function that, when given the training set and a particular theta, computes the logistic regression cost and gradient with respect to theta for the dataset (X,y).

The final theta value will then be used to plot the decision boundary on the training data, resulting in a figure similar to the figure below.






Evaluating logistic regression



Now that you learned the parameters of the model, you can use the model to predict whether a particular student will be admited. For a student with an Exam1 score of 45 and an Exam 2 score of 85, you should see an admission probability of 0.776.

But you can go further, and evaluate the quality of the parameters that we have found and see how well the learned model predicts on our training set.  If we consider the threshold of 0.5 using our sigmoid logistic function, we can consider that:


Where 1 represents admited and -1 not admited.

Going to the code and calculate the training accuracy of our classifier we can evaluate the percentage of examples it got correct.  Source code.



89% , not bad hun?! 



Regularized logistic regression



But when your data can not be separated into positive and negative examples by a straight-line trought the plot ?  Since our logistic regression will be only be able to find a linear decision boundary, we will have to fit the data in a better way. Let's go through an example.

Suppose you are the product manager of the factory and you have the test results for some microships  of two different tests. From these two tests you would like to determine whether the microships should be accepted or rejected.  We have a dataset of test results on past microships, from which we can build a logistic regression model.  





Visualizing the data



Let's visualize our data. As you can see in the figure below, the axes are the two test scores, and the positive (y = 1, accepted) and negative (y = 0, rejected) examples are shown with different markers.
Microship training set 

You may see that the model built for this task may predict perfectly all training data and sometimes it migh cause some troubling cases.  Just because ithe model can perfectly reconstruct the training set does not mean that it had everything figured out.  This is known as overfitting.   You can imagine that if you  were relying on this model to make important decisions, it would be desirable to have at least of regularization in there. Regularization is a powerful strategy to combat the overfitting problem. We will see it in action at the next sections.





Feature mapping



One way to fit the data better is to create more features from each data point. We will map the features  into all polynomial terms of x1 tand x2 up to the sixth power.


As a result of this mapping, our vector of two features (the scores on two QA tests) has been transformed into a 28-dimmensional vector. A logistic regression classifier trained on this higher dimension feature vector  will have a more complex decision boundary and will appear nonlinear when drawn in our 2D plot.


Although the feature mapping allows us to buid a more expressive classifier, it also me susceptible to overfitting. That comes the regularized logistic regression to fit the data and avoid the overfitting problem.


Source code.


Cost function and gradient


The regularized cost function in logistic regression is :


Note that you should not regularize the parameter theta, so the final summation is for j = 1 to n, not j= 0 to n.  The gradient of the cost function is a vector where the jn element is defined as follows:



Now let's learn the optimal parameters theta.  Considering now those new functions and our last numpy optimization function we will be able to learn the parameters theta. 

The all code now provided (code)







Plotting the decision boundary



Let's visualize the model learned by the classifier. The plot will display the non-linear decision boundary that separates the positive and negative examples. 

Decision Boundary


As you can see our model succesfully predicted our data with accuracy of 83.05%.

Code





Scikit-learn



Scikit-learn is an amazing tool for machine learning providing several modules for working with classification, regression and clustering problems. It uses python, numpy and scipy and it is open-source!

If you want to use logistic regression and linear regression you should take consider the scikit-learn. It has several examples and several types of regularization strategies to work with.  Take a look at this link and see by yourself!  I recommend!




Conclusions



Logistic regression has several advantages over linear regression, one specially it is more robust and does not assume linear relationship since it may handle nonlinear effects. However it requires much more data to achieve stable, meaningful results.  There are another machine learning techniques to handle with non-linear problems and we will see in the next posts.   I hope you enjoyed this article!


All source from this article here.

Regards,

Marcel Caraciolo


por Marcel Caraciolo (noreply@blogger.com) em 14 de November de 2011 às 18:43

November 08, 2011

PUG - PE

Público ganhando brindes do PUG-PE

Olá pessoal,

Neste último sábado (05/11/2011) tivemos a oportunidade de realizar o nosso XVI Encontro do Grupo de Usuários de Python de Pernambuco.  Este evento foi realizado pela segunda vez na Escola Politécnica de Pernambuco (POLI- UPE) em Recife-Pernambuco.  Foi um evento bem recheado de palestras, especialmente algumas ministradas por palestrantes que também ministraram na PythonBrasil, palestra convidada de outro grupo local: IXDA e diversas palestras relâmpago (maior edição do Toró de Palestras até hoje com 5 ao total).

Queremos agradecer a participação de todos em especial nossa equipe Luciano Rodrigues (@lucrodsilva), Guilherme Medeiros (@frenetic_br) , Fernando Rocha (@fernandogrd), Daker Fernandes (@dakerfp), Gregório Neto (nosso web-designer), Rodrigo Lira, Afif entre outros que nos auxiliaram na organização deste encontro.  Os nossos patrocinadores que tem um papel importantíssimo na construção deste evento: empresas Idealizza (@idealizza), Orygens (@orygens) e a Hostech.

Algumas fotos do público presente:

Público no XVI Encontro do PUG-PE

Público no XVI Encontro do PUG-PE

Público presente no XVI Encontro do Grupo de Usuários de Python de Pernambuco

Público presente no XVI Encontro do Grupo de Usuários de Python de Pernambuco

 

Nossa primeira palestra foi ministrada por Marcel Caraciolo (@marcelcaraciolo)) sobre comunidades open-source e o sucesso do PUG-PE. Esta palestra falou um pouco da história do Grupo assim como motivação para outros que desejam construir comunidades e células em sua cidade, região, bairro, faculdade, empresa, igreja, etc.  Uma palestra bem dinâmica e inspiradora!

Algumas fotos abaixo da palestra:

Marcel Caraciolo apresentando sobre o PUG-PE

Marcel Caraciolo apresentando sobre o PUG-PE

 

Slides disponíveis aqui:

A segunda palestra foi ministrada pelo Gustavo Henrique , doutorando do CIN/UFPE que falou sobre NoSQL, em especial, sobre a tecnologia e o uso do Cassandra, plataforma adotada pela empresa que ele trabalhou durante um projeto em que ele estava alocado.  Foi uma palestra bem didática com apresentação sobre vários conceitos relacionados a NoSQL e no fim com uma breve apresentação do Cassandra se comunicando com a plataforma Python! Vale salientar que também foi palestra apresentada na PythonBrasil!

Abaixo os slides disponíveis:

Algumas fotos de sua palestra:

 

Gustavo Henrique apresentando sobre o NoSQL

Gustavo Henrique apresentando sobre o NoSQL

Gustavo Henrique apresentando sobre Cassanda e NoSQL

Gustavo Henrique apresentando sobre Cassanda e NoSQL

 

Como sempre tivemos nosso belo coffee-break regado a salgadinhos e biscoitos! Mas o mais legal  é o networking construído durante esses intervalos! Muita discussão e troca de idéias!

Algumas fotos do intervalo:

Intervalo durante o Encontro do PUG-PE

Intervalo durante o Encontro do PUG-PE

Intervalo durante o Encontro do PUG-PE

Intervalo durante o Encontro do PUG-PE

No retorno tivemos a palestra do Daker Fernandes (@dakerfp) que apresentou sobre Python e Cadeias de Markov (GHMM) especialmente focado em Biologia Computacional. Esta palestra também apresentada na PythonBrasil. De maneira bem simples, Daker apresentou os conceitos iniciais desta poderosa área de computação científica e estatística para aplicação de previsão e modelagem de simulações.  E poucos sabem que Python também pode ser aplicado em Biologia Computacional!

Fotos da palestra de Daker:

 

Daker apresentando sobre GHMM e Cadeias de Markov

Daker apresentando sobre GHMM e Cadeias de Markov

Slides da Palestra de Daker:

A próxima palestra foi a do convidado Rodrigo Medeiros, membro do grupo IXDA (Design de Interação) que apresentou sobre visualização da informação. Uma palestra que brilhou os olhos de muita gente com vários modelos e formatos de exibição de dados e a sua atual necessidade de plataformas para construção dessas visualizações. Atualmente ele vem estudando Python para aplicar na construção de novos modelos e também na exposição dos dados públicos governamentais por meio de API’s.  Muito legal essa mesclagem com outros grupos e ver o que Python também pode ajudar!

Fotos do palestrante Rodrigo Medeiros

Rodrigo Medeiros falando sobre Visualização da Informação

Rodrigo Medeiros falando sobre Visualização da Informação

Rodrigo Medeiros apresentando sobre Visualização de Informação

Rodrigo Medeiros apresentando sobre Visualização de Informação

Slides da Palestra do Rodrigo

Depois da palestra do Rodrigo iniciamos nossa sessão de Toró de palestras com palestras sobre vários temas. Começamos com a palestra do Fernando Rocha (@fernandogrd) sobre o mitos de Python quando estamos na graduação.  Fernando discutiu sobre a existência de ponteiros em Python, que muitos às vezes não sabem que existem e acham que em Python é tudo automágico ( e na verdade não é , tem muita coisa acontecendo por trás!). Foi uma discussão bem aquecida com todos os presentes, apresentando diversos pontos de vista.

Abaixo slides e fotos:

Fernando Rocha apresentando sobre os Mitos de Python

Fernando Rocha apresentando sobre os Mitos de Python

Nossa segunda palestra relâmpago foi a do André Ericsson (@_aericson) que apresentou sobre o uso de Python em soluções automatizadas. Ele comentou como usou Python em seus projetos em que ele precisou automatizar algumas tarefas que ele tinha que realizar manualmente. Por exemplo: reserva de livros da biblioteca da sua faculdade ou até descoberta de legendas dos seriados de forma automática. Tudo isso usando Python, Mechanize, BeautifulSoup e uma série de outras ferramentas! Foi bem legal a palestra!!

Slides da palestra do André e fotos:

André Ericson apresentando sobre Tarefas Automatizadas com Python

André Ericson apresentando sobre Tarefas Automatizadas com Python

 

A próxima palestra foi a Hugo Serrano, mestre em ciência da computação pela POLI/UPE que apresentou seu trabalho com um doutorando focado em otimização de sistemas para captação de água pluvial. Por meio do uso de técnicas inteligentes de otimização, ele construiu um simulador com uma interface bem amigável para descobrir parâmetros que minimizem o tempo de retorno do investimento na construção do sistema. Ele usou plataformas como PyGtk, Python , Numpy e Scipy! Um trabalho muito bem feito e prato cheio pra futuras palestras!!

Abaixo slides e as fotos da palestra do Hugo:

Hugo Serrano apresentando sobre o seu trabalho: RainToolbox

Hugo Serrano apresentando sobre o seu trabalho: RainToolbox

 

A próxima palestra foi a do Daker Fernandes (@dakerfp) que falou sobre um plugin que ele desenvolveu durante a faculdade para processamento de sinais: DSP-Tools. Ele mostrou como python pôde simplificar na construção de um sistemas de pluggins por meio de decoradores que facilitou bastante seu trabalho durante o trabalho de uma disciplina da faculdade. Valeu Daker!

Link para o repositório no Github.

Por fim a palestra do Flávio Juvenal (@flaviojuvenal) que apresentou a experiência dele e de seu time em construir uma startup em 54 horas com Python durante a StartUpWeekend realizada em Recife há algumas semanas atrás. Eles tiveram que montar uma startup do zero e apresentar um produto concebido durante um fim de semana. Escolheram Python como plataforma de desenvolvimento pela rapidez e produtividade e Django como framework Web. O resultado foi a ferramenta TimeBreak.Me que foi bem votada entre as startups apresentadas no final do evento!  Parabéns a todo time!

Foto do TimeBreak.me:

TimeBreak.me em ação!

TimeBreak.me em ação!

Apresentação do Flávio em slides e sua foto:

Flávio Juvenal apresentando como Construiu uma Startup em 54 hrs com Python

Flávio Juvenal apresentando como Construiu uma Startup em 54 hrs com Python

E assim terminamos o nosso XVI Encontro! Infelizmente não pudemos tirar uma foto com todos reunidos, mas tivemos algumas fotos do público que recebeu os brindes sorteados durante o encontro!  Agradecemos a presença de todos e até a próxima!

Público ganhando brindes do PUG-PE

Público ganhando brindes do PUG-PE

 

 

 

 

Público ganhando brindes do PUG-PE

Público ganhando brindes do PUG-PE

 

Link para fotos do  XVI Encontro.

Atenciosamente,

Marcel Caraciolo

Links para os assuntos discutidos

 


por marcelcaraciolo em 08 de November de 2011 às 02:59

November 04, 2011

Artificial Intelligence in Motion

Google AI Challenge this year is open! Ants Battlefield!

Hi all,

One more time Google and the University of Waterloo's computer science club have launched an Artificial Intelligence challenge. This year the task is to write a program to compete in the Ants Multiplayer Challenge. The goal is seek and destroy the most enemy ant hills while defending their own hills.  You must create a bot that plays the game of Ants as intelligently as possible.  The contest supports languages in Python, Java, C# and C++.

The current state of the contest, which you can submit your project, is until December 18th. After, there will be a final tournament between the contestants to decide the ultimate winner!

See  the game in action at the video below.





It is a great opportunity to learn Artificial Intelligence and play with your skills at programming, machine learning and logical reason!

Regards,

Marcel Caraciolo  


por Marcel Caraciolo (noreply@blogger.com) em 04 de November de 2011 às 23:23

November 02, 2011

PUG - PE

XVI Encontro do Grupo de Usuários de Python de Pernambuco

Olá pessoal,

Gostaria de convidar a todos para a nossa Décima Sextaa edição (XVI) do Encontro mensal do grupo de usuários de Python de Pernambuco (PUG-PE) que será realizada na dependências da  Escola Politécnica de Pernambuco (POLI) no auditório situado na Rua Benfica vizinho ao clube Internacional no Derby.

O encontro será realizado no dia 05 de novembro de 2011 (Sábado) a partir das 08:30 no auditório da POLI com entrada gratuita!

 

XVI Encontro do Grupo de Usuários de Python de Pernambuco

XVI Encontro do Grupo de Usuários de Python de Pernambuco

Neste encontro teremos as palestras que foram realizadas durante o VII Encontro Brasileiro da Comunidade Python (PythonBrasil) pelos pernambucanos!   Teremos a palestra sobre NoSQL com Python por Gustavo da Neurotech e doutorando do CIN/UFPE, palestra sobre integração de plataformas com Python por Bruno Melo da startup AIBOX,  a palestra sobre GMM e Cadeias de Markov por Daker Fernandes, engenheiro da Nokia e recém-graduado do CIN/UFPE, palestra sobre sistemas de recomendação por Marcel Caraciolo, cientista chefe da startup Orygens.com e Atepassar.com e uma palestra convidada com Rodrigo Medeiros sobre Visualização de Dados da comunidade IXDAA e palestras relâmpago com vários assuntos desde criação de startups em 54 horas com Python à uso de crawlers com Python.  Vai ser muito maneiro!  Teremos o lançamento do projeto “Quero um Dojo na minha empresa” que deverá começar a partir de janeiro de 2012 e a experiência do PUG-PE Summer of Code que foi realizada neste mês pelos participantes do evento!

Para quem não conhece Python, eis uma excelente oportunidade de conhecer a plataforma e sua aplicação em diversos nichos como web, sistemas embarcados, computação científica, etc. Ela foi considerada a linguagem de programação de maior crescimento em 2010, de acordo com o índice Tiobe [1] e é utilizada por empresas reconhecidas no mercado como Google, Nasa, Globo.com, Sepro, etc. Para mais informações e a nossa programação completa visitar o link [2].

Para mais informações sobre o encontro , visitar o HotSite Oficial do XV Encontro [3]. Uma ótima oportunidade de fazer networking, aprendizado e conversar sobre software livre e colaborativo! Participe também da nossa lista de discussão para troca de idéias [4]. O Evento está sendo patrocinado pelas startups pernambucanas Orygens, Idealizza e Hostech.

[1 ]http://www.geeks3d.com/20110121/tiobe-index-january-2011-python-wins-the-tiobe-programming-language-award-of-2010/

[2] http://www.citi.org.br/blog/2010/12/14/python-entenda-a-tecnologia/

[3] http://pug-pe.python.org.br/encontro/xvi/

[4] https://groups.google.com/group/pug-pe?hl=pt

Aguardamos a presença de todos!

Atenciosamente,

Marcel Caraciolo


por marcelcaraciolo em 02 de November de 2011 às 14:23

October 31, 2011

Luciano Ramalho

Academia Python: de 0 a 100 em 3½ meses

Quem me conhece sabe que eu adoro lecionar, e nos últimos anos tenho trabalhado como desenvolvedor de sistemas usando a elegante e poderosa linguagem Python, a minha favorita no momento.

Agora estou unindo essas duas paixões, lançando em parceria com a Globalcode a Academia Python, uma formação completa para programadores, que leva do básico ao avançado nesta linguagem, em 3 meses e meio de aulas, 2 vezes por semana.

Porque Python é especial

Python é uma linguagem muito simples para começar a aprender, mas ao mesmo tempo é largamente utilizada para inovação em uma grande variedade de empresas, como YouTube, Industrial Light & Magic, Globo.com e Dropbox.

Existem outras linguagens simples de aprender, mas elas costumam ter limitações práticas que atrapalham seu uso em ambientes profissionais, e existem outras linguagens usadas profissionalmente, mas nenhuma é tão fácil de aprender quanto Python.

Qual é o segredo deste mistério? As principais idéias de Python vêm da linguagem ABC, desenvolvida ao longo de 10 anos de pesquisa científica e testes com usuários para chegar a uma linguagem amigável e prática. Por exemplo, o laço for do Python é o mais simples possível:


>>> for letra in 'Python':
... print letra
...
P
y
t
h
o
n

Ao mesmo tempo, é uma linguagem que oferece recursos avançados e modernos de programação, como Orientação a Objetos com sobrecarga de operadores e meta-classes, iteradores, co-rotinas, meta-programação. O resultado é que Python vem sendo cada vez mais usada como primeira linguagem em cursos de computação ao redor do mundo (da FATEC ao MIT), e ao mesmo tempo é usada em grandes sites como Google, YouTube, Globo.com, nas principais empresas computação gráfica, como Industrial Light & Magic, The Foundry, e Autodesk. Python vem pré-instalada no Mac OSX e em praticamente qualquerLinux, e é fácil de instalar no Windows.

Porque fazer uma Academia na Globalcode

A Globalcode é uma empresa que tem tido muito sucesso oferecendo cursos sobre Java há 10 anos. Uma das fórmulas desse sucesso tem sido as Academias: formações completas com mais de 100 horas de aula (para comparar, uma disciplina típica de computação na USP tem 60 horas). Enquanto muitos cursos livres concentram conteúdo em turmas intensivas de curta duração, as Academias oferecem 8 horas de aula por semana, assim os alunos têm tempo para absorver, exercitar e aplicar o que foi visto no curso. A Academia Python tem 112 horas, o que dá 14 semanas (sem contar feriados). São três meses e meio de convívio entre alunos e o instrutor, uma vivência muito mais rica do que um curso rápido pode oferecer.

Como é a Academia Python

A estrutura da Academia Python reflete as próprias características da linguagem: começa com um módulo básico de 16 horas, acessível para qualquer pessoa que saiba programar em qualquer linguagem, mas chega ao quinto módulo abordando tópicos avançados como bancos de dados não-relacionais, programação assíncrona de alto desempenho e arquiteturas de sistemas distribuídos na nuvem (cloud computing).

Os módulos são:

  1. Introdução à linguagem Python: dominando a sintaxe, tipos de dados e funções básicas através de tarefas práticas de conversão de arquivos (16h)
  2. Orientação a Objetos e frameworks: exemplos em Django (framework Web) e Tkinter (desktop GUI) para demonstrar para que servem e como usar os conceitos de encapsulamento, herança e polimorfismo (24h)
  3. Desenvolvimento Web com Django e JQuery: como construir uma aplicação Web moderna usando Django, framework adotado pela Globo.com e JQuery, a biblioteca JavaScript mais importante do momento (32h)
  4. Django profissional: tópicos avançados de desenvolvimento Web com Django, incluindo testes automatizados, deployment com Apache e lighttpd, migração de modelos de dados e geração de relatórios em PDF, entre outros (20h)
  5. Cloud, NoSQL e novas arquiteturas: Google App Engine, MongoDB e programação assíncrona com para sites altamente escaláveis (20h)

Para saber mais

A primeira turna da Academia Python está prevista para começar dia 8 de novembro, com aulas 3ª e 5ª de 19h a 23h na Globalcode de São Paulo (metrô Paraíso). Mais detalhes, preços e matrícula na página da Academia Python na Globalcode.

Dia 1º de novembro vamos oferecer um mini-curso gratuito de Introdução à Programação Orientada a Objetos em Python na Globalcode de São Paulo (metrô Paraíso) e também via Webcast. Inscrições pelo site da Globalcode.

por Luciano Ramalho (noreply@blogger.com) em 31 de October de 2011 às 11:56

October 27, 2011

Artificial Intelligence in Motion

Machine Learning with Python - Linear Regression

Hi all,

I decided to start a new series of posts now focusing on general machine learning with several snippets for anyone to use with real problems or real datasets.  Since I am studying machine learning again with a great course online offered this semester by Stanford University, one of  the best ways to review the content learned is to write some notes about what I learned. The best part is that it will include examples with Python, Numpy and Scipy. I expect you enjoy all those posts!


Linear Regression

In this post I will implement the linear regression and get to see it work on data.  Linear Regression is the oldest and most widely used predictive model in the field of machine learning. The goal is to  minimize the sum of the squared errros to fit a straight line to a set of data points.  (You can find further information at Wikipedia).

The linear regression model fits a linear function to a set of data points. The form of the function is:

Y = β0 + β1*X1 + β2*X2 + … + βn*Xn


Where Y is the target variable,  and X1X2, ... Xare the predictor variables and  β1β2, … βare the coefficients that multiply the predictor variables.  βis constant. 

For example, suppose you are the CEO of a big company of shoes franchise and are considering different cities for opening a new store. The chain already has stores in various cities and you have data for profits and populations from the cities.  You would like to use this data to help you select which city to expand next. You could use linear regression for evaluating the parameters of a function that predicts profits for the new store.

The final function would be:

                                                         Y =   -3.63029144  + 1.16636235 * X1


There are two main approaches for linear regression: with one variable and with multiple variables. Let's see both!

Linear regression with one variable

Considering our last example, we have a file that contains the dataset of our linear regression problem. The first column is the population of the city and the second column is the profit of having a store in that city. A negative value for profit indicates a loss.

Before starting, it is useful to understand the data by visualizing it.  We will use the scatter plot to visualize the data, since it has only two properties to plot (profit and population). Many other problems in real life are multi-dimensional and can't be plotted on 2-d plot.



If you run this code above (you must have the Matplotlib package installed in order to present the plots), you will see the scatter plot of the data as shown at Figure 1.

                               
                                  

Now you must fit the linear regression parameters to our dataset using gradient descent. The objective of linear regression is to minimize the cost function:


where the hypothesis H0 is given by the linear model:


The parameters of your model are the θ values. These are the values you will adjust to minimize cost J(θ). One way to do it is to use the batch gradient descent algorithm. In batch gradient, each iteration performs the update:



With each step of gradient  descent, your parameters θ, come close to the optimal values that will achieve the lowest cost J(θ).

For our initial inputs we start with our initial fitting parameters θ, our data and add another dimmension to our data  to accommodate the θo intercept term. As also our learning rate alpha to 0.01.



As you perform gradient descent to learn minimize the cost function J(θ), it is helpful to monitor the convergence by computing the cost. The function cost is show below:


A good way to verify that gradient descent is working correctly is to look at the value of J(θ) and check that it is decreasing with each step. It should converge to a steady valeu by the end of the algorithm.

Your final values for θ will be used to make predictions on profits in areas of 35.000 and 70.000 people.  For that we will use some matrix algebra functions with the packages Scipy and Numpy,  powerful Python packages for scientific computing.

Our final values as shown below:


                                                         Y =   -3.63029144  + 1.16636235 * X1


Now  you can use this function to predict your profits!  If you use this function with our data we will come with plot:



Another interesting plot is the contour plots, it will give you how J(θ) varies with changes in θo and  θ1.  The cost function J(θ) is bowl-shaped and has a global mininum as you can see in the figure below.



This minimum is the optimal point for θo and θi, and each step of gradient descent moves closer to this point.

All the code is shown here.



Linear regression with multiple variables



Ok, but when you have multiple variables ? How do we work with them using linear regression ? That comes the linear regression with multiple variables. Let's see an example:

Suppose you are selling your house and you want to know what a good market price would be. One way to do this is to first collect information on recent houses sold and make a model of housing prices.

Our training set of housing prices in Recife, Pernambuco, Brazil are formed by three columns  (three variables). The first column is the size of the house (in square feet), the second column is the number of bedrooms, and the third column is the price of the house.

But before going directly to the linear regression it is important to analyze our data. By looking at the values, note that house sizes are about 1000 times the number of bedrooms. When features differ by orders of magnitude, it is important to perfom a feature scaling that can make gradient descent converge much more quickly.



The basic steps are:

  • Subtract the mean value of each feature from the dataset.
  • After subtracting the mean, additionally scale (divide) the feature values by their respective “standard deviations.”

The standard deviation is a way of measuring how much variation there is in the range of values of a particular feature (most data points will lie within ±2 standard deviations of the mean); this is an alternative to taking the range of values (max-min).

Now that you have your data scaled, you can implement the gradient descent and the cost function.

Previously, you implemented gradient descent on a univariate regression problem. The only difference now is that there is one more feature in the matrix X. The hypothesis function and the batch gradient descent update rule remain unchanged.


In the multivariate case, the cost function can also be written in the following vectorized form:

                                                            J(θ)=12m(Xθy)T(Xθy)

After running our code, it will come with following function:

             215810.61679138,   61446.18781361,   20070.13313796


The gradient descent will run until convergence to find the final values of θ.  Next, we will this value of θ to predict the price of a house with 1650 square feet and 3 bedrooms.

                                                          θ:=θα1mxT(xθTy)



Predicted price of a 1650 sq-ft, 3 br house: 183865.197988


If you plot the convergence plot of the gradient descent you may see that convergence will decrease as the number of iterations grows.



The code for linear regression with multi variables is available here.

Extra Notes


The Scipy package comes with several tools for helping you in this task, even with a module that has a linear regression implemented for you to use!

The module is scipy.stats.linregress  and implements several other techniques for updating the theta parameters.  Check more about it here.

Conclusions


The goal of regression is to determine the values of the ß parameters that minimize the sum of the squared residual values (difference betwen predicted and the observed) for the set of observations. Since linear regression is restricted to fiting linear (straight line/plane) functions to data, it's not adequate to real-world data as more general techniques such as neural networks which can model non-linear functions.  But linear regression has some interesting advantages:


  • Linear regression is the most widely used method, and it is well understood.
  • Training a linear regression model is usually much faster than methods such as neural networks.
  • Linear regression models are simple and require minimum memory to implement, so they work well on embedded controllers that have limited memory space.
  • By examining the magnitude and sign of the regression coefficients (β) you can infer how predictor variables affect the target outcome.
  • It's is one of the simplest algorithms and available in several packages, even Microsoft Excel!



I hope you enjoyed this simple post, and in the next one I will explore another field of machine learning with Python! You can download the code at this link.


Marcel Caraciolo






por Marcel Caraciolo (noreply@blogger.com) em 27 de October de 2011 às 22:05

October 24, 2011

Aprenda Python

Programe conforme o PEP8

Quando escrevemos programas na linguagem Python, é bom seguirmos as recomendações do  PEP8, que é uma convenção com padrões de codificação e recomenda, dentre outras coisas, que não misturamos tabs e espaços. Como o PEP8 é formado de várias recomendações, às vezes é trabalhoso ficar conferindo se você está dentro do padrão ou não. Quando se aprende, tudo vai automático, mas quando você vem de

por Vinicius Assef (noreply@blogger.com) em 24 de October de 2011 às 16:14

October 17, 2011

Kodumaro

Racket

Racket Outro dia procurando por um bom interpretador/compilador para R⁶RS, encontrei algo muito mais interessante…

Encontrei o RAD-IDE Racket, antigo DrScheme.

O interessante do Racket é que, além de ser um interpretador e compilador de R⁵RS e R⁶RS, também suporta – aliás, por padrão – uma linguagem de programação baseada em Scheme, também chamada Racket – antiga PLT Scheme –, muito poderosa; também traz um ambiente de desenvolvimento chamado DrRacket.

Quando você escreve um script em Scheme, a primeira linha indica a versão que você pretende usar:
#!r4rs

Ou:
#!r5rs

Ou:
#!r6rs


Se o interpretador suportar a versão, ela será usada. Já no caso do Racket, outras opções são suportadas, como o padrão:
#lang racket

Para a linguagem padrão.

[update 2011-10-18]
Um script R⁶RS começa sempre com um import, por exemplo:
#!r6rs
(import (rnrs))


Você pode ter as funções de R⁶RS em um código Racket (PLT), basta usar:
#lang racket
(require rnrs)


O módulo rnrs traz toda a funcionalidade de R⁶RS.

Outra coisa legal da linguagem Racket é que, em vez de lambda, você pode usar λ (⌘\ / C-\).
[/update]


E até mesmo:
#lang planet jaymccarthy/c

Para linguagem de programação C – uma opção de C interpretado!

Para tanto você precisa ter em seu ~/.racketrc o seguinte conteúdo:
#lang racket
(require (planet jaymccarthy/c:1:2))


Para instalar o módulo C, você pode executar no widget de definições (⌘D no Mac OS X, C-d no Windows e no GNU/Linux):
> (require (planet "main.rkt" ("jaymccarthy" "c.plt" 1 2)))


[update 2011-10-18]
Eu acho que você não precise instalar o módulo, basta colocar sua chamada em ~/.racketrc e, na primeira execução, o módulo será automaticamente baixado e instalado.

Só não posso afirmar com certeza porque eu já havia instalado ele antes.

No Windows, o arquivo é racketrc.rktl e deve ficar no diretório de perfil do usuário.
[/update]


Programação visual


Para facilitar a vida de quem precisa desenvolver aplicações gráficas, você pode usar o MrEd Designer.

Para instalá-lo, execute no widget de definições do DrRacket:
> (require (planet orseau/mred-designer:3:7))


Para iniciar o processo, use (recomendo criar um alias):
bash$ gracket -e '(require (planet orseau/mred-designer:3:7))'


Olá Mundo!


Vamos criar um programa simples. Primeiro abra o MrEd Designer.

[update 2011-10-19]
Troquei os nomes dos widgets pelos nomes usados no código Racket.
[/update]


Na janela Hierarchy selecione project-XXX.

Na janela MrEd Designer, na seção Containers, clique no primeiro botão, frame%.

Vai surgir uma janela pequena e, na hierarquia do projeto, um frame% (frame-XXXX) sob o projeto.

Na janela Hierarchy selecione o frame% que apareceu e repare que a janela Properties mudou.

Em Properties, mude o valor de label (que está Frame) para Olá Mundo! e clique em Save & Update Preview.

Veja que o título da janela mudou.

Agora, ainda com o frame% selecionado, na janela MrEd Designer, na seção Controls, clique no primeiro botão, message%. Repare que surgiu um elemento message% (message-XXXX) na hieraquia, sob o frame%.

Selecione o novo elemento e mude o label (em Properties) para Olá Mundo!.

Clique em Choose Font… e escolha uma fonte maior, sugiro Arial Bold 20, e clique em Ok.

Clique novamente em Save & Update Preview.

Selecione de novo o frame% em Hierarchy e, em MrEd DesignerControls, clique no segundo botão, button%.

Surgirá um elemento button% (button-XXXX) sob o frame%. Selecione-o.

Mude o label para Ok e a fonte para Arial 14. Clique em Save & Update Preview.

Agora, na janela MrEd Designer, no menu File clique em Save Project – ou pressione ⌘S / C-s. Escolha o diretório e salve como ola.

Depois clique em FileGenerate Scheme File… – ⌘F5 no Mac. Salve como ola.ss no mesmo diretório onde você salvou o projeto.

Repare que você terá dois arquivos: ola.*.med (o projeto) e ola.ss (o código).

Abra agora o arquivo ola.ss no DrRacket:
bash$ drracket ola.ss


Procure a seguinte linha:
(button-XXXX-callback (lambda (button control-event) (void))))


Onde XXXX é uma sequência de dígitos decimais.

Mude para:
(button-XXXX-callback (lambda (button control-event) (displayln "Olá Mundo!"))))


Veja a linha 8 do script:
;;; Call (project-XXX-init) with optional arguments to this module


Acrescente a linha sugerida ao final do arquivo:
(project-XXX-init)


Salve o arquivo – ⌘S / C-s – depois rode/corra o programa – ⌘T / C-t – e veja a mágica.

Para executar o script sem precisar levantar o DrRacket, use o comando:
bash$ gracket ola.ss


Se preferir tornar o script executável, acrescente a primeira linha:
#!/usr/bin/env gracket


Outros recursos


Você pode encontrar uma série de módulos interessantes no PLaneT, como facilidades web, conexão a banco de dados, bzlib, Plan9, JSON, etc.

Sobre construção de aplicações web, leia Continue: Web Applications in Racket.

[]’s
Cacilhας, La Batalema

por noreply@blogger.com (Darth Batalema) em 17 de October de 2011 às 18:48

October 15, 2011

Kodumaro

R.I.P. Dennis Ritchie

Artigo original nas Reflexões de Monte Gasppa e Giulia C..

Dennis Ritchie No mesmo mês em que morreu o mago da distorção da realidade, também nos deixa Dennis Ritchie, criador das linguagens de programação B (baseada em APL) e C e cocriador do sistema operacional UNIX.

Se Steve Jobs esteve envolvido direta ou indiretamente com cada avanço tecnológico que não fosse voltado para resolver problemas da própria máquina, salvo raríssimas exceções, Dennis Ritchie foi o criador da linguagem de programação – e dos conceitos envolvidos – usada como base para quase todas as linguagens modernas, além de ter participado ativa e diretamente da criação do sistema operacional que serve de base para todos os sistemas atuais que funcionam.

A parte mais triste é ver todo o bafafá em cima do falecimento de Jobs, mas nada se fala de Ritchie, tão importante quanto. Ou pior… vi programadores que não sabem quem foi Dennis Ritchie!

Como eu disse, um programador que não conheça Dennis Ritchie, Dijkstra e Knuth precisa mudar de profissão ou tomar muita porrada.


[]’s
Cacilhας, La Batalema

por noreply@blogger.com (Darth Batalema) em 15 de October de 2011 às 12:22

PUG - PE

marcelcaraciolo

Pessoal,

Amanhã teremos o nosso primeiro Summer of Code (#PUGPeSoC).

O evento irá ocorrer no AUDITÓRIO DO ITBC - Que fica bem pertinho da praça do arsenal, lá no Recife Antigo.

Mapa: O B MARCA O LOCAL

 

O Evento COMEÇA AS 08:30 mas seria bom que todos procurassem chegar cedo para nos organizarmos, conversar um pouco e nos conhecermos melhor já que iremos passar o dia juntos (se ficarem até o fim #FicaVaiTerBolo)

 

A entrada é FRANCA, é DIGRATIS, é LIVRE a todos que se inscreveram no formulário.

Porém, gostariamos de fazer um pedido.

Quem puder levar extensões, garfos de força, adaptadores de tomada, por favor LEVE!

Muitas pessoas informaram que levariam notebooks e, por isso, podemos ficar sem tomadas disponíveis caso todo mundo queira carregá-los ao mesmo tempo.

No mais, estejam prontos para aprender, ensinar e colaborar!

 

Qualquer dúvida, basta falar no grupo pug-pe@googlegroups.com

 

Se alguém achar que pode se perder no Recife Antigo e não achar o local, enviar um email para o grupo!

 

Atenciosamente,

 

Equipe PUG-PE


por marcelcaraciolo em 15 de October de 2011 às 03:55

October 14, 2011

Thiago Avelino

Nova versão da API do Dropbox

Dia 14.09.2011 o Dropbox lançou a nova versão 1.0 da API, nesse lançamento trouxe muitas novidades e melhorias:

  • Suporte para aplicações web
  • Suporte para criação de pasta (Na versão 0.1 da API não tinha)
  • Novo site para desenvolvedores, com documentação simples e completa https://www.dropbox.com/developers_beta
  • Melhor compartilhamento de arquivo, streaming, busca por arquivo e suporte para revisão de arquivo
  • Implementação no controle de nomes de arquivos, para não sobrescrever arquivos já salvo
  • SDK atualizado para iOS, Android, Python, Ruby e Java que implementa todas modificações e documentação

Link do repositorio (Python Pypi) da nova biblioteca http://pypi.python.org/pypi/dropbox/1.1

O dropbox implementou um oauth onde podemos desenvolver software e fazer o usuário usar a conta de dropbox dele para armazenamento de arquivos: OAuth Dropbox

Vou falar um pouco sobre 3 metodos que esta dentro da biblioteca "dropbox" client, rest e session:

Com o metodo session é por onde tudo começa, onde você linka o seu software com uma conta Dropbox, exemplo:

# Include the Dropbox SDK libraries
from dropbox import session

# Get your app key and secret from the Dropbox developer website
APP_KEY = 'INSERT_APP_KEY_HERE'
APP_SECRET = 'INSERT_SECRET_HERE'

# ACCESS_TYPE should be 'dropbox' or 'app_folder' as configured for your app
ACCESS_TYPE = 'INSERT_ACCESS_TYPE_HERE'
sess = session.DropboxSession(APP_KEY, APP_SECRET, ACCESS_TYPE)

Caso esteja usando a conta do Dropbox do usuário podemos pegar informações da conta dele:

client = client.DropboxClient(sess)
print "linked account:", client.account_info()

Agora usando o metodo "client" podemos fazer get e put de arquivos:

from dropbox import client
f = open('working-draft.txt')
response = client.put_file('/magnum-opus.txt', f)
print "uploaded:", response

Após criar o arquivos podemos ler ele:

print client.get_file('/magnum-opus.txt').read()

Reescrever o arquivo com uma nova revisão para criar um novo arquivo:

out = open('magnum-opus.txt', 'w')
out.write(client.get_file('/magnum-opus.txt',rev='362e2029684fe').read())

Para trabalhar com REST temos um ótima documentação https://www.dropbox.com/developers_beta/reference/api


por avelino@chierry.com (avelino) em 14 de October de 2011 às 03:23

October 11, 2011

Artificial Intelligence in Motion

High Performance Computation with Python - Part 04


Hi all,

This article is the fourth one of the series about High Computation with Python.  For anyone that missed the first, second and third parts check this link about Python Profiling, this one about Cython and finally this about  Numpy Vectors. The goal is to present approaches to make CPU-demanding tasks in Python run much faster.

The techniques that are being covered:

  1.  Python Profiling - How to find bottlenecks
  2.  Cython -  Annotate your code and compile to C
  3.  Numpy Vectors - Fast vector operations using numpy arrays
  4.  Numpy integration with Cython - fast numerical Python library wrapped by Cython
  5.  PyPy - Python's new Just in Time  Compiler
In this post I will talk about PyPy - the JIT Compiler for Python!

The Problem


In this series we will analyze how to optimize the statistical Spearman Rank's Correlation coefficient,  which it is a particular measure used to compute the similarity between items in recommender systems and assesses how well the relationship between two variables can be described using a monotonic function. The source code for this metric can be found in the first post.


Pypy

PyPy is a Just in TIme compiler for the Python programming language. It is multi-platform and it runs Python 2.7.  With your code running in PyPy, it will make your code (depending on how you write your code) run faster (2 - 10 x speed-ups).   Sometimes some work has to be done in the code because of the use of shortcuts that works in CPython that aren't actually correct in the Python specification.

You can download and install PyPy here. To install it, just place it in your home directory and put a symlink from somewhere to it.  Let's run the spearman.py with PyPy and without Python and see the performance difference;



The difference is about 34.77% faster with PyPy against pure Python  considering the input with 190340 on my Macbook. The amazing part is that I didn't change any line of my code! \m/  
If you aren't using a C library like numpy then you should check PyPy - it might just make your code run several times faster. They are still porting PyPy to support Numpy since it some C libraries required   for running Numpy must be rewritten.   You can see some benchmarks of the porting here.

Although the PyPy team gave us a simple integration with array interfaces that behaves in a numpy-like fashion,  for now it has very few functions and only supports double arithmetic.



I strongly recommend you to take a look at PyPy, it shows a great promise for high performance Python with little effort and specially for the scientific community with the support with existing numpy would be a great advance!

I didn't mention until now by I will write a special post to close this series with High Performance with Python: It is about the module multiprocessing and how you can work with it. I will show some examples and a library called JobLib that wraps it where you can easily use the power of the processors of your machine and do some parallell work.


See you next time,

Regards,

Marcel Caraciolo



por Marcel Caraciolo (noreply@blogger.com) em 11 de October de 2011 às 05:38

October 10, 2011

Flávio Coelho

Scrapy, Google Scholar and MongoDB

I have been deeply involved in text mining problems lately, If you watched my presentation a EuroScipy this year (http://www.slideshare.net/fccoelho/mining-legal-texts-with-python) you have an idea of some of the things I am up to. Well part of problem of text mining is to get hold of the text you want to analyze in the first place. For many projects I am involved with, I already have mountains

por Flavio Coelho (noreply@blogger.com) em 10 de October de 2011 às 10:08

Artificial Intelligence in Motion

Presentation at VII Brazilian Symposium of Collaborative Systems (SBSC) about Recommender Systems

Hi all,

I am sharing the slides from my keynote at VII Brazilian Symposium of Collaborative Systems (SBSC) where I presented my current work at recommender systems focusing in social networks.

My work "Content Recommendation based on Data Mining in Adaptive Social Networks"  presents how I built the recommender system at the educational social network AtéPassar and the current results behind it. It is a novel project in brazilian social networks specially because I worked hard at the explanations that come along with each recommendation.




Soon I will provide the paper.  The special part of this event was the track only for recommender systems! I had the opportunity to meet brazilian researchers and developers interested in this field.

I hope I will participate again next year! It is a great event for the researchers who miss those events focused on recommender systems.

Regards,

Marcel



por Marcel Caraciolo (noreply@blogger.com) em 10 de October de 2011 às 06:32

MetaPython

Cartesian Product for Sets

(Python 2.x)

This is a short one - there is a thread on Python-ideas mailing lista bout adding a cartesian product operation for SET types in Python, using the " * " operator for it.

Such an operation would yield a set where each element would be a tuple with one element from the first set and an elemento f the second set, for all possible combinations.

Most likely it won't fly as a language modification, since using itertools.product seems both more explicit and more eficient than having a __mul__ operation defined for set * set.

However, for the few cases on will want a "set" object with a defined cartesian product operation, it is a simple matter, as are simple all thing Python, of adding a __mul__ method to a "set" subclass that calls itertools.product.

One straightforward way of doing so, one would think, would be to write:


>>> import itertools
>>> class mset(set):
...   __mul__ = itertools.product


However, this won't work for an implementation detail in cpython 2: itertools.product is a "built-in" (a.k.a. native code) function. And as such, it won't work as an ordinary instancemethod if put in a class body like above. Python functions addressed in class bodies like this automatically work as methods of the class, available as instance methods - that is, an extra "self" argument is inserted by the inner workings of Python whenever the method is called. Being a native function, the "self" argument won't be inserted by Python - and thus our __mul__ method would require two explicit arguments and would not be fit for acting as a method to be called when the "*" operator is used between our object and another one.

Thus, steps in meta-python. All that is needed for the itertools.product method to work as an operator is to wrap it with a "pure-python" function.

One could write
def __mul__(self, other):
     return itertools.product(self, other)

but...where is the _fun_ of that? It is so boring   it could be written even in Java. 

Instead, we define an "instancemethod" decorator, since pythona lready has the "classmethod" and "staticmethod" counterparts for it. And all an "instancemethod" decorator needs to do is to wrap a function call in "pure-python" so that it is promoted to a method by the type metaclass (the default Python mechanism for that):

import itertools
instancemethod = lambda f: (lambda *a, **kw: f(*a, **kw))
class mset(set):
   __mul__ = __rmul__ = instancemethod(itertools.product)

And there it is - it works now.
One can type soemthing like:
>>> a = set(range(5,10))
>>> b = mset(range(5))
>>> a * b
<itertools.product object at 0xaace10>

>>> set(a*b)
set([(4, 7), (4, 8), (2, 8), (0, 7), (1, 6), (3, 7), (2, 5), (4, 9), (2, 9), (1, 5), (3, 6), (2, 6), (4, 5), (3, 9), (0, 5), (1, 9), (0, 8), (3, 5), (2, 7), (4, 6), (3, 8), (0, 6), (1, 8), (1, 7), (0, 9)])


por João Sebastião de Oliveira Bueno (noreply@blogger.com) em 10 de October de 2011 às 06:17

October 09, 2011

Gustavo Niemeyer

Death of goroutines under control

Certainly one of the reasons why many people are attracted to the Go language is its first-class concurrency aspects. Features like communication channels, lightweight processes (goroutines), and proper scheduling of these are not only native to the language but are integrated in a tasteful manner.

If you stay around listening to community conversations for a few days there’s a good chance you’ll hear someone proudly mentioning the tenet:

Do not communicate by sharing memory; instead, share memory by communicating.

There is a blog post on the topic, and also a code walk covering it.

That model is very sensible, and being able to approach problems this way makes a significant difference when designing algorithms, but that’s not exactly news. What I address in this post is an open aspect we have today in Go related to this design: the termination of background activity.

As an example, let’s build a purposefully simplistic goroutine that sends lines across a channel:

type LineReader struct {
        Ch chan string
        r *bufio.Reader
}

func NewLineReader(r io.Reader) *LineReader {
        lr := &LineReader{make(chan string), bufio.NewReader(r)}
        go lr.loop()
        return lr
}

The type has a channel where the client can consume lines from, and an internal buffer
used to produce the lines efficiently. Then, we have a function that creates an initialized
reader, fires the reading loop, and returns. Nothing surprising there.

Now, let’s look at the loop itself:

func (lr *LineReader) loop() {
        for {
                line, err := lr.r.ReadSlice('\n')
                if err != nil {
                        close(lr.Ch)
                        return
                }
                lr.Ch - string(line)
        }
}

In the loop we'll grab a line from the buffer, close the channel in case of errors and stop, or otherwise send the line to the other side, perhaps blocking while the other side is busy with other activities. Should sound sane and familiar to Go developers.

There are two details related to the termination of this logic, though: first, the error information is being dropped, and then there's no way to interrupt the procedure from outside in a clean way. The error might be easily logged, of course, but what if we wanted to store it in a database, or send it over the wire, or even handle it taking in account its nature? Stopping cleanly is also a valuable feature in many circumstances, like when one is driving the logic from a test runner.

I'm not claiming this is something difficult to do, by any means. What I'm saying is that there isn't today an idiom for handling these aspects in a simple and consistent way. Or maybe there wasn't. The tomb package for Go is an experiment I'm releasing today in an attempt to address this problem.

The model is simple: a Tomb tracks whether the goroutine is alive, dying, or dead, and the death reason.

To understand that model, let's see the concept being applied to the LineReader example. As a first step, creation is tweaked to introduce Tomb support:

type LineReader struct {
        Ch chan string
        r *bufio.Reader
        *tomb.Tomb
}

func NewLineReader(r io.Reader) *LineReader {
        lr := &LineReader{
                make(chan string),
                bufio.NewReader(r),
                tomb.New(),
        }
        go lr.loop()
        return lr
}

Looks very similar. Just a new field in the struct and its respective initialization. We've used it as an embedded field just so we can use the Tomb methods directly in the lr variable.

Next, the loop function is modified to support tracking of errors and interruptions:

func (lr *LineReader) loop() {
        defer lr.Done()
        for {
                line, err := lr.r.ReadSlice('\n')
                if err != nil {
                        close(lr.Ch)
                        lr.Fatal(err)
                        return
                }
                select {
                case lr.Ch - string(line):
                case -lr.Dying:
                        close(lr.Ch)
                        return
                }
        }
}

Note a few interesting points here: first, Done is called to track the goroutine termination right before the loop function returns. Then, the previously loose error now goes into the Fatal Tomb method, flagging the goroutine as dying. Finally, the channel send was tweaked so that it doesn't block in case the goroutine is dying for whatever reason.

A Tomb has both Dying and Dead channels, which are closed when the Tomb state changes accordingly. These channels enable explicit blocking until the state changes, and also to selectively unblock select statements in those cases, as done above.

With the loop modified as above, a Stop method can trivially be introduced to request the clean termination of the goroutine synchronously from outside:

func (lr *LineReader) Stop() os.Error {
        lr.Fatal(tomb.Stop)
        return lr.Wait()
}

In this case the Fatal method will put the goroutine in a dying state from outside, and Wait will block until the goroutine terminates itself and notifies via the Done method as seen before. This procedure behaves correctly even if the goroutine was already dead or in a dying state due to internal errors, because only the first call to Fatal with an actual error is recorded as the cause for the goroutine death. The tomb.Stop value is used as a reason when terminating cleanly without an actual error, and it causes Wait to return nil once the goroutine terminates, flagging a clean stop per common Go idioms.

(UPDATE: there was a minor simplification in the API since this post was originally written, and the paragraph above was adapted to cover the new API)

This is pretty much all that there is to it. When I started developing in Go I wondered if coming up with a good convention for this sort of problem would require more support from the language, such as some kind of goroutine state tracking in a similar way to what Erlang does with its lightweight processes, but it turns out this is mostly a matter of organizing the workflow with existing building blocks.

The tomb package and its Tomb type are a tangible representation of a good convention for goroutine termination, with familiar method names inspired in existing idioms. If you want to make use of it, goinstall the package with:

$ goinstall launchpad.net/tomb

The API documentation with details is available at:

http://goneat.org/lp/tomb

Have fun!

por Gustavo Niemeyer em 09 de October de 2011 às 19:53

October 06, 2011

Gustavo Barbieri

PythonBrasil[7] = Excellent!

Last week from 29-Sep to 01-Oct we had the amazing 7th PythonBrasil conference, for the first time in São Paulo.

Since I’ve start to use Python in 2002 I loved the language, but after getting introduced to the PythonBrasil community in 2004 I’ve boosted my development skills, got some friends and even my first job (INdT-Recife) was a kind recommendation from Osvaldo Santana in 2005.

By 2005 we had the 1st PythonBrasil Conference, then called PyConBrasil, here in Campinas with the help of UNICAMP and our amazing non-stop contributor Rodrigo Senra. It was very cool, I even presented a talk there… and it motivated me to go to following conferences in 2006 and 2007 as well.

However if starting to work at INdT reduced my spare time since late 2006, after ProFUSION was born in 2008 I had no time to participate in the lists or even go to conferences. What a shame!

I couldn’t see how shameful it was until I did this PythonBrasil in 2011. I’ m yet to see a conference with so kind people. People still remembered me and I was ashamed when I couldn’t remind their names… although they did remember mine (NOTE TO CONFERENCE: bigger names next year!) Some would even let me know they still use Eagle-Py, something that I already forgot about. And people I had closer contact before were willing to talk as if we had met last week. Amazing.

During these talks I’ve catch up with Rodrigo Senra, Luciano, Osvaldo, Erico, Marco André, Sidnei, Fernando and many more I couldn’t remember. However one of the talks was very special: talked to Gustavo Niemeyer about Go programming language. That’s right, people were so kind and open we had a keynote about Go, and we talked a lot afterwards without problems! :-P  Gustavo showed me some nice details about the language and my mind is now burning! I must do Enlightenment Foundation Libraries (EFL) + Go = EGO, a perfect GUI tool.

But I was of use… not just a leecher! I went there to present 3 talks (slides in Portuguese!):

Last but not least, I’d like to thank everyone that did this amazing conference possible!

por Gustavo Barbieri em 06 de October de 2011 às 01:25

Introducing EWS to help EFL on FB and PS3

Lots of systems do not support multi-window on their own, consider standard Linux Frame Buffer (FB) or the PlayStation3. This makes it cumbersome as you’re restricted to a single window,  likely you’ll have to rewrite your apps to behave well in this scenario.

Traditionally this problem is worked around by toolkits like Qt that provides QWS, a great help for developers. Considering QWS I decided to help our PS3 friends with something similar which I shamelessly called EWS (Ecore + Evas Single Process Windowing System).

Ecore and Evas already made 99% of this work: they abstract rendering, abstract windowing and so on. There is even support for “inlined windows” in Elementary, these are rendered to buffers that are visible inside other windows. Actually the first version of EWS was a 30min hack in Elementary called “eland” (making fun of wayland). But as not everyone would use Elementary it was better to move it lower in the stack: Ecore_Evas.

Ecore_Evas is a glue layer between Ecore and Evas that takes care to configure actual windows and setup Evas on them, to capture events from various sources and feed them to canvas, etc. If you cope with its API you’ll work with most EFL libraries and applications out-of-the-box.

Ecore_Evas_EWS was created as a new engine that builds on top of others. It will use a backing-store engine like X11, FB, DirectFB, WinCE or PS3 to create an internal Ecore_Evas. Every new window created with ecore_evas_ews_new() is rendered to an Evas using the buffer engine and its pixels end as the image source in the backing-store engine, displaying it. This is very similar to existing ecore_evas_buffer feature ecore_evas_object_image_new(), however it will handle more things automatically.

Among the new features are events to allow window management. Things like “window created”, “window moved” and “window resized” are placed in the main loop for interested peers, they may handle these and decorate the windows, offer window management (close, maximize, …). To exemplify that I’ve added support in Elementary with basic controls such as move, maximize, restore and close. Unfortunately it looks  ugly like hell and then I’m not posting any screenshot or screencast ;-) Let’s wait for people doing themes to make a great work.

The work is far from complete, bugs remain,  optimizations could be applied for OpenGL… if you consider the rules “20/80″, 80% of the code was written in 20% of the time, now we’ll take 80% to make it work for sure :-D  But it’s not bad considering it took me 2 days,  1421 lines in ecore_evas_ews.c, 543 in elu_ews_wm.c and 317 in ews.edc…

That’s why I keep saying that EFL is an amazing technology to build products. It runs fast, it’s slick and it does not get in the way. Give it a try! :-)

por Gustavo Barbieri em 06 de October de 2011 às 00:51

October 04, 2011

Thiago Avelino

Problema com hashlib + md5 (Python 2.7)

Estava com o seguinte problema "Error: No module named _md5", primeiramente pensei que foce problema de de compilação do Python, mas olhando o problema proximo achei alguns artigo falando desse problema e um deles estava no bug.python.org

A solução que cheguei foi, criar uma lib chamada "_md5", criei um arquivo chamado "_md5py":

class _md5:
    def __init__():
        import md5
        return md5

Lendo as documentação vi que a lib "hashlib._md5" foi deprecada pois a md5 ficou no lugar. Espero que ajude outras pessoas que esta com esse problema.


por avelino@chierry.com (avelino) em 04 de October de 2011 às 20:04

Noticias da APyB

Carta à Comunidade Python

Olá amigos Pythonistas,

Perdoem-nos pelo longo email mas nessa semana que passou muita coisa aconteceu na nossa comunidade.

Como muitos devem saber a 7ª edição da PythonBrasil aconteceu entre os dias 29/09 e 01/10 em São Paulo e foi sensacional.

Além de ter sido sensacional tivemos uma assembléia para eleger a nova diretoria da Associação Python Brasil e começamos a discutir sobre a próxima edição da PythonBrasil. Esse email trata desses dois assuntos.

A Assembléia

Durante a assembléia elegemos uma nova diretoria e alguns novos conselheiros. Os detalhes serão colocados no site da associação tão logo os responsáveis pela ata da assembléia me enviem o material. Na diretoria ficamos com o seguinte quadro (tal como especificado em nosso estatuto):

  • Presidente: Osvaldo Santana
  • Vice-Presidente: Bruno Rocha
  • Diretor Financeiro: Ramiro Luz
  • Diretor de Marketing: Álvaro Justen
  • Diretor de Assuntos Acadêmicos: Tânia Andrea
  • Diretor de Ações Online: Rudá Porto
  • Diretor Administrativo: João Sebastião

Estava claro para todas as pessoas que participam da associação que algumas coisas precisariam ser mudadas, outras melhoradas e algumas delas já não eram mais necessárias. Depois de coletar algumas informações e discutir com outras pessoas da comunidade eu acho que chegamos à um bom plano. Tentarei detalhar melhor os nossos planos na forma de uma F.A.Q.

Como ficará a Associação Python Brasil?

Nesta primeira fase da nossa gestão vamos nos organizar para nos tornar "o braço institucional da comunidade Python."

Estaremos disponíveis para auxiliar qualquer iniciativa da comunidade sempre que esta precisar de algum tipo de apoio institucional.

É importante saber que a associação está à serviço da comunidade e não o contrário. A comunidade existe sem a associação, mas a associação não existe sem a comunidade.

Você enfatizou "primeira fase", haverá uma segunda?

É claro! E eu imagino que nessa segunda fase a associação deixe de ser apenas um "braço institucional" e comece a fomentar as iniciativas da comunidade tal como descrito no nosso estatuto.

E porque vocês já não fazem isso desde a primeira fase?

Porque queremos tratar os problemas um a um determinando objetivos e buscando atingir esses objetivos.

Quais as ações práticas que essa nova diretoria tomará para implantar essa visão?

Algumas mudanças já estão em andamento, outras serão feitas e algumas delas serão fruto de consultas à comunidade:

  1. Buscaremos manter a comunicação mais aberta e organizada.
  2. O funcionamento da diretoria será simplificado.
  3. Algumas mudanças de ordem prática serão feitas no estatuto (ex. endereço) e outras serão propostas com o objetivo de simplificar alguns processos.
  4. Distribuir responsabilidades com mais voluntários e deixar claro que a APyB tem a função de apoiar as ações da comunidade e não a de determinar quais serão essas ações.
  5. Apoiar a organização da PythonBrasil.
  6. Coordenar um "Python Roadshow" com eventos regulares organizados pelos grupos regionais.
  7. Iniciar o processo de registro de marcas como Python, Django, Web2Py, Zope, Plone, etc. afim de proteger o uso das mesmas no Brasil.

Como será a comunicação?

Vamos reativar alguns canais que estavam em desuso, reorganizar as listas de email para estimular as discussões em fórums mais abrangentes e vamos trabalhar para passar a mensagem de que a APyB está disponível para ajudar a comunidade.

  1. Reativar os canais de bate-papo da associação e manter reuniões regulares.
  2. Mover as discussões sobre iniciativas e projetos nas listas das comunidades vinculadas à tecnologias Python e usar a lista apyb-associados apenas para assuntos específicos da associação (anuidades, valores, estatuto, etc).
  3. "Encolher" a lista apyb-condir onde ficam os conselheiros e diretores e usá-la apenas para troca de dados mais sigilosos (ex. contas em banco, CPFs, endereços, telefones, etc).
  4. Melhorar o site da associação e corrigir alguns problemas (ex. renovação da associação, publicação de conteúdos e notícias, etc).
  5. Colocar os códigos fontes dos projetos desenvolvidos pela associação (e para a associação) em repositórios abertos para colaboração (ex. github.com, bitbucket.org, etc).
  6. Criação de um ponto de contato único e aberto para que as pessoas possam falar com a associação e fazer solicitações. Esse ponto de contato provavelmente será um sistema de controle de chamados do tipo "Issue Tracker" onde todos poderão acompanhar o andamento das suas demandas.

Como eu disse algumas dessas medidas já estão em andamento. É o caso do nosso repositório público de código que fica no Github (https://github.com/pythonbrasil/) e que permite que qualquer um possa colaborar (é só fazer 'fork' e depois um 'pull request' no projeto).

Teremos outras: criação de grupos de trabalho no site da associação, issue tracker, definição de uma política de acesso mais aberta para os sites da associação e para aqueles sites da comunidade que estão na infraestrutura da associação, melhoria no visual dos sites (procuramos voluntários!), e muitas outras coisas que anunciaremos em breve.

O que muda no funcionamento da diretoria?

Elegemos a nossa diretoria tal como rege o estatuto mas, nessa fase inicial, vamos experimentar uma nova distribuição de responsabilidades:

  • Presidente/Vice/Financeiro - responsáveis por todas as questões "burocráticas" da associação (estatuto, financeiro, ...).
  • Marketing/Assuntos Acadêmicos - relacionamento com a comunidade e apoio à organização da PythonBrasil.
  • Online/Administrativo - zelar pela nossa infraestrutura de sites.

Se essa organização funcionar bem e for necessário poderemos sugerir essa nova estrutura no estatuto.

Que mudanças serão feitas no estatuto?

Antes de abordar esse assunto é importante salientar que o estatuto só pode ser modificado por uma assembléia. O que faremos serão apenas propostas de mudanças.

A primeira delas será a mudança da sede da associação. Atualmente a associação está registrada no endereço da mãe de nosso saudoso amigo Dornéles Treméa e isso cria algumas dificuldades na gestão da associação (ex. conta em banco na mesma cidade, contadora na mesma cidade, correspondência, etc).

Seria interessante, também, remover a necessidade de que duas pessoas assinem as operações financeiras da associação. Aparentemente essa é uma das razões que nos impede de termos um cartão de crédito internacional para efetuarmos pagamentos de hostings, etc.

A outra é a proposta de mudar a organização da diretoria para diminuir o número de 'postos', diminuir o tamanho dos conselhos ao mínimo exigido por lei e estudar a possibilidade de se fazer assembléias online. O objetivo é tornar as coisas mais simples e ágeis do que são hoje.

Como pretendem distribuir as atividades da associação?

Lançaremos chamadas nas listas da comunidade à procura de voluntários que estejam dispostos a colaborar com documentação das atividades, manutenção dos sites, organização dos eventos, etc.

Comunicaremos os problemas e dificuldades da associação sempre que eles surgirem para que mais pessoas possam nos ajudar.

E, por último, se você tem uma idéia legal, quer colocá-la no ar e precisa de ajuda para um domínio, hospedagem ou de acesso especial a um de nossos sites é só falar com a gente. É pra isso que a associação existe.

Como/Quando/Onde será a PythonBrasil[8]?

Não sabemos ainda. Mais detalhes logo abaixo.

Roadshow? Como assim?

O Roadshow seria uma espécie de "Circuito Python" que percorreria todas as cidades que já possuem um grupo organizado de usuários Python promovendo ações e encontros voltados à apresentar Python e tecnologias relacionadas ao público local.

No início do ano seriam estabelecidas as datas em que cada cidade organizaria o seu evento e, com esse planejamento prévio, poderíamos apoiar cada uma dessas ações de maneira mais ordenada fornecendo auxílio para levar palestrantes convidados, material de divulgação, brindes para sorteio, dentre outros.

Esses eventos também podem ser usados para divulgar a PythonBrasil.

Porque deveríamos registrar essas marcas?

Para protegê-las de outras pessoas que possam querer fazer isso e usar em benefício próprio.

Buscaríamos apoio da PSF (Python Software Foundation), Plone Foundation, Zope Corp., etc para viabilizar financeiramente esses registros.

Esse registro não poderia ser usado para impedir manifestações da comunidade ou até mesmo uso comercial legítimo dessas marcas (ex. produção e venda de camisetas de Python em alguma loja).

Se o registro dessas marcas não pertencer à Associação Python Brasil outra empresa pode fazê-lo e impedir até mesmo a nossa comunidade de usar tais marcas. Um caso similar à esse aconteceu no Brasil com a marca OpenOffice que foi registrada por uma empresa que impedia o uso do nome. Resultado: o OpenOffice teve que usar o nome BROffice no Brasil.

PythonBrasil

O evento desse ano foi sensacional. A PythonBrasil vem ficando melhor a cada ano que passa e, consequentemente, a próxima sempre é a mais difícil de fazer.

Mas antes de falar da próxima é necessário parabenizar o Érico Andrei e a Karyn Nassif. Eles têm sido responsáveis pela organização direta ou indireta de quase todas as PythonBrasil que tivemos nos últimos anos.

Esse ano eles anunciaram a "aposentadoria" pois vão se dedicar à um projeto mais importante: eles estão "grávidos". Desejo sorte ao casal.

Com a "aposentadoria" dessa dupla a organização da próxima PythonBrasil será ainda mais desafiadora. Mas tenho certeza que com a comunidade organizada e com o apoio institucional da Associação Python Brasil faremos ainda melhor no ano que vem.

Data: 27 a 29 de setembro de 2012 (a confirmar)

Precisamos confirmar essa data com os organizadores da PyConAr pois temos um acordo que nos permite otimizar a utilização dos recursos necessários para trazer os palestrantes internacionais do evento.

O local não foi definido. O projeto é que a PythonBrasil seria sempre em São Paulo mas até o momento ninguém se ofereceu para assumir o papel de BigKahuna (organizador do evento) em São Paulo e não havendo propostas para essa cidade reabriremos a eleição da sede para as próximas 2 edições do evento (fazer o evento por 2 anos consecutivos na mesma cidade gera vantagens operacionais e financeiras).

Algumas propostas informais já surgiram: Rio de Janeiro, Brasília e Fortaleza. Agora esperamos receber as propostas oficiais para escolher a cidade.

Encerramento da submissão de propostas: 20 de novembro de 2011.

Data do anúncio do resultado: 27 de novembro de 2011.

Um comitê formado por diretoria, conselho deliberativo e por ex-bigkahunas (sendo esses últimos os mais importantes) escolherá o local para evitar alguma cidade seja escolhida apenas porque tem maioria numérica na votação.

Não existe um modelo formal para a proposta, mas ela deve apresentar itens como:

  • Quem será o BigKahuna, como ele trabalha, se tem disponibilidade de tempo, etc.
  • Local do evento (custo, endereço, estrutura, proximidade de aeroportos e rodoviárias).
  • Hospedagem (informações gerais sobre hospedagem na cidade, faixas de preços, categorias de hotéis, proximidade do local do evento e sugestões).
  • Deslocamento (sistema de transporte público, preços de táxis, etc).
  • Alimentação (ao redor do local do evento principalmente e no geral).
  • Turismo (local para os participantes irem durante a noite, por exemplo).
  • Empresas locais interessadas em apoiar ou patrocinar o evento.
  • A proposta ganha pontos positivos se vier acompanhada de orçamentos e/ou fornecedores de: sistemas de audio/video, gravação/edição/stream das palestras, fotógrafo, tradução simultânea, coffee-break, etc.

O item mais importante na escolha é o BigKahuna e sua disponibilidade de tempo, envolvimento com a comunidade, capacidade de aglutinar colaboradores, capacidade de execução, experiências anteriores, etc. Os outros critérios são:

  1. Infraestrutura do local do evento.
  2. Acesso à cidade (cidades que são hubs aeroviários possuem passagens mais baratas).
  3. Infraestrutura da cidade.
  4. Simpatia de patrocinadores/apoiadores (alguns patrocinadores preferem eventos em suas cidades)

Tenha em mente que os interessados precisam "vender" a sua cidade para o comitê avaliador.

Mais informações no Manual do BigKahuna (http://associacao.python.org.br/associacao/manual-do-big-kahuna). Ele está desatualizado mas trabalharemos nele nas próximas semanas.

por Osvaldo Santana em 04 de October de 2011 às 19:52

PUG - PE

PUG-PE Summer of Code

Venham participar do I PUG-PE Summer of Code!  O primeiro está marcado e será dia 15 de outubro pela manhã!

Para se inscrever ,  cadastre seu nome no formulário aqui.

Para mais informações falar com @frenetic_br ou @brunnogomes .

PUG-PE Summer of Code

PUG-PE Summer of Code

PUG-PE SUMMER OF CODE (com café, e cerveja)!

O que é isso?
O Google tem seu summer of code, uma “maratona” de programação no verão do hemisfério norte do blogo terrestre, e o PUG-PE terá sua maratona de programação em, wait for it, PERNAMBUCO!
Claro que aqui o verão é o ano todo, então a “maratona” pode demorar o tempo que for preciso :)
O nosso objetivo é envolver o pessoal do grupo de Python em um projeto para o próprio grupo, que é o portal pug-pe em python, o qual estamos precisando MUITO, ao passo em que todos os envolvidos podem aprender Django, trabalho em equipe, Scrum, Xp, e, principalmente, go horse!

Por que participar?
É mais fácil aprender fazendo do que aprender lendo!
É uma ótima estar lá para aprender coisas novas, para ensinar o que você sabe, e para se divertir enquanto escreve lindos códigos!

ONDE e QUANDO?
Faremos ciclos de desenvolvimento durante os meses. 1, 2 ou 3 dias por mês, o que for mais fácil para obtermos participantes e local para uni-los.
Um ciclo deve durar, o programado até então, cerca de 1 dia de trabalho. Algo de 8 da manhã até as 18 horas, parando para almoçar.
Claro que não é trabalho, é diversão e aprendizado!
E ninguém é obrigado a ficar esse tempo todo. Mas seria bom se ficassem.

O que eu preciso saber para participar?
Saber programar e saber Python.
Utilizaremos Django, mas você não precisa ser o “pica das galáxias” do Django para participar.
Mas, se você não quer chegar nos ciclos zerado de conhecimento, recomendamos que você leia http://www.aprendendodjango.com/ e/ou a documentação do Django https://www.djangoproject.com/

Como participar?
Para participar basta responder as threads e ir ao encontro.
Seria interessante que levasse um notebook para programar lá, visto que provavelmente não teremos computador para disponibilizar.

E se eu não tenho notebook?
Dependendo do local que for acontecer o ciclo, acredito que dê para levar o desktop de casa.

E se eu não tenho como levar o meu desktop?
Somo uma comunidade, não vejo problema em espremer 2 pessoas em 1 notebook. :)

Para finalizar esse manifesto longo do cão,

OS 5 MANDAMENTOS DO PUG-PE SUMMER OF CODE:
1 – DEVEMOS TODOS COMPARTILHAR CONHECIMENTO – Regra de ouro a ser cumprida a risca. Se alguém tem dúvida, devemos ajudá-lo. De preferência em voz alta pois a dúvida de um pode ser a dúvida de outro.
2 – TODOS DEVEM SER SEM VERGONHA – Ter vergonha de programar na frente dos outros, de mostrar o código, ter vergonha por achar que sabe pouco. NÃO TENHAM! Tirem dúvidas, façam seus códigos e aproveitem cada momento para aprender, e para colaborar com o projeto.
3 – É PROIBIDO SER FOMINHA – Ou seja, é proibido querer fazer tudo sozinho. As vezes, Romário, nós temos que passar a bola para nossos companheiros.
4 – DIVIRTAM-SE – Não é trabalho e não é escravidão. Vamos programar para alcançar um marco da nossa comunidade, um projeto que precisamos. Vamos fazê-lo juntos, e vamos nos divertir fazendo. Se for chato, começa a dar sono, e ai todo mundo vai querer ficar jogando fazendinha feliz no orkut. :P
5 – LAVEM AS MÃOS – Antes E depois de usar o banheiro.


por marcelcaraciolo em 04 de October de 2011 às 14:08

October 03, 2011

Artificial Intelligence in Motion

Slides from Keynotes at VII PythonBrasil

Hi all,

I'd like to share the slides of the keynotes I lectured at the VII PythonBrasil, the Brazilian Python Users Meeting that happens once a year.   This year I had the opportunity to give two talks: One is about the Open-Source Communities and the experience with the local community of Pernambuco: The Python User Group of Pernambuco (PUG-PE) and about the framework I am currently working on: Crab - A Python Framework for Building Recommender Systems.

It was an amazing event and with lots of amazing keynotes, opportunities to meet people and make some friends. I also had the opportunity to give two more lighting talks: the pipeline toolkit for scientific computations JobLib and about Ipython.

Below the slides provided:



                           The JobLib slides for download.



I'd like also to announce the launch of the new home page of the project Crab with a reformulated design. It still in development, with lots of work to do, but it's coming! The first release 0.1 will be launched until the second week of October.

Crab new Home Page 


Thanks for the feedback from all developers at PythonBrasil and I expect new contributors at the project.

Regards,

Marcel Caraciolo

por Marcel Caraciolo (noreply@blogger.com) em 03 de October de 2011 às 08:59

September 29, 2011

Elcio Luiz Ferreira

Configurando o encoding padrão no Python

Dica: ao iniciar o desenvolvimento com Python em uma máquina nova, procure pelo arquivo sitecustomize.py e acrescente:

import sys
sys.setdefaultencoding('utf-8')

O arquivo sitecustomize.py é automaticamente executado toda vez que você executa o Python (sim, você pode fazer o que quiser nele…) Ele fica em lugares diferentes dependendo da plataforma e da sua instalação do Python. No Ubuntu, fica em /usr/lib/python2.7/ (trocando 2.7 pela versão que você estiver usando.) As linhas acima configuram o encoding padrão como Unicode UTF-8. Claro, você pode configurar outro encoding como o padrão, se preferir.

Recomendo muito que, se você não entende nada de charsets ou nem sabe do que estou falando, use UTF-8.


por elcio em 29 de September de 2011 às 20:53

September 28, 2011

Christiano Anderson

É amanhã – Maior encontro da comunidade brasileira de Python

 

 
  Amanhã é o dia do maior encontro da comunidade brasileira de Python. Estou bastante ansioso pelo evento, ótima oportunidade para encontrar a comunidade, conversar e trocar conhecimento.

A grade do evento está muito boa, palestras abordando uma variedade enorme de temas para todos os níveis de conhecimento. Algumas pessoas me perguntaram se as palestras são muito avançadas, se é possível alguém iniciante ter bom aproveitamento do evento. A resposta é sim! Tem palestras para todos os níveis, se você está querendo aprender Python, essa é sua grande oportunidade. Se você já conhece e quer melhorar suas técnicas, também é o evento ideal. Para desenvolvedores experientes, também. Cada palestra tem sua classificação, se é iniciante, intermediária ou avançada, basta escolher de acordo com seu nível de conhecimento e interesse pelo tema.

Sem contar na oportunidade de conversar com quem utiliza Python profissionalmente, fazer networking e até gerar negócios. Portanto, se você tem interesse em Python, participe do evento, caso contrário, só terá outra oportunidade como esta no ano que vem.

Eu vou apresentar a palestra Django e MongoDB no sábado, dia 01, às 14h. Essa palestra tem um conteúdo mais avançado, vou falar um pouco da minha aventura em desenvolver projetos com Django utilizando um banco de dados não relacional, no caso, o MongoDB.

Espero encontrá-lo no evento! Até lá!

Mais informaçõeshttp://www.pythonbrasil.org.br/2011/

por Christiano Anderson em 28 de September de 2011 às 08:12

September 27, 2011

Aprenda Python

Inverter strings

Dada uma string, quero mostrá-la invertida. Em python é muito simples. >>> 'eu gosto de python'[::-1] 'nohtyp ed otsog ue' E se eu quiser inverter palavra por palavra, mas mantendo a ordem em que as palavras aparecem no texto? >>> ' '.join([word[::-1] for word in 'eu gosto de python'.split()]) 'ue otsog ed nohtyp' A dica aqui é usar o slicing de um jeito não muito comum: com o argumento step (o

por Vinicius Assef (noreply@blogger.com) em 27 de September de 2011 às 11:36

September 24, 2011

Artificial Intelligence in Motion

High Performance Computation with Python - Part 03

Hi all,


This article is the third one of the series about High Computation with Python.  For anyone that missed the first and the second parts check this link and this one.  The goal is to present approaches to make CPU-demanding tasks in Python run much faster.


The techniques that are being covered:


  1.  Python Profiling - How to find bottlenecks
  2.  Cython -  Annotate your code and compile to C
  3.  Numpy Vectors - Fast vector operations using numpy arrays
  4.  Numpy integration with Cython - fast numerical Python library wrapped by Cython
  5.  PyPy - Python's new Just in Time  Compiler

In this post I will talk about Numpy Vectors and how you can wrap it with Cython!


The Problem

In this series we will analyze how to optimize the statistical Spearman Rank's Correlation coefficient,  which it is a particular measure used to compute the similarity between items in recommender systems and assesses how well the relationship between two variables can be described using a monotonic function. The source code for this metric can be found in the first post.


Numpy


Numpy is a powerful extension to Python, adding support for large, multi-dimensional array and matrices, along with several mathematical functions to manipulate these arrays. To install it you can type this command at your terminal

$ sudo easy_install numpy

Or

$ pip install numpy

In our example we will change the spearman.py . Import the numpy library and change the spearman_correlation to look  the one below. If you run and test it you will ger the same output as before.



The numpy strength is that can simplify lots of operations on vectors or matrixes of numbers since they work directly in all list rather than on individual elements at one time.  So before we had nested for loops over individual terms in a list, now with numpy you could do the same job in a faster and simple way.
Some notes:

  • You define an array with numpy.array statement, in our case a list of tuples indexed by the labels keys and ranks. (lines 29 and 30).
  • Lots of operations already implemented in numpy, such as numpy.in1d which finds where the elements in the first vector are in the second vector returning an array os bools.
  •  We have numpy.sort which sort the elements based on a key, in this example (ranks) (lines 16 and 17).
  • diffs * diffs does a pairwise multiplication, think of it as diff[0] = diff[0] * diff[0]; diff[1] = diff[1] * diff[1]...; diff[n-1] = diff[n-1] * diff[n-1]. (line 36)
  • size is an attribute from numpy.array to fetch the m*n elements (count) from an array.
If it stills unclear I suggest you to try it at the command line, step-by-step to look over the results. Put a small number of elements in the array and see it in action.

Numpy with Cython


Numpy is a powerful library and uses very fast C optimized math libraries to perform these calculations very quickly. You can also wrap your python code with Cython. The main difference is the annotation of the numpy arrays. You can see the tutorial for further details.  The difference are how we import: cimport numpy as np and the assinature of the function _rank_dists.




Special Notes - Meeting Scipy

Another poweful library is Scipy, it is a package for Python that brings several algebra techniques for dealing with matrices and vectors.  One special module is the scipy.stats, which comes with the spearmanr function. It receives two arrays with the observations and returns the spearman coefficient. Amazing! Let's see our code below:


In the next post we will study the Pypy, a JIT Compiler which can speed your code with minimal changes at your code!

I hope you enjoyed this article,

Marcel Caraciolo

por Marcel Caraciolo (noreply@blogger.com) em 24 de September de 2011 às 14:10

September 23, 2011

PUG - PE

Python Brasil 2010 em Curitiba

Olá pessoal,

Gostaria de aproveitar este post para falar um pouco sobre 3 tópicos relacionados a Python em Pernambuco. Como todos sabem além das atividades correntes do nosso grupo, especialmente encontros, realizamos coding dojos, mini-cursos e workshops.

Gostaria de destacar em especial neste último encontro a realização do Workshop de Python em conjunto com o III Encontro Livre que foi realizado neste mês de setembro durante 3 dias. Com workshop de duração de 4 horas, tivemos Python Básico e Django Básico, o último Python com PySide não ocorreu por falta de público. Mas faz parte! :D Quero agradecer em especial aos membros Daker Fernandes (@dakerfp) , Fernando Rocha (@fernandogrd)  e Marcel Caraciolo (@marcelcaraciolo) pelo esforço e empenho nesta série de workshops!  Em breve disponibilizaremos fotos do workshop!

A segunda notícia é a publicação de um artigo especial no mês de agosto sobre Comunidades de Software Livre, onde foi utilizado o case do nosso Grupo de Usuários como exemplo de inspiração para outras comunidades!!!  O moderador Marcel Caraciolo (@marcelcaraciolo) foi responsável pelo artigo explicando sobre a história do grupo, as atividades e até dicas para outros comunidades e pessoas que desejam engatilhar uma comunidade de software livre na sua região!

Para download, acesse a revista nas páginas 72 – 76 da Revista Espírito Livre, n 29.

http://revista.espiritolivre.org/img/REL029_Capa.jpg

Construindo Comunidades Bem-Sucedidas: Experiência do PUG-PE na revista Espírito Livre de Agosto/2011

DOWNLOAD

Gostaria também de aproveitar este destaque para comentar um  pouco sobre o VII Encontro Brasileiro da Comunidade de Usuários de Python (PythonBrasil) que durante os dias 29 de setembro  à 01 de outubro estará sediado em São Paulo com uma série de palestras durante os três sobre diversos projetos, frameworks, trabalhos científicos e até palestras sobre comunidades de desenvolvedores Python no Brasil.

Encontro Python Brasil, São Paulo , 29 a 02 de outubro

Encontro Python Brasil, São Paulo , 29 a 02 de outubro

Gostaria de destacar a presença dos membros pernambucanos Marcel Caraciolo (@marcelcaraciolo) que teve 2 palestras aprovadas neste evento: uma sobre o framework Crab (@muricoca_crab) que ele vem desenvolvendo para construção de sistemas de recomendação e outra sobre Comunidades de Software Livre: A experiência do PUG-PE.   Outro membro com trabalhos aprovados foi o Bruno Melo (@brunojm) que teve seu trabalho:  Python na Torre de Babel: Integrando Python com Outras Linguagens! que vai focar na integração de Python com uma série de linguagens de programação.  Outra palestra aprovada foi o do membro Marcelo Lira sobre bindings de Python com C/C++ e por fim a palestra do Daker Fernandes (@dakerfp) que teve sua palestra Dominando Modelos Ocultos de Markov com Python e GHMM envolvendo Python com Inteligência Artificial também aprovada!! Todos estão de parabéns!!

Queremos convidar a todos a participar deste encontro, sem dúvidas não dá para perder! Muito networking, aprendizado e claro programação e coding sempre constante!  A PythonBrasil que este ano inclusive, como é de praxe, vai ter sprints (por sinal uma delas é a do Crab) , open spaces (para troca de idéias) e até um desafio de codificação para construção de plugins no Firefox.  Quem não for, vai perder!!!

Essa foto foi do encontro do Ano Passado:

Python Brasil 2010 em Curitiba

Python Brasil 2010 em Curitiba

Espero vê-los por lá!  E avante PUG-PE!

Atenciosamente,

Equipe PUG-PE


por marcelcaraciolo em 23 de September de 2011 às 01:53

September 17, 2011

Artificial Intelligence in Motion

High Performance Computation with Python - Part 02

Hi all,

Let's continue our series of posts about High Performance with Python. Last post I presented how you analyze your code using Python Profiling.  If you missed the first part please check this link.  To sum up, our goal is to present several techniques to make CPU-demanding tasks in Python run much faster.

The techniques that will be covered:

  1.  Python Profiling - How to find bottlenecks
  2.  Cython -  Annotate your code and compile to C
  3.  Numpy Vectors - Fast vector operations using numpy arrays
  4.  Numpy integration with Cython - fast numerical Python library wrapped by Cython
  5.  PyPy - Python's new Just in Time  Compiler
In this post I will talk about Cython and how do you compile your code to C with this powerful tool!

The Problem

In this series we will analyze how to optimize the statistical Spearman Rank's Correlation coefficient,  which it is a particular measure used to compute the similarity between items in recommender systems and assesses how well the relationship between two variables can be described using a monotonic function. The source code for this metric can be found in the last post.

Cython

Cython is a Python extension that lets developers annotate functions so they can be compiled to C. It takes a little time to develop but typically give a nice speed-up.  If you're starting now with Cython, I recommend you to check this tutorial, it quite useful for beginners.

In our previous example we decided to optimize the function spearman_correlation. So first we will start a new module called spearman_correlation_cython.py , and move the spearman_correlation function into this module. In the original source you will have to import the spearman_correlation_cython and replace the reference to spearman_correlation(...)  with spearman_correlation_cython. spearman_correlation(...).

So the code for your spearman_correlation_cython.py now is:



def spearman_correlation(ranks1, ranks2):



    """Returns the Spearman correlation coefficient for two rankings, which



should be dicts or sequences of (key, rank). The coefficient ranges from



-1.0 (ranks are opposite) to 1.0 (ranks are identical), and is only



calculated for keys in both rankings (for meaningful results, remove keys



present in only one list before ranking)."""



    n = 0



    res = 0



    ranks1 = sorted(ranks1, key=lambda k: -k[1])



    ranks2 = sorted(ranks2, key=lambda k: -k[1])





    ranks1 = [(t[0], ix) for ix, t in enumerate(ranks1)]



    ranks2 = [(t[0], ix) for ix, t in enumerate(ranks2)]






    for k, d in _rank_dists(ranks1, ranks2):



        res += d * d



        n += 1



    try:



        return 1 - (6 * float(res) / (n * (n * n - 1)))



    except ZeroDivisionError:



        # Result is undefined if only one item is ranked


        return 0.0


Next we will have to rename the spearman_correlation_cython.py to spearman_correlation_cython.pyx.  Cython uses .pyx  to indicate that it is a file that will compile to C.  Add also a new setup.py with the following contents:


# setup.py


from distutils.core import setup


from distutils.extension import Extension


from Cython.Distutils import build_ext


# for notes on compiler flags see:


# http://docs.python.org/install/index.html


setup(


cmdclass = {'build_ext': build_ext},


ext_modules = [Extension("spearman_correlation_cython", ["spearman_correlation_cython.pyx"])]


)


Now run the command:

$ python setup.py build_ext --inplace

This  command runs the setup.py script that we just created by calling the build_ext command. The new module is built in-place in the directory.  You will see that it will be generated a new r spearman_correlation_cython.so in the directory.

Run the new code using python cython_spearman 199999 and you will see a slight improvement in the speed of the calculation (very minor yet!).  You can take a look to see how well the slower Python calls are being replace with faster Cython calls by using:

$ cython -a rank_dists.pyx

It  will generate a rank_dists.html file. If you open it in your browser, you will see something like:

Result of cython -a spearman_correlation_cython

The workflow now that you will use at your code is progressive. Each time you add a type with Cython, it may improve the resulting code. When it does so successfully, you will see that the dark yellow lines will turn lighter and eventually they will turn white (it will represent that there is no need for improvements, it is faster!).  If you are interested to analyze deeper, you could expand the code by double clicking at one of the lines with yellow code. It will show the C Python API calls that it is making.

Double-Clicking at one of the yellow lines of code at html it will show the C  Python API calls

You could also add annotations. So if you add type definitions (such as cdef int or cdef double... )  and run the cython -a ... command, you will can monitor the reduction in yellow in your browser.  Don't forget to recompile using the setup.py command and confirm that the result is slightly faster!

Added some Cython types at the source code.


Cython Compiler Directives

You could also set several compiler directives that comes with Cython.  To enable them, you could use a comment at the top of the file or by changing the setup.py or even decorating the function individually.

Using the comment at top of the file.
   1 #cython: boundscheck=False

Using the decorate function
 import cython
...
@cython.boundscheck(False) # turn off boundscheck for this function
def f():
...
with cython.boundscheck(True): # turn it temporarily on again for this block
...

Using the setup.py

ext_modules = [Extension("spam", ["spam.pyx"]),
Extension("ham", ["ham.pyx"])]
for e in ext modules:
e.pyrex_directives = {"boundscheck": False}

One of the most used is the cProfile, that is useful for profiling cython code. It gives you exactly same output as running cProfile on a normal python module. Another common directive is the boundscheck.  It desables out-of-bounds index checking on buffered arrays (common in numpy arrays, so since it does not check for IndexError exceptions it will run faster. Remember that any mistake prepare to expect a segmentation fault. So be careful when you decide to use boundscheck, that is, be sure that code is working correctly as you planned.  There is also another one, the infer_types which is supposed to guess the type of variables.


Cython directly with C

But you may asking yourself if it is possible to wrap with Cython your existing libraries of C code. Yes it is possible!  Cython uses external declarations to declare the C functions and variables from the library that you want to use. So let's see a quick example:

Let's consider a simple fatorial function written in C and we want to wrap it and call with Python/Cython:
 
fatorialEx.c 


#include <stdio.h>





int fatorial(int n){





if (n == 1) {





return 1;


}





return fatorial(n-1) * n;


}










Now, you have to wrap it at your fatorial.pyx module:

fatorial.pyx

cdef extern from "fatorialEx.c":
int fatorial(int n)

def fat(n):
return fatorial(n)

See the line cdef extern (it's how Cython knows how to include external libraries). Finally create your setup.py module to build the extension:


# setup.py


from distutils.core import setup


from distutils.extension import Extension


from Cython.Distutils import build_ext


# for notes on compiler flags see:


# http://docs.python.org/install/index.html


setup(


cmdclass = {'build_ext': build_ext},


ext_modules = [Extension("fatorial", ["fatorial.pyx"])]


)







Build it:





$python setup.py build_ext --inplace 






You will see the module fatorial.so in the directory, this is the file that you will use now to import your code at Python. So in the Python console , type the following commands to test it:

>>> from fatorial import fat
>>> fat(5)
120

It is working!  I am providing the source for this example. For further information about writing your extension check the Cython docs.

That's all,   I hope  you enjoyed!

Regards,

Marcel Caraciolo

por Marcel Caraciolo (noreply@blogger.com) em 17 de September de 2011 às 05:54