Prompt para desarrolladores multi-scm (upgraded)

Encontre este post: http://gepatino.blogspot.com.ar/2013/01/prompt-para-desarrolladores-multi-scm.html (GRACIAS GABRIEL)

Y agregue el soporte para banchs de mercurial. UPDATE: separe svn y bazar para que funcione mejor

PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[01;34m\] \w\[\033[01;33m\]$(get_repo_info) \[\033[01;34m\]\$ \[\033[00m\]'

function get_repo_info {
    INFO=""
    DIRTY=""

    if [ "$INFO" == "" ] && [ `svn info 2> /dev/null | wc -l` -gt 0 ]
    then
        [ `svn status 2> /dev/null | grep -v '?' | wc -l` -gt 0 ] && DIRTY='*'
        INFO="⚡svn$DIRTY"
    fi

    if [ "$INFO" == "" ] && [ `bzr info 2> /dev/null | wc -l` -gt 0 ]
    then
        [ `bzr status -S 2> /dev/null | grep -v '?' | wc -l` -gt 0 ] && DIRTY='*'
        INFO="⚡bzr$DIRTY"
    fi

    if [ "$INFO" == "" ] && [ `hg branch 2> /dev/null | wc -l` -gt 0 ]
    then
        BRANCH=`hg branch 2> /dev/null`
        [ `hg status 2> /dev/null | grep -v '?' | wc -l` -gt 0 ] && DIRTY='*'
        INFO="⚡hg:$BRANCH$DIRTY"
    fi

    if [ "$INFO" == "" ] && [ `git branch 2> /dev/null | wc -l` -gt 0 ]
    then
        BRANCH=`git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e "s/* \(.*\)/\1/"`
        [ `git status --porcelain 2> /dev/null | wc -l` -gt 0 ] && DIRTY='*'
        INFO="⚡git:$BRANCH$DIRTY"
    fi

    echo $INFO
}

Agregan eso a su ~.bashrc y van a ver algo como esto:

2013-01-12-000458_660x177_scrot

PD: si alguien se anima a seguir por branch de bazar aca hay un codebase
http://blog.grahampoulter.com/2011/09/show-current-git-bazaar-or-mercurial.html

Snippet para usar un unittest bottle.py con un proceso separado

Necsitaba probar un api rest y se me ocurrio levantar bottle en un proceso separado dentro de un testcase; y necesite hacer todos este chicle.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# "THE WISKEY-WARE LICENSE":
# <jbc.develop@gmail.com> wrote this file. As long as you retain this notice you
# can do whatever you want with this stuff. If we meet some day, and you think
# this stuff is worth it, you can buy me a WISKEY in return Juan BC

import multiprocessing
import urllib2
import unittest

import bottle

class BottleTest(unittest.TestCase):

    def setUp(self):
        self.process = multiprocessing.Process(
            target=bottle.run,
            kwargs={"port": "8081"}
        )
        self.process.start()

        # wait until bottle process full started
        # si no ponen esto el testcase se va a ejecutar antes
        # que bottle este listo para recibir peticiones
        started = False
        while not started:
            try:
                urllib2.urlopen("http://127.0.0.1:8081/")
            except urllib2.HTTPError:
                started = True
            except urllib2.URLError as err:
                if err.reason.args[0] == 111:
                    pass
                else:
                    raise err
            else:
                started = True

    def tearDown(self):
        self.process.terminate()

    def test_something(self):
        pass

dPaste.com “API”

“API” for http://dpaste.com/

#!/usr/bin/env python
# -*- coding: utf-8 -*-

#
# THE WISKEY-WARE LICENSE
# -----------------------
#
# "THE WISKEY-WARE LICENSE":
# <jbc.develop@gmail.com> wrote this file. As long as you retain this notice you
# can do whatever you want with this stuff. If we meet some day, and you think
# this stuff is worth it, you can buy me a wiskey in return JuanBC
#

# ==============================================================================
# DOC
# ==============================================================================

"""A Simple Client for http://dpaste.com/

"""

# ==============================================================================
#
# ==============================================================================

__author__ = "JuanBC"
__mail__ = "jbc.develop@gmail.com"
__version__ = "0.1.1"
__license__ = "WISKEY_WARE"
__date__ = "2011/11/14"


# ==============================================================================
# IMPORTS
# ==============================================================================

import os
import urllib
import urllib2


# ==============================================================================
# CONSTANTS
# ==============================================================================

DPASTE_URL = "http://dpaste.com/"

FORMAT_2_EXT = {
    "Python": ["py", "pyw"],
    "PythonConsole": [],
    "Sql": ["sql"],
    "DjangoTemplate": [],
    "JScript": ["js"],
    "Css": ["css"],
    "Xml": ["xml"],
    "Diff": ["diff"],
    "Ruby": ["rb"],
    "Rhtml": ["rhtml"],
    "Haskell": ["hs"],
    "Apache": [],
    "Bash": ["sh"],
    "Plain": ["txt"]
}

EXT_2_FORMAT = {}
for k, vs in FORMAT_2_EXT.items():
    for v in vs:
        EXT_2_FORMAT[v] = k

# ==============================================================================
# FUNCTIONS
# ==============================================================================

def filename2format(filename):
    """Retrieves the format of a given filename

    """
    basename = os.path.basename(filename)
    if "." in basename:
        ext = basename.rsplit(".", 1)[1].lower()
        return EXT_2_FORMAT.get(ext, "Plain")
    return "Plain"


def paste(source, file_format="Plain", title="", poster=""):
    """Paste a given source code into dpaste.com with a given format

    """
    file_format = "" if file_format == "Plain" else file_format
    data = urllib.urlencode({"content": source,
                             "language": file_format,
                             "title": title,
                             "poster": poster})
    conn = urllib2.urlopen(DPASTE_URL, data)
    return conn.geturl()


def copy(dpaste_id):
    """Retrieve a code from a given dpaste id

    """
    return urllib2.urlopen(DPASTE_URL + str(dpaste_id) + "/plain").read()


# ==============================================================================
# MAIN
# ==============================================================================

if __name__ == "__main__":
    print(__doc__)

Ninja-IDE Snippet Plugin (con screencast)

Acabo de terminar mi primer plugin  para Ninja-IDE 2.x, el cual consiste en un gestor de snippets.

Como funciona? 

  • Primero bajan el plugin y lanzan Ninja (estoy usando la 2.0b2)con una de estas intrucciones para que corra mi codigo.
  • En la ventana de settings “edit -> preferences -> plugin -> snippets” y van a ver algo asi

    • La lista de la izquierda enumera todos las exenciones disponibles para los snippets y la de la derecha los snippets, propiamente dicho, de
      dicha extensión. En la ventana de abajo se ve el texto de reemplazo de dicho snippet.
Los snippets deben crearse dentro de un lenguaje y una extensión (siendo un caso particular *General*) y poseen variables que se resuelven al momento de ser aplicados (la lista de todas las variables aparece si presionan el botón HELP)
  • Al momento de escribir un snippet en el editor de texto en el cual esta codificando y apretando la tecla <TAB> el plugin operara de la siguiente manera:
    1. Buscara la palabra justo anterior de apretar <TAB>  en la lista de plugins correspondiente a la extension del archivo que estamos editando.
    2. Si no encuentra un reemplazo en esa lista lo busca en *GENERAL*.
    3. Si no lo encuentra en general no hace nada
Screencast 😀 (los glitches son cosa de mi editor de video)
Descargenlo es Beerware

Snippet: game_solver.py

Implementación de Teoría de juegos que estoy preparando para un paper

#!/usr/bin/env python
#-*-coding:utf-8-*-

# 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 3 of the License, 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.

#===============================================================================
# DOC
#===============================================================================

"""This code is a simple implementation of an algoritm published in the paper

    "Aplicación de Teoría de Juegos a una Inteligencia Artificial de un Browser
     Game Persistente de Estrategia" (JAIIO 40, 2011, http://www.40jaiio.org.ar)

    (EN: Applying Game Theory to an Artificial Intelligence Persistent Browser
     Strategy Game)

"""

#===============================================================================
# META
#===============================================================================

__version__ = "0.1"
__license__ = "GPL3"
__author__ = "JBC"
__mail__ = "jbc dot develop at gmail dot com"

#===============================================================================
# IMPORTS
#===============================================================================

import operator
import random

#===============================================================================
# FUNCTIONS
#===============================================================================

def liar_solve(mtx):
    """Returns the probability of victory of all strategies with respect to the
    strategies that were not used.

    @param mtx: a matrix where each row represents the strategies of player 1,
    each column the strategies of player 2, and each cell has the advantage that
    the strategies of the row over the column (negative values ​​imply advantages
    in the column on the rows and ​​None values siginifca that these strategies
    never encountered)

    @return A tuple with 2 list, the first one with the probabilities of the
    row strategies, and te second one with the probablities of the colum

    """
    to_percent = lambda values: [(v * 100.0) / sum(values) for v in values]
    row_nones = [l.count(None) for l in mtx]
    col_nones = [c.count(None) for c in zip(*mtx)]
    return to_percent(row_nones), to_percent(col_nones)

def game_theory_solve(mtx):
    """ Approximate the strategy oddments for 2
    person zero-sum games of perfect information.

    Applies the iterative solution method described
    by J.D. Williams in his classic
    book, The Compleat Strategyst, ISBN 0-486-25101-2.
    See chapter 5, page 180 for details.

    @param mtx: a matrix where each row represents the strategies of player 1,
    each column the strategies of player 2, and each cell has the advantage that
    the strategies of the row over the column (negative values ​​imply advantages
    in the column on the rows)

    @return A tuple with 2 list, the first one with the probabilities of the
    row strategies, and te second one with the probablities of the colum

    Based on the work of:
        @author: Raymond Hettinger
        @contact: http://code.activestate.com/recipes/496825/

    """
    iterations = 100
    transpose = zip(*mtx)
    numrows = len(mtx)
    numcols = len(transpose)
    row_cum_payoff = [0] * numrows
    col_cum_payoff = [0] * numcols
    colpos = range(numcols)
    rowpos = map(operator.neg, xrange(numrows))
    colcnt = [0] * numcols
    rowcnt = [0] * numrows
    active = 0
    for i in xrange(iterations):
        rowcnt[active] += 1
        col_cum_payoff = map(operator.add, mtx[active], col_cum_payoff)
        active = min(zip(col_cum_payoff, colpos))[1]
        colcnt[active] += 1
        row_cum_payoff = map(operator.add, transpose[active], row_cum_payoff)
        active = -max(zip(row_cum_payoff, rowpos))[1]
    return rowcnt, colcnt

def best_strategy(mtx, plyr):
    """Returns the suggested strategy for a given player. If all of the values
    ​​of all non-null lamatris used game theory is used otherwise a selection to
    try to encourage the elimination of null values​​.

    @param mtx: a matrix where each row represents the strategies of player 1,
    each column the strategies of player 2, and each cell has the advantage that
    the strategies of the row over the column (negative values ​​imply advantages
    in the column on the rows and ​​None values siginifca that these strategies
    never encountered)

    @param plyr: Two values are accepted. "0" for the "row" player and "1" for the
    column player.

    @return An integer that represents the strategy n-th of row or column

    """
    probs = None
    solver = None

    # Verify if matrix are empty
    if not any([l.count(None) for l in mtx]):
        probs = game_theory_solve(mtx)[plyr]
        solver = "game_theory_solver"
    else:
        probs = liar_solve(mtx)[plyr]
        solver = "liar_solver"

    # Calculate the cumulative frequency
    for idx, prob in enumerate(probs):
        cum = probs[idx-1][1] if idx != 0 else 0
        probs[idx] = (idx, prob + cum)

    # Find E*
    while True:
        roll = random.randint(1, 100)
        for stg, prob in probs:
            if roll < prob:
                return stg, solver

def update_mtx(mtx, row, column, plyr):
    """Update the matrix to improve decisions.

    @param mtx: The matrif to update.

    @param row: The index of the row strategy.

    @param column: The index of the column strategy.

    @patam player: Two values are accepted.
        0: for the "row" player the mtx[row][column] must be incremented in 1
        1: for the "column" player the mtx[row][column] must be decremented in 1

    """
    value = mtx[row][column] or 0
    if plyr == 0:
        value += 1
    elif plyr == 1:
        value -= 1
    else:
        raise ValueError("'plyr' must be '0' or '1', found: %s" % str(plyr))
    mtx[row][column] = value

#===============================================================================
# TEST
#===============================================================================

FULL_MTX = ([4,    0,     1],
            [100,  23,    2],
            [5,    23,    1],
            [1,    1,     0])

INC_MTX = ([4,      0,    1],
            [100,   None, 2],
            [5,     23,    None],
            [None, 1,     None])

print best_strategy(FULL_MTX, 0)
print best_strategy(INC_MTX, 1)

Aplicación de Teoría de Juegos a una Inteligencia Artificial de un Browser Game Persistente de Estrategia

Snippet: caller.py (0.2)

Durante la Organizacion del Pyday hice unos cuantos snippets que me sirvieron para generar cosas y demas, uno de ellos es este.

Para X-ip caller.py 0.2, en el cual elimine la clase Caller y la reemplace por una funcion.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

# caller.py

__author__ = "jbc <jbc.develop@gmail.com>"
__version__ = "0.2"
__license__ = "lgpl3"

import subprocess
import shlex


class CallError(Exception):

    def __init__(self, cmd, stderr, code):
        msg = "External call '%s' fail with code '%i'. Cause: '%s'" % (cmd, code, stderr)
        super(CallError, self).__init__(msg)
        self.cmd = cmd
        self.stderr = stderr
        self.code = code


def call(cmd):
    """Execute the cmd an return the standar output or raises an exception

    """
    pcmd = shlex.split(cmd)
    p = subprocess.Popen(pcmd, stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE)
    stdout, stderr = p.communicate()
    if p.returncode:
        raise CallError(cmd, stderr, p.returncode)
    return stdout

uso:

import caller
print caller.call("ls -lia")

Snippet: caller.py

Me suelo olvidar como usar el modulo subprocess asi que mantengo aca este snippet

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import subprocess
import shlex


class CallError(Exception):
    
    def __init__(self, cmd, stderr, code):
        msg = "External call '%s' fail with code '%i'. Cause: '%s'" % (cmd, 
                                                                                                  code, stderr)
        super(CallError, self).__init__(msg)
        self.cmd = cmd
        self.stderr = stderr
        self.code = code
                   

class Call(object):
    """Wraps a system call"""
    
    def __init__(self, cmd):
        """Creates a new instance of call
        
        @param cmd: the system command to be executed
        
        """
        self._cmd = cmd
        self._pcmd = shlex.split(cmd)

    def __repr__(self):
        return "<Call '%s' at %s>" % (self._cmd, hex(id(self)))

    def call(self):
        """Execute the cmd an return the standar output or raises an exception
        
        """
        p = subprocess.Popen(self._pcmd, stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE)
        stdout, stderr = p.communicate()
        if p.returncode:
            raise CallError(self.cmd, stderr, p.returncode)
        return stdout
        
    @property
    def cmd(self):
        return self._cmd

uso:

import caller
ls_lia = caller.Call("ls -lia")
print ls_lia.call()