viernes, 11 de septiembre de 2020

Caso muy especifico de herencia y override en Java

Teniendo una estructura de herencia 


Donde

- Tenemos isBiped overriden en Kangaroo

- Kangaroo hereda el metodo getMarsupialDescription

Si implementamos la siguiente logica en el main de Kangaroo
 public class Marsupial {  
   public boolean isBiped() {  
     return false;  
   }  
   public void getMarsupialDescription() {  
     System.out.println("Marsupial walks on two legs: " + isBiped());  
   }  
 }  
 class Kangaroo extends Marsupial {  
   public boolean isBiped() {  
     return true;  
   }  
   public void getKangarooDescription() {  
     System.out.println("Kangaroo hops on two legs: " + isBiped());  
   }  
   public static void main(String[] args) {  
        Marsupial marsupialOne = new Marsupial();
        marsupialOne.getMarsupialDescription(); 
        marsupialOne.getKangarooDescription(); 

        // Marsupial Ref, Kangaroo obj        
        Marsupial marsupialTwo = new Kangaroo();
        marsupialTwo.getMarsupialDescription();
        marsupialTwo.getKangarooDescription(); 

        // Kangaroo Ref & obj
        Kangaroo kangaroo = new Kangaroo();
        kangaroo.getMarsupialDescription(); 
        kangaroo.getKangarooDescription(); 
   }  
 }  





Tenemos un output:
 
$ javac Marsupial.java
Marsupial.java:27: error: cannot find symbol
        marsupialOne.getKangarooDescription(); 
                    ^
  symbol:   method getKangarooDescription()
  location: variable marsupialOne of type Marsupial
Marsupial.java:32: error: cannot find symbol
        marsupialTwo.getKangarooDescription(); 
                    ^
  symbol:   method getKangarooDescription()
  location: variable marsupialTwo of type Marsupial
2 errors
Tratando de explicar este resultado debo primero lanzar una hipotesis de lo que esta haciendo la JVM

Al compilar

 
Marsupial marsupialOne = new Marsupial();
marsupialOne.getMarsupialDescription(); 
marsupialOne.getKangarooDescription();
Al ser marsupial una referencia tipo Marsupial, el compilador busca en esta clase la definicion de los metodos getMarsupialDescription y getKangarooDescription, y solamente encuentra el primero, el segundo no esta definido en esta clase por lo cual arroja el primer error

Para el caso:


 
Marsupial marsupialTwo = new Kangaroo();
marsupialTwo.getMarsupialDescription();
marsupialTwo.getKangarooDescription();
En este caso aunque el objeto es de tipo Kangaroo, la referencia en la que se almacena es de tipo Marsupial, el compilador, entonces, busca en esta clase la definicion de los metodos getMarsupialDescription y getKangarooDescription, y solamente encuentra el primero, el segundo no esta definido en esta clase por lo cual arroja el segundo error

En tiempo de compilacion aun no existe ningun objeto, asi que la JVM se limita a examinar la definicion de las clases


 
Kangaroo kangaroo = new Kangaroo();
kangaroo.getMarsupialDescription();
kangaroo.getKangarooDescription();
kangaroo es un objeto de tipo Kangaroo, la referencia en la que se almacena es de tipo Kangaroo, el compilador, entonces, busca en esta clase la definicion de los metodos getMarsupialDescription y getKangarooDescription, y solamente encuentra el segudno, el primero no esta definido en esta clase, entonces, busca en la clase padre, donde si encuentra la definicion y da por valida la sentencia

Se puede corregir los errores removiendo las lineas


 
marsupialOne.getKangarooDescription();
...
marsupialTwo.getKangarooDescription();
Output:
 
Marsupial walks on two legs: false
Marsupial walks on two legs: true
Marsupial walks on two legs: true
Kangaroo hops on two legs: true
Sabiendo que getMarsupialDescription llama al metodo isBiped, ¿porque hay resultados diferentes en marsupialOne y marsupialTwo? La respuesta es que marsupialOne es un objeto de tipo Marsupial y y marsupialTwo es un objeto Kagaroo, y estas clases tienen su propia implementacion del metodo isBiped, a la cual llaman respectivamente
Que ocurre si cambiamos la implementacion de isBiped a static en las dos classes
 
public static boolean isBiped()
 
Marsupial walks on two legs: false
Marsupial walks on two legs: false
Marsupial walks on two legs: false
Kangaroo hops on two legs: true 
En este caso, al ser isBiped un metodo estatico esta vinculado al tipo de referencia, no al objeto, asi, cuando se llama getMarsupialDescription usando una referencia Marsupial, se llama al metodo estatico isBiped de esa clase en particular

domingo, 21 de junio de 2015

Python, Modules

Empezamos una sesión interactiva en la consola, y revisaremos los nombres que tenemos definidos:















Problema: Tengo un módulo con una clase definida. Esta clase tiene un método










importo únicamente la clase, creo una instancia y uso el método








Cuando hago un cambio en la definición del método, espero que con volver a reimportar la clase, el cambio se vea reflejado. Pero no es asi, porque supuestamente la operación de import se lleva a cabo una sola vez. Asi que probamos importando el módulo entero(import script1)


domingo, 5 de abril de 2015

EventQueue.invokeLater

------------------------------------------------------------------------------------------------------------------
 Creating and modifying the components outside the EDT(Event Dispatching Thread) breaks the threading rules, but the breakage is not necessarily visible. The larger the program grows, the more likely it starts behaving badly sometimes, on some systems, and on some java versions

-------------------------------------------------------------------------------------------------------------------

- The complete Swing processing is done in a thread called EDT (Event Dispatching Thread). Therefore you would block the GUI if you would compute some long lasting calculations within this thread.

The way to go here is to process your calculation within a different thread, so your GUI stays responsive. At the end you want to update your GUI, which have to be done within the EDT. Now EventQueue.invokeLater comes into play. It posts an event (your Runnable) at the end of Swings event list and is processed after all other GUI events are processed.

Also the usage of EventQueue.invokeAndWait is possible here. The difference is, that your calculation thread blocks until your GUI is updated. This must not be used from the EDT.

Be careful not to update your Swing GUI from a different thread. In most cases this produces some strange updating/refreshing issues.

Still there is Java code out there that starts a JFrame simple from the main thread. This could cause issues, but is not prevented from Swing. Most modern IDEs now create something like this to start the GUI

---------------------------------------------------------------------------------------------------------------------

- You only need to use invokeLater when you want to update your UI from another thread that is not the UI thread (event dispatch thread).

Suppose you have a handler for a button-click and you want to change the text of a label when someone clicks the button. Then it's perfectly save to set the label text directly. This is possible because the handler for the button-click event runs in the UI thread.

Suppose, however, that on another button-click you start another thread that does some work and after this work is finished, you want to update the UI. Then you use invokeLater. This method ensures that your UI update is executed on the UI thread.

So in a lot of cases, you do not need invokeLater, you can simply do UI updates directly. If you're not sure, you can use isDispatchThread to check whether your current code is running inside the event dispatch thread.

--------------------------------------------------------------------------------------------------------------------
You need to do this only if you're not already on the event dispatch thread. Unless you've started new threads or executed code from the main thread all your code probably already runs from the event dispatch thread making this unnecessary. For example, all the UI event handlers are called on the event dispatch thread so you would not need to do that for code called from there.

--------------------------------------------------------------------------------------------------------------------

- Java's GUI is strictly single-threaded.
All GUI related things in java should always go through a single thread. The thread is our legendary "AWT-EventQueue-0"   . Hence all GUI related actions should necessarily go through the AWT Event thread. If not so you may end up in a deadlock. For small programs, this might never happen. But for a huge java application if you try frame.setVisible(true) kind of thing in main thread, you will soon find yourself searching a new job. What invokeLater() does is to post your Runnable in the AWT thread's event queue. So the code in your run method will be executed in the AWT-Eventqueue thread.

------------------------------------------------------------------------------------------------------------------

To avoid the possibility of deadlock, you must take extreme care that Swing components and models are created, modified, and queried only from the event-dispatching thread
-------------------------------------------------------------------------------------------------------------------
Most code that invokes Swing methods also runs on this thread. This is necessary because most Swing object methods are not "thread safe": invoking them from multiple threads risks thread interference or memory consistency errors. Some Swing component methods are labelled "thread safe" in the API specification; these can be safely invoked from any thread. All other Swing component methods must be invoked from the event dispatch thread. Programs that ignore this rule may function correctly most of the time, but are subject to unpredictable errors that are difficult to reproduce

-----------------------------------------------------------------------------------------------------------------

Tasks on the event dispatch thread must finish quickly; if they don't, unhandled events back up and the user interface becomes unresponsive.

----------------------------------------------------------------------------------------------------------------

When a Swing program needs to execute a long-running task, it usually uses one of the worker threads, also known as the background threads

--------------------------------------------------------------------------------------------------------------

SwingUtilities.invokeLater() vs EventQueue.invokeLater() 

-  SwingUtilities class was built to combine all general utility methods used in swing to be in one single class. Internally SwingUtilities.invokeLater() calls EventQueue.invokeLater()

sábado, 8 de noviembre de 2014

Instalando virtualenv para python2.7.8 y python3.4



http://toomuchdata.com/2014/02/16/how-to-install-python-on-centos/

domingo, 2 de noviembre de 2014

Instalar distintas versiones de python

- Instalar diferentes versiones de pyton
https://www.python.org/downloads/

- Descomprimir, entrar a cada carpeta de python
  • ./configure --prefix=/usr/local
  • make
  • make install
- Se tendrà esto en /usr/local
 lrwxrwxrwx. 1 root root       7 nov  2 15:01 python -> python2
lrwxrwxrwx. 1 root root       9 nov  2 15:01 python2 -> python2.7
-rwxr-xr-x. 1 root root 6221591 nov  2 14:59 python2.7
-rwxr-xr-x. 1 root root    1674 nov  2 15:01 python2.7-config
lrwxrwxrwx. 1 root root      16 nov  2 15:01 python2-config -> python2.7-config
lrwxrwxrwx. 1 root root       9 nov  2 15:21 python3 -> python3.4
-rwxr-xr-x. 2 root root 8777220 nov  2 15:19 python3.4
lrwxrwxrwx. 1 root root      17 nov  2 15:21 python3.4-config -> python3.4m-config
-rwxr-xr-x. 2 root root 8777220 nov  2 15:19 python3.4m
-rwxr-xr-x. 1 root root    3019 nov  2 15:21 python3.4m-config
lrwxrwxrwx. 1 root root      16 nov  2 15:21 python3-config -> python3.4-config
lrwxrwxrwx. 1 root root      14 nov  2 15:01 python-config -> python2-config


- Revisando el PATH:
    echo $PATH:
/usr/lib64/qt-3.3/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin:/home/manuel/bin

- Al ingresar "python" en la consola, se abrirà por defecto la version 2.7
 [manuel@oracle bin]$ python
Python 2.7.8 (default, Nov  2 2014, 14:58:46)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>


- Esto se resuelve cambiando el orden de las carpetas en el PATH, de tal manera que quede como primera opcion del python del sistema(/usr/bin)
Editar el archivo /home/usuario/.bashrc

export PATH=/usr/lib64/qt-3.3/bin:/usr/bin:/usr/local/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin:/home/manuel/bin

Ubicaciones
/usr/local/bin
   easy_install (python del sistema)
   easy_install-2.7
   easy_install-3.4

Instalaciòn de python
/usr/local/lib


La version de pip es la
pip 1.5.6 from /usr/lib/python2.6/site-packages/pip-1.5.6-py2.6.egg (python 2.6)


Fuentes:
http://toomuchdata.com/2014/02/16/how-to-install-python-on-centos/

miércoles, 29 de octubre de 2014

Preparàndo el Buildout -- Python

Como no tengo easy_install procedo a instalarlo

  • Yum
    • yum install python-setuptools python-setuptools-devel

sábado, 4 de enero de 2014

miércoles, 9 de enero de 2013

Apletviewer width vrs. JApplet setSize



1) applet sin setSize:

        El contenido del applet se acopla a la ventana del appletviewer

2) applet setSize menor que el appletviewer width:
      
        La ventana del appletviewer se acopla a las dimensiones especificadas en el método setSize

3) applet setSize mayor que el appletviewer width:

        La ventana del appletviewer toma las medidas especificadas en el método setSize, pero únicamente muestra el contenido del applet hasta la longitud especificada en su parámetro width

Para hacer que el contenido del applet(según este sitio) coincida exactamente con la ventana del appletviewer es posible que el applet lea los valores width y height de la etiqueta applet usando la función getParamenter y luego pasar estos valores a la función setSize:
  
 int ancho = 0, alto = 0;
 try{
  ancho = Integer.parseInt(getParameter("width"));
  alto = Integer.parseInt(getParameter("height"));
 }
 catch(NumberFormatException e){
  showStatus("Error en los valores width & height");
 }        
 
 setSize(ancho, alto);  


Situación al usar appletviewer. Error NoClassDefFoundError

Al usar el appletviewer:

                appletviewer MaximoCD.html

me arrojaba este error:

  java.lang.NoClassDefFoundError: MaximoCD (wrong name: Ejercicios/ventiocho/MaximoCD)
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:634)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
    at sun.applet.AppletClassLoader.findClass(AppletClassLoader.java:197)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:321)
    at sun.applet.AppletClassLoader.loadClass(AppletClassLoader.java:146)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
    at sun.applet.AppletClassLoader.loadCode(AppletClassLoader.java:608)
    at sun.applet.AppletPanel.createApplet(AppletPanel.java:798)
    at sun.applet.AppletPanel.runLoader(AppletPanel.java:727)
    at sun.applet.AppletPanel.run(AppletPanel.java:380)
    at java.lang.Thread.run(Thread.java:636)


Bien, la causa de esto es que en la clase original(MaximoCD) había declarado un package

    package Ejercicios.ventiocho;

lo cual hacía que se buscara la clase en un paquete(o estructura de directorios) 
    
   Ejercicios/ventiocho

dentro del mismo directorio donde reside el archivo html, arrojándome el errror anterior. La solución fue eliminar la declaración

   package Ejercicios.ventiocho;

de la clase original.

martes, 8 de enero de 2013

Mejor algoritmo para números primos en código java


public void determinarPrimo(int numero){

           int contador = 2;

           while(numero % contador != 0)
                    contador++;

            if(contador == numero)
                areaSalida.append(numero + " es primo");

}

lunes, 7 de enero de 2013

Manjear caracteres de escape junto con un método drawString de Graphics

Como el método drawString de Graphics no maneja caracteres de escape como "\n",  "\t", etc., a la hora de querer imprimir un string que contenga éstos caracteres de escape a través de un método drawString se debe de hacer como sigue a continuación, pero antes el planteamiento:

Problema: No se pueden imprimir el caracteres de escape de nueva línea (\n) de un string con el método drawString de Graphics.

Causa: El método drawString no maneja caracteres de escape.

Solución: Dividir el string en partes usando el caracter de escape  de nueva línea(\n) como separador.

Código en Java:

    for(String asteriscos : texto.split("\n") ){
            g.drawString(asteriscos, x, y);
            y+=25;
        }


Donde el texto original seria la variable texto, es decir, la que contiene el caracter de escape "\n".

lunes, 12 de noviembre de 2012

Inluyendo el comando ifconfig al PATH

Un dia de estos estaba curioseando la configuración de red local de mi máquina Debian a través del ícono de red de la barra de estado y la Configuración de Red. Estas herramientas dan cierta información útil que te puede servir en determinado momento. Sin embargo, como usar linux es querer ir más allá de las herramientas gráficas tenia la inquietud de usar el comando ifconfig el cual da información un poco más detallada. Así que abrí un ventana del shell y digité el comando pero me encontré que la consola me devolvía el mensaje

bash: ifconfig: no se encontró la orden

Bueno, ¿A que se debía esto?  Luego de averiguar un tanto supe que ciertos comandos no vienen incluídos en el PATH para el usuario por defecto (cualquiera que no es root). Entonces ¿Cómo se incluye en el PATh un comando? Son dos pasos principales:

  • Determinar donde reside el ejecutable(el comando)
  • Incluirlo en el PATH
Lo primero se resuelve con whereis:

whereis ifconfig

respuesta de la consola

ifconfig: /sbin/ifconfig /usr/share/man/man8/ifconfig.8.gz


 Son dos rutas, la primera es donde se encuentra en si el ejecutable. La segunda es donde reside la documentación del comando

Para incluir el directorio donde está ifconfig en la variable de entorno se digita en la consola:

export PATH=$PATH:/sbin

 
¿Qué estamos diciendo aqui?
 Por partes:
  • export PATH, indicamos que agregaremos una ruta al PATH
  • $PATH, es la variable de sistema PATH
  • :(dos puntos) empiezan las rutas a agregar
  • $PATH:/sbin, poniendo primer la variable $PATH y luego la ruta le indicamos que la ruta se adicione al final de la variable. $PATH tambien se puede colocar al final de esta manera:  export PATH=/sbin:$PATH con lo que la ruta se agrega al incio de la variable.

Esta forma de usar ifconfig o cualquier otro comando es solamente en esa sesión de la consola que se haya abierto. Una vez cerrada se tendrá que repetir el procedimiento.

lunes, 13 de agosto de 2012

viernes, 29 de junio de 2012

Nueva distribución de particiones en disco duro ex windows

1 - Ubuntu, para probar lo más comercial (45GB)
2 - Gentoo, para ponerse serio (45GB)
3 - Fedora, para conocer RPM (45GB)
4 - LFS, para ponerse metafísico (25GB)
5 - Swap (Ajuste GB)

lunes, 25 de junio de 2012

SID Updates

25/06/2012 recomienda pero no instala : gnupg-curl uuid-runtime

viernes, 15 de junio de 2012

Wheezy updates

recomendo  pero no instalara los paquetes:
libatm1 uuid-runtime

28/06/2012  cryptsetup-bin gnupg-curl uuid-runtime
02/07/2012  libatm1


Reciente apitude

El ultimo aptitude update & upgrade en debian SID me recomienda algunos paquetes pero no los instalar, asi que ma tocará a mi hacerlo:

apt-xapian-index aptitude-doc-cs (en, es, fi, fr, it, ja)
libparse-debianchangelog-perl

jueves, 7 de junio de 2012

Cups

Accediendo al servicio CUPS

service cups restart/stop/start

lunes, 4 de junio de 2012

Instalar Gestor de Sesión en Wheezy

Según esto

Sitio web de SLIM

Además con esto

..........en progreso