Arquivo da tag: Programming

Linguagens de programação / Programming languages

HTML hates Regexp

English version below.

This probably should get HTML tags out of a string...

This probably should get HTML tags out of a string...

Visto no http://www.codinghorror.com/:

You can’t parse [X]HTML with regex. Because HTML can’t be parsed by regex. Regex is not a tool that can be used to correctly parse HTML. As I have answered in HTML-and-regex questions here so many times before, the use of regex will not allow you to consume HTML.
Regular expressions are a tool that is insufficiently sophisticated to understand the constructs employed by HTML. HTML is not a regular language and hence cannot be parsed by regular expressions. Regex queries are not equipped to break down HTML into its meaningful parts. so many times but it is not getting to me. Even enhanced irregular regular expressions as used by Perl are not up to the task of parsing HTML. You will never make me crack. HTML is a language of sufficient complexity that it cannot be parsed by regular expressions.
Even Jon Skeet cannot parse HTML using regular expressions. Every time you attempt to parse HTML with regular expressions, the unholy child weeps the blood of virgins, and Russian hackers pwn your webapp. Parsing HTML with regex summons tainted souls into the realm of the living. HTML and regex go together like love, marriage, and ritual infanticide. The <center> cannot hold it is too late. The force of regex and HTML together in the same conceptual space will destroy your mind like so much watery putty. If you parse HTML with regex you are giving in to Them and their blasphemous ways which doom us all to inhuman toil for the One whose Name cannot be expressed in the Basic Multilingual Plane, he comes.

Artigo completo: http://www.codinghorror.com/blog/archives/001311.html
Nunca cheguei a fazer nenhum parsing sério de HTML com expressões regulares, mas pelo visto não é uma boa idéia. A menos que você queira apenas checar algumas tags simples.
Este comentário no artigo esclarece um pouco mais:

For the brave of heart: Write a regular language to recognize all strings of balanced parens.
Actually, don’t, because this is provably impossible.
Why? Because regular expressions recognize *regular languages*, a specific, well-defined class of languages. HTML, like the balanced parens problem above, doesn’t conform to this pattern.
Every once in a while, I’m reminded of why studying bona fide computer science in college was the right idea. It won’t necessarily make you a better programmer, but it has saved me from doing really stupid things from time to time, like trying to parse html with a regex.
David R. Albrecht on November 16, 2009 10:23 AM

