[lang_en]Previously… Useful bash functions

This new version is a tad more efficient since there are no more echo and pipes involved on the processing. Just one eval and one awk script.
[/lang_en][lang_pt]Previamente… Funções úteis em bash

Esta nova versão é ligeiramente mais eficiente, porque não existem mais comandos echo e pipes envolvidos no processamento. Apenas um eval e um script awk.
[/lang_pt]


1
2
3
4
5
6
7
8
9
10
11
12
unique_path() {
  eval $(awk -v VAR="${1}" 'BEGIN {                 \
    if((N=split(ENVIRON[VAR],vals,":"))<2) exit(0); \
    sep = out="" ; i=split(out,seen);               \
    do { if(!(vals[++i] in seen)) { seen[vals[i]];  \
           gsub("["]","\\"",vals[i]);             \
           out=sprintf("%s%s%s",out,sep,vals[i]);   \
           sep=":";                                 \
    } } while (i<N);                                \
    printf "%s="%s"; export %s;\n",VAR,out,VAR;   \
  }'
/dev/null)
}

[lang_en]Similarly, these also had remove unnecessary uses of sub-shell echo…[/lang_en][lang_pt]Estas funções também foram melhoradas removendo usos desnecessários de sub-shells para echo[/lang_pt]


1
2
3
4
5
6
7
8
9
10
11
safe_prepend_path() {
  VAR=$1 ; shift ; eval VAL=\$${VAR}
  for i_;do [ -d "$i_" ] && VAL=$i_${VAL:+":$VAL"} ;done
  eval export ${VAR}=${VAL}
}

safe_append_path() {
  VAR=$1 ; shift ; eval VAL=\$${VAR}
  for i_;do [ -d "$i_" ] && VAL=${VAL:+"$VAL:"}$i_ ;done
  eval export ${VAR}=${VAL}
}

[lang_en]
If you are like me, you have regular conference calls where you have to send some bridge identification number or profile to sign in.

On a Nokia N9 it’s really not obvious how to set up a contact that automatically sends those digits after the call is connected, especially if you use the Swype virtual keyboard.

The first thing to know is that in order to specify a pause separation for the digits you need to enter a ‘p’. To me this was a surprise, as I was used to other cellphones which used the comma (‘,’), semi-colon (‘;’) or period (‘.’) for the same purpose, sometimes with different pause intervals
[/lang_en][lang_pt]
Pessoas como eu têm conferências telefónicas regulares em que é necessário enviar digitos para entrar ou activar a conferência.

Num Nokia N9 não é nada óbvio como configurar um contacto para enviar esses digitos automaticamente após a chamada ter sido estabelecida, particularmente se usar o teclado virtual Swype.

A primeira coisa a saber é que para indicar uma pausa no N9 para os digitos é necessário entrar um ‘p’. Para mim isto foi uma surpresa, porque estava habituado a outros telemóveis em que usava a virgula (‘,’), ponto e virgula (‘;’) ou ponto final para isso.
[/lang_pt][lang_en]
If you have swype, when you enter a phone number here is what the screen looks like the image below, a numeric pad virtual keyboard. You disregard the currency symbols and try to enter either the comma or the period and they don’t work.

What you need to do is to tap the bottom ABC button so that it switches to the main alphanumeric virtual keyboard and then you can enter the ‘p’.
[/lang_en][lang_pt]
Se está a usar Swype, quando vai entrar um número de telefone, verá algo como a imagem abaixo, um teclado numérico virtual. Primeiro ignora os simbolos monetarios e tenta digitar a virgula ou o ponto, mas não funciona.

O que precisa fazer é usar o botão ABC do fundo, para mudar para o teclado alfanumerico principal e finalmente pode digitar o ‘p’
[/lang_pt]

