lunes, 29 de diciembre de 2008

levantar IP que apunte a la loopback interface en ubuntu

Comandos mágicos para que las IPs 10.1.0.2 y 10.1.0.3 apunten a la loopback interface:

sudo ifconfig lo up
sudo ifconfig lo 127.0.0.1
sudo ifconfig lo:0 10.1.0.2
sudo ifconfig lo:1 10.1.0.3

sudo route add -host 127.0.0.1 lo
sudo route add -host 10.1.0.2 lo:0
sudo route add -host 10.1.0.3 lo:1

y así sucesivamente para agregar las IPs que se quiera

miércoles, 10 de diciembre de 2008

Cuidado con acceder a BD dentro un rowhandler ibatis

IDbConnection documentation says:

Note that while a DataReader is open, the Connection is in use exclusively by that DataReader. You will not be able to execute any commands for the Connection, including creating another DataReader, until the original DataReader is closed

jueves, 27 de noviembre de 2008

variable++ o ++variable?

Por fin me topé con un caso real en que cometí el error de usar variable++ sin pensar en las fatales consecuencias.

Lo siguiente deja siempre a c con el valor 0:

int c = 0;
for (int i = 0;true; i++) {
c =(c++)%1000;
...
}

Eso porque c++ quiere decir que justo luego de evaluar la expresión de la derecha, c debe incrementarse en 1. Entonces, la expresión se evalúa en cero, c queda en 1, pero como a c luego se le asigna el valor de la expresión, que es cero, c queda en cero.

Solución: ++c.

sábado, 22 de noviembre de 2008

Cómo dejar a Tuna como demonio en init.d

Copiar o mover el archivo:
dist/tuna_in_init.d
en la ruta:
/etc/init.d/tuna

Tiene la siguiente estructura:

pablo@pablo-desktop:~$ more /etc/init.d/tuna

#!/bin/sh
#
# chkconfig: - 90 90

### BEGIN INIT INFO
# Provides: tuna
# Description: SSH-Tunnel Administrator
### END INIT INFO

case "$1" in
'start')
COMANDO PARA INICIAR
;;
'stop')
COMANDO PARA DETENER
;;
*)
echo "Usage: $0 { start | stop }"
;;
esac
exit 0

Finalmente, avisarle al sistema que hay un nuevo script en init.d:

pablo@pablo-desktop:~$ sudo update-rc.d tuna defaults

Opcionalmente a eso, se puede crear un link simbólico en:
/etc/rc6.d/K90tuna que apunte a
/etc/init.d/tuna

jueves, 20 de noviembre de 2008

Cómo setear encoding ISO a sitio web alojado en apache UTF8

Simplemente escribir en la raiz del sitio un .htaccess:

[pablo@pc mipaginaweb]# more .htaccess
AddDefaultCharset ISO-8859-1

martes, 18 de noviembre de 2008

Google Apps Gets a 99.9% Guarantee

David Gerard passes along a posting on Google's official blog announcing that they have extended the three-nines SLA for the Premier Edition of Google Apps from Gmail alone to also cover the Calendar, Docs, Sites, and Google Talk services. 99.9% uptime translates to 45 minutes a month of downtime, and the blog post puts this in context with Gmail's historical reliability, which has been between three and four times as good over the last year (10-15 min./mo.). It also claims, based on research by an outside group, that Gmail's historical reliability beats that of in-house hosted solutions such as Groupwise and Exchange, on average. Reader Ian Lamont adds an article in The Standard that digs down into the details of the SLA, revealing for instance that outages of less than 10 minutes aren't counted against the monthly 45 minutes.

http://tech.slashdot.org/article.pl?sid=08/11/02/2222226

viernes, 14 de noviembre de 2008

Comando linux para eliminar archivos que cumplan una regex

Ejemplo, eliminar todos los archivos (incluyendo subdirectorios) que contengan la palabra "200":

find . -regex ".*200.*" -exec rm {} \;

Nota: {} es tomado como el nombre del archivo encontrado por find.

Comando linux para contar cada tipo de linea de un archivo

Si tengo un archivo archivo con lineas iguales agrupadas (lo que se puede crear con sort), como el sgte contenido:

hola como estas
hola como estas
hola como estas
Hola, como has estado?
Hola, como has estado?
Yo estoy bien
Yo estoy bien
Yo estoy bien
Yo estoy bien
Yo estoy bien

