martes, 28 de octubre de 2014

SVN: Tree conflicts Solution

Solución de conflictos de árbol (Tree conflicts solution):

[user@dev]$ svn st
...
!     C t/unit/models/Toolbox/Restrictions
     >   local delete, incoming edit upon merge
Summary of conflicts:
 Tree conflicts: 32

[user@dev]$ mkdir t/unit/models/Toolbox/Restrictions
[user@dev]$ svn revert t/unit/models/Toolbox/Restrictions
Reverted 't/unit/models/Toolbox/Restrictions'

[user@dev]$ svn st
...
?       t/unit/models/Toolbox/Restrictions
Summary of conflicts:
 Tree conflicts: 31

#Luego enviar los cambios

Reference:
http://stackoverflow.com/questions/4317973/svn-how-to-resolve-local-edit-incoming-delete-upon-update-message
http://svnbook.red-bean.com/en/1.7/index.html

jueves, 23 de octubre de 2014

SVN: Machete de comandos mas usados

Status
svn st

Checkout
svn co https://URL/branches/branch --ignore-externals


Reintegrate del trunk
trunk]$ svn up --ignore-externals
trunk]$ svn merge ^/branches/branch --reintegrate
trunk]$ svn ci -m "message"

Enviar cambios

svn ci -m "msg”

svn commit PATH -m "Message"

Revertir cambios locales
svn revert . -R

Update
svn update --ignore-externals
svn up --ignore-externals



Referencias:
https://code.google.com/p/relaxtives/wiki/Subversion



SVN: Crear y aplicar un Patch

Crear y aplicar un Patch



svn diff > ~/BUG_FIXED_.diff

patch -p0 -i ~/BUG_FIXED_.diff




Patch para volver a hacer un commit revertido:



Si el commit revertido fue r999 y su commit anterior r998, como indica el log:
svn log -l2
------------------------------------------------------------------------
r999 | dario | 2015-01-13 17:32:35 +0000 (Tue, 13 Jan 2015) | 1 line
MY COMMIT: comment.
------------------------------------------------------------------------
r998 | juan | 2015-01-13 12:53:00 +0000 (Tue, 13 Jan 2015) | 1 line
PREVIOUS COMMIT: comment.


Se puede hacer un diff de la siguiente manera:


svn diff -r r998:r999 > Patch_MY_COMMIT.diff


Luego aplicamos el Patch:


patch -p0 -i Patch_MY_COMMIT.diff



Referencia:
- Quick-n-Dirty Guide to Creating and Applying diff-style Patches.
- Crear y aplicar parches (patches) en Linux.


SVN: Log (Consultar Historial)

¿Cómo recuperar información histórica de commits y revisiones?



Traigo mis commit
svn log -l 100 | grep USER
svn log -l 100 | grep -A 3 -B 3 USER

Todos los commit de un usuario entre dos fechas:
svn log -r '{2010-12-10}:{2010-12-11}'|sed -n '1p; 2,/^-/d; /USER/,/^-/p'
svn log -r '{2014-09-23}:{2014-10-15}'|sed -n '1p; 2,/^-/d; /USER/,/^-/p' > $HOME/resultado_USER_commits.log

Revisar commits de una revisión dada
svn log -r NRO_REVISION -v
svn log --revision NRO_REVISION

Revisar commits de un rango de revisión dado
svn log -r NRO_REVISION_1:NRO_REVISION_2

Listar commit entre fechas
svn log -v -r {2014-05-23}:{2014-05-28} --xml > $HOME/resultado_log_entre_fechas.xml
svn log -v -r {2014-08-20}:{2014-08-24} > $HOME/resultado_log_entre_fechas.log

Listar historia de un archivo
svn log FILE

Listar últimos 5 commit
svn log -l 5 -v

Show author and revision information inline for the specified files or URLs
svn blame -v filename
svn blame -v filename > $HOME/resultado_blame.xml


Referencias:

lunes, 20 de octubre de 2014

SVN: Rollback commit (revert revision)


Revertir los cambios de una revisión

¿Cómo deshacer un commit o una revisión?
Podemos querer revertir (deshacer) un commit que hicimos o volver a una revisión pasada.

Si queremos revertir un commit que hicimos con numero_de_revision dado, la forma general es:
                svn merge -r -numero_de_revision url-del-repositorio
... y despues hacer commit.

#Otra manera:
svn merge -c -1003 file:///path/my_project/trunk
svn commit -m "Rollback de la revisión 1003 (revert commit 1003)"

O podemos querer volver a una revisión pasada. La forma general es:
                svn merge -r version-actual:version-anterior url-del-repositorio
... y despues hacer commit.

#Por ejemplo:
svn merge -r 1003:1002 http://repo/project/trunk
svn commit -m "Revert a la revisión 1002"

#Otra forma:
cd ruta/de/miproyecto/
svn merge -r 1003:1002
svn commit -m "Reversión de cambios del ultimo commit"

#Otra
svn merge -r 1003:1002 .
svn commit -m "Rollback de la revisión 1003"

#También podemos indicar tan solo un dir o un archivo al que volver (no toda la rama).
svn merge -r HEAD:543 my_file.pm

#Una forma simulada:
svn merge --dry-run -r 1003:1002 http://repo/project/trunk
#La opción --dry-run lo que hace es mostrarte en la terminal el resultado del merge si hacerlo realmente.

#Si quieremos ver exactamente que cambiará en cada archivo y cada dir, también puedes hacer un:
svn diff -r 1003:1002 http://repo/project/trunk


lunes, 13 de octubre de 2014

Java: Static Analysis

Inspección y análisis de código Java.



1) Complejidad ciclomática (Cyclomatic Complexity)



2) Covertura de test (Coverage)



3) Análisis de dependencia (Dependancy Analysis)



4) Análisis de Bytecode  (Bytecode Analysis)



5) Análisis de código fuente (Source Code Analysis)


6) Monitoreo de memoria


JPS es similar a PS de linux y sirve para averiguar los procesos que estan corriendo en la VM java. Y JSTAT es una herramienta para benchmark para java incluida en el JDK.
Ejemplo para consultar la memoria PermGen que esta utilizando el proceso 666:

       jstat -gcpermcapacity 666


Ejemplo: jconsole processID



Referencia:
-Top 5 Static Analysis Plugins for Eclipse.
-Memoria PermGen en Java.
-Oracle: Using Jconsole.
-5 things you didn't know about ... Java performance monitoring, Part 2.
-InstallVisualVM and JSTAT.


lunes, 6 de octubre de 2014

Perl: Unit Test con Test::More

Unit Test con Test::More y Test::MockObject


El módulo Test::More es un módulo para hacer unit test en Perl y Test::MockObject es un módulo que permite hacer mocking en forma fácil.


Ejemplo de un simple UnitTest

A continuación un simple ejemplo de un unit test con Test::More (usando la estructura de clase de Moose).

Clase a probar:


#File: Person.pm
package Person;

    use Moose;
    use strict; 
    use warnings; 
    use namespace::autoclean;
   
    has '_firstName' => (
                is         => 'rw', 
                isa        => 'Str', 
                required => 1,
                reader => 'getFirstName',
                writer => 'setFirstName',
    );    

    has '_secondName' => (
                is         => 'rw',
                isa        => 'Str', 
                required => 1,
                reader => 'getSecondName', 
                writer => 'setSecondName',
    );
    
sub getFullName{
  my ( $self ) = @_;
  my $full_name = join ' ' => $self->getFirstName(), $self->getSecondName();
  return $full_name;
}

no Moose;
__PACKAGE__->meta->make_immutable;
1;

Unit Test:


#File: PersonTest.t
package PersonTest;

    use Moose;
    use Test::More tests => 3; #Cantidad de test
    use Test::MockObject; #uso de mocking
    use strict; 
    use warnings; 
    use namespace::autoclean; 
    use Person; #Clase a probar
    
    #Primer test
    subtest 'classTest' => sub {
      plan tests => 2; #Cantidad de evaluaciones (aserciones) de test
      require_ok( 'Person' ); #Comprueba que esté el módulo
      my $persona = Person->new(_firstName=>"", _secondName=>"",);
      isa_ok ($persona, 'Person'); #Comprueba si es la clase correcta   
    };
    
    #Segundo test
    subtest 'getFullName' => sub {
      plan tests => 3; #Cantidad de evaluaciones (aserciones) de test
      my $persona = Person->new(_firstName=>"Diego", _secondName=>"Maradona",);
      is($persona->getFullName(),"Diego Maradona",'Full name is right');
      isnt ($persona->getFullName(), "Other name", "Bad full name!");
      ok( length $persona->getFirstName() == 5,       'First Name length is ok!'  );
    };  

    #Tercer test
    subtest 'getFullName_Using_Mock' => sub {
      plan tests => 1;
        my $mockPerson = Test::MockObject->new();
        $mockPerson->mock( 'getFullName',
             sub { 'Ejemplo' } ); #Mocking de la clase Person
      is( $mockPerson->getFullName,"Ejenplo",'Full name is ok with mocking');
  };

no Moose;
__PACKAGE__->meta->make_immutable;
1;


Resultado de la corrida del test:


1..3
    1..2
    ok 1 - require Person;
    ok 2 - The object isa Person
ok 1 - classTest
    1..3
    ok 1 - Full name is right
    ok 2 - Bad full name!
    ok 3 - First Name length is ok!
ok 2 - getFullName
    1..1
    ok 1 - Full name is ok with mocking
ok 3 - getFullName_Using_Mock



Referencias:
-Test::More doc.
-Test::More wikipedia.
-Test::More Tutorial.
-Test::MockObject doc.

sábado, 4 de octubre de 2014

Perl: Switch Statement

Sentencia Switch

Las versiones antiguas de Perl (la vieja escuela o "perl old school") no tienen sentencia switch. O sea que la sentencia switch no es propia del lenguaje, pero se puede simular o hacer construcciones que cumplan el mismo propósito.
A continuación algunos ejemplos:

Ejemplo usando diferentes maneras de switch

#This is perl 5, version 14, subversion 2 (v5.14.2)
#File: UingSwitch.pm
package UsingSwitch;

    use Moose;
    use strict;
    use warnings;
    #use namespace::autoclean;
    use Switch; #Usado en switch_modo_1_

#Switch using 'use Switch' (usando el módulo Switch)
sub switch_modo_1_(){
  my ($self, $i) = @_;
  #use Switch
  switch ($i) {
case 0  { return 'uno' }
        case 2  { return 'dos' }
        case 3  { return 'tres' }
        case [4..9]  { return 'entre 4 y 9' }
        else {return 'Default...'}
        }
     
  return;
}

(Nota: Ojo... Que usar la librería Switch de Perl, impacta negativamente en el rendimiento aumentando el tiempo de ejecución. Si es importante el rendimiento puede ser preferible no usar la librería Switch.)

#Switch using bare block (usando estructura de bloques)
sub switch_modo_2_(){
  my ($self, $i) = @_;
  SWITCH: {
     $i == 1 && do { return "1";};
     $i == 2 && do { return "2";};
     $i == 3 && do { return "3";};
     return "Default...";
  }
=pod
  #Otra forma:
  $var = 2;
  SWITCH: {
    $var == 1 && do { print "1\n"; last SWITCH; };
    $var == 2 && do { print "2\n"; last SWITCH; };
    $var == 3 && do { print "3\n"; last SWITCH; };
    print "\$var is not equal with 1 or 2 or 3\n";
}
=cut
  return;
}

#Switch using hash (usando los valores de un hash)
sub switch_modo_3_(){
  my ($self, $i) = @_;
  my %my_switch = (
     1 => "1",
     2 => "2",
     3 => "3",
  );
  return $my_switch{$i};
}

#Switch using hash with functions (usando un hash con valores funciones)
sub switch_modo_4_(){
  my ($self, $i) = @_;
  my %my_switch = (
     1 => sub {return "uno";},
     2 => sub {return "dos";},
     3 => sub {return "tres";}
  );
  my $res = $my_switch{$i}->();
  return $res;
}

no Moose;
__PACKAGE__->meta->make_immutable; #no voy a cambiar mi clase
1;

#...............................................................................................
#test_UsingSwitch
#!/usr/bin/perl
#use strict;
use warnings;

use UsingSwitch;

my $ex = UsingSwitch->new();

#Switch using 'use Switch'
print $ex->switch_modo_1_(2); #imprime 'dos'
#Switch using bare block
print $ex->switch_modo_2_(1000); #Default
#Switch using hash
print $ex->switch_modo_3_(3); #Default
#Switch using hash with functions
print $ex->switch_modo_4_(1); #Default
print "...end \n";
#............................................................................................end

dario:~/examples$ perl test_UingSwitch.pl 
Esto imprime:
dosDefault...3uno...end 


Referencia:
-http://perldoc.perl.org/5.8.8/Switch.html.
-Writing a Switch Statement.
-Perl Switch statement.
-Older versions of Perl have no switch statement. How do I avoid a long if-else-if pattern?



Perl: POO con Moose, paso de parámetros

En perl todos los objetos son una referencia. Es decir, cuando tenes un $obj es una variable scalar que simplemente mantiene la referencia al objeto.

Ejemplo de paso de objetos

#This is perl 5, version 14, subversion 2 (v5.14.2)
#File: Example.pm
package Example;

    use Moose;
    use strict;
    use warnings;
    #use namespace::autoclean;

    has 'c' => (
                is         => 'rw', #Lectura-Escritura
                isa        => 'Maybe[Str]', #Tipo String
                reader => 'getValor', #getter
                writer => 'setValor', #setter
    );  

sub metodo1{
  my ($self) = @_;

  my $obj = Example->new(obj=>"Primer valor.");
  #$obj = $self->metodo2($obj);
  $self->metodo2($obj);
  print $obj->getValor() . "\n";#Modificado
  return;
}

sub metodo2{
  my ($self, $obj) = @_;

  $obj->setValor("Modificado..."); #usa el objeto pasado como argumento
  return $obj;
}

no Moose;
__PACKAGE__->meta->make_immutable; #no voy a cambiar mi clase
1;

#test_example.pl
#Main.......................................................................
#!/usr/bin/perl
#use strict;
use warnings;

use Example;

my $ex = Example->new();
print $ex->metodo1();
print "\n";
#...........................................................................end

Resultado:
~/examples$ perl test_example.pl
Modificado...


miércoles, 1 de octubre de 2014

Perl: HTML y UTF8 encoding

HTML y UTF8 encoding

Ejemplo de utf8 encoding:

#This is perl 5, version 14, subversion 2 (v5.14.2)
#File: ExampleEncoder.pm
package ExampleEncoder;

    use Moose;
    use strict;
    use warnings;
    #use namespace::autoclean;
    use HTML::Entities;
    use Encode::Encoder;
 
sub encodeHTMLtoUTF8{
  my ($self, $parametro) = @_;

  my $s = HTML::Entities::decode($parametro);
  $s = Encode::Encoder::encoder($s)->utf8;

  return $s;
}

no Moose;
__PACKAGE__->meta->make_immutable; #no voy a cambiar mi clase
1;

#!/usr/bin/perl
#use strict;
use warnings;
use ExampleEncoder;

my $ex = Example->new();
my $str = "Córdoba";
print $ex->encodeHTMLtoUTF8($str);