Truco de Python, como crear objetos “flojos” (Lazy objects)

Este es un “re-post” en español de este otro articulo que escribí en inglés: Python trick: How to make lazy objects?. Si ya leíste aquel articulo igual te invito a que leas este, compares y compartas.

Esta vez voy a hablar de los “lazy objects”, los he llamado así porque son mas o menos similar a lo que usaba con los “Lazy treeviews” en GTK donde el árbol muestra los expansiones pero no se cargan los nodos hijos hasta que expandes el nodo. Lo que quiero entonces es crear objetos que sirvan para contar, que tengan un tipo de dato, pero que no carguen nada de datos hasta que se necesite. read more

8 errores que todo programador novato comete

1. Escribir código sin planear

Este es el primero, cuando nos cuentan de un proyecto lo primero que hacemos es empezar a divagar, es mas, ni bien nos estan terminando de contar los requerimientos y ya hemos escogido el lenguaje, el framework y a veces hasta el pilón.

Siempre es importante pensar el proyecto, ¿es viable?, hay que investigar y planear, entonces, escribe, valida los resultados y modifica.

2. Planear demasiado las cosas

También este es un error, a veces sobrepasamos demasiado las cosas y terminamos creando un monstruo porque “en el futuro puede que llegue a necesitar esta característica”, es mejor implementar algo simple y que logre el propósito aunque despues tengamos que reescribr parte del código. read more

Things that can make macOS better

I use macOS as the main OS in my computer, actually the only one in my personal computer, but I have other computers with Linux as desktop too, but macOS is the one that I use the most. And over the time I have learned how to get more from the OS as the default installation.

For example, I currently don’t use Spotlight, I use another tool called “Alfred” you all might know it.

Alfred > Spotlight

Spotlight was a good thing back in the days were it was basically a search tool for the OS living in the corner, where nobody looks. But it was not good as a some sort of launcher, and having all my apps in the Dock was not a good idea. Then Alfred arrived and it came with other functionality like workflows and search in places where spotlight just don’t do, also the fuzzy word search (like GC and expect to get Google Chrome) works very well. read more

Tips and tricks: Django – Mostrar cierto contenido seleccionado en un ChoiceField

Si hemos usado Django seguro nos hemos enamorado de su forma de hacer formularios, sobre todo los que están relacionados con un modelo, puesto que son simplísimos. Hay que reconocer lo simple de Django, y gracias a esta simplicidad que no busca satisfacer completamente todas las necesidades podemos encontrarnos con situaciones que pues, no se apegan a lo que queremos hacer.

tmux

So, for the people that follows my blog or me in twitter/facebok knows that I usually works on Linux/macOS, when using servers I use to use Linux and I’m a huge fan of the shell. In linux while I enjoy using GNOME/XFCE none of them are my favorite desktop (that’s why I’m using macOS).

One of the things I enjoy with the shell is using SSH (Secure Shell), although is pretty simple (launching a remote shell) there is a post in this blog about re-using the current ssh connection, which I tend to use since I discovered.

But  sometimes I need to monitor a server, and then I use several apps, like iftop/nload, etc… and it was pain in the ass opening serveral shells to launch every program.

Then I found tmux, which allows you to have several shells in the same shell, I believe using ncurses but it works!.

So, now I was able to launch a tmux session, create my panes (split the windows) then launch the programs I like, and since tmux will remain even if I close the connection I’m able to start whenever I was before closing the connection.

Now, what happens if I have to restart the server?, or what if the computer I’m monitoring have an issue and shutdown?. Well, I’ll have to start another tmux session again, do the split and launch the program.

Could that be easy to do?. Turns out that there is a way to do that, just create a script and launch tmux asking to do the splits and opening the programs in each pane, something like this:

#!/bin/bash
tmux new-session -d iftop  -m20m -F192.168.2.0/24 -i eth1
tmux split-window -h nload eth1
tmux split-window -v nload enp2s0
tmux split-window -v nload eth2
tmux split-window -v 
tmux select-pane 0
tmux -2 attach-session -d 

Then, after you login with ssh, just run the script. It will create a set of panes and run a command in every pane. Note that this script is just an example, you have to create your own based on it.

I know this is not something new, and my sysadmin friends have been using this for a long time, they sure know better options for tmux, you probably will, if that’s the case I would love you to leave a comment with your tips for tmux or better alternatives.

Did this post was useful to you?, share it!

REPOST: Speed up SSH with ControlMaster

NOTE: This  is a re-post from the old blog which you can find here

Quick post, this is an ancient method to speed up ssh connections, I’m just leaving it here.

When we use SSH mostly all the times we create a new connection, even if we are connecting with the same host at the same port with the same user. I’ve been using SSH for a long time and to me this was fine, at the end the connection is “pretty” fast and the delay time creating the connection is just ok.

The problem is when you are editing a file that is in the server, whenever I can I use ssh and with that use vim to edit remote files using “scp”, with this I can test the file in the remote server without worrying to sync the file (rsync/scp) manually. At the end I just write back the file in my hard drive if needed.