y quiero un conteo de cada tipo de línea, como el sgte ejemplo:
hola como estas => 3
Hola, como has estado? => 2
Yo estoy bien => 5


Uso:

cat archivoConLineasIgualesAgrupadas.txt | awk -F'jasdjfasdfsd' 'BEGIN {ultima="";contador=0;} {if ($1 == ultima) {contador++;} else { printf ("%s => %i\n",ultima,contador);contador=1;ultima=$1; }} END { printf ("%s => %i\n",ultima,contador);contador=1;ultima=$1; }'> resumen.txt

lunes, 10 de noviembre de 2008

xrdp: remote desktop server para linux

Based on the work of rdesktop, xrdp uses the remote desktop protocol to present a GUI to the user.
Unlike Windows NT/2000/2003/2008 server, xrdp will not display a Windows desktop but an X window desktop to the user.


http://xrdp.sourceforge.net/

Google Chart API

The Google Chart API lets you dynamically generate charts. To see the Chart API in action, open up a browser window and copy the following URL into it:

http://chart.apis.google.com/chart?cht=p3&chd=t:60,40&chs=250x100&chl=Hello|World

Press the Enter or Return key and - presto! - you should see the following image:

Yellow pie chart


http://code.google.com/apis/chart/

miércoles, 5 de noviembre de 2008

Evitar escribir passwords ssh con sshpass

No sólo se puede con putty en windows, también en linux con sshpass.

En ubuntu se instala como se intuiría:
sudo apt-get install sshpass

Entonces, para crear una conexión ssh con la password (ej: dIjfl3nSS) en la línea de comandos:

sshpass -p dIjfl3nSS ssh algunhost.cl -lpablo

Gnome Launch Box en xubuntu

El katapult o launchy o quicksilver para gnome, llamado Gnome Launch Box funciona en xubuntu.

Instalación:
sudo apt-get install gnome-launch-box

Configurar el clásico space:
"Xfce Menu"-> Settings -> Keyboard Settings, hacer una asociación entre gnome-launch-box y gnome-launch-box.

Logout, login en el Xfce, tipear space y algo como "spread" para que encuentre el SpreadSheet de OpenOffice.

Probado en
Xubuntu 7.04 "Feisty Fawn"

jueves, 30 de octubre de 2008

Encodings: Strings "Windows-1252" en python

Me topé en:
http://noticias.iglesia.cl/noticia.php?id=7946
con un texto que tenía un guión misterioso que en el browser se ve como un guión un poco más largo que lo normal.
Descubrí que ese guión venía encodeado en "Windows-1252".

Al obtener el texto de esa página en un string en python, me fue deseable reemplazar ese guión por el guión normal.

Para ello, tuve primero que leer bien el string recibido desde la web:
html = html.decode('Windows-1252')

Luego, descubrir el código Unicode de ese caracter raro, usando la consola de python:
>>> u"–"
u'\u2013'


Finalmente, reemplazar ese guión por el guión normal:
html = html.replace(u'\u2013',"-")

miércoles, 29 de octubre de 2008

Sólo un login, con OpenID

SourceForge ofrece login usando OpenID, teniendo asociado, entre varios sistemas de login, el de blogspot.
Yo tengo login en blogspot, por este sitio de pildorascomputinas, por lo que lo ingreso en el login de sourceforge:




y como ya estoy logueado en blogspot, SourceForge usa esa sesión para validar el inicio de sesión en su sitio y me da la bienvenida!

Nota: La primera vez que me logueo de sea manera en SourceForge, me pregunta a qué login de SourceForge está asociado el login de blogspot.

Tuna news: Download History Statistics


No está mal...

viernes, 17 de octubre de 2008

SQL update para convertir data latin1 a utf8

En SQLyog, si queremos ver los datos de una tabla en latin1, ejecutar el sgte SQL:

SET NAMES 'utf8';

Ese comando se ejecuta por defecto al abrir una conexión en SQLyog.

Luego, para cambiar de latin1 a utf8 la data de un campo de una tabla:

update TablaTest set campotest=convert(CONVERT(CONVERT(campotest USING utf8) USING binary) using latin1)


Si vemos ahora los datos de la tabla veremos garabatos, pues quedaron en utf8. Para verlos bien, ejecutar:


SET NAMES 'latin1';


Refrescar los datos de la tabla en pantalla y lo que está almacenado en utf8 ahora se verá legible.

Cómo montar un directorio remoto por ssh en linux con fuse

