Tag error:   ->  Textpattern Notice: Page template default does not contain a txp:article tag  on line 464
Netxus Foundries: Internet

Es una pena que pasen estas cosas

Portada del Jueves

For secret reasons I need to usually convert hex strings to decimal notation. This can be easily done with a scientific calculator, like the one supplied with Windows, but it’s slow and I’m usually in a hurry to convert them :)

So I took a look at GreaseMonkey, which is an extension for Firefox which allows to modify a web page once rendered with a simple javascript file.

To install it you’ll first need to have GreaseMonkey installed and activated (a little monkey face on Firefox’s status bar), then click on this link satkeystringconversor.user.js

Here is the highlighted source code so you can review it easily. It’s a pretty simple script which traverses the DOM performing regular expression tests on text nodes and converting the matched strings into span elements with an onclick behaviour.

javascript:
  1. // ==UserScript==
  2. // @name           Sat key string conversor
  3. // @namespace      http://blog.netxus.es
  4. // @description    Converts satelite key strings from hex to dec or vice versa
  5. // @include        http://www.satscreen.ws/forum/*
  6. // @include      https://www.blogger.com/*
  7. // @include      http://floresd.blogspot.com/*
  8. // @include      http://galeon.com/tusflores/*
  9. // ==/UserScript==
  10. function HEXDEC ( node ) {
  11.  
  12.   function hex2dec(hex) {
  13.     var dec = [],
  14.       re = /([0-9A-Za-z]{2})s*/g,
  15.       m,
  16.       conv;
  17.     while (m = re.exec(hex)) {
  18.       conv = parseInt(m[1], 16);
  19.       dec.push( (conv < 100 ? ( conv < 10 ? '00' : '0' ) : '') + conv );
  20.     }
  21.     return dec.join(' ');
  22.   }
  23.  
  24.   function dec2hex(dec) {
  25.     var hex = [],
  26.       re = /([0-9]{3})s*/g,
  27.       m,
  28.       conv;
  29.     while (m = re.exec(dec)) {
  30.       conv = (m[1]-0).toString(16).toUpperCase();
  31.       hex.push( conv.length < 2 ? '0'+conv : conv );
  32.     }
  33.     return hex.join(' ');   
  34.   }
  35.  
  36.   function swapHexDec( e ){
  37.     var target;
  38.     if (!e) var e = window.event;
  39.     if (e.target) target = e.target
  40.     else if (e.srcElement) target = e.srcElement
  41.     if (target.nodeType === 3) target = target.parentNode;
  42.     var tmp = target.firstChild.nodeValue;
  43.     target.firstChild.nodeValue = target.getAttribute('hexdec');
  44.     target.setAttribute('hexdec', tmp);
  45.     if (target.className === 'hexdec')
  46.       target.className = 'dechex';
  47.     else
  48.       target.className = 'hexdec';
  49.   }
  50.  
  51.  
  52.   // if no node is specified then start processing on the page body
  53.   node = node || document.body;
  54.    
  55.   var skipRe = /^(script|style|textarea)$/i;
  56.   var re = /((?:[0-9A-Ha-h]{2}s*){6,})|((?:[0-9]{3}s*){6,})/g;
  57.   // get all nodes from dom
  58.   var nodes = node.all || node.getElementsByTagName('*');
  59.   var i, cnode, span;
  60.  
  61.   // loop thru all the nodes
  62.   for (i=0; i<nodes.length; i++) {
  63.     // skip if it has no child nodes, it's already processed or the tag is not valid
  64.     if (!nodes[i].childNodes.length ||
  65.       nodes[i].hasAttribute('hexdec') ||
  66.       skipRe.test(nodes[i].tagName)
  67.     )
  68.       continue;
  69.    
  70.     // loop thru all children
  71.     cnode = nodes[i].childNodes[0];
  72.     while (cnode) {
  73.       // we just care about text nodes
  74.       if (cnode.nodeType === 3) {
  75.         // loop thru all regex matches
  76.         while (m=re.exec(cnode.nodeValue)) {
  77.           // if there is text before the match add it on its own node
  78.           if (m.index > 0)
  79.             cnode.parentNode.insertBefore( 
  80.               document.createTextNode( cnode.nodeValue.substr(0, m.index) ), cnode
  81.             );
  82.           // create a new span node for the key string
  83.           span = document.createElement('SPAN');
  84.           // if the first capture parenthesis is found then it's in hex format
  85.           if (m[1]) {
  86.             span.className = 'hexdec';
  87.             span.setAttribute( 'hexdec', hex2dec(m[0]) );
  88.           // otherwise it is in decimal format
  89.           } else {
  90.             span.className = 'dechex';
  91.             span.setAttribute( 'hexdec', dec2hex(m[0]) );
  92.           }
  93.           span.setAttribute( 'title', 'Click to swap betwen hex and decimal notations' );
  94.           span.appendChild( document.createTextNode( m[0] ) );
  95.           //span.onclick = swapHexDec;
  96.           span.addEventListener( 'click', swapHexDec, true );
  97.           cnode.parentNode.insertBefore( span, cnode );
  98.          
  99.           // remove the already processed text from the node
  100.           cnode.nodeValue = cnode.nodeValue.substring( m.index + m[0].length );
  101.           // reset the regex text pointer
  102.           re.lastIndex = 0;
  103.         }
  104.       }
  105.       // point to next children or null
  106.       cnode = cnode.nextSibling;
  107.     }
  108.   }
  109. }
  110.  
  111. window.addEventListener( 'load', function () { HEXDEC() }, true );
  112.  
  113. function addGlobalStyle(css) {
  114.     var head, style;
  115.     head = document.getElementsByTagName('head')[0];
  116.     if (!head) { return; }
  117.     style = document.createElement('style');
  118.     style.type = 'text/css';
  119.     style.innerHTML = css;
  120.     head.appendChild(style);
  121. }
  122. addGlobalStyle( '\
  123.   .hexdec, .dechex { \
  124.     cursor: hand;\
  125.     cursor: pointer !important;\
  126.     border-bottom: 1px dotted #888;\
  127.     padding-left: 32px;\
  128.     background: url(http://pollinimini.net/hex.png) no-repeat left;\
  129.   }\n\
  130.   .dechex {\
  131.     background: url(http://pollinimini.net/dec.png) no-repeat left;\
  132.   }' );

