Arquivo da categoria: Computadores

Licenças de Software Livre e de Código Aberto

Ontem dei uma palestra no Serpro, onde trabalho, na Regional Brasília. sobre o tema Licenças de Software Livre e de Código Aberto. O conteúdo está disponível para download na página aulas e palestras.
UPDATE: pode-se assistir ao vídeo da apresentação e baixar o vídeo aqui.

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.

Extraindo o último elemento de uma linha com o awk

awk, o mastigador de linhas de texto

awk, o mastigador de linhas de texto

Hoje surgiu a necessidade de manipular, via script (shell), um arquivo texto e pegar o último elemento de uma linha, que é um código. Como a linha de exemplo abaixo:

DISSE0074I Operation successfully submitted. Distribution ID is 1234567890.123456.

No caso eu preciso pegar o código numérico no fim da linha. Geralmente eu usaria apenas o comando cut, como: cut -d’ ‘ -f8, mas e se a mensagem variar de tamanho (quantidade de palavras)? Como saber o índice do último elemento?
Entra em ação o awk. Usando awk ‘{print $8}’ dá pra imprimir o elemento número 8; e há a variável NF que informa a quantidade de campos. Então dá pra extrair o último campo assim:

cat arquivo.txt | awk ‘{print $NF}’

Perfeito para o que eu queria.

Análise de Tráfico