Instalación de fuse y sshfs:

sudo apt-get install fuse-utils
sudo apt-get install sshfs
mkdir mihostmontado
sudo gpasswd -a pablo fuse

desloguearse y loguearse nuevamente

Ref:
http://ubuntu.wordpress.com/2005/10/28/how-to-mount-a-remote-ssh-filesystem-using-sshfs/

Ejemplo para montar:


sshfs mihost.cl:/var/www/html/misitio/ mihostmontado/


para desmontar:

fusermount -u mihostmontado/

Cómo hacer que SQLyog me hable en latin1 y a la BD en utf8

La magia es ejecutar en la ventana de Query de SQLyog el sgte comando:


SET NAMES 'latin1';


luego refrescar cualquier resultado que SQLyog haya entregado antes.

jueves, 16 de octubre de 2008

Plugins en Java

Java 6 ofrece la clase ServiceLoader, que permite cargar plugins en tiempo de ejecución.

Los plugins son objetos que implementan cierta interfaz. Por ejemplo, la sgte interfaz :


package plugintest;

public interface Saludador {
public abstract void saludar(String name);
}


Esa interfaz la podemos compilar en un .jar, para ser incluído en el proyecto principal y en el proyecto del plugin.

Entonces, en el proyecto del plugin, creamos la sgte clase que implementa la interfaz:


package plugintest.impl;

import plugintest.Saludador;

public class SaludadorIngles implements Saludador {

public void saludar(String name) {
System.out.println("hello "+name);
}

}


Luego, el proyecto del plugin lo compilamos como un jar para incluirlo en el proyecto principal.
Antes de compilar el jar del plugin, hay que crear, dentro de su directorio src, un directorio META-INF/services/ y allí, un archivo con las rutas de los plugins que implementan la interfaz. Para indicar qué interfaz implementan, ese archivo debe tener el mismo nombre que el nombre completo de la interfaz: plugintest.Saludador
El contenido del archivo debe tener una línea por cada ruta de plugin. En nuestro ejemplo el contenido será:

plugintest.impl.SaludadorIngles


Finalmente, en el proyecto principal incluímos el jar del plugin. Estos jars de plugins, en vez de dejarlos en el directorio lib, se pueden dejar en un directorio especial, ej: "plugins"

De esta manera, usando la clase ServiceLoader de java, podemos instanciar y usar los plugins. Ej:


