Monday, January 27, 2014

WTF-of-the-day: jQuery + iOS + click event

According to this discussion jQuery won't detect click events on iOS until a "pointer" cursor is applied to the clickable elements via CSS.


Saturday, January 4, 2014

CSS cursor property "not working"

If the CSS cursor property isn't working it might be not your fault.
Check instead whether you have opened your browser's developer tools, because when viewing the page with them switched on the cursor shown is always the default one.

This little issue had me scratch my head for some minutes with Chrome.

Monday, December 30, 2013

Da piccoli c'era la giornata degli alberi


La Sardegna, la mia e la tua terra, è la regione più inquinata d'Italia.
Non è più tempo di tentennare e dire l'ennesimo "non è colpa mia".
È colpa prima di tutto di noi Sardi che non abbiamo vigilato (o che, peggio, siamo stati spesso conniventi) e solo dopo è colpa di chi ci ha avvelenato con i suoi rifiuti, le sue scorie, il suo cemento, il suo amianto.
Ecco perchè tocca a noi iniziare il cambiamento. E dobbiamo iniziare da noi stessi, dal nostro popolo.
Solo dopo aver cambiato noi stessi potremo chiedere conto a chi ha approfittato della nostra incapacità di vigilare. E state tranquilli: sarà un conto salato.

Ma prima di questo, molto prima della giustizia delle aule di tribunale e delle Istituzioni, prima è necessario ristabilire la cultura dell'Ambiente e della sua salvaguardia, partendo fin dalle scuole per arrivare fino alle associazioni e passando, ovviamente, per la politica.
È necessario impartire a noi stessi, quotidianamente, la lezione del vero Ambientalismo, vale a dire quello delle piccole cose che noi tutti possiamo fare, ogni giorno. Quello che sfrutta i piccoli contributi di tutti per arrivare al risultato più grande.

È per questo necessario per ciascuno di noi imparare cosa sia il rispetto verso l'Ambiente e la Natura, in tutte le loro incarnazioni.
È necessario investire nelle economie Green: quelle vere, non quelle della speculazione e dell'opportunismo dei grandi interessi che tutto sono salvo che interessi dei Sardi e della Sardegna.

È necessario vigilare e insegnarci l'un l'altro quello che sappiamo: come si fa la raccolta differenziata, cosa fare con i propri rifiuti quando si è al mare, in montagna, nella propria tanca, Come comportarsi quando si ha in mano una sigaretta, una busta di plastica vuota, una lattina, l'olio esausto della propria automobile, persino come si cura un giardino.

È necessario diventare delle persone migliori per poterci meritare delle Istituzioni migliori, una terra migliore, un turismo migliore, un'economia migliore.
È necessario impegnarsi e fare impegnare gli altri.

Quando ci guarderemo indietro, quando avremo fatto questi piccoli passi e terminato questo grande viaggio sarà tutto diverso. E migliore. Noi Sardi per primi e la nostra Sardegna insieme a noi.

Thursday, October 17, 2013

Pulsarjs

Here's my new pet project: Pulsarjs.

I realized it to solve a simple problem: scheduling recurrent javascript functions can already be achieved with "setTimeout()/setInterval()" but this way the code becomes a mess very quickly.
Functions and the timers that schedule them get tossed around your code-base and self-imposed conventions aren't too much of an help.

Pulsarjs is a centralized organizer for your functions that stores them across restarts of your app, thanks to nedb.

I'm done implementing the main features of the module and some "getting-started" documentation. Next steps are intensive testing and more docs.

Pulsarjs is already listed as an NPM package.

Wednesday, July 17, 2013

Bagarino: what is it good for?

Tickets Have I ever told you about bagarino, a ticketing system I created?
Last time I wrote some code for it I added multi-CPU support to its existing nodejs-, expressjs-powered core.
It uses Redis as its backend store and sports some simple Javascript code I wrote during a few sleepless nights.