By default the following sites are enabled (you can configure it for whatever sites you need):

  • http://www.satscreen.ws/forum/
  • http://floresd.blogspot.com/
  • http://galeon.com/tusflores/
  • https://www.blogger.com/

It uses a neutral blue coloring for the styling which shouldn’t break most web designs. The images are served from my own server, so they aren’t very reliable, don’t be afraid if one day they stop showing :)

Jun 11, 02:33 PM 1 comment

Quite so often a web developer starts thinking what’s wrong with the guys who make the rules of how Internet works. And if we dig a bit in the problem, we can many times see that the ‘non-sense’ is there not because the specs were flawed but because the popular implementations didn’t follow completely the spec.

The ‘non-sense’ I’ve been thinking about lately is why the hell we use the ampersand [&] to separate the arguments in a URL. My problem with using the & as separator is that in todays world of XML crazyness, the ampersand must be handled with care.
It seems that the specs said that any character could be used after the initial query char mark [?] but the [#] which marks the start of the fragment. In the current specs for URI/URL syntaxis they recommend the semicolon [;]

So the decision to choose the ampersand as the defacto standard was taken by the guys who took the lead with the CGI scripts and the dynamic web content generation.

Since the specs recommend the use of the semicolon I thought “ok, no problem, I’ll just use it from now on” with a grin in my face. If you are thinking the same keep reading because it’s not that easy. My server-side language of choice right now is PHP, so I build up a simple test script to check out if the semicolon worked ok, but it didn’t.
After consulting php.net for a bit more of information I found the solution, there are two ini directives which define the argument separators, one for input and the other for output (I guess this last one is used to manage the session id without cookies).

arg_separator.input and arg_separator.output are the names of the directives. The first one takes a string as argument and every char in that string becomes an argument separator, the second one defines what will PHP use when building URLs as separator.

The bad news is that the default value is just the ampersand [&]. The good news is that both directives can be defined per directory, so we can put them in our .htaccess in our shared hosts. If you control the host just edit the php.ini file. Logically we can’t modify them with ini_set() because the URI is already processed when our script starts execution (see below for a solution to this).


php_value arg_separator.input "&;"
php_value arg_separator.output ";"

Note that I left both: the ampersand [&] and the semicolor [;] as valid argument separators, I’m far too used to the ampersand and I don’t want to expend my whole life debugging an application just because I forgot that I decided that the semicolon was a better suit :)

Even if we can’t use the ini_set() function to modify the PHP behaviour for this, we can still make use of a different argument separator by processing the $_GET and $_REQUEST arrays and splitting them by our preffererd argument separator. The following code snippet show do it but please don’t use it in production environments, it’s probably flawed!

php:
  1. // first join the PHP splitted arguments
  2. $get = '';
  3. foreach ($_GET as $k=&gt;$v)
  4. {
  5.     $get.= $k . '=' . $v . ';';
  6.     // remove from the arrays, we'll add the correct ones later
  7.     unset($_GET[$k]);
  8.     unset($_REQUEST[$k]);
  9. }
  10.         // split the query string using our desired char
  11. $args = split(';', $get);
  12.         // process the query string and rebuild the _GET and _REQUEST array
  13. foreach ($args as $arg)
  14. {
  15.     // now separate the key from the value and assign them to the arrays
  16.     list($k,$v) = explode('=', $arg);
  17.     if (! empty($k))
  18.     {
  19.         $_GET[ $k ] = $v;
  20.         $_REQUEST[ $k ] = $v;
  21.     }
  22. }

Changing the argument separator does not only help out when working with XML based technologies but also to give your site URLs a geeky look ;)

Leo en arstechnica que el ejercito estadounidense ha aprovado un presupuesto de unos $450000 para desarrollar un sistema de análisis de blogs.

El proyecto en cuestión se hace llamar “Automated Ontologically-Based Link Analysis of International Web Logs for the Timely Discovery of Relevant and Credible Information”, que en castellano vendría a ser algo como “Análisis de enlaces automatizado basado en ontologías de los blogs internacionales para el rápido descubrimiento de información relevante y creíble”. Ahora entiendo como han conseguido la financiación, mi próximo proyecto también tendrá un título con subordinadas y mogollón de esdrújulas :)

La idea es que si analizan los blogs, basandose en los enlaces que contienen, pueden obtener la información más importante disponible en Internet. Aunque yo diría que lo más popular no es siempre lo más importante. Me imagino que lo que esperan encontrar son videos en Youtube o Goolge Video de talibanes con metralletas AK-47 medio oxidadas. Sin embargo, lo más probable es que los espias de la CIA se pasen el día partiendose la caja con el marketting viral.

Según los encargados del proyecto, el sistema será un gran éxito porque van a usar una técnica muy novedosa. La importancia de la información vendrá dada por el número de enlaces que haya hacia ella en los blogs.
Si alguien tiene unos cuantos cientos de miles de euros para invertir en otra tecnología novedosa, he inventado un nuevo sistema para compartir información, se trata de páginas web que son librebemente editables y que permiten crear nuevas páginas simplemente escribiendo dos palabras juntas. El nombre en clave para este proyecto es Wiki, pero no os preocupéis, que al final le pondré un nombre largo y confuso. ;)

Si no sabéis lo que son los MicroFormats podéis visitar su web oficial

En mi opinión suponen un paso atrás en la formalización del universo web. En la época del XML (xhtml, rss, soap, xul, xaml …) se empeña en prostituir los estándares con la excusa de que la tecnología no permite actualmente implementarlos de forma adecuada.

Mientras que yo estoy de acuerdo en que siempre hay que tener en cuenta los estándares de hecho (de facto) me choca que se promuevan, aunque sea de forma oficiosa, este tipo de pseudos-estándares.
Podríamos decir que HTML4 es ya agua pasada, pertenece a los 90 y ya estamos en el siglo XXI. Ahora tenemos XML y su especialización para el hipertexto web: XHTML.
El XML tiene ventajas e inconvenientes, pero si pensamos en algunas de sus ventajas: disponibilidad de cientos de herramientas para su manipulación (soporte de la industria), la multitud de estándares basados en él o su flexibilidad para ofrecer soluciones a un amplio abanico de problemas; las desventajas: su verbosidad o su complejidad para según que tareas; no creo que tengamos dudas sobre el gran paso adelante que supone esta tecnología para el intercambio de información en un entorno heterogéneo y distribuido por naturaleza como es Internet.

Lo que intento reflejar con este artículo es que los MicroFormats, tal y como han sido definidos, suponen un graso defecto de forma. El XHTML nos permite representar hipertexto, para lo cual pone a nuestra disposición un conjunto de etiquetas con una semántica definida. Si queremos representar una vCard en una web deberemos hacerlo basándonos en las reglas que define el XHTML, las cuales son simplemente semánticas en el contexto de la presentación de información

   Ejemplo en MicroFormat
   <div class="vcard">
    <a class="url fn" href="http://tantek.com/">Iván Montes</a>
    <div class="org">Netxus</div>
   </div>
   Ejemplo en XHTML 
   <div class="vcard">
    <h1><a href="http://netxus.es/">Iván Montes</a></h1>
    <p>Netxus</p>
   </div>

Este ejemplo es demasiado simple como para ser realmente obvio, sin embargo ya se puede observar lo siguiente:

  • Necesitamos recurrir al CSS para dar sentido al contenido
  • No hay forma estandarizada de validar la sintaxis
  • La sintaxis es simple pero no lo suficiente como para ser introducida de forma manual

Los MicroFormats en general, no nos aportan una gran ventaja respecto al uso de elementos XHTML de forma natural. Es más, sin la disponibilidad de la tecnología CSS ese contenido tiene aún menos sentido con el MicroFormat que sin él.

En definitiva, si la excusa es que hemos de adaptarnos a las tecnologías ampliamente soportadas, bien podríamos decir que actualmente cualquier sitio web es publicado con la ayuda de un CMS. Por lo tanto, todo este tipo de tareas pueden automatizarse y no supondría una barrera la verbosidad del XML y sus especializaciones.
Si realmente queremos homogeneizar el contenido para que sea accesible e ínter operable, no podemos publicar toda la información como text/xhtml, hay muchos tipos MIME que podemos usar y enlazar entre si. Solo necesitamos tomar el camino correcto y no el más fácil cuando diseñamos las aplicaciones de publicación, después de todo el propósito es que el contenido publicado pueda ser consultado por el mayor número de individuos, así que por que limitarnos con estándares o recomendaciones que solo permiten acceder al contenido a un tipo de visitante?