public class Tester {

public static void main(String[] args) throws IOException {
ServiceLoader loader = ServiceLoader.load(Saludador.class,getClassLoader());
for (Saludador inst : loader) {
inst.saludar("Pablo");
}
}

private static ClassLoader getClassLoader(){
File dir = new File("plugins");
File[] files = dir.listFiles();
ArrayList urls = new ArrayList();
for (File file : files) {
System.out.println("agregando jar: "+file.getName());
try {
urls.add(file.toURI().toURL());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
URLClassLoader cl = new URLClassLoader(urls.toArray(new URL[0]));

return cl;
}

miércoles, 15 de octubre de 2008

RAE Simple: Mi primera aplicación en Google App Engine

Mi primera aplicación para GAE la subí a:
"http://rae.appspot.com"

Sirve para consultar en la RAE por los significados de palabras.
Por ejemplo, para obtener el significado de la palabra "diéresis", se puede acceder al link:
http://rae.appspot.com/diéresis

¿Cuál es la gracia?

1.- Entrega los significados de la palabra en un formato html simplificado, esto para ahorrar plata si se accede con un celular en que el cobro es por KB bajados.
Obtener los significados de una palabra desde el sitio de la RAE, sin contar imágenes ni css, ni js, cuesta entre 3KB y 13KB. En cambio, desde rae.appspot, cuesta entre 0.3KB y 3KB

2.- En Chile acceder al sitio de la RAE es lentísimo, en cambio, a las máquinas de google es muy rápido. Una simple prueba con el Apache HTTP server benchmarking, usando 10 tests resultó en:

"http://rae.appspot.com/saltar"
Requests per second: 2.12 [#/sec] (mean)

"http://buscon.rae.es/draeI/SrvltGUIBusUsual?TIPO_BUS=3&LEMA=saltar"
Requests per second: 0.61 [#/sec] (mean)

lunes, 13 de octubre de 2008

Cómo saber y cambiar el charset de un archivo en linux

Con el comando file y la opción mime se puede saber el charset de un archivo:

[pablo@mipc admin]$ file --mime test.html
test.html: text/plain; charset=iso-8859-1

Para cambiar el charset, con el comando iconv:

[pablo@mipc admin]$ iconv --from-code=iso-8859-1 --to-code=utf-8 test.html > test_new.html

miércoles, 8 de octubre de 2008

SQL select con count-if

By embedding an IF() function within a COUNT() function, you can gather several counts on the same table at once.

If you use an IF() function to evaluate the condition, and return NULL if it's false, you can collect both totals in a single query:

SELECT COUNT(IF(something="this",1, NULL)) AS somethingcount, COUNT(*) AS total FROM mytable;

http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html

lunes, 6 de octubre de 2008

Tuna news: ahora se visualiza bien en chrome

Ahora se puede usar chrome, además de Firefox3, para visualizar Tuna.
Una foto:




Tuna is a SSH-Tunnel Administrator to configure port forwardings, for Linux, Windows, and Mac. It has a web GUI for local or remote (if installed on server) management, on-hot setup and description of each forwarding, loopback IP support, encrypted passwords storage.
http://tunadmin.sourceforge.net/

jueves, 2 de octubre de 2008

Requests a otros Web Services con Google App Engine

En mis primeros pasos usando Google App Engine me encontré con la sorpresa de que, desde una aplicación web creada para correr en la gapp-engine, se puede hacer requests http a otros hosts, sin embargo sólo a puertos estándares: 80 (http) y 443 (https).

http://code.google.com/appengine/docs/urlfetch/

martes, 30 de septiembre de 2008

Process monitoring with ps-watcher

Once you have ps-watcher installed the next step is to create a configuration file that contains the rules your want to use for monitoring or acting on what ps-watcher reports, based on the output of the ps command. Along with the supplied configuration file, you can use command-line options to fine-tune the behavior of ps-watcher and assist in debugging.

http://www.linux.com/feature/148189
http://ps-watcher.sourceforge.net/

Tuna news: release 1.2

Lo nuevo:
  1. Nuevo skin web
  2. Reconexiones automáticas de los port-forwardings
http://sourceforge.net/projects/tunadmin/
http://tunadmin.sourceforge.net/

miércoles, 24 de septiembre de 2008

libro para comprar: Clean Code

Quedé muy interesado en este libro, tiene muchas papitas para hacer mejores códigos.
Ej:
The Error Handling chapter is important because of the application of earlier chapters — the Do One Thing rule. Your functions should do one thing — either handle business logic, or exception handling, but not both. It's the difference between this:

try { s = new Socket(4000); s.OpenSocket(); string data = s.ReadFromSocket(); if(data == "32") data = "42"; printer.print(data); } catch(Exception ex) { if(ex == NetworkInterruptException) { //do something } if(ex == PrinterOnFireException) { //do something } logException(ex); }

And this

try { tryToPrintDataFromSocket(); } catch(Exception ex) { logException(ex); }

http://books.slashdot.org/books/08/09/23/2243216.shtml

Timeout en mysql usando jdbc

Ya que ibatis al parecer no soporta timeout para mysql, se puede usar propiedades
  • connectTimeout
  • socketTimeout
  • enableQueryTimeouts para usar Statement.setQueryTimeout()

Ellas son especificables en el string de conexión a mysql:
jdbc:mysql://[host:port],[host:port].../[database] [?propertyName1][=propertyValue1][&propertyName2][=propertyValue2]...

http://dev.mysql.com/doc/refman/5.0/en/connector-j-reference-configuration-properties.html

lunes, 22 de septiembre de 2008

Cambio servidor web de proyectos de SourceForge

El acceso ya no es por shell.sourceforge.net, sino por web.sourceforge.net, además hay que usar como login la sgte truculencia:
"The new username spec is USERNAME,PROJECTNAME@web.sourceforge.net"

http://sourceforge.net/community/forum/topic.php?id=3518&page

Cómo obligar al browser respetar un estilo !important

"an "!important" declaration (the keywords "!" and "important" follow the declaration) takes precedence over a normal declaration"

http://www.w3.org/TR/CSS2/cascade.html#important-rules

lsof descubre por qué du dice que hay menos espacio usado que df

Cuando ocurran cosas raras como que du dice que var usa 17G y sin embargo df dice que hay usados en var 41G, como en este ejemplo:

[pablo@test var]$ du . --max-depth=1 -h
8.7G ./www
4.9G ./log
...
17G .

[pablo@test var]$ df -h
Filesystem Size Used Avail Use% Mounted on
...
/dev/mapper/Log02 41G 39G 0 100% /var

se debe a que algún proceso tiene tomados archivos eliminados que aún usan espacio en disco, pero no se ven con ls, quedan como archivos fantasmas. Solución: detener el proceso que tiene tomados esos archivos y ver por qué no hizo "close".

Con el comando lsof se puede ver qué procesos tienen abiertos qué archivos.

miércoles, 17 de septiembre de 2008

solr-tomcat5.5: Solr app does not start: Exception starting filter SolrRequestFilter

Debugging apache-solr-1.2.0.jar, using tomcat 5.5 running on java 5, I found the problem comes from another hidden exception:
Caused by: java.lang.RuntimeException: XPathFactory#newInstance() failed to create an XPathFactory for the default object model...

Two solutions:
  • Remove $TOMCAT_HOME/common/endorsed/xml-apis.jar (I mean mv xml-apis.jar xml-apis.jar.removed). So, the runtime libraries of java 5 will be used, not the tomcat endorsed.
Or:
Then, restart tomcat.

Ref del problema:
http://groups.google.com/group/linux.debian.bugs.dist/browse_thread/thread/f551fc6f05c48d17

Framework PHP: CakePHP




Mientras leía de LimeSurvey, vi que está hecho sobre CakePHP
Ref: http://www.limesurvey.org/

Me recordó a ruby on rails, con el "convention over configuration".
Ref: http://cakephp.org/

La típica lata es que necesita que la BD esté hecha para él (ej: palabras_separadas_por_underscore, las tablas tienen que tener un id autoincrement, etc) no está hecho para BD ya establecidas.

Resumen:
CakePHP is a rapid development framework for PHP that provides an extensible architecture for developing, maintaining, and deploying applications. Using commonly known design patterns like MVC and ORM within the convention over configuration paradigm, CakePHP reduces development costs and helps developers write less code.

Tuna news: nuevo skin con css refresh

Screenshot con su nueva pinta:




http://sourceforge.net/projects/tunadmin/
http://tunadmin.sourceforge.net/

martes, 16 de septiembre de 2008

Platform-as-a-Service: Google App Engine

Interesante sería usar la facilidad de google, para hacer alguna aplicación web y de pasada aprender más python:

One interesting example of a PaaS is Google App Engine. App Engine is a service that allows you to deploy your Web applications on Google's very scalable architecture. App Engine provides you with a sandbox for your Python application that can be referenced over the Internet (and additional languages will be supported in the future). App Engine provides Python APIs for persistently storing and managing data (using the Google Query Language, or GQL) in addition to support for authenticating users, manipulating images, and sending e-mail. The sandbox in which the Web application runs restricts access to the underlying operating system. Although App Engine limits the functionality available to your application, it supports the construction of useful Web services. Check out Resources for more information.


http://code.google.com/appengine/

Rewrite rules para tener REST en PHP

Varias veces olvido los pasos necesarios para que funcione esa truculencia de apache:
  • Make sure that an .htaccess override is allowed. In your httpd.conf, you should have a section that defines your Directory on the server. Make sure the AllowOverride is set to All for the correct DocumentRoot.
  • Make sure you are editing the system httpd.conf rather than a user- or site-specific httpd.conf.
  • Make sure you are loading up mod_rewrite correctly. You should see something like LoadModule rewrite_module libexec/httpd/mod_rewrite.so (Unix/Linux users should also see something like AddModule mod_rewrite.c) in your httpd.conf. Also make sure that those lines have not been commented out (by being prepended with a #). Restart Apache to make sure your conf settings are active.
  • If you are installing into a user directory (http://example.com/~username), you'll need to modify the .htaccess file in the base directory of your installation. Just add the line "RewriteBase /~myusername/".
http://book.cakephp.org/view/37/Apache-and-mod_rewrite

Popularity of Programming languages

Echarle un vistazo cada cierto tiempo...
http://www.hurricanesoftwares.com/popularity-of-programming-languages-september-2008/

Nombres geniales de proyectos

The Eucalyptus project (Elastic Utility Computing Architecture for Linking
Your Programs To Useful Systems) ...
http://eucalyptus.cs.ucsb.edu/

jeje

viernes, 12 de septiembre de 2008

La nueva GUI de VMware es web!

VMware 2 (beta aún) trae una interfaz web para administrar las máquinas virtuales.


Es como una desktop-app, pero es web.
Permite administración remota, con, p.ej. firefox, de las máquinas virtuales que uno tenga en un servidor de un data center.

jueves, 11 de septiembre de 2008

CSS gratis para dejar con estilo las páginas web

http://www.styleshout.com/

Sólo piden poner un link en los créditos a su página, vale la pena...
Vamos a ver cómo queda Tuna y su página web con un buen estilo.

Process Explorer v11.21


Interesante aplicación para ver los procesos, así como con ctrl-alt-supr, pero de manera mucho más detallada:



The unique capabilities of Process Explorer make it useful for tracking down DLL-version problems or handle leaks, and provide insight into the way Windows and applications work. http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx

miércoles, 10 de septiembre de 2008

Monitorear memoria, cpu, etc con comando linux top

El comando ps a veces no da buenos resultados, para esos casos, usar top:

ps -wfea --cols=400 | grep "algun_identificador_del_proceso" | egrep -v "grep|vi" | awk '{printf("%s\n",$2)}'|head -n1|xargs top -n 1 -b -c -p | grep java| awk '{printf("Cpu: %s Memoria: %s Recurso: %s Compartido: %s\n",$9,$5,$6,$7)}'

Comando linux para hacer pipe de la primera linea

head - output the first part of files
-n N
print the first N lines instead of the first 10

lunes, 8 de septiembre de 2008

Acceso a objetos COM desde .net

Siempre olvido las herramientas que se usan para acceder a COM desde .net, para que no pase de nuevo:
"COM Interop Part 1: C# Client Tutorial"
la papa es usar Tlbimp.exe

viernes, 5 de septiembre de 2008

Parche para que prototype permita ajax con methods PUT, DELETE, etc

Acerca del post anterior de este tema, en la discusión se agregó una interesante solución, que es agregar un argumento forceMethod=true/false en la creación del objeto Ajax. Así, para cuando se quiera forzar usar el método (ej: DELETE) se ingresa forceMethod en true y así se deja al programador la decisión de usar o no métodos no compatibles con todos los browsers (aunque sí para IE7 y Firefox3)

http://prototype.lighthouseapp.com/projects/8886/tickets/289-allow-put-delete-and-other-http-methods-on-ajax-requests

miércoles, 3 de septiembre de 2008

Manejo de XML en PHP5

SimpleXMLElement permite parsear XML y manejarlo como objetos php:
$xml = new SimpleXMLElement($xmlstr);
echo $xml->movie[0]->plot;

y escribir estos objetos php como un string xml
echo $xml->asXML();

Referencia:
http://cl2.php.net/manual/en/simplexml.examples.php

El encoding interno es UTF-8. Si se necesita obtener en ISO-8859-1:
// This is what we have today
$sxml = simplexml_load_string($xmlstr);
//$sxml = simplexml_import_dom($dom);
var_dump($sxml->asXML()); // OK
echo utf8_decode($sxml->menu->historico);

$internalEncoding = 'iso-8859-1';
$sxml = simplexml_load_string($xmlstr, $internalEncoding);
//$sxml = simplexml_import_dom($dom);
var_dump($sxml->asXML()); // OK
echo $sxml->menu->historico; // now, no need of utf8_decode

Referencia:
http://bugs.php.net/bug.php?id=32431

Tuna news: reconexiones automáticas

Ahora Tuna tiene un proceso en background que revisa cada conexión y cada port-forwarding y si algo está abajo, lo sube automáticamente. Esta revisión es cada minuto.

http://sourceforge.net/projects/tunadmin/

martes, 2 de septiembre de 2008

Vaciar input de un socket antes de escribir en él y esperar respuesta

Antes de escribir en un socket para luego intentar leer la respuesta, es bueno vaciar todo el buffer de entrada. Esto para que no pase que cualquier byte escrito por el servidor al otro lado (por iniciativa propia) se asuma como parte de la respuesta al comando enviado y conduzca a un error

Solr case sensitive wildcard searches

Al poner un * solr lo toma como que ya hiciste la pega de analizador, toma la palabra tal cual la escribiste y la busca en la BD de palabras que está en lowercase. Por eso, "Kong*" hace que busque en una BD donde está "kong", por lo que no arroja resultados.
Si buscas "Kong", ahí sí que hará la tarea de análisis, entre las cosas que hará está ponerla en minúsculas y encontrará a kong.
Cuando buscas sin *, puedes poner mayúsculas y minúsculas. Si buscas Kong, kong o kong*, no tiene problemas en encontrar resultados.
La idea es que si le pones * solr lo toma como que ya le estás ayudando de manera suficiente al motor de búsqueda, y se salta la tarea de análisis, por lo que él no hará más modificaciones a la query con *, como ponerla en lowercase, quitarle espacios, guiones, etc.
Entonces, se necesita que las búsquedas con * vayan en minúsculas.
Ref:
Wildcard queries are tricky here. What happened when you indexed is the analyzer lowercased the terms. But wildcard "terms" are not analyzed (think about stemming and other types of filters, where passing a wildcard term just doesn't make sense).
http://groups.google.com/group/acts_as_solr/browse_thread/thread/42920dc2dcc5fa88

ant al compilar un jar toma todos los .java

Si eclipse logra compilar un proyecto e incluso hacerle run, pero al intentar compilar el jar con ant falla, puede ser que haya un directorio con archivos .java que ant los esté tomando en su compilación, plop!

lunes, 1 de septiembre de 2008

Parche para que la libreria jsch permita saber estado de conexión de un forwarding

Session.java:
public boolean isPortForwardingLConnected(String boundaddress, int lport){
try {
PortWatcher pw = PortWatcher.getPort(this, boundaddress, lport);
if(pw==null)
return false;
return pw.isConnected();
} catch (Exception e) {
return false;
}
}

PortWatcher.java:
private ChannelDirectTCPIP channel;
En run() setear el channel de la clase
public boolean isConnected(){
if(channel==null)
return false;
return channel.isConnected();
}

Charsets encodings (latin, UTF, ISO) en apache, mysql, php, etc

rfc2376 acerca de los documentos XML:
"the use of the charset parameter is STRONGLY RECOMMENDED...
"UTF-8" [RFC-2279] is the recommended value, representing the UTF-8 charset.
UTF-8 is supported by all conforming XML processors [REC-XML]"

En apache:
AddDefaultCharset On enables a default charset of iso-8859-1
http://httpd.apache.org/docs/2.2/mod/core.html

En Mysql:
By default, MySQL uses the latin1 (cp1252 West European) character set and the latin1_swedish_ci collation that sorts according to Swedish/Finnish rules. These defaults are suitable for the United States and most of Western Europe.
http://mysql2.mirrors-r-us.net/doc/refman/5.0/en/character-sets.html

latin1 is the default character set. MySQL's latin1 is the same as the Windows cp1252 character set. This means it is the same as the official ISO 8859-1
http://dev.mysql.com/doc/refman/5.5/en/charset-we-sets.html

Internet Explorer:
Microsoft Internet Explorer uses the character set specified for a
document to determine how to translate the bytes in the document into
characters on the screen or on paper. By default, Internet Explorer uses
the character set specified in the HTTP content type returned by the
server to determine this translation. If this parameter is not given,
Internet Explorer uses the character set specified by the meta element
in the document. It uses the user's preferences if no meta element is
specified.
http://msdn.microsoft.com/en-us/library/aa752010(VS.85).aspx

Timeout en ibatis

De acuerdo a la documentación de ibatis, el timeout de queries fue incorporado a partir de la versión 2.2.0.

defaultStatementTimeout
(iBATIS versions 2.2.0 and later)
This setting is an integer value that will be applied as the JDBC query timeout for all statements. This value can be overridden with the “statement” attribute of any mapped statement. If not specified, no query timeout will be set unless specified on the “statement” attribute of a mapped statement. The specified value is the number of seconds the driver will wait for a statement to finish. Note that not all drivers support this setting.

Parche para que prototype permita ajax con methods PUT, DELETE, etc

"request" function of Ajax.Request class, simulate other verbs (e.g. DELETE, PUT, HEAD, etc) over post.

Why restrict to only get and post requests?

To enable prototype use servlets of my project (that requires DELETE and PUT methods), as a patch, I replaced in that function this line:


this.transport.open(this.method.toUpperCase(), this.url,
this.options.asynchronous);

by this:


this.transport.open(this.options.method.toUpperCase(), this.url,
this.options.asynchronous);

and works perfectly.

http://prototype.lighthouseapp.com/projects/8886/tickets/289-allow-put-delete-and-other-http-methods-on-ajax-requests