But, "what is it good for?"
Well, let's pretend you want to grant, secure and govern access to a certain content one of your users rented/bought/subscribed-to/won on your system (e.g. a game item, or a picture, an illustration, a book or even an entire movie hosted on a CDN).

You may need to establish how many times (or how long) that good can be accessed by that user.
You may also need to enforce these rules in a simple, predictable manner.

Unique, alphanumerical, tickets that "mark" your content come to the rescue.
And bagarino allows you to manage them using different policies that establish when exactly a ticket expires.
Some of these policies are as simple as time-based counters. Some of them are a bit more complicated (but not too much, don't worry).

Give it a try and let me know.

... By the way, after "what is it good for?" I hope you didn't jump right to the "absolutely nothing" line ;-)


Photo courtesy of Sam Howzit

Saturday, April 20, 2013

RIP. Di sicuro.

Con Bersani si chiude l'era delle buone intenzioni condite da nessuna azione. A volte persino da azioni stupidamente e volutamente cattive ed autolesioniste.
Di sicuro si chiude un ciclo disastroso per il PD, un partito ormai in cenere.
Un partito che avrebbe dovuto "salvare" l'Italia e che invece ha contribuito in maniera preponderante all'immobilità che ci sta oggi condannando.
Di sicuro per il PD non c'è un futuro in Renzi, nè nell'attuale dirigenza.
Di sicuro l'unico partito italiano che non aveva intenti palesemente truffaldini (ma che in compenso aveva cento altri difetti) è da reinventare totalmente, da zero.

Di sicuro chi oggi sorride felice delle disavventure del PD non ha ben capito che, insieme al PD, ieri è stata anche la Democrazia italiana a subire l'ennesimo, disastroso colpo.
Chi oggi ride felice delle disavventure di Bersani e di Prodi è peggio di quel furbacchione di Renzi che ieri avrà pure guadagnato un partito, ma di sicuro ha perso un altro pezzo di Paese.
Chi oggi ride felice neppure immagina che ha contribuito ad arrecare altri terribili danni al Paese.


Nel bene, ma soprattutto nel male, il PD si è dimostrato uno specchio impietoso e quantomai accurato dei peggiori mali e difetti dell'Italia tutta.


RIP PD. RIP Italia.

Wednesday, February 13, 2013

Dreams of the perfect habitat

The product I've always dreamed on realizing came true thanks to Inkling Habitat.
And you still don't know the best part: they are also making it public!

Habitat is a digital publishing platform based on standards and hosted on the cloud.
Starting Tuesday (today n.d.r) they are releasing it for public access.
They are proposing legacy contents import, the possibility of a full Google indexing of the books created with their platform, the ability to export as EPUB and a bunch of big names of the industry as their partners (O'Reilly, Pearson, Time Inc. and Lonely Planet, just to name a few).

I'm both sad and happy about it: sad because I was starting to design a similar solution; happy because now I know I took the right path in designing it. It's the path of open-standards and the path of the better web.


It's like Inkling is really creating a completely new habitat for digital publishing, by simply using the foundations of the World Wide Web (HTML and its complimentary technologies) and finally detaching the digital publishing from the old, paper-based, publishing industry (that's still only able to mimic the paper magazines on an electronic device and propose them as "the future").

Well, Inkling, with Habitat, built that digital publishing of the future and they did it powerful, standards-based, open and beautiful.

They didn't kill paper. They simply extended it until it reached the web and the mobile world.

Wednesday, December 5, 2012

Ignore single-tap before double-tap on Windows 8 apps


The new development platform for Windows 8 has been released too early. The number of dirty tricks I had to resort to in just a few months working with it made it pretty clear to me.

One of the most infamous bugs I found affects all the versions of the platform (x86, x64 and ARM) and it's an erroneous sequence of events that is propagated after a double-tap. I found it propagating from a ScrollViewer control, but I'm pretty sure other controls may behave this way as well.

When a user double-tapped on the screen I was expecting a single call to my double-tap event handler to be made, but with a bit of sadness a single-tap event was called immediately before it... with no fucking reason, if you ask me.
My code needs to be certain about which one of the two is called, because I need to react in two different, alternative ways to them. So I was stuck, trying to find a clever way to figure out when a single tap erroneously fired by the framework. And obviously when it's not.

With the help of my collegues we found a really simplicistic way of dealing with it, but it's actually a trick that mitigates the issue, not a definitive cure.

Here it is:

// Here's the part I hate the most: heuristics...
private const int DOUBLETAP_DELAY_MILLIS = 190;

private DateTime singleTapTime;
private bool singleTapCancelled;

private async void scrollViewer_Tapped(object sender,
                           TappedRoutedEventArgs args)
{
    // Save the moment the single tap
    // has been detected...
    this.singleTapTime = DateTime.Now;

    // ... but wait some time to be sure
    // that no double-tap event follows
    await Task.Delay(Viewer.DOUBLETAP_DELAY_MILLIS + 10);

    // A double-tap event will cancel our single- one 
    // before we reach this point...
    if (!this.singleTapCancelled)
    {
        // ...
    }

    this.singleTapCancelled = false;
}

private void scrollViewer_DoubleTapped(object sender,
                     DoubleTappedRoutedEventArgs args)
{
    TimeSpan tapsDelay =
        DateTime.Now - this.singleTapTime;

    // If we are between the configured timespan,
    // we cancel the previously fired single-tap event
    this.singleTapCancelled = (tapsDelay <= TimeSpan.FromMilliseconds(Viewer.DOUBLETAP_DELAY_MILLIS));

    // ...
}


An improvement would be protecting the boolean variable with a lock.
Also would be better to be tolerant on the number of milliseconds we wait. E.g. we could wait Viewer.DOUBLETAP_DELAY_MILLIS +/- some time.

But the only improvement should be done by Microsoft I guess...

Thursday, November 15, 2012

Dead On Arrival


Riassumendo cosa ne penso, vorrei mettere una pietra tombale sui miei commenti alle recenti vicende del Movimento 5 Stelle e del suo lider maximo.
Procedo.

Il Movimento 5 Stelle mi è sempre stato più che simpatico ma ultimamente lo vedo purtroppo ostaggio di un vecchietto con le solite manie di potere e dei suoi scaltri amici.
Mi spiace per tutte quelle persone che ci hanno creduto (e continuano a crederci), che gli hanno dato l'anima e il proprio impegno, che lo hanno sostenuto, accolto o anche solo ascoltato (oggigiorno non è poco).
Ma la sostanza è che Grillo sta rovinando una speranza di rinnovamento (il M5S) come ce n'erano state veramente poche finora.

Ideali splendidi e pessima sostanza dietro. Connubio forse nato sano, ma arrivato già morto al pronto soccorso della "Democrazia dal basso".


[Photo courtesy of Wikimedia http://en.wikipedia.org/wiki/File:Dissent_develops_democracy_sticker.jpg [Which in turn credits Jason Wilson http://www.flickr.com/people/hive/ ]]

Thursday, August 9, 2012

A tale of two twins

"Once upon a time an unfortunate poor design decision in Windows Metro class library had two brave classes named the same: "Uri".
One of them lived in the village of "System" while the other had a gracious hut in the "Windows.Foundation" hood."

Wait! What?!?
Does it mean that there are two different classes both named "Uri" classes in two basic namespaces?

Do I look like one old mage that goes around mumbling some non-sense fairy-tale? No; hence this is exactly what I meant: two classes, same name, same job, two different basic namespaces, both have an one-argument constructor with the same parameter type (string).

No need to say that you'll eventually end up using System.Uri instead of Windows.Foundation.Uri or viceversa (like I did).
And you can trust this old man when I say that you will ("Metro-style .NET application"... does it ring any bell?).

Now, this wouldn't be such a big issue and I will be no putting such a scene up since they are in two different namespaces.
After all namespaces are supposed to be born in this era to support exactly this behavior.
At least to support classes named the same way but that perform different tasks.
But that's not the case: the do exactly the same things.


Well, the story has a happy ending, you know: you end up on this post, know that the world is full of tricky tricks in the shape of class named the same and you return to your code sound and safe.

But I'd like to add an epilogue.
Please, dear Microsoft architect, consider the following two options:

  • Either provide ONLY ONE class to perform the same job
  • Or provide ONLY ONE class to perform the very same job
Choose one.
The End

Tuesday, August 7, 2012

Migliori e peggiori


Ma lasciarlo in pace Schwazer, no? Ha sbagliato, è distrutto e sicuramente la pagherà molto più cara di tanti degli ipocriti che fanno come lui ogni giorno (in tanti ambiti diversi) e la fanno invariabilmente franca.
Gli stessi che adesso lo condannano senza se e senza ma.

Se mai leggerà questo messaggio: "Da oggi cerca di essere solo migliore di te stesso. Non degli altri."


P.S. Il Codacons, nella persona del suo presidente Carlo Rienzi, si infili la sua causa legale su per quel culo flaccido che non pensa mai a denunciare chi davvero denigra e fa sfigurare l'Italia.

Tuesday, July 31, 2012

E' il mercato, baby

Ai millantatori che scrivono che sviluppare su Android rende meno... faccio umilmente notare che siete a corto di cose interessanti da dire che non siano già state dette da almeno 2 anni e, per vostra sfortuna, già estese a tutte le piattaforme Store-based.
In soldoni: o le vostre apps sono basate sull'in-app purchase o rischiano fortemente di finire nel gruppone di quelli che non rientrano nemmeno dalle spese di sviluppo e marketing.
Questo vale per tutti.

Si chiama Mercato, e non ti chiede se sei figo o nerd. Lui ti schiaccia, ti mastica e ti risputa. E dopo ti schiaccia di nuovo. Non ti rimastica perchè è schizzinoso.

Ah... e non lo dico solo io:
http://arstechnica.com/apple/2012/05/ios-app-success-is-a-lottery-and-60-of-developers-dont-break-even/

Thursday, February 16, 2012

Youtube Remote

La "nuova" GoogleTV che in questi giorni in molti hanno atteso potrebbe essere stata anticipata, e purtroppo ignorata, già da un pò.
Esiste infatti qualcosa che già oggi può trasformare qualsiasi apparecchiatura dotata di browser e uscita video in una Internet TV.
Si tratta di Youtube Remote, un applicativo che promette di portare una GoogleTV o, meglio, una "YoutubeTV" dentro le nostre case.
Oggi.
E senza che sia necessario acquistare nuovo hardware.

Basta collegare il proprio pc/portatile alla TV, aprire un browser e andare alla seguente pagina: http://www.youtube.com/leanback



Usando il vostro tablet Android potete procedere a fare il pairing tra quest'ultimo e la pagina "leanback".
Sul mio tablet il pairing ha richiesto 1 minuto (grazie a Google Goggles).

Dopo questo, utilizzare il tablet per comandare a distanza la mia "nuova" TV è stato semplice:




Il messaggio che passa è piacere digitale allo stato puro:
  1. Ho in casa un prodotto nuovo e innovativo, che non sapevo di avere
  2. I contenuti disponibili sono... ehm, parecchi. E Youtube non ha certo problemi a proporne di nuovi ogni giorno/ora/minuto
  3. Il tablet o lo smartphone Android permettono un controllo remoto completo ed evoluto

Dal punto di vista dello sviluppatore sono poi rimasto favorevolmente colpito dall'intelligente mix di tecnologie pre-esistenti e standard,
cosa che implica che un qualsiasi hardware (anche di basso profilo) potrebbe offrire la medesima esperienza, preconfezionata in un set-top box a basso prezzo e di facile realizzazione.

Riassumendo questa analisi possiamo porci la domanda "Perchè è una buona idea Youtube Remote?" e (marzullamente) risponderci:
  • Di sicuro perchè non ha bisogno di nuovo hardware: nella maggior parte delle nostre case sono già presenti un PC e uno smartphone/tablet
  • Qualora così non fosse i produttori di hardware non dovranno realizzare dispositivi costosi e complicati, nè implementare nuovi standard, ma solo un set-top box contenente un browser di buona qualità e poco altro
  • Non dover installare niente sul PC (nemmeno un'estensione del browser!)... non ha prezzo.

Fatemi sapere cosa ne pensate.

Monday, February 6, 2012

Illustrazione per far riflettere

Causa poco tempo a disposizione vi lascio l'idea, se ci fossero illustratori disposti ad usarla:
Una serie di strati geologici mostra al suo interno alcuni scheletri umani sedimentati accanto a uno o più strumenti teconlogici odierni (pensavo a un tablet e a un'automobile).
Dall'alto, fuori campo, in contrasto con l'aridità e il grigio delle rocce sedimentate e degli scheletri al loro interno, scendono uno o più rampicanti con fiori dai colori sgargianti, ma "diversi" dai fiori odierni (avevo pensato di realizzare un fiore con dei denti bianchi al centro).
I rampicanti fanno ombra agli strati, ma li lasciano scoperti abbastanza da lasciar intravvedere sia le ossa che i manufatti tecnologici.

La scritta, al di sotto, è breve e in un font essenziale (stile Arial):
Our planet will last long. Will we?
In grassetto la frase "Will we?".

L'immagine deve avere caratteristiche di fotorealismo spinto tali che mi hanno fatto desistere dal proposito di realizzarla con software tipo Illustrator/Inkscape.

L'ideale sarebbe partire da foto vere, da ritoccare con Photoshop/Gimp.

Se qualcuno fosse in possesso di queste foto potrei anche trovare il tempo di realizzare l'illustrazione.

Altrimenti beccatevi l'idea e, se vi piace, sfruttatela e fatemi sapere :-)
Simple as it is:
The earth will survive pollution, global warming and so on.
We won't.

Wednesday, January 25, 2012

AI. At least.

Last night I had time to focus my thoughts on a topic somewhat forgotten nowadays: Artificial Intelligence.

I found myself more and more concerned about not being literally surrounded by AIs that help and assist us on doing all sort of everyday tasks.
If you ask I would have expected for the AIs to be a constant and common presence at least in technology-related areas of the society such as IT, energy companies, transportation and military, healthcare, banks and trading, education and... well, almost everywere an AI with just a grain of intelligence could automate, manage and help men perform complex and/or repetitive tasks.
At least.

What we got instead? Zero-intelligence systems that would be dead after 5 minutes without a man supervising and managing them.
Even worse: systems that put man as the main information-processing unit.
I.e. applications that beautifully display bars, pies and reports that will be read, judged (and finally forgotten) by a human that will then formulate one or more possible actions to take as a consequence of those data.
Let alone the possibility to completely erase the human from that process, why not at least let the AI analyze the data and formulate possible scenarios to be judged by a human?

And what about an AI that asks me which author I'd like to read these month and then begins fetching data, ordering the books, paying them using my credit card, waiting for them to be shipped (eventually triggering an alert to me and/or the shipping AI in case the delivery is taking too much time) and putting together a brief introduction to that author so I could then enjoy a more complete experience from reading his/her books?

I don't feel like fearing (much) more intelligent systems as dangerous nor I think pleople would lose their jobs to an AI.
Nor man will get any lazy than he actually is...
Simply there would be more people doing different jobs that need no automation but a great amount of creativity instead.
By the way I think mankind may actually benefit of such a shift from automation to creation.

But aside from that there is a fact that bothers me: the technology for these kind of intelligent systems was ready a long time ago (let's see months and years from the technology perspective). I mean, we have multi-core processing since the early 1990s and AIs are one of the most ancient and studied topics of the Computer Science. We now have cloud-computing for exploiting even more computational power and we sure as hell don't lack minds that can design these Everyday AIs.

Thus I'm utterly disappointed that we still lack them.
They would make life easier and let people focus their lives on more meaningful activities (living their life above all...).
But I'm disappointed that I can't comprehend why they are not here yet.
I also thought of giving my contribute but it would seem that people and market are simply "not interested" in it.
Did I missed something? Am I drawing a wrong scenario when reality is much more promising instead?
Are we already there and I didn't notice?

I'll send a link to the new Megaupload to the first ones who answer my questions.

Thursday, December 1, 2011

Integrating HTML5 and UPnP

I posted a really good link I found about integrating HTML5 and UPnP:
https://plus.google.com/u/0/112160333465217123290/posts/EKYW1wh8Wwd

Altough it seems still a bit rough this is a good idea.
If interested leave comments here or on my Google+ account.
I'm definitely studying it and I hope it will evolve and be implemented.

Monday, November 7, 2011

Vala compile error: cannot infer generic type argument for type parameter `GLib.Thread.create.T'

Today I tried to work with Vala and threads.
Turned out that documentation, even the official sources, is still sketchy and young.
E.g. I tried to build the following, taken from here:
void* thread_func()
{
    stdout.printf("Thread running.\n");
    return null;
}

int main(string[] args)
{
    if (!Thread.supported())
    {
        stderr.printf("Cannot run without threads.\n");
        return 1;
    }

    try
    {
        Thread.create(thread_func, false);
    }
    catch (ThreadError exc)
    {
        return 1;
    }  

    return 0;
}
It will give up compiling with the following error:
$ valac --thread main.vala
 main.vala:19.9-19.21: error:
 cannot infer generic type argument
  for type parameter `GLib.Thread.create.T'
        Thread.create(thread_func, false);
        ^^^^^^^^^^^^^
 Compilation failed: 1 error(s), 0 warning(s) 
The compiler does complain about an actual lack in my code. Infact the declaration of "Thread.create()" is:
Thread<T> create<T>(ThreadFunc<T> func, bool joinable)
The culprit is the generic type "T" to be passed to the create method.

But the type of what I need to provide?
Thread.create<?>(thread_func, false)
It's the return type of the thread function "thread_func" passed as the first parameter to the create method.
Hence I need to call it this way instead:
Thread.create<void*>(thread_func, false)
In the case thread_func had returned bool:
Thread.create<bool>(thread_func, false)
And so on.

Here's the incomplete documentation for the create method that led me to the initial impasse.
Here is where I found the solution (thanks to Abderrahim Kitouni) instead.
Yeah, a bit of Googling helped me as well.

Tuesday, October 4, 2011

MAC to IP address resolution

Today I couldn't find a way to resolve an host's IP starting from its MAC address, without using RARP (which isn't supported by some kernels ("This kernel does not support RARP"...)).
The solution I came up with is the following: given that two hosts already "know" (i.e. pinged) each other at least once you can perform the command
ping `arp -n | grep -i 00:17:C8:3B:81:94 | grep -o -E "\b[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\b"`

The only issue here is that the two hosts MUST have already "met" at least once.
This is because of the kernel ARP cache used by the "arp" command.

Useful?

Friday, September 30, 2011

Suppress "unused parameter" warnings

Here's a way to suppress the annoying "unused parameter" warning given by the following code:
void aFunction(int unusedParameter)
{
    // Do something but ignore the 'unusedParameter'
}

I use this define:
#define CHECKED_UNUSED(x) (void)x

And then I surround unused parameter with it, right after the opening bracket of the function (so I can easy find and modify the parameter if I start using it):
#define CHECKED_UNUSED(x) (void)x

void aFunction(int unusedParameter)
{
    CHECKED_UNUSED(unusedParameter);
}


I looked at the generated assembly before and after and it didn't change:
                  aFunction(int):
00000000004007d4:   push %rbp
00000000004007d5:   mov %rsp,%rbp
00000000004007d8:   mov %edi,-0x4(%rbp)
15                }
00000000004007db:   pop %rbp
00000000004007dc:   retq
18                {


Disclaimer: use it only after you carefully checked that you really not need to use that parameter.
Unused parameters (and all the warnings in general) could really lead to a bug (or simple misunderstandings) in your code.