Entrei hoje na página do Projeto Tor (http://www.torproject.org/) e dei de cara com este texto:
Análise de "tráfico" de rede...
O Projeto Tor serve para redirecionar os pacotes TCP enviados pelo seu computador, de forma que eles passem por dentro de uma rede espalhada pelo mundo todo antes de atingir seu destino. Um dos vários objetivos disso é proteger você contra a análise de tráfego na rede. Não tem nada a ver com traficantes agindo na internet… :p 😉

Como trocar o Windows pelo Ubuntu

Geralmente eu não gosto de ficar criando posts no meu blog só pra colocar links para matérias em outros sites, mas esta não dava pra deixar de lado. O fato do portal G1 publicar alguma coisa favorável ao Linux já é, em si só, uma notícia, que dirá uma matéria explicando ao público que o Linux não é um bicho de sete cabeças.
Especial Linux: saiba como trocar o Windows pelo Ubuntu em seu PC
Nem li a matéria ainda, mas parece ser o suficiente para um iniciante dar seus primeiros passos com o Ubuntu. Lembrando que é possível rodar o Ubuntu direto do CD, sem instalá-lo no seu computador, ou seja, se você quer apenas ver este tal de Linux para conhecê-lo, não precisa apagar nada da sua máquina. Com o mesmo CD é possível tanto testar o Ubuntu sem instalar, quanto instalá-lo, se assim quiser.

Linux is not Windows.

Linux is not Windows.

It's all DNS's fault

English version below.
Retirado de http://www.debian-administration.org/users/lykwydchykyn/weblog/18:

I remember reading somewhere recently (and my experiences in the past pay testament to it):
If you see a baffling problem, it’s surprising how often its down to DNS or host name resolving.

Tradução livre do texto acima:

Eu me lembro de ter lido em algum lugar recentemente (e minhas experiências passadas confirmam isso): se você encontrar um problema que você não faça idéia de qual seja a causa, é surpreendente o quão comum que a causa seja DNS ou resolução de nomes.

Basicamente, o camarada atualizou o Debian e então um programa passou a ficar incrivelmente lento ao conectar com o MySQL. No final o problema era com o DNS.
Eu me lembro alguns anos atrás, quando minha máquina com Debian de uma hora para outra começou a levar vários minutos pra dar boot, quando antes ela iniciava em cerca de um minuto apenas. No fim o problema era o exim (configurado como servidor local), que tentava resolver o nome da máquina durante sua inicialização, e por causa de algum motivo estranho de que não me lembro agora, o arquivo /etc/hosts perdeu a entrada da própria máquina.
Então eis a lição… ao encontrar problemas estranhos sobre lentidão súbita e inexplicável, confira se a resolução de nomes está funcionando (DNS, arquivo hosts, WINS ou o que quer que seja)
(e eu acabei de me lembrar que esse tipo de problema já me deu muita dor de cabeça com o Tivoli Framework em várias ocasiões…)


Taken from http://www.debian-administration.org/users/lykwydchykyn/weblog/18:

I remember reading somewhere recently (and my experiences in the past pay testament to it):
If you see a baffling problem, it’s surprising how often its down to DNS or host name resolving.

Basically, this guy updated Debian and then some app started behaving very slow when connecting with MySQL. Turns out it was a name resolution problem (DNS).
I remember some years back ago, when my Debian machine suddenly started taking several minutes or so to boot up, when previously it just booted in a minute or so. Turned out the problem was with exim (configured as local server only), which tried to resolve the machine name during start up, and because of some weird reason that I can’t remember now, the /etc/hosts file lost the entry for the own machine.
So here’s the lesson… if facing weird problems concerning suddenly, unexplainable slowness, check if the name resolution is working (DNS, hosts file, WINS, or whatever)
(and I just remembered that these issues give me a lot of headache with Tivoli Framework in several occasions…)

MetaRogue

English version below.
Idéia para uma mistura entre os gêneros de jogo “roguelike” e ficção interativa, usando metadefinições

Conceitos

Considerações

Jogos “roguelike”, apesar de terem uma interface à primeira vista mal-feita (há versões gráficas mas elas não têm o mesmo nível de qualidade esperado dos jogos modernos), oferecem uma forma de jogo com muitas possibilidades, fator de “rejogabilidade” impressionante, e às vezes centenas de interações possíveis entre o jogador, o ambiente, as criaturas inimigas e os itens encontrados no jogo. Isso pra não mencionar a aleatoriedade: cada nova partida jogada é completamente diferente da anterior, porque partes do “mundo” serão dinamicamente geradas para aquele jogador. É por isso que este gênero de jogo continua ganhando fãs e mantendo esses fãs leais ao gênero, mesmo depois de décadas de diversão. Mesmo depois de jogar o mesmo jogo durante anos a fio, ainda é possível se descobrir novas formas de combinar itens, lidar com criaturas, interagir com o ambiente, ou apenas jogar o jogo com alguma limitação autoimposta que mude completamente seu estilo de jogo, só pela diversão de descobrir novas formas de fazer as coisas. Porém, mesmo o roguelike mais complexo terá um limite a essas possibilidades – a imaginação de seus desenvolvedores. Pode ser possível, claro, que as regras estabelecidas pelos programadores no código do jogo abram o caminho para fazer alguma coisa que não havia sido prevista por eles, mas ainda assim o jogo não irá, sozinho, criar ou inferir novas regras para o mundo do jogo.

Tela de Nethack, um jogo roguelike. Eu sou o @, o d marrom é um coiote, e o d branco é meu cachorro.

Tela de Nethack, um jogo roguelike. Eu sou o @, o d marrom é um coiote, e o d branco é meu cachorro.


Outra característica notável dos roguelikes é a sua relação estrita com o posicionamento de seus elementos; o jogador, as criaturas e outros elementos “vivem” dentro de uma grade quadrada, e todas as relações possíveis destes elementos são diretamente conectadas à sua posição na grade. Claro, isto nada mais é que apenas mais uma regra do mundo do jogo, e que é facilmente compreendida e aplicada. E apesar de que existem algumas exceções e alternativas (geralmente em roguelikes conceito) para se mover dentro da grade, o básico se mantém. Logo um roguelike poderia ser adaptado a outras formas de interface (tela de caracteres, quadriculado de imagens, 3D, etc.), mas a grade sempre estaria lá porque é um conceito intrínseco do gênero, e o jogo precisa da grade para funcionar. Volto a este assunto mais adiante.
Jogos de Ficção Interativa são muito diferentes dos roguelikes, exceto pelo fato de que estes também se baseiam em texto, deixando de lado as capacidades gráficas dos computadores. E o fato de serem baseados em texto somente não diminui nem um pouco o valor deste gênero de jogo – alguns jogos de FI têm um enredo tão profundo ou mesmo mais profundo que um bom romance. Pra não mencionar que existem estórias de FI em uma variada gama de temas, indo desde aventuras até histórias de horror e fantasia. Resumindo, jogar uma FI é similar a ler um livro – só que você está livre para interagir à vontade com o mundo apresentado pelo livro, você não pode pular os capítulos para ver o final de antemão, e a estória não vai progredir a menos que você tome as atitudes corretas. Eu acho que estas características definem muito bem porque este gênero de jogo é tão interessante.
Anchorhead - interactive fiction game

Anchorhead, um jogo de ficção interativa excelente de horror lovecraftiano. Recomendo.


Ainda, diferente do que acontece com os roguelikes (neste ponto eu acho que deveria me desculpar com o leitor por estar insistindo em comparar dois gêneros de jogos tão diferentes, e eu sei que eles na verdade não têm nada em comum então não tem nem jeito de pensar em compará-los, mas continue seguindo meu raciocínio), jogos de Ficção Interativa não põem o jogador dentro de uma grade; é comum que o mapa de um jogo de FI se pareça com uma grade (ou seja uma) mas isto não é necessário para que o jogo funcione; você pode andar de um lugar para outro sem se preocupar em como estes lugares estão dispostos um em relação ao outro. Vou colocar isto de forma mais clara: em alguns jogos os locais estão logicamente posicionados em relação aos outros – pense nas salas dentro de uma casa – de forma que eles funcionam com esta lógica posicional, mas novamente essa restrição não é intrínseca a este tipo de jogo; você poderia ter, digamos, três salas adjacentes em linha, e como a sala do meio não é de interesse àquele jogo em particular sendo jogado, o jogador poderia se mover diretamente da primeira sala para a terceira; a sala do meio seria ignorada ou o jogo poderia apenas dizer “você segue até a terceira sala passando pela segunda” mas essa ação seria realizada em apenas um movimento. Então a estrutura “física” (se eu posso usar esta palavra) de um jogo de FI é livre das restrições normalmente encontradas em nosso mundo. Ela não tem que seguir a forma de uma grade, uma estrutura plana, uma estrutura em 3D, ou mesmo seguir a geometria euclidiana – ela pode ser qualquer coisa que a imaginação do autor quer que ela seja.
Ainda, um jogo de FI pode ser completamente diferente de qualquer outro jogo de FI, da mesma forma que um livro pode ser completamente novo no seu próprio estilo. As regras do mundo do jogo – com relação a movimento, interação com objetos, ou qualquer outra coisa – podem ser definidas pelo autor como este assim o quiser. E o jogo ainda será reconhecível como um jogo de FI. Este grau de liberdade é esperado neste estilo de jogo, e os limites das ações e interações são definidas pelo próprio jogo, da mesma forma que este explicita as relações possíveis. Geralmente em apenas alguns minutos da estória o jogador terá noção das regras do mundo do jogo e seguirá explorando-o por si mesmo. E aqui, assim como no gênero roguelike, explorar é parte da diversão.
E, assim como eu comentei no caso dos roguelikes, jogos de FI têm a limitação inerente de deixar o jogador ir apenas aonde o autor pensou que ele poderia ir (com talvez algum grau de liberdade, indo um pouco além do que o autor tinha imaginado, mas não muito além disso). Claro, ninguém espera que o programa do jogo sozinho crie ou invente novas regras e situações.
Então, depois de considerar estes pensamentos, pode-se perguntar: ok, então jogos roguelikes e de ficção interativa são divertidos e complexos em seu próprio estilo, mas que raios um gênero tem a ver com o outro? E a resposta é – absolutamente nada, além das fracas comparações que eu fiz aqui, e por serem dois gêneros de jogo pouco conhecidos do grande público. Mas o exercício imaginativo de comparar os dois me levou à ideia que eu apresento a seguir.

Ideia

Então após toda esta introdução, a ideia, de forma resumida, é misturar características destes dois gêneros de jogo, e ao mesmo tempo adicionar à mistura a capacidade de gerar regras de interação automaticamente, baseando-se em metaregras definidas pelo autor do jogo. Como misturar os gêneros de jogo e manter o resultado “jogável” e como definir regras de interação de forma realista baseando-se em metadefinições de uma forma que funcione será o assunto de comentários (futuros) sobre este assunto. Mas vou acrescentar que eu pensei nisso enquanto estava tentando aprender a programar em Lisp, e pensei em construir algum tipo de jogo baseado em texto para aprender melhor as capacidades do Lisp.


Idea for a mix between the game genres roguelike and interactive fiction, using metadefinitions

Concepts

Considerations

Roguelike games, despite the seemingly crude interface (there are graphical versions but they do not stand up to common visual effects in modern games), offer depth of gameplay, incredible replayability, and sometimes hundreds of different possible interactions between the player, the environment, the enemy creatures and the items found in the game. Not to mention the randomness: every new game played is completely different from the previous one, because parts of the “world” will be dinamically generated for that player. That’s why they continue to gather fans and keep those fans loyal to this game genre, even after decades of enjoyment. Even after playing the same game for years it can still be possible for one to discover a new way to combine items, deal with creatures, interact with the environment, or even just play the game with some self-imposing limitation that changes entirely one’s gameplay style, just for the fun of discovering new ways of doing things. However, even the most intricate of roguelikes will have a limit to these possibilities – the imagination of its developers. It may be possible, sure, that the rules devised by the developers in the game code open way to doing something else that wasn’t in the developers minds, but still the game won’t itself create or infere new rules for the game world.

Screen of Nethack, a roguelike game. I'm the @, the brown d is a coyote, the white d is my dog.

Screen of Nethack, a roguelike game. I'm the @, the brown d is a coyote, the white d is my dog.


Another notable trait of roguelikes are their strict relation with the positioning of its elements; the player, the creatures and other elements “live” inside a square grid, and all their possible relations are directly connected with their position in this grid. Of course, this serves well just as another rule for the game world, one that is easily grasped and dealt with. And although there are some exceptions and alternative ways (mostly in some concept roguelikes) to move inside a grid world, the basics are the same. So a roguelike could be adapted to other kinds of interfaces (character based, tile based, 3D, etc.), but the grid would always be there because it’s an intrinsic concept of the genre, and the game needs the grid to work. More on these thoughts later.
Interactive fiction games are very different of roguelikes, unless for the fact that they also rely heavily in text, ignoring computers’ graphics capabilities. And the fact of relying only in text doesn’t detract from this game genre not even a bit – some IF games have a plot as deep or even deeper than a good novel. Not to mention that there are IF stories in a whole variety of themes, ranging from adventures to horror to fantasy. In short, playing an IF game is very much like reading a book – only that you’re free to really interact with the world presented by that book, you can’t just skip chapters to see the end beforehand, and the story wouldn’t advance unless you take the right steps. I believe these traits define well why this game genre is so interesting.
Anchorhead - interactive fiction game

Anchorhead, an excellent interactive fiction game of lovecraftian horror. I recommend.


Also, differently from roguelike games (at this point I think I should beg the reader’s pardon for insistently comparing two such different game genres, and I know they actually have nothing in common so there’s no way to even think about comparing them, but please keep with me), Interactive Fiction games doesn’t put the player inside a grid; it is common that the map of an IF game places resemble a grid (or is actually one) but this isn’t needed for the game to work; you can walk from place to place without actually worrying about how these locations are disposed one in relation with another. Let me clarify this: in some games the locations are logically positioned in relation to the others – think the rooms inside a house – so they work with that positional logic, but again that restriction isn’t intrinsic for this kind of game; you could have, say, three adjacent rooms in line, and just because the middle room is of no interest to the particular game being played, the player could move directly from the first room to the third one; the middle room would be ignored or the game could just say “you go to the third room passing through the second one” but that action would be done in just one movement. So the “physical” (if I can use this word) structure of an IF game is free of usual constraints found in our world. It hasn’t to resemble a grid, a plain structure, a 3D structure, or even conform with euclidian geometry – it may just be anything the author’s imagination wants it to be.
Also, an IF game can be completery different of any other IF game, just like a book can be completely new in its own style. The rules of the game world – concerning movement, object interaction, or anything else – may be defined by the author as he pleases. And still it will be recognizable as an IF game. This degree of freedom is expected in this game style, and the limits of actions and interactions are defined by the game itself, as well as it explicites the possible interactions. Usually with just some minutes of story the player will be aware of the game world rules and go on exploring it by himself. And here, like the roguelike genre, exploring is part of the fun.
And, just like I pointed in the roguelikes case, IF games have the inherent limitation of just letting the player go where the author thought it could go (with maybe some little degree of freedom, going a little further than the author had imagined, but not much beyond that). Of course, we won’t expect the game program to create or invent itself new rules and situations.
So, after considering these thoughts, one may ask: ok, so roguelikes and interactive fiction games are interesting and fun and complex in their own ways, but what the heck have one genre to do with the other? And the answer is – absolutely nothing, apart from the loose comparisons I did here, and for being two non mainstream game genres. But the imagination exercise of comparing the two lead me to the idea I present next.

Idea

So after all this introduction, the idea, in short, is to mix together characteristics of these two game genres, and at the same time throw in the mix the capability of generating interaction rules automatically, based on metarules defined by the game author. How to mix the game genres and keeping the result playable and how to realistically define interaction rules based on metadefinitions in a way that works is the subject of the (future) comments on the subject. But I will add that I was thinking of this while trying to learn how to code in Lisp, and thought of building some kind of text game to learn better Lisp’s capabilities.

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.

Things to do in Emacs 22: regexp

Stevey’s Blog Rants: Shiny and New: Emacs 22

It’s just like a normal M-x {query-}replace-regexp, but you’ll prefix any lisp expressions in the replacement string with the sequence `\,’ (i.e., a backslash and a comma). In this case, we match the whole word, and invoke the Emacs-Lisp function `capitalize’ to capitalize the word we just matched:
M-x replace-regexp
Replace regexp: \(\w+\)
Replace regexp with: \,(capitalize \1)