Improve everyday.

js_async_await.md

|

Using promises in javascript can be a little painful. If you use a recent enough revision of js, you can handle this differently. For example, this code:

function do_stuff(url) {
  return new Promise((resolve) => {
     fetch(url).then(response => {
       response.json().then(data => {
         resolve(data);
       });
     });
  });
}

Can be rewritten like this using async/await:

async function do_stuff(url) {
  const response = await fetch(url);
  const data = await response.json();
  return data;
}

Marking a function async makes it return a promise. Putting await before a promise waits for it to resolve and returns the argument that would have been passed to resolve.

WARNING: this feature is not included in ES6, but can be added with plugins and is part of ES7. This is understood by many browsers.

creating-terminal-in-python.md

|

The objective

The library cmd helps you to create a simple terminal with simple help and autocompletion build in templates.

The bases

You create a class MyShell that herites from cmd.Cmd. To run the prompt just use Shell().cmdloop() in your python code.

If you want to create a feature get_something in your shell, you write 3 methods :

  • MyShell.do_get_something(arg) : the function that gets the something if you write in the prompt get_something
  • MyShell.help_get_something(arg) : this will give you some help if you write in the prompt help get_something
  • MyShell.complete_get_something(text, line, begidx, endidx) : this will allow you to create an autocompletion method for your function (this is optional)

A simple example

#!/usr/bin/env python2.7
# Simple example of a command line tool that just list the movies or display the movie id
import cmd, sys
import os
import time
import MySQLdb
import subprocess
from tabulate import tabulate

MOVIES = {1: 'batman', 2: 'robin_et_batman', 3: 'batman_et_robin'}
NAMES_TO_ID = {movie_name: movie_id for movie_id, movie_name in MOVIES.items()}

print "The database of movies:"
print tabulate(MOVIES.items())

class Shell(cmd.Cmd):

    MOVIES = MOVIES
    NAMES_TO_ID = NAMES_TO_ID

    intro = "Welcome message ! Type help for more infos"
    prompt = "(Simple example RFFP) "

    # Get all movies function
    def do_get_movies(self, arg):
        print tabulate(self.MOVIES.items())

    def help_get_movies(self, arg):
        print "Get all movies"

    # Get the id of a specific movie
    def do_get_movie(self, movie_name):
        print 'movie_name :', movie_name
        print 'movie_id : ', self.NAMES_TO_ID[movie_name]

    def help_get_movie(self):
        print 'Display the name and the id of the selected movie'

    def complete_get_movie(self, text, line, begidx, endidx):
        if not text:
            completions = self.NAMES_TO_ID.keys()
        else:
            completions = [ f
                            for f in self.NAMES_TO_ID
                            if f.startswith(text)
                            ]
        return completions

    def do_exit(self, arg):
        'Stop recording, close the turtle window, and exit:  BYE'
        print('Good bye !')
        return True

    def do_EOF(self, arg):
        print "exit"
        return self.do_exit(arg)

if __name__=="__main__":
    Shell().cmdloop()

Resources

  • https://wiki.python.org/moin/CmdModule

linked_figure_reference.md

|

To link a figure in a latex document :

\usepackage{hyperref} … \hyperref[fig:label]{Figure \ref*{fig:label} }

Then, when clicking on the “Figure N” text, it will send you to the caption of the figure.

You can add

\usepackage[all]{hypcap}

And it will send you to the top of the figure.

adding_request_delays.md

|

Can be useful when porgramming JS so that the UI is resilient to slow requests.

In one line:

docker run -v /var/run/docker.sock:/var/run/docker.sock gaiaadm/pumba pumba netem --tc-image gaiadocker/iproute2 -d 24h delay -t 100  <docker_container_name>

This adds a 100ms delay on every packet for the chosen container.

<docker_container_name> can be a regexp by prefixing with re2:. For example to add delay to all containers prefixed with nlpnertoolbox:

docker run -v /var/run/docker.sock:/var/run/docker.sock gaiaadm/pumba pumba netem --tc-image gaiadocker/iproute2 -d 24h delay -t 100  re2:^nlpnertoolbox

More doc on the github README. pumba can actually be used for much more than just delay.

custom-auto-completion.md

|

Custom auto-completion for bash functions

First, create a bash function (in .bash_aliases or .bashrc).

# Attach a docker container with a new bash, with completion
docker-new-bash(){
    docker exec -t -i $1 /bin/bash
}

Custom autocompletion from a list of words

complete -W "coucou pouet" docker-new-bash

Outputs when tabbing

alexandre@father03:~$ docker-new-bash [tab]
coucou  pouet

Custom autocompletion from a bash function

Auto-completion proposals are in COMPREPLY array

_docker-new-bash(){
    COMPREPLY=("coucou" "pouet")
}
complete -F _docker-new-bash docker-new-bash

Outputs when tabbing

alexandre@father03:~$ docker-new-bash [tab]
coucou  pouet

Copy the autocompletion of another bash function

# Copy autocompletion from other function
get_completions(){
    local completion COMP_CWORD COMP_LINE COMP_POINT COMP_WORDS COMPREPLY=()
    # load bash-completion if necessary
    declare -F _completion_loader &>/dev/null || {
        source /usr/share/bash-completion/bash_completion
    }
    COMP_LINE=$*
    COMP_POINT=${#COMP_LINE}
    eval set -- "$@"
    COMP_WORDS=("$@")
    # add '' to COMP_WORDS if the last character of the command line is a space
    [[ ${COMP_LINE[@]: -1} = ' ' ]] && COMP_WORDS+=('')
    # index of the last word
    COMP_CWORD=$(( ${#COMP_WORDS[@]} - 1 ))
    # determine completion function
    completion=$(complete -p "$1" 2>/dev/null | awk '{print $(NF-1)}')
    # run _completion_loader only if necessary
    [[ -n $completion ]] || {
        # load completion
        _completion_loader "$1"
        # detect completion
        completion=$(complete -p "$1" 2>/dev/null | awk '{print $(NF-1)}')
    }
    # ensure completion was detected
    [[ -n $completion ]] || return 1
    # execute completion function
    "$completion"
    # Return array of completions
    echo "${COMPREPLY[@]}"
}

_docker-new-bash(){
    local cur=${COMP_WORDS[COMP_CWORD]}
    local comp=$(get_completions 'docker attach ')
    COMPREPLY=( $(compgen -W "$comp" -- $cur) )
}
complete -F _docker-new-bash docker-new-bash

Outputs when tabbing

alexandre@father03:~$ docker-new-bash [tab]
vod_product_compute vod_product_mysql
alexandre@father03:~$ docker attach [tab]
vod_product_compute vod_product_mysql