[lang_en]
You have the stock virtual keyboard things are a little simpler, you tap the ‘‘ and notice how it becomes red underlined, tap again and it becomes a ‘+’ and again… the ‘p’ finally. The three taps have to be in quick succession.
[/lang_en][lang_pt]
Se tem o teclado virtual original isto é um pouco mais simples. Basta premir o ‘
‘ e note que fica sublinhado a vermelho, prima de novo e fica um ‘+’ e de novo… e finalmente o ‘p’ aparece. Tem que premir as três vezes em rápida sucessão.
[/lang_pt]



[lang_en]If you, like me, strive to keep a well organized and modular configuration setup, sooner or later will split your bash configuration into multiple files. And if you want it to be valid for multiple machines you’ll appreciate the following function:[/lang_en][lang_pt]Se, como eu, sempre tenta organizar e ter uma configuração modular, mais cedo ou mais tarde vai separar a configuração bash em vários ficheiros. Além disso, se quiser usar a mesma em várias máquinas, esta função dá jeito:[/lang_pt]


1
2
3
source_if_exists () {
    for i_; do test -f "$i_" && source "$i_"; done
}

[lang_en]This way, you can try to process other configuration fragments only when they exist:[/lang_en][lang_pt]Desta forma pode tentar incluir os fragmentos apenas onde e quando existem:[/lang_pt]


1
source_if_exists ${HOME}/etc/bash_completion

[lang_en]Another common need for bash configuration is to either append or prepend paths to an environment variable. When doing a configuration for multiple machines it is always a pain to make sure those paths exist. These functions take care of that making adding directories to the path a breeze:[/lang_en][lang_pt]Algo que também é comum fazer é acrescentar um directório a uma variável de ambiente. Quando se faz uma configuração para várias máquina é sempre um inconveniente assegurar que os directórios existem. Estas funções tratam do problema:[/lang_pt]


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
safe_prepend_path() {
    VAR=$1
    shift
    VAL=$(eval echo \$${VAR})
    for i_; do
        test -d "$i_" && VAL=$i_${VAL:+":$VAL"}
    done
    eval export ${VAR}=$(echo ${VAL})
}

safe_append_path() {
    VAR=$1
    shift
    VAL=$(eval echo \$${VAR})
    for i_; do
        test -d "$i_" && VAL=${VAL:+"$VAL:"}$i_
    done
    eval export ${VAR}=$(echo ${VAL})
}

[lang_en]Example:[/lang_en][lang_pt]Exemplos:[/lang_pt]


1
2
safe_prepend_path PATH /opt/local/bin ${HOME}/bin
safe_append_path MANPATH /opt/local/man ${HOME}/man

[lang_en]Also, it is not unusual to have some path variables with duplicate entries, which is not very efficient. This function makes sure that a path only occurs once, and retains only the first occurrence, thus keeping the search order intact.[/lang_en][lang_pt]É frequente que as variáveis de ambiente com directórios apresentem entradas duplicadas o que torna a pesquisa menos eficiente. Esta função assegura que cada directório ocorre apenas uma vez e retem apenas a primeira entrada, mantendo por isso a ordem.[/lang_pt]


1
2
3
4
5
6
7
8
9
10
11
12
13
14
unique_path() {
    eval export $1=$(echo $(eval echo \$${1}) | \
        awk -F:                   \
        '{ a[$1];                 \
           printf "%s",$1;        \
           for(i=2;i<=NF;i++) {   \
             if(!($i in a)) {     \
               printf ":%s",$i;   \
             };                   \
             a[$i];               \
           };                     \
           printf "\n";           \
         }'
)
}

[lang_en]Example:[/lang_en][lang_pt]Examples:[/lang_pt]


1
2
unique_path PATH
unique_path MANPATH

