sábado, 22 de diciembre de 2012

Use zip

The following examples illustrate typical uses of the command zip for packaging a set of files into an "archive" file, also called "zip file". The command uses the standard zip file format. The archive files can therefore be used to tranfer files and directories between commonly used operating systems. 

 zip archivefile1 doc1 doc2 doc3
This command creates a file "archivefile1.zip" which contains a copy of the files doc1, doc2, and doc3, located in the current directory. 

 zip archivefile1 *
This command creates a file "archivefile1.zip" which contains a copy of all files in the current directory in compressed form. However, files whose name starts with a "." are not included. The extension ".zip" is added by the program. 

 zip archivefile1 .* *
This version includes the files that start with a dot. But subdirectories are still not included. 

 zip -r archivefile1 .
This copies the current directory, including all subdirectories into the archive file. 

 zip -r archivefile2 papers
This copies the directory "papers", located in the current directory, into "archivefile2.zip". 

 zip -r archivefile3 /home/joe/papers
This copies the directory "/home/joe/papers" into "archivefile3.zip". Since in this case the absolute path is given, it doesn't matter what the current directory is, except that the zip file will be created there.
The command unzip extracts the files from the zip file.
 unzip archivefile1.zip
This writes the files extracted from "archivefile1.zip" to the current directory. 

jueves, 22 de noviembre de 2012

git crib

Install git (debian)

sudo apt-get install git-core

Workflow

Generate SSH keys


View: https://help.github.com/articles/generating-ssh-keys

Clone a project (svn checkout equivalent)

git clone https://github.com/username/projectname.git
Creates projectname directory and clones the project.

Add a file to the repository

git add filename

Show project status

git status

Commit to the local repository

git commit -a -m "change description"

Upload to the central repository

git push git@github.com:username/projectname.git
or (see user configuration),
git push

Discard all local changes including newly added files

git reset --hard

Discard options

f you want to revert changes made to your working copy, do this:
git checkout .
If you want to revert changes made to the index (i.e., that you have added), do this:
git reset
If you want to revert a change that you have committed, do this:
git revert ...
Taken from: http://stackoverflow.com/questions/1146973/how-to-revert-all-local-changes-in-a-git-managed-project-to-previous-state

Show differences


Update project, download changes (svn update equivalent)

git pull

Show diff between master and local repository

git diff


Branches


Make a new branch

git branch rama

Show branches

git branch

Go to the branch rama

git checkout rama

Merge with master

git branch master (goto the main branch)
git merge "rama" (merge rama with main)


User configuration


User

To automate the pulls:

View the reponame
git config -l

And then
sudo git config remote.origin.url https://{USERNAME}:{PASSWORD}@github.com/{USERNAME}/{REPONAME}.git

Find all *.pyc and remove from the repository

find . -name "*.pyc" -exec git rm -f {} \;

Ignore some types of files (global)

git config --global core.excludesfile ~/.gitignore_global

Edit ~/.gitignore_global and add patterns like *.pyc

Ignore some types of files (local)

At the local repository edit .gitignore and add patterns.

sábado, 17 de noviembre de 2012

Chuleta de git

Instalar git (debian)

sudo apt-get install git-core

Ciclo de trabajo

Generación de claves SSH


Ver: https://help.github.com/articles/generating-ssh-keys

Clonar un proyecto (equivale a checkout de svn)

git clone https://github.com/nombreusuario/nombreproyecto.git
Crea el directorio nombreproyecto y clona el proyecto en él.

Añadir fichero a repositorio

git add nombrefichero

Ver status del proyecto

git status

Hacer commit al repositorio local

git commit -a -m "descripción de los cambios"

Subir cambios al repositorio central

git push git@github.com:nombreusuario/nombreproyecto.git
o bien,
git push


Descartar cambios locales


i
f you want to revert changes made to your working copy, do this:
git checkout .
If you want to revert changes made to the index (i.e., that you have added), do this:
git reset
If you want to revert a change that you have committed, do this:
git revert ...


Fuente: http://stackoverflow.com/questions/1146973/how-to-revert-all-local-changes-in-a-git-managed-project-to-previous-state



Volver a un commit en concreto

git checkout commit_id

véase: http://stackoverflow.com/questions/4114095/revert-to-previous-git-commit

Ver diferencias


Actualizar el proyecto local, bajar los cambios, hacer "update"

git pull

Ver diferencias entre rama de desarrollo y repositorio local

git diff

Ver diferencias entre repositorio local y HEAD

git diff --cached

Ver diferencias entre rama de desarrollo y HEAD

git diff HEAD

Ramas


Crear rama a partir de la actual

git branch rama

Mostrar ramas y en la que nos encontramos

git branch

Situarnos en una rama

git checkout rama

Merge de una rama "rama" con la principal

git branch master (nos situamos en la rama principal)
git merge "rama" (merge de la rama con la principal)


Configurar usuario


Usuario

Automatizar los pulls:

Ver nombre de repositorio
git config -l

Y con el reponame

sudo git config remote.origin.url https://{USERNAME}:{PASSWORD}@github.com/{USERNAME}/{REPONAME}.git

Encontrar todos los *.pyc y eliminarlos del repositorio
find . -name "*.pyc" -exec git rm -f {} \;

Ignorar algunos tipos de fichero (global)

git config --global core.excludesfile ~/.gitignore_global

Editar ~/.gitignore_global y añadir patrones p.e. *.pyc

Ignorar algunos tipos de fichero (local)

En el repositorio local editar .gitignore y añadir los patrones.

miércoles, 17 de octubre de 2012

Campos calculados en django

Las operaciones sobre los objetos model de django se mapean a SQL mediante el ORM (Object-relational mapping). Un problema que tiene el ORM de django es que no tiene soporte directo para los campos calculados, que son aquellos que se obtienen a partir de los valores de los campos del registro para cada registro.

Por ejemplo, tenemos unos movimientos en los que interviene cantidad, precio y comisión. ¿Qué sentido tiene guardar en la BD el campo importe si en realidad ya tenemos toda la información para calcularlo?.

class Movimiento(models.Model):
   cantidad=models.DecimalField()
   precio=models.DecimalField()
   comision=models.DecimalField()

¿Cómo calculamos entonces el importe?. Hay dos alternativas: Una usando una property de python en el propio objeto model y otra usando extra en el queryset. Veamos:

class Movimiento(models.Model):
   cantidad=models.DecimalField()
   precio=models.DecimalField()
   comision=models.DecimalField()

   def _get_importe(self):
      return self.cantidad*self.cambio*(1-self.comision)
   importe = property(_get_importe)

Y ahí tenemos el importe del movimiento via movimiento.importe

La otra solución es usar extra en el queryset para añadir "a mano" el campo en la consulta SQL, sería:

target=movimiento.objects.extra(select={
          'importe': 'cantidad*cambio*(1-comision)',})
for f in target:
    print f.importe

Entonces, ¿Cuál es el problema?. Pues que todo esto son soluciones "de mentirijilla" puesto que realmente el campo importe no existe como tal en el gestor de BD y no podemos hacer cosas como sumar todos los importes haciendo una agregación, así esto

total_importe=modelo.aggregate(Sum('importe'))

Nos genera un error diciendo que el campo importe no existe.

Sin duda, el soporte para campos calculados es uno de las mejoras del ORM que puede trabajarse.


Fuentes:
http://stackoverflow.com/questions/3690343/django-orm-equivalent-for-this-sql-calculated-field-derived-from-related-table

lunes, 8 de octubre de 2012

Localizar las plantillas

Si queremos que los importes monetarios de nuestras plantillas nos salgan (en España) así:

1.256,56 €

en vez de así:

1256.56 €

tenemos que localizar la plantilla y dejar que django haga el trabajo duro.

Para empezar, en settings.py indicamos que queremos usar la localización añadiendo:

DEFAULT_CHARSET='utf-8'
THOUSAND_SEPARATOR= '.'
DECIMAL_SEPARATOR = ','
NUMBER_GROUPING = 3
USE_THOUSAND_SEPARATOR = True
FIRST_DAY_OF_WEEK = 1
LANGUAGE_CODE = 'es-es'
USE_L10N = True


En la plantilla, cargamos l10n y activamos la localización así:

{% load l10n %}
{% localize on %}

blah, blah, blah...

{% endlocalize %}


Y de forma mágica los importes aparecerán correctamente formateados. Para controlar la cantidad de decimales diferentes del estándar también podemos usar el filtro floatformat:precision así:

{{ importe|floatformat:6 }}


Error de codificación de caracteres al generar pdf con django y pisa

Hacía tiempo que me perseguía un pequeño problema al generar pdf desde django/pisa con caracteres utf8>255. Por defecto, pisa usa latin-1/ISO 8859-1 (un byte) para generar los pdf y al transcodificar los caracteres de la template (p.e. el símbolo euro €) me saltaban errores.

En la doc oficial de pisa tenemos que:


pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), result)


Pero buscando en stackoverflow he encontrado que pisaDocument acepta además el parámetro encoding con el que en realidad le indicamos la codificación que debe usar con lo que queda:

pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), result, encoding='UTF-8')  

;-)

Minimizar y maximizar en gnome3

Una forma de configurar los botones que queremos en el marco de la ventana es instalar el programa


sudo apt-get install gnome-tweak-tool

Y desde él configurar este y otros aspectos del entorno.