Wednesday, April 22, 2009

Using OS X Terminal keys on a Macbook Pro

The default key settings on the Mac OS X (10.5) Terminal are pretty weird, especially on a Macbook Pro, and took me a while to figure them out and setup as I wanted.

This is how it works:

«fn» + left/right arrows is equivalent to home and end
«fn» + up/down is equivalent to page up/down

Problem is, by default, these keys don't send escape sequences, and don't work as expected. This is how I setup my terminal keys:

On the Terminal preferences, go to the Settings item, and choose the Keyboard tab.
Find these keys and edit them (note that the \033 you can get by pressing the esc key):

End - send string to shell: \033[4~
Home - send string to shell: \033[1~
Page down - send string to shell: \033[6~
Page up - send string to shell: \033[5~
Shift page down - scroll to next page in buffer
Shift page up - scroll to previous page in buffer

These bindings should get you close to what you'd expect from a sane terminal. There are a few more settings I use to setup Bash (and other programs that use readline), which are located on the .inputrc file on your home dir.

Edit ~/.inputrc and add this:

# Be 8 bit clean.
set input-meta on
set output-meta on
set convert-meta off

# Auto completion options
set show-all-if-ambiguous on
set completion-ignore-case on

# Keybindings
"\e[1~": beginning-of-line # Home key
"\e[4~": end-of-line # End key
"\e[5~": history-search-backward # Page Up
"\e[6~": history-search-forward # Page Down
"\e[3~": delete-char # Delete key
"\e[5C": forward-word # Ctrl+right
"\e[5D": backward-word # Ctrl+left

With these settings, «shift» + «fn» + up/down scrolls the buffer, and «fn» + up/down searches your history based on what you typed on the line.

References:

Labels:

Monday, November 10, 2008

Code::Blocks Oblivion

Code::Blocks is a cross-platform programming editor/IDE written using wxWidgets. I use it to program in C++ with wxWidgets in Linux and cross-compiling with MinGW to win32.

By default it comes with a white theme, while I prefer darker colors for programming. So I put together a color scheme that suits me better, following the Oblivion Tango color theme available in Gedit by default, with a few changes. Here's what it looks like:



If you want to try it, get the file codeblocks_oblivion.conf and use the command cb_share_config to merge it into your ~/.codeblocks/default.conf .

Labels: , ,

Thursday, November 6, 2008

Selfish Python

No post «O porquê do self explícito... será que agora vai?» Pedro Werneck demonstra, passo a passo, uma implementação do funcionamento das classes em Python utilizando apenas dicionários e funções.

Fica claro o modo como Python resolveu implementar o suporte à orientação à objeto, de maneira bem simples e prática, sem mágicas obscuras para tentar fornecer algum suporte sintático questionável, como seria se fosse sem explicitar o self.

Pessoalmente, já estava confortável com a utilização do self explícito (a ponto de sentir falta disso em C++ :) e esse post só veio para ajudar a entender melhor o funcionamento "por detrás dos panos", que é muito interessante.

Pontos extras por ter mostrado o funcionamento das metaclasses, e como as classes em Python não são nada especiais em termos de implementação.

Labels:

Thursday, September 4, 2008

Pidgin e Google Talk group chat

O GTalk tem função de group chat, porém se você usa o Pidgin irá apenas receber um link para acessar pelo navegador, usando um cliente em Flash.

Investigando um pouco, descobri que é possível entrar no group chat usando o próprio Pidgin, ou até mesmo criar uma sala:
  1. ao receber um convite, siga o link e quando aparecer o botão para iniciar o cliente Flash, selecione para ver o código fonte da página.
  2. Procure pela string de conexão, algo parecido com: private-chat-12345678-dead-beef-feed-fedcba987654@groupchat.google.com
  3. No menu "Amigos" do Pidgin, selecione "Adicionar bate-papo..." e preencha o campo de sala com a parte antes do @ da string anterior e o servidor com groupchat.google.com e clique em Adicionar.
  4. Pronto, você já tem a sala na sua lista e já pode conversar
O mesmo vale para criar novas salas, é só criar uma string para o nome da sala que seja compatível e conectar. Se ela não estiver sendo usada uma nova sala será criada e você pode convidar pessoas para entrar (menu "Conversa" -> "Convidar...").

Se você tem uma conta Jabber, pode criar salas no servidor conference.jabber.org da mesma forma, ou mesmo ver as salas já existentes pelo menu "Ferramentas" -> "Lista de salas", selecione sua conta Jabber, clique em "Obter lista" e preencha com o endereço do servidor.

Fontes:

Labels: ,

Thursday, July 17, 2008

Promoção para ajudar a Wikipédia e outros projetos

O BR-Linux.org e Efetividade.net estão novamente promovendo campanha para fazer doação para a Wikipédia e outros projetos importantes relacionados à livre difusão de conhecimento (software ou não).

Segue o texto de chamada da campanha:

Ajude a sustentar a Wikipédia e outros projetos, sem colocar a mão no bolso, e concorra a um Eee PC!
…e também a pen drives, card drives, camisetas geeks, livros e mais! O BR-Linux e o Efetividade lançaram uma campanha para ajudar a Wikimedia Foundation e outros mantenedores de projetos que usamos no dia-a-dia on-line. Se você puder doar diretamente, ou contribuir de outra forma, são sempre melhores opções. Mas se não puder, veja as regras da promoção e participe - quanto mais divulgação, maior será a doação do BR-Linux e do Efetividade, e você ainda concorre a diversos brindes!


Quem tiver um blog, não deixe de participar também.

Monday, June 9, 2008

Cálculo da variância em Python

Este post segue uma seqüência iniciada no blog Kodumaro, comparando a implementação de alguns cálculos de estatística usando linguagens como Lisp, C e depois seguido de Ruby no blog Programando sem cafeína, e Smalltalk.

Como estou vendo um pouco de estatística na faculdade agora, me animei para tentar uma implementação em Python também.

import math

def arithmetic_mean(dataset):
"""
Simple arithmetic mean (average)

Example:
>>> arithmetic_mean([10,100,1000])
370
"""
return sum(dataset) / len(dataset)


def root_mean_square(dataset):
"""
RMS (quadratic mean)

Example:
>>> root_mean_square([10,100,1000])
580.25856305616037
"""
return math.sqrt(sum(x**2 for x in dataset) / len(dataset))


def var_num(dataset, mean_function=arithmetic_mean):
"""
Divisor for variance calculation
"""
mean = mean_function(dataset)
return sum((x - mean)**2 for x in dataset)


def populational_variance(dataset):
"""
Population variance

Example:
>>> populational_variance([10,100,1000])
199800
"""
return var_num(dataset) / len(dataset)


def sample_variance(dataset):
"""
Sample variance

Example:
>>> sample_variance([10,100,1000])
299700
"""
return var_num(dataset) / (len(dataset) - 1)

Preferi implementar como funções simples pois assim é fácil de aplicar sobre qualquer conjunto de dados iterável como listas, tuplas, dicionários ou sets.

Na função de numerador da variância, um dos parâmetros é a função de média que se deseja utilizar para o cálculo, com o padrão sendo a média aritmética (pois como nota o blog Kodumaro, o uso da função depende de quem pediu o cálculo ;).

Vale notar também o uso de generator expressions para os somatórios, que substituem as mais tradicionais list comprehensions nesse caso por questão de performance, principalmente para grandes conjuntos de dados.

Apliquei ainda doctests simples para validar os resultados das funções.

Labels:

Friday, April 25, 2008

Dist-upgrade Hardy

Just dist-upgraded my Gutsy laptop to Hardy and a few issues have come up.

Gateway 5570Z (model 5570-2607)

Sound

00:1b.0 Audio device: Intel Corporation 82801G (ICH7 Family) High Definition Audio Controller (rev 02) [8086:27d8 (rev 02)]

After the upgrade there was no more sound, whereas it was working fine in Gutsy. Needs further investigation.

PARTIALLY SOLVED: Seems the bug is on the headphone output detection. I had external speakers connected to the headphone out and no sound was playing, either on the internal or external speakers. If I unplug the external speakers, sound comes out from the internal ones. If I plug the external, no sound is heard again, only if I manually check the Headphone key on the volume control app. Definitely a bug.
https://bugs.launchpad.net/ubuntu/+source/linux-source-2.6.22/+bug/126157


WiFi

03:00.0 Network controller: Broadcom Corporation BCM94311MCG wlan mini-PCI (rev 01)

I was using a manually compiled ndiswrapper on Gutsy, and on the upgrade it was probably replaced. Tried using the new b43 driver, which installed fine and even activated the device, but it isn't detecting my wireless network, so I'm going back to ndiswrapper. Seems ndiwrapper doesn't like loading in Hardy tho... hmm.

SOLVED: the ndiswrapper module doesn't like to be loaded after the ssb module, so you must remove b44 and ssb, load ndiswrapper and then load ssb and b44 back again. Fun.
https://bugs.launchpad.net/ubuntu/+source/linux/+bug/188621
https://bugs.launchpad.net/ubuntu/+bug/214917


USB Keyboard

I use an external usb keyboard when at home, and Hardy is having issues in detecting the numeric keypad... any key I press there is completely ignored. Needs further investigation.

SOLVED: completely stupid bug, it is fixed by going in System->Preferences->Keyboard and disabling Allow to control the pointer using the keyboard on the Mouse Keys tab.
Thanks to this blog post: Fixing the borked numeric keypad in Ubuntu Hardy


Touchpad

Just doesn't works (completely disabled). A major regression from Gusty, where it was perfectly detected and functioning. No solution yet, just a workaround:

sudo rmmod psmouse && sudo modprobe psmouse

this makes it work, kind of, since no advanced synaptic driver functions are enabled (like the scroll button, tap gestures, touch scrolling, etc).
https://bugs.launchpad.net/ubuntu/+source/linux/+bug/191024


Firefox 3

Firefox 3 is great, but I was having speed issues with it, in that accessing a Flickr picture (for instance) would make it use 100% cpu and lockup. Since it was using my old FF2 profile, I created a new one (Alt+F2 -> firefox -ProfileManager) and tried the same pages, and sure enough it worked fine. So I just imported the old bookmarks to this new profile, installed a few extensions and all was good.

Labels: