¿Cómo configurar Vim para evitar archivos swap?

Algo que me molesta de Vim es que a veces al abrir un archivo me topo con algo así:

Found a swap file, Vim

Found a swap file, Vim

Para evitar esto hay que añadir a nuestro archivo .vimrc la línea:

set noswapfile

Ojo: Evitar los archivos swap no es una buena idea (el archivo swap almacena los cambios en el proceso de edición), ya que el archivo swap funciona como archivo de recuperación cuando Vim se rompe. Pero la verdad a mí me molesta mucho.

Notas sobre Git y Github

¿Qué es Git?

Git es un sistema de control de versiones distribuido (no existe un servidor central), fue creado por Linus Torvalds. Un sistema de control de versiones es útil para cosas como:

  • Crear un historial de las versiones de tu código, snapshots.
  • Revertir los cambios hechos en un proyecto.
  • Trabajar con muchos desarrolladores al mismo tiempo.

La colección de archivos y el historial completo son almacenados en un repositorio.

Clonar

El proceso de hacer una copia local de un repositorio externo es conocido como cloning.

Cambios en el repositorio

Un cambio se hace en dos pasos:

  • Staging: Se añade el archivo al index: git add 'algo'
  • Committing: Se almacenan los cambios en el repositorio: git commit 'algo'

Instalar Git

La instalación en sistemas Debian y derivados es sencilla: sudo aptitude install git. Lo que se instala con este comando es un cliente Git.

También existen buenos servidores Git como Gitolite.

Configurar Git

Ya con Git instalado vamos a configurar algunos datos:

git config --global user.name "John Winston Lennon"
git config --global user.email "j.w.lennon@gmail.com"

Estos datos son útiles si usamos servicios como Github o Bitbucket.

Manos a la obra con Github

Github es una plataforma Git en la nube. Generas una cuenta, creas llaves SSH o bien trabajas a través de HTTPS.

Lo que haremos ahora será clonar el repositorio del proyecto Class2Go, que es una plataforma MOOC de la Universidad de Stanford, (dado que este repo es bastante extenso, se puede elegir cualquier otro):

git clone git@github.com:omartrinidad/class2go.git
Clonando un repositorio

Clonando un repositorio

Después de eso vamos a la cuenta de Github que aloja el proyecto Class2Go y picamos en el botón Fork. En automático tendremos una copia de ese proyecto a nuestra disposición.

Fork

Fork

Entramos a la carpeta que se ha generado, modificamos el archivo README.md y ejecutamos los siguientes comandos:

git add README.md
git commit -m "Modificamos el archivo README"

En caso de que hayamos modificado más de un archivo también es posible utilizar wilcards:

git add *.py
git commit -m "Se han modificado todos los archivos Python"

Sin embargo los archivos que hemos modificado aún no están en el nuestro repositorio madre. Si es la primera vez que hacemos un cambio ejecutaremos:

git push -u origin master

El cambio se debe haber efectuado, lo que hemos hecho es un fork, o sea, a partir de un proyecto de código abierto podremos empezar a escribir el nuestro (similar a un sisma religioso según Wikipedia).

A partir de la segunda vez podemos usar una versión abreviada:

git push

¿Qué pasa si alguien más realizó un cambio en el archivo que pretendemos cambiar? Recibiremos un mensaje de error, para saltar ese error debemos ejecutar el comando:

git pull

Lo que este comando hace es jalar al repositorio local hasta el último cambio hecho en el repositorio mamá.

Crear un repositorio

Ahora vamos a crear un repositorio desde cero, se supone que estamos usando Github, picamos el botón indicado para crear un repositorio o vamos a la url https://github.com/new:

Crear un repositorio desde Github

Crear un repositorio desde Github

mkdir mirror
cd mirror
git init

El comando git init crea una carpeta llamada .git que es donde se guarda la magia detrás de Git.

git add .
git commit -m "Cambios en los archivos de este folder"
git remote add origin git@github.com:omartrinidad/mirror.git
git push -u origin master

El comando remote add origin añade un repositorio remoto, en este caso el que anteriormente creamos en Github: mirror.

Otros comandos útiles en Git

git log

Nos ayuda a ver el historial de commits con información como fecha, autor, comentario.

git status

Nos dice qué onda con los commits, si hay commits pendientes nos avisa, si no los hay pues también.

Referencias

Propósito de guidata(hObject, handles) en Matlab

Cada objeto (o figure, o axes, o button, o textbox, etc.) es representado por una variable handles. O sea hObject.

Si estás construyendo una GUI, seguro quieres almacenar datos acerca del estado del programa dentro de la GUI en algún lado. Piensa en una GUI con dos botones (uno con una +, otro con un -) y un texto que inicia en 1. Si el usuario hace click en +, el texto debería incrementar, si el usuario hace click en - debería decrementar.

En algún lugar de la GUI, una variable contador necesita almacenarse. Una forma de hacerlo es almacenarla (la variable) en el guidata de la GUI, que es una ubicación especial específica para GUIs. Creo que aquí hay dos razones de por qué es especial:

  1. Cada hObject (un pushbutton, un axes, etc.) que es hijo de la misma figura apunta al mismo guidata. Así que es un lugar común para todas las partes de la GUI compartir datos.
  2. Cualquier función callback en la GUI automáticamente obtiene el guidata como su tercer argumento. O sea, siempre que hagas click en el botón de una GUI con alguna configuración para guidata, el parámetro de entrada (por default) es siempre una copia de guidata(GUIhandle), hecha al momento exacto de hacer click al botón.

De tal manera que una función callback lucirá de la siguiente forma:

function pushButtonCallback(buttonHandle, eventData, handles)
...
disp(handles)

Ahora, handles es sólo una estructura, vamos a decir que nosotros hemos almacenado el contador que estamos utilizando en handles.counter, pero también queremos este valor disponible para cada uno de los otros callbacks. Para hacer eso, necesitamos actualizar el campo handles.counter y entonces, poner los handles de regreso en el guidata de la GUI. Tan pronto como hemos hecho eso, la próxima vez que un usuario le de click a un botón usará la versión actualizada de handles.

function plusPushButtonCallback(buttonHandle, eventData, handles)
% En ESTE punto, 'handles' es sólo una copia del guidata de la GUI

handles.counter = handles.counter + 1;
% En ESTE punto, 'handles' es diferente al guidata de la GUI

guidata(buttonHandle, handles);
% En ESTE punto, 'handles' ha regresado como el nuevo guidata de la GUI

Este post es la traducción de una respuesta a la pregunta ¿Cuál es el próposito o rol de guidata(hObject, handles)? en el foro oficial de Mathworks: aquí.

2012: 314159bits in review

LoL, I like the review prepared by monkeys WordPress. Albeit in this year that is ending I didn’t publish many posts it was the best year for my humble blog:

The WordPress.com stats helper monkeys prepared a 2012 annual report for this blog.

Here’s an excerpt:

4,329 films were submitted to the 2012 Cannes Film Festival. This blog had 26,000 views in 2012. If each view were a film, this blog would power 6 Film Festivals

Click here to see the complete report.

Introducción a MongoDB, 1 de 5

MongoDB es un sistema gestor de base de datos no relacional (o sea, nada que ver con tablas y todo ese desmadre), MongoDB es en cambio un sistema orientado a documentos. MongoDB usa una representación binaria de JSON, se llama BSON.

¿Qué pedo con JSON?

¿Jason o JSON?

¿Jason o JSON?

No estamos hablando de Jason Voorhes, of course. Platiquemos un poco de los archivos JSON. JSON es un standard para representar estructuras de datos y arrays asociativos, objetos en JavaScript. Es una alternativa a XML. Un archivo JSON comienza con una llave { y termina con otra }. Los elementos de un archivo JSON se separan con comas y son del tipo key and value:

{
   "name":"Scooby",
   "lastname":"Doo"
}

Un elemento a su vez puede tener una estructura que comienza con otra llave:

{
   "name":"Homer",
   "address": { 
       "street": "Siempre Viva",
       "city":"Springfield"
   }
}

También un elemento puede a su vez tener una estructura tipo lista, que se representa con apertura [ y cierre ] de corchetes:

{
   "name":"Introducción a MongoDB",
   "comment": [ 
       {"author":"el oso barrigoso",
        "email":"oso@barrig.oso"
       },
       {"author":"el cashi shin kerer",
        "email": "ximena@sarinana.com"
       }
   ]
}

También podemos usar datos numéricos y booleanos. Este brevísimo repaso de JSON nos ayudará a comprender más de MongoDB.

Crear y usar una base de datos

Vamos a empezar usando el intérprete de MongoDB (asumiendo que ya está instalado en el sistema). Tecleamos mongo y por default ya tendremos creada la base de datos llamada test y también la estaremos usando; algo que debemos tener en cuenta es que el interpréte está construido con Javascript.

Si quisieramos crear otra base de datos (y también usarla) tecleamos: use otrabasededatos.

Crear un documento

  • Lo equivalente a una fila en el modelo relacional es un documento en MongoDB

Vamos a crear un documento que sea útil para guardar el nombre y fecha de nacimiento de mujeres guapas y calientes: girls = { "name":"Lindsay Lohan", "birthday":"July 2, 1986" }.

Guardar un documento en una colección

  • Lo equivalente a una tabla en el modelo relacional es una colección en MongoDB

Ahora guardaremos el documento en lo equivalente a una tabla, es decir, una colección: db.hotgirls.insert(girls). Como puedes ver hemos creado implícitamente la colección hotgirls al hacer el primer insert. También podemos crear la colección explícitamente: db.createCollection("hotgirls") el intérprete nos devolverá esto: { "ok" : 1 }.

Para ver cuántas colecciones hay en nuestra base de datos escribimos: show collections y el resultado será: hotgirls system.indexes.

Antes de seguir vamos a insertar a más chicas hots a nuestra base de datos:

db.hotgirls.insert({"name":"Megan Fox", "birthday":"May 16, 1986"});
db.hotgirls.insert({"name":"Jessica Alba", "birthday":"April 28, 1981"});
db.hotgirls.insert({"name":"Adriana Lima", "birthday":"June 12, 1981", "birthplace":" Salvador, Bahia, Brazil"});

Quizás te preguntes ¿por qué madres al insertar los datos de Adriana Lima, quien por cierto es una mamasota, le añades un campo que antes no habías usado, eso es posible en MongoDB ya que los documentos no tienen que apegarse a un esquema determinado: schemaless, esta palabra en español suena como: esquimales. También gracias a eso podríamos hacer algo así: "name":666.

Ver el contenido de una colección

Ahora vamos a preguntarle a la base de datos ¿qué almacena en la colección hotgirls? El comando es igual de sencillo que los anteriores: db.hotgirls.find():

Es como el ya conocido select * from database de las bases de datos relacionales. El resultado será el siguiente:

{ "_id" : ObjectId("50c8de28f1e3991f167fd41a"), "name" : "Lindsay Lohan", "birth" : "July 8, 1986" }
{ "_id" : ObjectId("50c8e1d8f1e3991f167fd41b"), "name" : "Megan Fox", "birthday" : "May 16, 1986" }
{ "_id" : ObjectId("50c8e1d8f1e3991f167fd41c"), "name" : "Jessica Alba", "birthday" : "April 28, 1981" }
{ "_id" : ObjectId("50c8e1d9f1e3991f167fd41d"), "name" : "Adriana Lima", "birthday" : "June 12, 1981", "birthplace" : " Salvador, Bahia, Brazil" }

¿Qué pedo con el campo _id? Es la llave primaria de nuestra colección, MongoDB la crea automáticamente.

Veamos ahora una instrucción similar db.hotgirls.findOne():

{
	"_id" : ObjectId("50c8e357f1e3991f167fd41e"),
	"name" : "Lindsay Lohan",
	"birthday" : "July 8, 1986"
}

Esta instrucción nos retorna un sólo documento, el primero que hayamos insertado. Por el momento ahí muere, para el siguiente post, veremos operaciones de consulta más divertidas.

¿Cómo guardar una imagen en Matlab?

Matlab es un lenguaje muy bueno, pero a veces se empeña en hacer pinche las cosas, por ejemplo para guardar una imagen… el proceso es fácil, pero coño, nada como en OpenCV: imwrite('image.extension', image).

En Matlab no es tan obvio, es fácil pero no es obvio. No es obvio por que usamos para ello una función llamada print() y son tres los parámetros que esta función recibe:

  • Una referencia a la imagen
  • Un driver para especificar qué tipo de imagen vamos a guardar
  • El nombre y extensión de la imagen

Es fácil pero es pinche, aquí un código pequeño que guarda la imagen como PostScript y como JPG también:

fig = figure;
imhist(img, 100);
print(fig, '-djpeg', 'figure1.jpg');
print(fig, '-dps', 'figure1.ps');

imhist(img2, 100);
print(fig, '-djpeg', 'figure2.jpg');
print(fig, '-dps', 'figure2.ps');

Y así se guarda una imagen en Matlab.

iWoz: How I read the autobiography of Wozniak and had enjoy doing it!

iWoz, hardcover

iWoz, hardcover

One of the things that inspire me is read about magical hackers. I have read iWoz: How I invented the personal computer, co-founded Apple, and had fun doing it. These people are the kind of people like we (the wannabes) want to become. Wozniak started from a very young age, he says his father was his teacher:

He never started out by trying to explain from the top down what a resistor is. He started from the beginning, going all the way back to atoms and electrons, neutrons, and protons [...] I remember we actually spent weeks and weeks talking about different types of atoms and then I learned how electrons can actually flow through things- like wires.

Steve built with his friends, The Electronic Kids, a house-to-house intercom connecting about six houses, wow! Can you imagine that? Steve explains about the things he learned like Boolean algebra, only reading and rereading journals:

That’s the type of mathematics computers use. And I learned about De Morgan’s Theorem, which is what Boolean algebra is based on. And that’s how logic became the hearth of my existence, there in the fifth grade.

In his book Wozniak teaches us the the importance of building projects. Since childhood he participated in science competitions. He almost always won, but he says:

And that’s not important as the most important thing: that you’ve done the learning on your own to figure out how to do it [...] For me it’s the engineering, not the glory, that’s really important.

When I read that part I thought lately I have not had very positive results in my projects but I kept working on them and according to iWoz that’s what matters.

Woz was a prankster. He built a device called the TV Jammer, device that let you jam a TV if you just dialed into the right frequency. He could play with the people who was seeing the TV.

About the politics

In a section of the book he talks about Bush, (I remembered things about Peña Nieto):

I voted for George W. Bush in 2000, because I thought it would be nice to have an average Joe kind of person in the White House instead of smart, well-educated one. Someone who could only speak in very small words. Okay, I’m joking.

He also recounts in the book how he escaped to go to war in Vietnam and what he thought about it:

I thought, what if I’m in Vietnam and I’m shooting at some guy? He’s just like me, that guy. He sits down just like I do. He plays cards and he eats pizza, or the equivalent of it, just like normal people I know. He has a family. Why would I want to hurt this person?

Three hackers together

Of course, he tells of how he met Steve:

Steve and I got close right away, even though he was still in high school [...] We two Steves did have a lot in common. We talked electronics, we talked about music we liked, and we traded stories about pranks we’d pulled. We even pulled a few together.

Another hacker who must be named is Captain Crunch, the legendary hacker who created the blue boxes. Woz read in the magazine Esquire an article called: “Secrets of the Little Blue Box”, an article about phone phreaks:

These people were able to figure out that by just whistling certain tones into a phone handset, they could make telephone call within the Bell phone system for free [...] The article also talked about the ethics these guys supposedly had. That it wasn’t just about free calls. One of the guys said he was basically trying to do a good thing by finding flaws in the system and letting the phone company know what they were.

The Steves got to call and contact to John Draper and also got to meet him:

So I asked, “Are you Captain Crunch?” And he said, “I am he”

Can you imagine three wizards together is like John, Ringo, Paul and George but about computers.

By the way, albeit Woz had the Blue Box he paid his calls:

I always told people how I was ethical phone phreak who always paid for my own calls and was just exploring the system. And that was true. I used to get huge phone bills, even though I had my Blue Box that would’ve let me make any call for free.

Steve worked in HP designing calculators, while he was working there he built a dial-a-joke that became really famous in Cupertino. He posed as Polish guy named Stanley Zebrazutsknitski. Wozniak always was building things, for example, he built with pure hardware a game like Pong. Pong was the first successful video game (first in the arcade, later at home), Pong came from a company called Atari:

All in all, I ended up with twenty-eight chips for the Pong design. This was amazing, back in the days before microprocesors. Every bit of the game had to be implemented in wires and small gates- in hardware, in other words. There was no game program- that is, a game in software for that someone could load. It was all hardwired.

Jobs worked at Atari, therefore he (Woz) had the opportunity to show his work to the people of Atari and they invited him to work in a new Pong game:

And Steve says, “Well, there’s a caveat. It has to be done in four days” [...] I didn’t sleep for four days and nights during this project [...]The bottom line of this history is that I actually did finish this project in four days and nights somehow, and it worked.

Wow! Someday, I guess one of these days I will play-hack for four days equal to Wozniak.

Maybe you know about the Homebrew Computer Club. After the firs meeting he attended he began to build what would be the first computer in the world: Apple I, I really liked the following paragraph:

You see, whenever I solve a problem on an electronic device I’m building, it’s like the biggest high ever. And that’s what drives me to keep doing it, even though you get frustrated, angry, depressed, and tired doing the same thing over and over. Because at some point comes the Eureka moment. You solve it [...] I didn’t realize it at the time, but that day, Sunday, June 29, 1975, was pivotal. It was the first time in history anyone had typed a character on a keyboard and seen it show up on the screen right in from of them.

Well, if you are geek, nerd or newbie you must read this book. You will find many interesting stories.

My first book in English

I am learning English, and this book was the first book I have ever read in this language. The reading is easy, albeit I didn’t know some words I felt I understood all paragraphs.