[lang_en]Nokia sure knows how to make very weird decisions. So you’d think that if you manage an email service in order to add to your value proposition in the mobile space, upon deciding to sub-contract it to Yahoo, you’d make sure your current users would be able to migrate…[/lang_en][lang_pt]A Nokia realmente é perita em fazer decisões estranhas. Seria lógico pensar que ao gerir um serviço de email grátis para melhorar a proposta de valor no espaço da telefonia móvel, ao tomar a decisão de passar a sub-contratar esse serviço à  Yahoo, que seriam feitas as diligências para garantir que os utilizadores actuais poderiam migrar sem problemas…[/lang_pt]


(Amazon)

[lang_en]Half a decade ago, while discussing interesting books on software development, a good friend of mine recommended me the book The Soul of a New Machine. Today I happened to come across my copy of the book and was surprised at how much of a strong impression it made.
It only makes it ring closer to home the fact that I work for the company that ultimately acquired Data General…[/lang_en][lang_pt]Há cinco anos atrás, enquanto conversavamos sobre livros interessantes sobre desenvolvimento de software e afins, uma colega e amiga recomendou-me o livro ” The Soul of a New Machine”. Hoje calhou de folhear a minha cópia do livro e fiquei surpreendido com o quanto ainda lembrava dele.
Ainda para mais, hoje em dia trabalho para a empresa que acabou por adquirir a Data General…[/lang_pt]

[lang_pt]Hoje em dia somos bombardeados com sugestões para que façamos reciclagem.
Há uns meses atrás fiquei surpreendido com um exemplo “Web 2.0” de reciclagem: Reciclagem de logotipos.
Comparem o logo da foto de um artigo promocional da empresa System Management ARTS (SMARTS) e o do Adobe AIR.
Provavelmente como a SMARTS foi adquirida pela EMC a marca registrada do logo expirou e a Adobe pode usar, mas não deixa de ser curioso.[/lang_pt]
[lang_en]Nowadays we get bombarded with recycling suggestions.
Quite a few months ago I was very surprised to find a recycling example very “Web 2.0”: Product logo recycling.
Compare the photo from a promo flashlight from the System Management ARTS (SMARTS) company and Adobe AIR.
Most likely the SMARTS logo trademark has expired since EMC has acquired the company, so Adobe can use it. Interesting nonetheless.[/lang_en]

Adobe AIR SMARTS

[lang_pt]Adobe AIR é uma marca registrada da Adobe Systems Incorporated[/lang_pt][lang_en]Adobe AIR is a trademark  of Adobe Systems Incorporated[/lang_en]

[lang_en]If you were looking for the universal recycling logo you might want to look here[/lang_en][lang_pt]Se estava à  procura do logotipo de reciclagem, veja aqui[/lang_pt]

[lang_pt]Mais um serviço público, desta vez do xkcd.com: Entenda Fluxogramas[/lang_pt][lang_en]Another useful public service, this time from xkcd.com: Guide to Flowcharts[/lang_en]
Guide to flowcharts

[lang_pt]Reinstalei o XP de forma “quick&dirty” numa partição para fazer uns testes, e como estava incluido no Google Desktop acabei por aceitar o Norton Security Scan como “anti-virus”. Google e Norton, mesmo grátis, que segurança é essa que precisa de “upgrade” para retirar cookies? Para mim isto é Norton Security Scam. Ainda bem que eu sei como remover as cookies selectivamente :-).

Mas que vergonha destas duas empresas supostamente com boa reputação de fazerem este tipo de coisas para extrair dinheiro dos utilizadores menos conhecedores.[/lang_pt][lang_en]I reinstalled Windows XP “quick&dirty” in a partition to do some testing, and, because it was included in the Google Desktop, I ended up trying Norton Security Scan as my anti-virus/security suite. Now I have a question for Google and Norton: Dudes, even for free, how can you call this a security suite if I need to upgrade just to remove cookies? I’d call this Norton Security Scam. I am so glad I know how to remove my cookies selectively.

Still, these two companies should be ashamed for doing this kind of bait-and-switch to get money from less knowledgeable users.[/lang_en]

Norton Security Scam

Norton Security Scam

keep looking »
-->