This is kind of… annoying, vim+scp creates a new connection every time you want to save the file, and it mean a lot of time when editing a file, more if you are like me, saving the freaking file every time I stop writing. So, how can I improve that?.

Well, it turns out its pretty simple. ssh can create a socket (in a predefined place) when connected to a server, with this socket any other ssh instance for the same server+user+port can use this socket and avoid the connection delay. To enable this just add this lines in your ssh config:

 

Host *
     ControlMaster auto
     ControlPath ~/.ssh/socket/ssh_mux_%h_%p_%r

Just make sure that ~/.ssh/socket/  exists. This will create a socket like ~/.ssh/socket/ssh_mux_localhost_22_markuz  and all new connections will use it instead of creating a new connection. Of course, there are some downsides, since the first connection is the only one that is connected, if you loose that connection you’ll disconnect all other ssh instances.You’ll probably do this. So, the way I’ve managed to fix it. Well, it’s kind of simple and of course, it is not magic, just create a master connection whenever you can:

ssh -MNn user@host

Put this somewhere to create it magically (let’s say a script that run in the background), with this you’ll have that ssh connection open, you’ll never have it in the terminal and you’ll not close it until you “kill” that ssh connection.

So, the fix is more like a hack, but works, and helps a lot if you are using a lot of connections to a server.

Quick tip, vagrant with less RAM

Vagrant is a popular solution to isolate your development environment, while there are many images to use with vagrant the most popular is an Ubuntu server image cooked by HashiCorp. Although with the current computer specs having a virtual machine that uses 512MB in RAM is almost nothing (I bet Google Chrome is wasting more than that now) if you are like me you don’t like to have a Virtual Machine wasting resources.

The main reason of why vagrant images uses that amount of RAM is because they don’t have SWAP, so, if your program/script is using more RAM than what is in the VM the program/script is killed.

You can add a SWAP file by using dd

$ dd if=/dev/zero of=/swapfile bs=1024 count=655360
$ chmod 00600 /swapfile
$ swapon -a

Then add it to /etc/fstab. Pretty simple, but you have a big file that may or may not be used in totality.

A better approach is to use swapspace daemon, it will create a swap space that will grow/shrink as needed. You can install the service in your VM if you already have it working or, add this to your Vagrantfile to have it done automagically.

config.vm.provision "shell", inline: "sudo apt install swapspace -y"

If you do this with a VM already working just shut it down, use vagrant up --provision to run the provision instruction and you are done!.

Having a Swap space allows you to reduce the amount of RAM dedicated to your VM.

Quick tip when using vagrant+django

I started to use vagrant to hold my development environment, it helps to keep the development environment isolated, since the app will run on a Linux server, with a specific database engine and probably some other specific modules, I don’t want to clutter my OS with all that stuff. More if I plan to work on another project that maybe, have a dependency on other versions of the same base (legacy Django perhaps?)

So, finally discover how to set the default blog in WordPress

I have multiple blogs, one personal and others for projects that I have, I trust in WordPress because it’s pretty flexible and since version 3.5 the improvements are awesome, making the writing a lot easier.

Still I had a problem, I’m used to the WordPress app for iOS and Mac to avoid having to load the whole page. It is kind of limited (not all plugins are available in the App) but for a quick post it works. Well, the problem I had is that I post mostly to my personal blog, but one of my projects blog was the default and I didn’t knew how to set a default. I event asked for help.

Well, today I discovered that it is possible.

First, you need to go to WordPress.com and go to your account settings.

Then go to the Account settings section.

 

And there just select your default blog. hit save and you are done!.

How is that I didn’t do this before?.

Python: Simple HTTP Server on python.

(Repost from old blog)

Python have several modules that help you to achieve your goals. This week, on my spare time that is getting every day more scarce I spend time figuring out how to create a Python Web Server, I was planing to use it over an application that I’m developing on ICT Consulting. At the end I didn’t use it because I didn’t want a “passive” communication, but probably I will use this code on the CRM Desktop application that we use here.

Anyway, this code may be helpful for you too. I found that creating a small web server is really simple, It starts getting bigger as you add functions to that web server, but the basis is quite simple.

import os
import cgi
import sys
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler

class customHTTPServer(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write('<HTML><body>Get!</body></HTML>')
return

def do_POST(self):
global rootnode
ctype,pdict = cgi.parse_header(self.headers.getheader('Content-type'))
if ctype == 'multipart/form-data':
query = cgi.parse_multipart(self.rfile, pdict)
self.send_response(301)
self.end_headers()
self.wfile.write('Post!')

def main():
try:
server = HTTPServer(('',8080),customHTTPServer)
print 'server started at port 8080'
server.serve_forever()
except KeyboardInterrupt:
server.socket.close()

if __name__=='__main__':
main() read more

Option-arrow navigation in iTerm2 – BrettTerpstra.com

useful way to map “Option+left”/”Option+right” keys in iTerm2 to do by word jump (left and right). Although sending ^[b and ^[f seems to be cleaner.

I’ve been trying to get Option-arrow keys to move by word in iTerm2. I figured out a solution, but it’s weird. If anyone has an explanation or a better way to do this, let me know.

Source: Option-arrow navigation in iTerm2 – BrettTerpstra.com