diale.org

Blog e página pessoal de Tiago Charters de Azevedo (Blog and personal webpage of Tiago Charters de Azevedo)

Shorten URLs in Emacs Lisp

2012/01/27-09:26:54

O código é este:

(defun short-url (url)
  (interactive "M")
  (let ((url-request-method "GET"))
    (url-retrieve (concat "http://is.gd/create.php?format=simple&url=" url)
                   (lambda (x)
                     (goto-char (point-min))
                     (search-forward-regexp "http://.*")
                     (setq s-url (match-string-no-properties 0))))
   (insert s-url)))

Etiquetas/Tags: is.gd, short urls, Emacs Lisp


diaspora(dot)el -- Simple Emacs-based client for diaspora*

2012/01/18-15:04:19

I've started a simple set of functions for posting to diaspora using Emacs.

Some of the ideas should be credit to Christian and his auth-get. I'm still trying incorporate Christian's ideas in one package. I've used the authenticity token function and not, yet, the streaming...

I don't have many experience in sharing code that is still incomplete, it is not mature enough; and so have a question. What is the thumb rule, in terms of completeness, for sharing code? It can go from a simple idea to a far complete code, right :)

Usage

  1. copy the code to a buffer and safe it
  2. eval it
  3. open a file which content you like to post to diaspora; write something
  4. type (diaspora)
  5. authenticate

smile

The code

;;; diaspora.el --- Simple Emacs-based client for diaspora*
;; Copyright 2011 Tiago Charters Azevedo
;;
;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 2, or (at your option)
;; any later version.
;;
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this program; if not, write to the Free Software
;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
;; 02110-1301, USA.

;;; Commentary:

;; A diaspora* client for emacs


;;; Code:


(require 'url)
(require 'url-http)

(defvar diaspora-username nil)
(defvar diaspora-password nil)


(defconst diaspora-url-sign-in
  "https://joindiaspora.com/users/sign_in"
  "URL used to signing in.")

(defconst diaspora-url-status-messages
  "https://joindiaspora.com/status_messages"
  "URL used to update diaspora status messages.")

(defun diaspora-ask ()
  (list
   (read-from-minibuffer "username: "
                         (car diaspora-username)
                         nil nil
                         'diaspora-username)
   (read-from-minibuffer "password: "
                         (car diaspora-password)
                         nil nil
                         'diaspora-password)))

(defun diaspora-authenticity-token (url)
  (let ((url-request-method "POST")
        (url-request-extra-headers
         '(("Content-Type" . "application/x-www-form-urlencoded")))
        (url-request-data
         (mapconcat (lambda (arg)
                      (concat (url-hexify-string (car arg)) "=" (url-hexify-string (cdr arg))))
                    (list (cons "user[username]" (car diaspora-username))
                          (cons "user[password]" (car diaspora-password)))
                    "&")))
    (url-retrieve url 'diaspora-find-auth-token)))

(defun diaspora-find-auth-token (status)
;  (switch-to-buffer (current-buffer))
  (save-excursion
    (goto-char (point-min))
    (search-forward-regexp "<meta name=\"csrf-token\" content=\"\\(.*\\)\"/>")
    (setq auth-token (match-string-no-properties 1)))
  auth-token)

(defun diaspora-post (post &optional id)
  (let ((url-request-method "POST")
        (url-request-extra-headers
         '(("Content-Type" . "application/x-www-form-urlencoded")))
        (url-request-data
         (mapconcat (lambda (arg)
                      (concat (url-hexify-string (car arg)) "=" (url-hexify-string (cdr arg))))
                    (list (cons "user[username]" (car diaspora-username))
                          (cons "user[password]" (car diaspora-password))
                          (cons "status_message[text]" post)
                          (cons "user[remember_me]" "1")
                          (cons "authenticity_token" auth-token)
                          (cons "commit" "Sign in")
                          (cons "aspect_ids[]" "public"))
                    "&")))
    (url-retrieve diaspora-url-status-messages
                  (lambda (arg) 
                    (kill-buffer (current-buffer))))))

(defun diaspora ()
  (interactive)
  (diaspora-ask)
  (diaspora-authenticity-token diaspora-url-sign-in)
  (diaspora-post (buffer-string)))

(global-set-key (kbd "C-c d") 'diaspora)


(provide 'diaspora)

ç

Etiquetas/Tags: diaspora, emacs, client, diaspora.el


My way into LISP

2012/01/07-17:10:36

There are a lot of ways of learning a programing language, the tips that follows describe my way into LISP. This my work for you, or, maybe not.

  1. Work out the Introduction to Programming in Emacs Lisp; it is not THE lisp that we are aiming, but we will run Lisp with SLIME, and it is a good thing to learn: emacs lisp; learn the difference between Dynamic Binding and Lexical Binding
  2. Run Steel Bank Common Lisp in Emacs with SLIME
  3. Move on to some fundamentals on lisp an read "The roots of LISP" by Paul Graham; try to reproduce the results in another programing language, e.g., in my case GNU/Octave :)
  4. Read the original McCarthy's paper on Recursive Functions of Symbolic Expressions and their Computation by Machine (Part I)
  5. Find a copy of the 2nd ed. of the "The little lisper": read it
  6. Start reading On Lisp, by Paul Graham
  7. Find out about Scheme and run it on a GNU/Linux system
  8. Read some of The Original 'Lambda Papers' by Guy Steele and Gerald Sussman
  9. Start reading Structure and Interpretation of Computer Programs, by Abelson, Sussman, and Sussman
  10. Start reading Paradigms of Artificial Intelligence Programming: Case Studies in Common Lisp, by PeterNorvig
  11. Have a look at the lispmachine.net
  12. do what ever you like...

(To be continued...)

ç

Etiquetas/Tags: lisp


Street view

2012/01/02-12:01:44

Made with Hugin - Panorama photo stitcher.

ç

Etiquetas/Tags: photo,panorama, hugin


Foyer - Salão Nobre: Escola de Música do Conservatório Nacional

2011/12/20-08:48:00

ç

Etiquetas/Tags: emcn, foto, salão nobre, foto, foyer


Salão Nobre: Escola de Música do Conservatório Nacional

2011/12/18-15:44:22

ç

Etiquetas/Tags: emcn, foto, salão nobre, foto


Foto Bairro Alto

2011/12/18-14:29:03

ç

Etiquetas/Tags: Foto, Bairro Alto, Lisboa, Portugal


Write off the debt, bankrupt the banks, nationalize the financial system, and start all over again: Entrevista a Steve Keen

2011/12/11-22:59:57

Keen's entry in Wikipedia

Gostei especialmente do convite à invasão aos departamentos de economia das universidades, e a referência final ao Max Planck! É uma "chatice" estar sempre do contra!!!!

Etiquetas/Tags: economia, entrevista, Keen, BBC


Algoritmo

2011/11/08-09:34:34

Sobre uma muito antiga revelação revelada de Miguel Sousa Tavares:

"Não conhecemos, em todo o mundo árabe, o nome de um cientista, músico, arquitecto, cineasta, explorador, atleta, enfim, alguém que faça sonhar ou avançar a humanidade."

Cópia de um selo emitido pela antiga URSS em 1983.
Cópia de um selo emitido pela antiga URSS em 1983.

Aqui está o contra exemplo, uma cópia de um selo emitido pela antiga URSS em 1983 comemorando o 1200º aniversário de Muhammad al-Khowarizmi, do qual o vocábulo algoritmo deriva.

Ref.: http://www-cs-faculty.stanford.edu/~uno/

Mais detalhes aqui.

Etiquetas/Tags: algoritmo, Muhammad al-Khowarizmi


1 Watt amplifiers (lower than)

2011/10/20-13:41:20

The Bulbamp

Ultra Class A Superdrive Power Amp

1 Watt mosfet guitar amplifier

ç

Etiquetas/Tags: 1 watt, amplifiers, guitar


Nuvens: stratus, nimbus cumulus e cirrus

2011/10/18-09:14:19

ç

Etiquetas/Tags: nuvens


Light bulb projects

2011/10/15-23:17:39

I had a broken light bulb and wonder if I could do anything useful with it.

It contains two 13003X with a typical hfe of 20. Maybe I could use them to make a fuzz face!

Etiquetas/Tags: fuzz face, diy, guitar, light bulb


Atenuação de um sinal de áudio para amplificador de guitarra (act.)

2011/10/14-15:59:38

Muitas vezes queremos atenuar o sinal de saída de um amplificador de guitarra sem alterar as características do sinal, i.e., manter a distorção e todas as qualidades que o amplificador adiciona ao sinal. O que se descreve a seguir foi sujeito a uma patente - Constant distortion volume control, Donald T. Scholz (Mar 6, 1979), Patent number: 4143245. A ideia é bastante engenhosa mas de mérito duvidoso, do meu ponto de vista, para a atribuição de uma patente. É de facto um divisor de tensão! São designados por L-pad (Loss Pads).

As características do sinal de áudio à saída do amplificador dependem fortemente da impedância de saída do próprio amplificador e do altifalante que se usa. Na quase totalidade dos casos o "tom certo", aquele que os guitarristas procuram incessantemente, obtém-se fazendo um overdrive, uma saturação ao pré-amplificador e ao amplificador. O problema é que para isso, mesmo um pequeno amplificador de meia dúzia de Watts, passa a fazer um barulho excessivo, para o guitarrista e para todos aqueles que se encontram numa vizinhança deste (estou a pensar nos vizinhos).

Esquema de um L-pad.
Esquema de um L-pad.

A maneira de conseguir uma atenuação na potência do amplificador sem perder as características de overdrive é conseguir dissipar a potência debitada pelo amplificador sem modificar a forma do sinal eléctrico, ou seja, desviar parte da potência e aplicar apenas uma fracção desta no altifalante, e claro, mantendo constante a impedância que o amplificador vê à saída (isto é a parte essencial para não se perder o tom final).

Consideremos o esquema da figura anterior. A tensão Vi é a tensão à saída do amplificador e Vo a tensão aplicada ao altifalante. As resistências R1 e R2 são dois reóstatos; R11 e R21, R12 e R22 são, respectivamente, as resistências antes e depois do cursor para cada um dos reóstatos. Assim o valor de Vo é dado por, sem o altifalante, latex2png equation

Colocando o altifalante a impedância vista pelo amplificador é dada por latex2png equation onde R é a impedância do altifalante.

Para se manter as características do sinal aplicado ao altifalante temos que pôr latex2png equation O que dá latex2png equation onde latex2png equation o que determina R11. O valor de R2 é determinado pela atenuação epsilon em dB.

Como latex2png equation vem que latex2png equation o que dá para R22 latex2png equation

Assim para uma determinada atenuação epsilon tem-se latex2png equation e latex2png equation que são as expressões finais para os valores de R11 e R22.

Um pequeno programa em Octave permite obter os diferentes valores das resistências como função da atenuação.

#1;
clear all
n=5
epsilon=linspace(-20,-3,n);

#8 Ohms
R=8;
R2=R*10.^(epsilon/20)./(1-10.^(epsilon/20));
R1=R-R2*R./(R2+R);


figure(1)
clf
hold on
title("8 Ohm speaker")
xlabel("dB")
ylabel("Ohm")
plot(epsilon,R2,'o-r;R2;')
plot(epsilon,R1,'o-b;R1;')
grid

w=[epsilon' R1' R2']


#4 Ohms
R=4;
R2=R*10.^(epsilon/20)./(1-10.^(epsilon/20));
R1=R-R2*R./(R2+R);

figure(2)
clf
hold on
title("4 Ohm speaker")
xlabel("dB")
ylabel("Ohm")
plot(epsilon,R2,'o-r;R2;')
plot(epsilon,R1,'o-b;R1;')
grid

w=[epsilon' R1' R2']

Com as tabelas e gráficos: para 8 Ohm

     dB         R1         R2
  -20.00000    7.20000    0.88889
  -15.75000    6.69506    1.55928
  -11.50000    5.87142    2.90026
   -7.25000    4.52792    6.13453
   -3.00000    2.33643   19.39217

e para 4 Ohm

     dB         R1         R2
  -20.00000    3.60000    0.44444
  -15.75000    3.34753    0.77964
  -11.50000    2.93571    1.45013
   -7.25000    2.26396    3.06727
   -3.00000    1.16822    9.69609

Existem no mercado L-pad's prontos a serem usados para a atenuação de sinais de áudio para uma dada impedância do altifalante.

L-Pad 100W Mono 1" Shaft 8 Ohm, Amazon
L-Pad 100W Mono 1" Shaft 8 Ohm, Amazon

No entanto a utilização de dois reóstatos é mais versátil e permite cobrir impedâncias de altifalante de 4 a 16 Ohm sem dificuldade.

Acabei mesmo por montar um numa pequena caixa de madeira (1Eur na "loja dos chineses").

Refs.:

Etiquetas/Tags: audio, guitar, l-pad


Fotografia do interior do Conservatorio Nacional

2011/10/11-15:57:27

URL: http://www.em-conservatorio-nacional.com/

ç

Etiquetas/Tags: monumentos,fotografia


The "triode" emulator revisited

2011/10/11-13:30:16

After reading the excellent page at http://www.runoffgroove.com about the Fetzer Valve circuit and the paper that supports it (Dimitri Danyuk, "Triode Emulator", 116th Audio Engineering Society Convention, May 2004 in Berlin, Germany), I wonder how the results in that paper could be obtained analytically. This page contains my impressions on it. I've found that the exact value of the magic constant is latex2png equation.

The basic circuit of a class A JFET amplifier is given in the following figure.
Plain circuit of a class A JFET amplifier.
Plain circuit of a class A JFET amplifier.

The basic equations that governs the behavior of a JFET, in the saturated regime, are given by latex2png equation Where latex2png equation is the threshold voltage (pin-off voltage) and latex2png equation is the drain current with latex2png equation. Then we can write the drain current as a function of the input voltage as latex2png equation In order to simplify the analysis let us define the variables (normalized current and voltage, respectively) latex2png equation and the constant, which determine the value of the source resistor, latex2png equation We also need the normalized input voltage latex2png equation The relation between the normalized current latex2png equation and voltage latex2png equation can be put into the form latex2png equation

We want to obtain a power law relation between normalized current latex2png equation and the normalized input voltage latex2png equation and, in particular, the exponent 3/2 for the triode emulation. So, in order to get that, let us assume that one has latex2png equation that is latex2png equation Taking the logarithm derivative of the last expression and solving it in order oflatex2png equation one gets latex2png equation or latex2png equation

The next figure shows the value of the exponent latex2png equation as a function of the normalized input voltage latex2png equation
The exponent n as a function of the normalized input voltage z.
The exponent n as a function of the normalized input voltage z.

The value of the constant latex2png equation that determines the value of the source resistor is given by latex2png equation For latex2png equation andlatex2png equation one gets latex2png equation which is closed to the value obtained by Dimitri, 0.83, but not exactly the same. This is the exact value of the constant that determines the value of the source resistor.

One can also see that the expression latex2png equation permits to obtain for any working voltage latex2png equation and exponent latex2png equation the value of the parameter latex2png equation that emulates a super-triode, a "triode" with a exponent between one and two.

Who says that math doesn't pay off?

If you have any comments about this page, please fell free to send me an email: tiago.charters.azevedo@gmail.com

ç

Etiquetas/Tags: DIY, triode valve, fet, electronics


Condomínio fechado reservado a pombos

2011/09/29-16:16:59

Etiquetas/Tags: Fotografia, pombos, sociedade


Glenn Gould - Montage

2011/09/13-16:55:42

ç

Etiquetas/Tags: Glenn Gould, foto, montage


Comentários sobre abusos de copyright

2011/09/13-09:31:20

Desde que voltei a montar circuitos de electrónica, com um intervalo de mais de 20 anos, que fico cada vez mais perplexo com os abusos de copyright e falsos direitos de utilização nos circuitos que estão espalhados por aí.

O caso paradigmático é este Mini-Booster. Conta a história que o circuito foi baseado nas notas de aplicação da National Semiconductor. A figura seguinte mostra o circuito original dessas notas.

A minha primeira consideração recai sobre o circuito Mini-Booster do Jack Orman, que nos obriga, aparentemente,a respeitar uma licença de legalidade duvidosa. Pode ler-se no site:

The documents and information on this site may be used solely for personal, informational, non-commercial purposes, and may not be modified or altered in any way. The text, images and sound files on this Site may not be distributed in any manner including posting on web sites.

A ironia da coisa é que o próprio Jack fez exactamente ao circuito da National Semiconductor o que diz que não se pode fazer aos seus circuitos: não usa a informação para uso estritamente pessoal, comercializa-a, modificou-a e alterou-a e reproduz uma cópia do circuito no site que mantém.

Um facto curioso é que o circuito do Mini-Booster não aparece em mais sítio nenhum se não no site http://www.muzique.com. A obediência cega mantém-se, excepto aqui!

Etiquetas/Tags: guitar, copyright, circuitos, electrónica


Buffer para guitarra

2011/09/09-15:29:24

Depois de montar uns quantos, e de desmontar outros tantos, resolvi mesmo fazer uma versão mais permanente. Corresponde a uma versão alterada daquele que é usado no Ruby. Dá, como vem descrito no Ruby, um som tipo Fender (vá-se lá saber o que isto significa! :P).

Esquema de um buffer para guitarra com o MPF102.
Esquema de um buffer para guitarra com o MPF102.

Resolvi montar tudo ponto-a-ponto num jack de audio (como se pode ver na figura).

A caixa é uma caixa de derivação que custou 2 Eur.

Pôs-se uma placa de plástico sobre os jacks para evitar o contacto com a pilha e um led.

E já está!

Etiquetas/Tags: guitar, buffer


Potpourri

2011/07/08-15:03:15

Um dos próximos projectos que vou executar é este pequeno amplificador de 1/2W e corresponde à junção de vários esquemas que se podem encontrar por aí.

É constituído por um pré-amplificador (aliás, um buffer de ganho unitário) com o MPF102, um depletion-mode mosfet, cuja ideia foi retirada do Ruby, já montado anteriormente. De modo a evitar confusões sobre a autoria da utilização deste tipo de topologia, facto que perturba o sono da malta (ver aviso no início da página), a verdade é que a ideia de colocar um mosfet à entrada do amplificador foi usada em 1969 por Linsley Hood num famoso artigo da Wireless World sobre um "Simple Class A Amplifier: A 10-W design giving subjectively better results than class B transistor amplifiers". Uma colectânea de artigos relacionados um este amplificador pode ser consultada em: The JLH Class-A Amplifier.

A segunda parte consiste no amplificador que usa um IRF510, circuito retirado da página do The Radio Amateur Society of NorwichA Potpourri of Audio Amplifiers. Note-se que este amplificador foi já testado como amplificador para guitarra (http://www.beavisaudio.com), no entanto, e segundo o construtor "Sounds ok, but not great". Veremos!

Nelson Pass, autor da mais expressiva forma de amplificadores de classe A, o Zen amplifier, expressa muito bem a vantagem de se usar uma configuração em classe A para amplificação de áudio.

Simplicity is not the only reason for the use of the single-ended topology. The characteristic of a single-ended gain stage is the most musically natural. Its asymmetry is similar to the compression / rarefaction characteristic of air, where for a given displacement slightly higher pressure is observed on a positive (compression) than on a negative (rarefaction). Air itself is observed to be a single-ended medium, where the pressure can become very high, but never go below 0. The harmonic distortion of such a medium is second harmonic, the least offensive variety.

Ref.: Zen Amplifier, by Nelson Pass

Dito isto aqui ficam mais alguns detalhes técnicos da montagem do amplificador:

Etiquetas/Tags: amplificador, guitarra, 1/2W


Palavras chave: página pessoal, blog, vida-exacta

Última actualização/Last updated: 2012-01-27 [09:27]


1999-2011 (c) Tiago Charters de Azevedo

São permitidas cópias textuais parciais/integrais em qualquer meio com/sem alterações desde que se mantenha este aviso.

Verbatim copying and redistribution of this entire page are permitted provided this notice is preserved.