Realmente, regexps não podem ser usadas para nada além de checar tags simples, e nunca para um texto HTML inteiro: (http://www.perlmonks.org/?node_id=8624)

you cannot write a regexp that will match any level of nested balanced parentheses. You can always write one to match a specific number of balanced ones, but not one that can match a non- fixed number of these. I think there is an explaination in the Friedl book.

Um comentário retirado do Regular Expression HOWTO que resume bem a situação:

(Note that parsing HTML or XML with regular expressions is painful. Quick-and-dirty patterns will handle common cases, but HTML and XML have special cases that will break the obvious regular expression; by the time you’ve written a regular expression that handles all of the possible cases, the patterns will be very complicated. Use an HTML or XML parser module for such tasks.)

Portanto… não faça isto.


This probably should get HTML tags out of a string...

This probably should get HTML tags out of a string...

Visto noSeen at http://www.codinghorror.com/:

You can’t parse [X]HTML with regex. Because HTML can’t be parsed by regex. Regex is not a tool that can be used to correctly parse HTML. As I have answered in HTML-and-regex questions here so many times before, the use of regex will not allow you to consume HTML.
Regular expressions are a tool that is insufficiently sophisticated to understand the constructs employed by HTML. HTML is not a regular language and hence cannot be parsed by regular expressions. Regex queries are not equipped to break down HTML into its meaningful parts. so many times but it is not getting to me. Even enhanced irregular regular expressions as used by Perl are not up to the task of parsing HTML. You will never make me crack. HTML is a language of sufficient complexity that it cannot be parsed by regular expressions.
Even Jon Skeet cannot parse HTML using regular expressions. Every time you attempt to parse HTML with regular expressions, the unholy child weeps the blood of virgins, and Russian hackers pwn your webapp. Parsing HTML with regex summons tainted souls into the realm of the living. HTML and regex go together like love, marriage, and ritual infanticide. The <center> cannot hold it is too late. The force of regex and HTML together in the same conceptual space will destroy your mind like so much watery putty. If you parse HTML with regex you are giving in to Them and their blasphemous ways which doom us all to inhuman toil for the One whose Name cannot be expressed in the Basic Multilingual Plane, he comes.

Full article: http://www.codinghorror.com/blog/archives/001311.html
I never used regular expressions to do any serious HTML parsing, but thinking about it it doesn’t looks a good idea. Unless you just want to check some simple tags.
This comment in the article is interesting:

For the brave of heart: Write a regular language to recognize all strings of balanced parens.
Actually, don’t, because this is provably impossible.
Why? Because regular expressions recognize *regular languages*, a specific, well-defined class of languages. HTML, like the balanced parens problem above, doesn’t conform to this pattern.
Every once in a while, I’m reminded of why studying bona fide computer science in college was the right idea. It won’t necessarily make you a better programmer, but it has saved me from doing really stupid things from time to time, like trying to parse html with a regex.
David R. Albrecht on November 16, 2009 10:23 AM

Indeed, regexps cannot be used to anything else beyond checking simple tags, and never for a full HTML text: (http://www.perlmonks.org/?node_id=8624)

you cannot write a regexp that will match any level of nested balanced parentheses. You can always write one to match a specific number of balanced ones, but not one that can match a non- fixed number of these. I think there is an explaination in the Friedl book.

A comment taken from the Regular Expression HOWTO that sums it up well:

(Note that parsing HTML or XML with regular expressions is painful. Quick-and-dirty patterns will handle common cases, but HTML and XML have special cases that will break the obvious regular expression; by the time you’ve written a regular expression that handles all of the possible cases, the patterns will be very complicated. Use an HTML or XML parser module for such tasks.)

So… don’t do this.

Software Engineering is Dead

http://www.codinghorror.com/blog/archives/001288.html

Software development is and always will be somewhat experimental. The actual software construction isn’t necessarily experimental, but its conception is.

I can publicly acknowledge what I’ve slowly, gradually realized over the last 5 to 10 years of my career as a software developer: what we do is craftsmanship, not engineering.

control is ultimately illusory on software development projects.

Rogue'm Up

English version below.
Linux Application Development book
Uns dois anos atrás, comprei numa promoção o livro Linux Application Development, e até hoje não consegui acabar de lê-lo. Acontece sempre isso com todo livro técnico que compro. Nunca consigo ler pelo menos um parágrafo de uma só sentada, sempre perco o interesse e vou fazer outra coisa.
Resolvi então mudar de estratégia: vou lendo os capítulos fora de ordem, procurando por temas que me interessem no momento. Vi então que o livro tem um capítulo sobre uso da lib S-lang, que serve para abstrair o acesso ao terminal (console). Tradicionalmente se usa a biblioteca ncurses, mas a S-Lang parece ser mais moderna.
Enfim, não só finalmente li um pouco mais do livro, como comecei a brincar com as funções da S-Lang e fiz um pequeno jogo, um shooter lateral, com o mesmo. Como a nave é representada pelo caracter @ e os inimigos são, digamos, familiares para quem já jogou um certo jogo em modo caractere, resolvi chamar este de Rogue’m Up – mistura de Roguelike com Shoot’em Up.
Ou seja, é um shooter para se jogar em modo caractere. Não espere nada muito bem feito, afinal foi só o resultado de uma tarde brincando com as funções da lib S-Lang. Movimente-se com as teclas wasd ou hjklyubn (todas minúsculas), atire com o espaço, saia com Q (maiúsculo). Cada colisão com um inimigo tira 2 pontos de HP.
Atualizado: agora com mais de uma versão e usado como exemplo de programação em C, aqui.


Linux Application Development book
Two years or so ago I bought the book Linux Application Development at bargain price, but I still didn’t finished reading it. This always happens with all technical books I bought: I sit down to read the book, and before I finish even a chapter, I shift my attention to something else and drop the book.
I decided to change my strategy: now I’ll try reading the chapters out of order, selecting chapters by its themes, looking for something I’m interested in reading at that moment. Then I found that this book had a chapter about the S-lang lib. S-Lang provides an abstraction of the terminal (console), easing the programming of console applications. Traditionally the ncurses lib is more used and talked about, but S-Lang seems to be updated more often.
So I’ve finally advanced a little more in reading this book, and also spent some time playing with the S-Lang functions, enough to make a small game – a lateral shooter. The ship is an @ character and the enemies are, let’s say, somewhat familiar to anyone who ever played a certain character-mode game. And so I named this little experiment Rogue’m Up – from the wordsRoguelike and Shoot’em Up.
In other words, it’s a character-mode shooter. Don’t expect anything nice, this was just a result of an afternoon’s play with the S-Lang lib functions. Move the ship with the keys wasd or hjklyubn (all lowercase), shoot with the spacebar, quit with Q (uppercase). Every time an enemy collides with you, you lose 2 HP.
Updated: now with more than one version and used as example of C programming, here.

Plonq

English version below.
Faz um tempo que encontrei por acaso um joguinho chamado Qonk. Simples, pequeno, mas criativo. Exige estratégia e rapidez. Basicamente, o objetivo é conquistar um sistema solar, eliminando os concorrentes, conquistando outros planetas, e usando as naves espaciais produzidas por esses planetas para conquistar outros.
Também faz um tempo que conheci a linguagem Lua. Simples, pequena, mas criativa e bem flexível. E para conhecer melhor a linguagem e brincar um pouquinho com ela, instalei uma variante da mesma no meu Palm Tungsten: Plua. Como a melhor forma de aprender uma linguagem de programação é escrever um programa nela, resolvi tentar fazer um joguinho: um pequeno clone do Qonk. O jogo ainda não está completo mas já está funcional. Coloquei o jogo e o código fonte aqui:
Plonq


Some time ago I found a little game called Qonk. Simple but creative, it requires strategy and quick thinking. Basically, the goal is to conquest a solar system, eliminating the adversaries, conquering more planets, and using the spaceships produced by those planets to conquer others.
Some time ago, I also knew the Lua language. Simple, small, but creative and flexible. And in order to know it better, I installed a variant of it in my Plam Tungsten: Plua. Since the better way to learn a new programming language is to write a program in it, I decided to try making a little game: a Qonk clone. The game isn’t complete yet but already works. I’ve uploaded the game and its source code here:
Plonq

Emacs

Emacs
Retirado da Wikipédia, com adaptações:

O Emacs é um conceituado editor de texto, usado notadamente por programadores e usuários que necessitam desenvolver documentos técnicos, em diversos sistemas operacionais.
A primeira versão do Emacs foi escrita em 1976 por Richard Stallman. Sua versão atual é 22.1 de 2 de junho de 2007.
O Emacs é considerado por muitos o editor de texto mais poderoso que existe. Sua base em Lisp, especificamente num dialeto de Lisp chamado Emacs Lisp, permite que ele se torne configurável ao ponto de se transformar em uma ferramenta de trabalho completa, uma espécie de “canivete suíço” para escritores, analistas e programadores.
Alguns recursos disponíveis no Emacs:

  • Edição colorida e destacada para programação (seja em Lisp, Assembly, HTML, PHP, Python, ShellScript, C, C++ etc. e etc. e etc.)
  • Aceita configurações para comandos de shell (a EShell)
  • Programável em Emacs Lisp
  • Sua flexibilidade faz com que possa rodar dentro dele até mesmo jogos, navegadores web, clientes de e-mail e news e outros programas
  • Tem embutido um programa de inteligência artificial, que simula uma consulta entre o usuário e um psicanalista (sim, é sério).

Para alguém que tente buscar bons editores de texto que sirvam para um programador, o Emacs sempre aparece como um dos indicados, principalmente se você programar para Linux ou em Lisp. Falam que é um editor extremamente poderoso, configurável, customizável, e que pode servidr como uma boa IDE (Integrated Development Environment – Ambiente de Desenvolvimento Integrado) para qualquer linguagem. Contanto, claro, que o usuário se disponha a aprender a operar o editor, cujos comandos chegam a ser quase crípticos. Por exemplo, da primeira vez que você executar o programa e quiser abrir um arquivo, o que você vai fazer? Em um editor “normal” você esperaria encontrar uma barra de menu com um menu “Arquivo”, e dentro dele um item “Abrir”. Bem, não que o Emacs não tenha um menu – ele tem um que pode ser usado no ambiente gráfico, e até no modo caractere, mas o que se espera do usuário é que ele aprenda a combinação de teclas Ctrl+x Ctrl+f para abrir um arquivo.
Emacs em Windows, com o menuUsando Gnus para ler news
Complicação desnecessária? Pode ser, mas o principal argumento a favor disto é que, aprendendo estas combinações de teclas, com o hábito você será mais produtivo, pois o tempo que é gasto pressionando estas teclas é mais rápido que tirar a mão do teclado, pegar o mouse, mover o mouse até o menu, clicar, mover o mouse novamente até o item “Abrir”, e assim por diante. Ainda assim, se você preferir, você pode usar o menu gráfico e até uma pequena barra de botões. Mas tudo no editor é pensado e direcionado ao uso intensivo do teclado.
Falando assim o Emacs soa mais como um vestibular para nerds, só passa quem decorar um milhão de atalhos enigmáticos de teclado. Ou como uma sala de tortura especializada em punir os usuários de mouse, esses hereges que insistem em prestar culto à setinha do mouse ao invés de se render ao mundo dos atalhos de teclado, o único caminho verdadeiro. Mas tudo tem o seu motivo: a seqüência Ctrl+x Ctrl+f fica facilmente ao alcance da mão esquerda, assim como outras seqüências começando com Ctrl+x (são muitas). E depois, mesmo que pareça difícil demais a princípio, há coisas que facilitam muito a vida – tenha em mente que o Emacs não é um editor de texto customizável, ele é um verdadeiro ambiente operacional programável. E as suas capacidades de ser programado para executar tarefas especializadas vão muito além da mera gravação de macros, coisa que outros bons editores têm. Por exemplo, em que outro editor de texto você conseguiria editar seus arquivos, seus códigos-fonte na sua linguagem preferida, compilá-los e debugá-los, e, dentro do mesmo editor, acessar seus e-mails, participar de discussões em um grupo de news, e até mesmo jogar Tetris? (e com essa última descoberta eu cheguei à conclusão de que não sobrou nenhuma fronteira no espaço para o Tetris: se bobear é capaz dele ter sido gravado até no disco dourado do satélite Voyager e estar chegando agora aos confins do universo.)
Tudo isso, claro, se você se dispuser a entender e domesticar o bicho.

Squeak e Smalltalk no OLPC

Tirado da notícia Fisl – relato inicial e apanhado geral da primeira manhã do evento, do site br-linux.org:

…Mas pra começo, que dei uma passada voando pelo pavilhão, me diverti horrores com a criançada no estande da OLPC.

Nota: OLPC é o projeto “One Laptop Per Child”, Um Computador por Criança, que visa criar uma espécie de mini-notebooks a custo ao redor de 100 dólares para distribuir a estudantes da rede pública de ensino – tente pensar nestas máquinas como “pequenos cadernos eletrônicos”, ao invés de “vão dar notebooks de graça a crianças”; a idéia do projeto está muito além disso.

Sim, pode ser que não de certo, pode ser que dê muito cero, mas que é muito bom ver crianças brincando com interfaces inteligentes (Squeak, pra quem não conhece um smalltalk simples e perfeito para alimentar a fome de conhecimento dos nossos guris e gurias novinhos :-), e vendo que o “brinquedo” funciona.

Squeak e Smalltalk…
Conheci o Squeak uns anos atrás, quando fiquei curioso em conhecer a linguagem Smalltalk e saber como seria uma linguagem orientada a objetos ‘pura’. Achei a linguagem muito interessante, mas mais ainda o projeto Squeak e o fato de ele ser usado, principalmente, para ensinar princípios de computação e programação para crianças – vejam em http://squeakland.org/ , isto já existia muito tempo antes do OLPC ser sequer cogitado. O ambiente Squeak é inteiramente interativo, todo e qualquer objeto pode ser editado, remodelado, programado, ter eventos criados e assim por diante (*todo* e qualquer objeto, até a barra de título de uma janela, os botõezinhos de maximizar/minimizar, e até um label de texto qualquer dentro da janela).
Continue lendo

Dois Softwares Livres

Existem dois movimentos de software livre: um filosófico, o outro técnico.
Isto não significa que existam dois movimentos de software livre completamente separados entre si, nem que não haja uma área de intersecção. Certamente há. Talvez a mistura das duas se apresente com mais freqüência que sua separação.
Mas, para todos os efeitos, qualquer um que sente do lado de fora do software livre como um todo e o observe de fora, tentando apreender o movimento, irá notar (ao menos) dois movimentos – duas forças com sentido e direção – atuando dentro do que chamamos como um todo de comunidade de software livre. Uma força que aponta para a filosofia, a ideologia, que tem por fim último beneficiar seres humanos e suas sociedades e que apregoa a liberdade acima de tudo; e outra que aponta para o desenvolvimento aberto, o compartilhamento livre de código e idéias, que tem por fim último atingir a perfeição tecnológica até onde for possível, tornando a atividade de se transformar pensamentos e idéias em códigos de máquina que dêem forma a essas idéias livres de qualquer forma de restrição. Note que apesar das duas terem fundamento no conceito de liberdade, os objetivos finais diferem. Pouco, diriam alguns, pouco o suficiente para que ambos os objetivos sejam conciliados em um único objetivo e movimento; mas ainda assim o suficiente para que eles também possam ser encarados individualmente e separadamente, em algumas ocasiões.

The Nature of Lisp

The Nature of Lisp [defmacro.org]
English version below.
Excelente introdução à linguagem Lisp. O autor passa boa parte do texto comparando a linguagem Lisp com o formato XML, o que a princípio soa estranho, mas logo logo dá pra ver onde ele quer chegar. Para iniciantes ou curiosos como eu, que ainda estou dando os primeiros passos nesta linguagem. Ah, e não deixe de visitar o site do Lisp-BR.
Excellent introduction to the Lisp language. The author initially compares Lisp to the XML data format, which at first sounds strange, but soon you realize what he wants you to understand. To the Lisp newbies or curious ones that, just like me, are still making their first steps into Lisp.