My JavaScript book is out! Don't miss the opportunity to upgrade your beginner or average dev skills.

Thursday, March 22, 2007

PHP 5 static keyword feature - Part 2

To explain better what did I mean when I talked about static keyword problems, here is some code examples (same result with different languages)

C# (Console Application)

using System;
namespace ConsoleApplication1{

public class StaticString{
private String str;
public StaticString(String str){
this.str = str;
}
public String getString(){
return str;
}
public void write(){
str += " from instance";
StaticString.write(this);
}
public static void write(StaticString what){
Console.WriteLine(what.getString());
}

}

class Program{
static void Main(string[] args){
StaticString ss = new StaticString("Hello World!");
StaticString.write(ss); // I have a static method to do something
ss.write(); // and an instance method to do something else
Console.ReadLine();
}
}
}


ActionScript 2.0

class StaticString { // StaticString.as

// generic public instance method
public function getString(Void):String {
return str;
}

// generic public class static method (correctly not inherited)
public static function write(what:StaticString):Void {
trace(what.getString());
}

/*
// AS 2.0 doesn't accept methods overload
// ... however, this is not a method overload
// this should be an instance method (not a class method)
public function write(Void):Void {
StaticString.write(this);
}
// */

// You could solve this problem ... how ?
// Using a sort of bug (lol)

public var str:String;

// public constructor
public function StaticString(str:String) {
this.str = str;

// AS 2 "bug"
this["write"] = function(Void):Void{
StaticString.write(this);
}
}
}
/* // Test them!
import StaticString
var ss:StaticString = new StaticString('Hello World!');
StaticString.write(ss);
ss["write"]();
// */


JavaScript (!!!)

function StaticString(str){
this.getString = function(){
return str;
};
this.write = function(){
str += " from instance";
StaticString.write(this);
};
if(!StaticString.write)
StaticString.write = function(StaticString){
alert(StaticString.getString())
};
}(new StaticString);

ss = new StaticString("Hello World!");
StaticString.write(ss);
ss.write();


And finally ... what I was doing with PHP before the feature

class StaticString{
private $str;
public final function __construct($str){
$this->str = $str;
}
public final function __call($method, $values){
switch($method) {
case 'write':
$this->str .= ' from instance';
StaticString::write($this);
break;
}
}
public function getString(){
return $this->str;
}
public static function write(StaticString $what){
echo $what->getString(), '<br />';
}
}

$ss = new StaticString("Hello World!");
StaticString::write($ss);
$ss->write(); // Catchable fatal error:
// Argument 1 passed to StaticString::write() must be an instance of StaticString
// none given (hey PHP, I didn't call static class method !)


C++ should be able to do the same thing using overload as C# example.
Instances will inherit static method too but this will not be a problem.

Probably Java and many other languages can do something like these example ... while with PHP You can't.

I don't know about Python overload and specific problem solution, I think Python will have a solution.

Finally, this limit is efficent and simple way to code ... as PHP 5 developers said ... come on guys, I like very much PHP since version 4, but if You implement something, please, do it correctly!

PHP 5 developers teach us what does static keyword mean (and this is a feature!)

PHP 5 introduced a "new" keyword called static.
You can read here what does this keyword mean when it's applied to one method.

As You can read in documentation page
Declaring class members or methods as static makes them accessible without needing an instantiation of the class. A member declared as static can not be accessed with an instantiated class object (though a static method can).

They put last tiny point inside brackets as it's not a really important point to analize!

As You know, with PHP4 every method should be used as static one.
The difference between PHP 4 and PHP 5 seems to be this one:
The big difference between php 4 and php 5 is that a method declared as "static" does not have $this set. You'll get a fatal error, in fact, if you try to use $this in a static method.

Well ... static method cannot have a $this reference inside its scope but every static method is inherited into every instance ... this is absolutely hilarious:

  1. You can't call with the same name two different methods (one static, for class and one metod for instances)

  2. You can't overload manually instance method

  3. Static methods are inherited while static parameters cannot be used from instances

  4. You can't use $this reference even if You're calling method from an instance (wow, it's really OO)



To solve PHP 5 static method logic You have to forget static keyword.

class StaticString {
private $content = '';
function __construct($content){
$this->content = $content;
}
// I need different methods, not static one inherited!!!
function write($what = null){
echo func_num_args() === 0 ? $this->content : $what->get(), '
';
}
function get() {
return $this->content;
}
}

StaticString::write(new StaticString('static'));
$test = new StaticString('instance');
$test->write();

The above example shows You how to "solve" static inheritance problems, based on sent arguments (then it's a fake method overload) but shows obviously an E_STRICT notice.

So, at this point, we need a workaround to make a language feature "less buggy and more featurely" ... but static keyword shouldn't be implemented if the diference is only that you can't use instance reference inside one of these method.

This is another example, based on Singleton pattern:

class Singleton {

static private $instance;
static private $init = false;

public final static function instance(){
if(!Singleton::$init) {
Singleton::$instance = new Singleton();
Singleton::$init = true;
}
return Singleton::$instance;
}
}

$test = Singleton::instance();
var_dump($test->instance() === $test);

WoW! ... my Singleton instance inherits Singleton pattern, it's amazing!

Obviously, C# and other program languages doesn't assign static class methods into instances ... and the reason is:
If you are wanting absolutely "perfect" OO, there are plenty of other languages that will provide exactly the straightjacket and punishment you desire. If you want to code efficient, easy to maintain, working programs, use PHP.

To code efficient, easy to mantain I need a clear Object Oriented logic ... and if You're thinking about C++ there's a little difference ...

C++ instances inherit static methods and static parameters too but the big difference is that if you don't declare a class method as static, You can't use them as static method (and You can't use parameters too).

static method and public (instance) one are two different things (as you know) ... but hey, cellog gives me a fantastic, "pure OO way", example to solve my debug problem

class ExampleClass {

public $StaticExample;

public final function __construct(){
// bye bye public *parameter*
$this->StaticExample = create_function('$never', 'return "welcome PHP5
ambiguity";');
}

public final static function StaticExample(){
echo "StaticExample", "<br />";
}
}

$test = new ExampleClass();
ExampleClass::StaticExample();
exit($test->StaticExample());

That's not portable, not scalable ... absolutely a bad solution ... but it could be simply solved with this code

call_user_func_array(get_class($a), 'method', $args);

And "WoW" again! .. that's what I call OOP!!!

Thank you PHP 5 developers to introduce static methods, I hope PHP 6 will be more Object Oriented and less ambiguous than version 5.

Best regards!

[edit]
This is my bug report ... pardòn, bogus report:
http://bugs.php.net/bug.php?id=40886

Tuesday, March 20, 2007

for in loop prototype safe

In many different libraries there should be one or more prototype method for every native JavaScript constructor.

Every time You do a for in loop
for(var key in object) ...

You probably need to check object[key].

Add prototype to Object constructor is never a good practices, but for in loop can be used with other native constructors too, as example, Array.


Array.prototype.randomValue = function(){
return this[Math.floor(Math.random() * this.length)];
};

var myArray = [1, 2, 3];
alert(myArray.randomValue()); // 1 or 2 or 3


The common way to loop over an array is a loop that uses index integer values but sometime You should need to loop over a generic variable just using a for in loop.


for(var key in myArray) {
// dostuff
}

In this case the "randomValue" key is part of loop but You can't know everytime wich library add its Array prototype so this is my simple proposal, the $for function.

function $for(obj, callback){
var proto = obj.constructor.prototype,
h = obj.hasOwnProperty, key;
for(key in obj) {
if((h && h.call(obj,key)) || proto[key] !== obj[key])
callback(key, obj[key]);
}
};

With these few lines of code You can perform a for in loop without prototype problems, for example:

var myArray = [1, 2, 3],
total = 0;
$for(myArray, function(key, value){
total += value;
});
alert(total);

Used function is automatically cached by $for one so I think this kind of loop will be fast enought (expecially working with internal scope).

Do You like this prototype safe solution? I hope so :)

Wednesday, March 14, 2007

Ultra Zipped Bitmap - a new (un)probable image standard?

Microsoft is working on a new image format, called HD.

It seems to be better than standard JPEG format but it's not a loosequality format.

I've done some strange and stupid test to find a way to obtain the better quality/size effort for an image, and this is the result: uzb image ... what's that? :D

It's quite a joke but it should be a proposal for FireFox, Opera or other browser plugin (is it ridiculous?)

The original uzb image format is Bitmap, that's a looseless image type but it's an "old" format and generated size is amazing.

But, for example, this is an 885 Kbytes ... how many bytes do You think I removed?

Exactly 829,1 Kbytes for a final result of 55,9 Kbytes!!!

This "incredible" final size was obtained using fantastic LZMA compression Algorithm and this size si even better than every png and, as png format, is looseless!

This is what i think about uzb:

Features
- looseless
- extremely fast decompression
- best quality/size ratio


Problems
- slow encoding
- final client "realtime" unpacked size (cache or ram) is probably too much big
- no alpha channel (as JPEG)


You can test by yourself (only for Windows users) decoding speed unpacking in a folder this zip file.
After that You just need to click twice on decode.bat file.

Isn't Wonderful?

If, for some reason, You loose packed file You can get them directly from this link.

The coolest thing is that You're testing a big image that's not "perfect" for your web site, so think about a generic header image like this one, the BitBox header gif image (11,5 Kb), that should be served in 10,3 Kb or another image like this one (216,45 Kb), that should be served in 115 Kb.

Ok guys, it's only a joke :D and packed size is not alawys better than png but quality is always better than JPG, bye!

Tuesday, March 13, 2007

function or var function ? part #2

I did an error talking about difference using function, var function and (function), because as Matteo said in my last post I didn't explain perfeclty the difference from an anonymous function and a simple reference variable.

Here You can view an example, probably better than every word:

var // temporary scope variable declaration

myfunc // variable name (as function referer)

=

function(){}; // anonymous function


alert(myfunc.name);
// empty string because myfunc
// is a reference of an
// anonymous function


// ---------------------------- //



function // temporary scope function declaration

myotherfunc(){};// "the" myotherfunc function


alert(myotherfunc.name);
// string "myotherfunc" because
// myotherfunc is not a reference
// but exactly a function


So, an anonymous function has some limit, as I said on my old post but if You need a simple, tiny function that you're not using as class, You could declare anonymous function even inside a for loop

for(var f = function(){}, a = [1,2,3], b = a.length; b > 0; b--)
// do stuff

but if You need a class or a more complex function I suggest to use the "old classic" way:


function f(){
// do stuff
}


That's all, You should remember that first example doesn't work, obviously, on Explorer, try them with other standard compilant browser (FireFox, Opera, Safari, Konqueror ... etc)

Unobtrusive Blog Entry Date

I really like this Brainstorms Raves blog CSS based entry date tutorial but I like unobtrusive content and graceful enanchemet too :)

That's why I created a simple example page to show You how to create a better unobtrusive example, using less tags on page and a bit of JavaScript for compatible browsers (I suppose every recent browser should support that code).

You could view directly CSS or JavaScript source code, do You like it?

Thursday, March 08, 2007

Five (better) Javascript Tools Someone Should Have ...

Sometimes there's a JavaScripter that "teach us" wich function should be on our Top Ten function list.

My first disappointment is that if You use a good library, such jQuery, Dojo, !YUI or MooTools You'll never need these functions because these library probably will have better or more powerful implementation.
However, if You absolutely need a "Top Ten" I think it should be created using best version of each function or prototype (write once and forget them).

Please Read JS manual and Respect Standards
This is a common javascripter error, he probably doesn't know well each official method so he thinks we need its code implementation.

For example the common find Array prototype is, at least in my opinion, a big error because JavaScript 1.5 has its dedicated standard function to do the same thing.

We don't need another prototype to do exactly the same thing of standard function, but if we need a different version we should create a little perfect function, don't You agree with me?

Array.prototype.find = function(re){
var result=[],i=this.length;
while(i--) {
if(re&&re.constructor===RegExp&&re.test(this[i]))
result.push(i);
else if(this[i]===re)
result.push(i);
};
return result.length?result.reverse():false;
};

This function works inline too (less spaces) but please remember (always) to check if another library has its own implementation.

if(![].find)Array.prototype.find = function(){
// ...
}

This is an OpenAjax "compilant way" to make your code unobtrusive and compatible with other libraries too.

The second standard You should respect is method map and any version I've seen respect correctly standard version.
This is a tiny optimized function that should respect them:

Array.prototype.map = function(callback){
for(var i=0,j=this.length,result=new Array(j),self=arguments[1],u;i<j;i++){
if(this[i]!==u)result[i]=callback.call(self,this[i],i,this);
};return result
};

Directly from my ByteFW (Byte Framework) Array normalizer.

So, if we just have some standard method why we should use another not standard version with another name?
In this case a standard compilat browser will work in core (fastest way) while other uncompilant browsers will have, I hope, a method like that so "tomorrow" You'll just delete this function from your Top Ten.


Optimize code and take care about its size
Another example should be a generic formatNumber function, that doesn't require to be complex because it should be just this one:
function formatNumber(num, pref){
function r(s){return(''+s).split('').reverse().join('')};
return(pref||'')+r(r(num).replace(/^(\d+\.)?(\d+)$/,function(num,d,i){return d+i.replace(/(\d{3})/g,'$1,').replace(/,$/,'')}));
};


This function should be more short, more simple and probably more fast than other function You could find over the net ... as, for example, this should be a better and more compact way to know if a variable is an Array and not an Object ...

function isArray(testObject){return testObject&&testObject.constructor===Array};


Wow, "just two checks" ... but it's obvious guy, constructor is there from 5 years or more ...



Make your common function "more realistic"
If You need for example a prototype called htmlEntities why You should create a "specialChar like" proto?

Html Entities should parse every html char and not just ['&', '<', '>'] that aren't all possible htmlentitties.

This is for example a better htmlEntities implementation, or probably a real htmlEntities and not a fake htmlspecialchar ...

String.prototype.htmlEntities = function(){
return this.replace(/[^\x09\x0A\x0D\x20-\x7F]|[\x21-\x2F]|[\x3A-\x40]|[\x5B-\x60]/g,function(e){return '&#'+e.charCodeAt(0)+';'});
};


Choose correctly your "teacher"
He, he ... it's just a joke and I'm absolutely not a teacher but if You want to learn something about JavaScript, please visit Mozilla Developer Center and after that, read code from good libraries "powered by" good developers (jQuery, Dojo, YUI!, others ....
After that Yuo'll never look for a Top Ten "but it's Top Fifteen or Top Twenty" JavaScript post because You'll be able to create them by yourself.

That's all ;-)

Tuesday, March 06, 2007

Working on Byte Framework ...

Byte What?
He he :-)
.... I'm working on a framework that will include every interesting personal experiment such bytefx, byteson, bytedom and many others as JSL, Astar for game development, something from JHP, some component, some JS/Canvas/Flash interaction like PixelFont and more and more ... that's why this framework will be probably ready at the end of 2007, at least I hope because as You know, time is never enought.

This post is only a preview of my work in progress and it includes:


... and a work in progress documentation page.

Finally, these are some interesting features about this project:

  • Compatible with IE 5 or greater

  • full compatibility with IE 5.5 or greater

  • better FX implementation

  • clear source code, parsed and cached directly with my GzOutput class

  • cross-browser and quality code for a fast framework

  • unobtrusive single namespace, compatible with every other library

  • OpenAjax ready



I hope this project will be interesting but now, I know, it's only a pre alpha release so please stay tuned :-)

Monday, March 05, 2007

[IT] Italia - Finalmente i conti tornano - Atto Secondo

Ancora sul portale del turismo?
Assolutamente no, semplicemente una ulteriore riflessione sulle competenze generali in ambito informatico e nello specifico Web di questo bel paese.

Solo oggi scopro la notizia delle Olimpiadi Informatiche e per la prima volta mi ritrovo nel sito dell'evento.

Mentre tutto il mondo parla di Web 2.0 in Italia la situazione è da Web 0.0.1 Alpha.

Se le potenzialità tecniche e teoriche dei cervelli italiani sono riconosciute a livello internazionale come di altissimo livello quelle inerenti la progettazione Web farebbero rabbrividire anche i paesi che si sono affacciati alla New Economy solo da un paio di giorni.


  • nessuna dichiarazione del tipo di documento, non sappiamo nemmeno cosa sia il DocType

  • utilizzo preistorico di più frame per un sito graficamente discutibile

  • utilizzo di applicativi degni di un webmaster al primo giorno di studi (sito realizzato con Microsoft FrontPage 5.0)

  • tabelle ed orrori tipici di questi software da principiante amatoriale del Web



Gli italiani verranno quindi rappresentati alle olimpiadi internazionali dell'informatica con un sito simbolo della nostra assoluta incompetenza.

Metaforicamente parlando è come se alle olimpiadi della matematica si presentasse un team di studenti rappresentati da un sito con scritto in testata una castroneria del tipo:
1 + 2 = 7.914

Questo lo sviluppo tecnologico, questa la realtà dei fatti.
Studenti capaci di disimparare ancora prima di apprendere le basi come vada strutturato un semplice sito, come vada utilizzato un linguaggio di markup, come vadano distribuite o enfatizzate le informazioni, come si possano rendere accessibili dei contenuti, come vada dichiarato un documento, come vadano evitati i frameset, come vada assolutamente "cestinato" un programma discutibile quanto base e mal riuscito come è Front Page per un sito degno di tale nome.

L'italia delle riforme scolastiche e dell'evoluzione Informatica viene rappresentata da quello che è oggettivamente uno dei più discutibili programmi di generazione automatizzata di contenuti che ci siano sul mercato.

Quale novità? Nessuna, dato che gli sviluppatori del portale del turismo pare abbiano scopiazzato funzioni client prese in rete, eliminandone perfino i copyright, come ulteriore conferma del basso livello di preparazione tecnica, questo il team selezionato per il più ambizioso progetto Web mai finanziato in Italia, non smetterò mai di congratularmi con i governi per l'insieme di assurdità racchiuse in un solo progetto.

Non a caso qualche giorno fa ho scritto un post sul nuovo portale oneweb2.0 rigurado la necessità evidente di riconoscere quella dello scripter una vera e propria professione, probabilmente mi sono sbagliato poichè abbiamo bisogno di molte professioni ufficialmente riconosciute e tecnicamente valide nel settore Web a partire dalla formazione degli stessi docenti della scuola dell'obbligo.

Concludo lasciandovi ammirare il favoloso sito delle Olimpiadi, firmato dal Ministero della Pubblica Istruzione, complimenti ministero!

Saturday, March 03, 2007

DOM Google Translator

Hi guys :-)
I've just uploaded my last function on devpro that's compatible with most common browser.
It's based on DOM and creates automatically translation request url to view a selected text or an entire page inside wonderful Google Translator free service page.

Its usage is really simple:

onload = function(){
document.body.appendChild(
GoogleTranslator()
);
};

With these example You'll append at the end of document.body a select with LANG - TRANSLATION values and a link.

Returned div has exactly these two elements and You could customize them using your own CSS.

Here You can view another example

<style type="text/css">
#mytranslator {
font-size: 8pt;
font-family: Verdana, Helvetica, sans-serif;
border: 1px solid silver;
padding: 4px;
background-color: #F5F5F5;
color: #000;
width: 160px;
}
#mytranslator select {
font-size: 8pt;
}
#mytranslator a {
display: block;
color: #00F;
text-decoration: none;
border-bottom: 1px dotted black;
}
</style>
<script type="text/javascript">
onload = function(){
var translator = GoogleTranslator(
"Translate",
"es",
"ENG - ESP"
);
document.getElementById("mytranslator").appendChild(translator);
};
</script>

In this way You'll create a translator shortcut with default English to Espanol translation.

You can view an example, using English to Italian as default, on the right content of this page, do You like it? :-)

Friday, March 02, 2007

function, (function) or var function?

Few days ago Dustin Diaz wrote about function declaration ambiguity.

In my opinion the best way to declare a function (class) is the classic way

function MyClass(){
// constructor
};

The reason is simple: a class could be a very big function and some version of Explorer could generate an error if big function is declared using

var MyClass = function (){
// constructor
};

However this post talks about other function "strange things", expecially about usage of brackets after function declaration.


function MyTest(){alert(arguments.length)}();

This will produce an error, exactly a Syntax error.
The "strange thing" is that You could do something inside brackets then function will not be called and syntax error will disappear.

function MyTest(){alert(arguments.length)}
(alert(MyTest));

This is a strange "feature" and it's different from this one:

(function MyTest(){alert(arguments.length)})
(alert(MyTest));

This code will produce a reference error because MyTest, declared inside brackets, has not a global scope then MyTest is correctly undefined.
This is one of the best way to create a lambda function inline too.

var len = (function(){return arguments.length})(1,2,3);

As You know len variable will not be a function but a Number with value equal to 3.
The strange thing is that "var" keyword doesn't produce the same result of regular function.

var MyTest = function(){alert(arguments.length)}();

This example will not produce any error and function is called correctly even without arguments.
Next example shows that function works correctly but it's not the value of MyTest variable.

var MyTest = function(){
alert([arguments.length, arguments[0]])
}(MyTest);
alert(MyTest); // undefined

That's why We need to return called function.

var MyTest = function(){
alert([arguments.length, arguments[0]]);
return arguments.callee
}(MyTest);
MyTest(MyTest);

Finally You could use these informations to create a real-time interval.

onload = function(){

var interval = function(){
document.body.appendChild(document.createTextNode("\n".concat(Math.random() * 1234567)));
return interval ? 0 : setInterval(arguments.callee, arguments[0]);
}(2000);

setTimeout(function(){
clearInterval(interval);
}, 20000);
};

This code will call 10 times the function (20/2 seconds) and not 9.
Do You think this is interesting?

Wednesday, February 28, 2007

Web or Potatoes ?

Yesterday TV (TG1) said that a job called "Potatoes Watcher" is paid 8,00 euro each hour.
In Italy a web/desktop developer with 10 years experience and more than one official certification is paid about 4 or 5 euro each hour.

Potatoes Watcher look for bad potatoes 40 hours each week.

An expert web/desktop developer study every day new languages, new technologies and creates program quite more complex than a potato ... about 60 hours each week (but paid for 40 hours).

I'm really thinking to change my job, sending curriculum vitae to italian potatoes factory.

I'll probably have more chance to grow up my own salary and why not, my potatoes skill too, even having less work to do.

This is Information Technology in Italy and that's why We are on Top Ten of Europe UnTechnology.

Regards (and please, eat potatoes!)

Monday, February 26, 2007

[IT] Italia - Finalmente i conti tornano

problemi XSS ed un blog iniettato nel portale

Premessa
I riferimenti a persone o a cose di questa mia riflessione pubblica non sono puramente casuali ma sono solo parte, come appena detto, di una mia personale riflessione del tutto opinabile.

La realtà italiana del settore IT
Sono diverse settimane che seguo gli interessanti interventi di Punto Informatico che riguardano il settore IT.

Addetti ai lavori di ogni tipo con esperienza da 0 a 100 e per ogni età lamentano problematiche analoghe, quali:

  • retribuzione non adeguata rispetto le competenze richieste

  • ricerca di professionisti senior di ogni tipo per offerte spesso sotto le 1.000 euro mensili

  • mancata consapevolezza sulle reali necessità aziendali, annunci improbabili per ricoprire ruoli che non hanno nulla a che fare col curriculum ideale

  • sfruttamento d'orario, contratti raramente a tempo indeterminato

  • carriere "ghiacciate" dalle dubbie prospettive future

  • mancata disponibilità di fondi, mancata voglia di investire

  • esubero di "gonfia curriliculum" e professionisti qualificati e veramente capaci messi spesso sullo stesso livello dei primi


Unanime l'idea che in Italia il progresso in ambito IT sia tra i più discutibili d'Europa mentre alcuni giurerebbero tra i più arretrati a livelo mondiale.

La news che ha creato un frastuono imbarazzante in questi ultimi giorni è che finalmente abbiamo le prove inconfutabili che in italia non si ha nemmeno vagamente la concezione di cosa sia un sito Web, cosa sia la sicurezza, come si inseriscano semplici contenuti ne di come un servizio possa realmente essere di pubblica utilità.

Il caso in esame è il tanto atteso portale del turismo italiano, una macchina divora soldi accesa da 3 anni capace di trangugiare "solo" 45 milioni di euro contro i potenziali 90 previsti inizialmente per offrire ai cittadini italiani una inconfutabile prova che:

  • in Italia non abbiamo le competenze per valutare i costi effettivi di un qualunque progetto, inutile quindi proporre finanziarie su finanziarie quando la capacità di sperperare in ogni dove è intrinseca

  • in Italia nessuno da il buon esempio, inutile presentare per primi una legge ben fatta quando in 3 anni di tempo non si ha avuto il buon senso di rispettarla

  • in Italia alcune persone che ci rappresentano non hanno i requisiti tecnici per valutare obbiettivamente i risultati ottenuti, tantomeno darci delle corrette informazioni

  • in Italia mancano percorsi di formazione pubblici e dedicati, non a caso da alcuni mesi un gruppo di professionisti sta lavorando per definire ruoli e competenze utili per lo sviluppo Web, non ci sono quindi competenze tecniche ufficiali per garantire la buona riuscita di un qualunque progetto Web



Da un punto di vista puramente tecnico è come se un supermercato affidasse al proprio macellaio lo sviluppo e la realizzazione di un'automobile Gran Turismo.
L'esempio non regge comunque il confronto, dato che la cultura automobilistica italiana è un vanto documentato dal successo dei più noti produttori di auto.

In questo settore abbiamo ingegneri meccanici, ingegneri informatici, ingegneri edili ed ingegneri aereonautici, che cosa abbiamo invece per il Web? Nulla!

Nulla che prepari tecnicamente un professionista di settore, nulla che sia una effettiva specializzazione o come dicono nella pagina accessibilità del portale in esame, nulla che garantisca una competenza DE FACTO.

Il messaggio per tutti gli italiani è quindi il seguente:

  • se non avete adeguate competenze per svolgere il vostro lavoro, nonostante un budget praticamente illimitato affidato solo a voi, scrivete che il risultato ottenuto è un risultato de facto, il che implica la totale mancanza di responsabilità da parte vostra sulla corretta riuscita del progetto

  • se superate i limiti di velocità scrivete nel verbale la seguente giustificazione: de facto ero convinto di rispettare i limiti

  • se siete evasori fiscali dichiarate che de facto avete avuto spese di altro tipo paragonabili a delle tasse

  • se vi danno una scadenza e voi non la rispettate, non preoccupatevi, de facto potreste dire di averla rispettata proponendo un risultato estremamente parziale del progetto

  • se pagate le tasse regolarmente, se siete brave persone, se a stento arrivate a fine mese o a stento siete disposti a pagare milioni di tasse grazie al vostro invidiabile reddito, de facto state buttando via i vostri soldi



Se nel nostro piccolo facciamo del nostro meglio, chi ci governa ha intere strutture capaci di decidere come investire i nostri soldi.
Queste strutture sono state selezionate, oserei dire "giustamente", per collaborare con colossi della portata di IBM, la quale ha fornito la piattaforma di sviluppo configurata in modo tale da permettere di includere codice arbitrario all'interno di una pagina capace di mostrare avvisi, prendere informazioni (cookie) degli utenti navigatori e reindirizzarle altrove o, perchè no, includere interi siti all'interno dello stesso portale.

Tutto questo in un unico disservizio dal costo proibitivo ma capace di creare lavoro grazie ad una cifra che non richiede certamente una garanzia di fatturato.

Unica pecca è che non essendoci un albo dei professionisti di settore, non essendoci ancora un ente ufficiale capace di valutare le effettive capacità di settore, la selezione del personale sarebbe stata comunque e probabilmente all'italiana.

Il dubbio che questo sia accaduto lostesso è il fatto stesso che i responsabili del sito siano stati prontamente cancellati dalla pagina "chi siamo".

Tanti dunque gli avvenimenti percepibili in tempo reale dalla fatidica data di lancio.
Mentre la televisione non ha infatti dato alcuna notizia sul putiferio causato dall'uscita del portale, gli artefici dello stesso hanno provveduto a:

  1. eliminare un'introduzione animata dal peso affatto contenuto della durata di 15 secondi con reindirizzamento dopo 18 secondi che impediva ad utenza di ogni tipo di accedere alle informazioni del portale

  2. eliminare un'ulteriore introduzione "holliwoodiana" pesantissima per tutte le persone non servite da ADSL

  3. risolvere problemi di caratteri illeggibili

  4. risolvere alcuni problemi di inclusione codice grazie al debug effettuato gratuitamente da noi stessi, professionisti di settore

  5. risolvere in tempi records, sempre grazie alle critiche ed ai consigli di noi stessi, il problema delle tabelle



Sembra quindi evidente che mentre stampa e televisione continuano a non raccontarci praticamente niente, qualcuno si è preso le proprie responsabilità e sta tentando di rimediare agli inopinabili errori tecnici presentati giorni fa con troppo entusiasmo.

Solo alcune domande, per concludere, che vorrei rivolgere a tutti coloro che hanno partecipato alla realizzazione di questo portale:

  1. 3 anni per un un flop come questo non erano sufficienti per presentare un sito a norma di legge?

  2. è possibile avere i dettagli, ente per ente e singolo incaricato per singolo incaricato, di come sono stati spesi i nostri soldi?

  3. è possibile pretendere le vostre scuse nei confronti di chi questo lavoro se lo suda veramente e quotidianamente e che grazie a questo portale è stato ridicolizzato in tutto il mondo?

  4. è possibile che a prescindere dal governo le cose in Italia vadano sempre per lo stesso verso?

  5. cosa possiamo fare noi elettori per far si che i nostri rappresentanti o come dice Beppe Grillo "i vostri datori di lavoro" smettano di buttare via continuamente soldi e invece di aiutare a risolvere reali esigenze e problematiche della nazione, ci fanno semplicemente imbestialire?



Ora provate a dire che i conti non tornano, provate a pensare che "è strano che accadano certi fatti" ... provate a dire che siete orgogliosi di come veniamo rappresentati, tutto torna, tutto ha un filo logico ben definito: Welcome Italy.

Sunday, February 25, 2007

A better Singleton pattern example

JavaScript Singleton examples are often not so correct.
In these pages for example, top Google search results, any showed code is a Singleton design pattern:


Why these examples are not good enought?


As You can see, Singleton uses a private constructor and a static public method to get a uniq object instance.

// Java example
public class Singleton {

// Private constructor suppresses generation of a (public) default constructor
private Singleton() {}

private static class SingletonHolder {
private static Singleton instance = new Singleton();
}

public static Singleton getInstance() {
return SingletonHolder.instance;
}
}

In JavaScript a constructor can't be private but It should has a private variable so why we should use a public static instance property when we could have a private one?

// Singleton pattern with JavaScript
function Singleton(instance) {
if(!Singleton.getInstance) {
Singleton.getInstance = function(){
return instance;
}; instance = new Singleton;
};
}(new Singleton);

Constructor is public but it's assigned directly to have a single private instance that will be always the same everytime we call Singleton.getInstance public method.

function Me(
instance // private class instance
) {

// public static method (Singleton design pattern)
if(!Me.getInstance) {
Me.getInstance = function(){
return instance;
}; instance = new Me;
};

// generic public properties and methods

this.name = "Andrea";
this.surname = "Giammarchi";

this.whois = function(){
return this.name.concat(" ", this.surname);
};


}(new Me);


// and now try to modify instance ...
var me = Me.getInstance(),
others = new Me({name:"No", surname:"Others"}),
you = Me.getInstance();

you.constructor.prototype = {
name:"No",
surname:"Changes"
};

Me.instance = {name:"Private", surname:"Scope"};

alert([
me.whois(),
others.whois(),
you.whois()
].join("\n"));

alert(me === you && you === Me.getInstance());

The result is my name on first alert and true on second.
Is there a simple way to implement singleton with every class ? Of course :-)

Function.prototype.Singleton = function(instance){
if(!this.getInstance) {
this.getInstance = function(){
return instance;
};
};
};


function Me(){
this.name = "Andrea";
this.surname = "Giammarchi";
this.whois = function(){
return this.name.concat(" ", this.surname);
};
};
Me.Singleton(new Me);

var me = Me.getInstance();
me.blog = "webreflection";
alert(me === Me.getInstance() && me.blog === Me.getInstance().blog);



P.S. for MarCamp "fast demo": sorry guys, bad cut and paste on showed example, just add this line if You want to test the example (damn time !!!)
instance = new Singleton;

after getInstance declaration

Thursday, February 22, 2007

Monday, February 12, 2007

Could I change a native function ?

Just a quick post about how to modify a document (and others generic objects) native methods.


// basic example
document.createElement = (function(createElement, Element){
return function(nodeName){
var element, key;
try{element = createElement(nodeName)}
catch(e){element = createElement.call(document, nodeName)};
for(key in Element)
element[key] = Element[key];
return element;
}
})(document.createElement, {});


What's that ?
... a really simple way to extend with your defined object each element created using document.createElement function.
This is an example with useful comments (I hope)

// redefine document.createElement native function
// using anonymous function
document.createElement = (
function(
// original document.createElementFunction
createElement,

// object used to extend created elements
Element
){

// new document.createElement function
return function(

// type of element (div, p, link, style ... )
nodeName
){

// element and key to loop over object
var element, key;

// IE like this
try{element = createElement(nodeName)}

// FireFox like that
catch(e){element = createElement.call(document, nodeName)};

// loop over Element
for(key in Element)

// and assign each method to new element
element[key] = Element[key];

// return created element
return element;
}
})(
// send to anonymous, the original function
document.createElement,

// send object used to extend created elements too
{
// read firstChild node
read:function(){
return this.firstChild.nodeValue
},

// write text into node
write:function(text){
this.appendChild(document.createTextNode(text))
}
}
);

// basic example
onload = function(){
var div = document.createElement("div");
document.body.appendChild(div);
div.write("Hello World !!!");
alert(div.read()); // Hello World !!!
};

That's all, and this method is only a basic native method override example, have fun with JavaScript :-)

Friday, February 02, 2007

GzOutput 0.5 finally approved !!!

PHPClasses has approved my last notable uploaded class, GzOutput :-)

Features

  • compatible with both php version 4 and 5 (E_ALL | E_STRICT notice free)

  • create runtime every kind of content-type with or without dedicated charset

  • cache automatically every kind of file or file list (one or more JavaScript, CSS, XML, xHTML, TXT, others)

  • decrease client download time (about 5 times faster!)

  • increase server performances if cache option is enabled (about 3 times faster!)

  • give you control with differents public static methods, easy to use, secure and portable

  • "perfect" unobtrusive solution, compatible with every browser, every page parser (W3, WatchFire, WebSiteoptimizzation, others) and doesn't modify sources, just crunch them with different levels if you choose to crunch so you don't need any kind of packer, for example for your javascript files

  • "forgettable solution", automatically update chached file when one or more required file has been changed



Use them to optimize your feeds, your javascripts, your css, your txt files ... or why not, every page of your portal, e-commerce or everything else.

Do you need an example ? My overbyte.Editor single script source use them from different weeks without any problem, using crunch level 2 and compression level 9.

Easy to configure and mod_reqrite ready.

Could be enought ?

Saturday, January 27, 2007

Who's running to get Vista ?

Yesterday HTML.it posted a nice question about Vista: "If You have Vista or You'll install them quickly put your hand in the air".

This is just a mini report about users opinions (totally: 47) and I think these informations should be interesting:

  • I'll install Vista as soon as I can or I just have Vista
    12.8 %

  • I don't believe in Vista and I'll be on XP for many other months/years
    38.3 %

  • I'm thinking to spend money for a Mac (with OSX) instead of Vista license
    8.5 %

  • I'm thinking to install Ubuntu or I'll never instal Vista (I'm just on Ubuntu or other Linux distributions)
    40.4 %


So what are You waiting for to change your OS ? Get Linux !

Wednesday, January 24, 2007

bored with something to array convertion ? map them !

I'm rewriting my JSL to include by default inside my next project.
This project will include automatically a lot of standard JS 1.5 methods or functions, and Array.map is one of those.

While I'm testing some proto performances, I've thought about a really simple way to switch from an array or from a node list (getElementsByTagName) with a simple, fast and single line of function.

// old example version
// function _A(a){return [].map.call(a,function(a){return a})};

// new version, Daniel suggest, faster and doesn't require any prototype !
function _A(a){return [].slice.call(a)};

and that's all, do You like it ?

As first point, You need FireFox 1 or greater (or Mozilla if You prefere) or this short piece of code:

if(!Array.prototype.map) Array.prototype.map = function(callback){
for(var i = 0, j = this.length, result = new Array(j), self = arguments[1], u; i < j; i++) {
if(this[i] !== u)
result[i] = callback.call(self, this[i], i, this);
};
return result;
};


Then You have "everything You need" to get quickly every iterable element.

These are just two examples

function sort(){
return _A(arguments).sort().join("<br />");
};
document.writeln(sort("Luke", "Jabba", "Fenner"));
document.writeln(sort("c", "a", "b"));



var firstScript = _A(document.getElementsByTagName("script")).shift();
alert(firstScript);

var allUnorderedList = _A(document.getElementsByTagName("ul"));

alert(_A(null).constructor === Array); // true ;-)


These nice trick should be used with forEach method too.
Stop for and while loops, each them !

function changeLinks(onclick){
[].forEach.apply(document.getElementsByTagName("a"),
function(link){
link.onclick = onclick;
});
};

changeLinks(function(){
window.open(this.href, "");
return false;
});


... and sure, You need forEach prototype too ...

I suppose every other JS 1.5 Array method should be cool enought to work with DOM nodes too ... do You agree ?

Are thinking about performances ? Well guys, quite the same of generic loops, even faster (works in core) with every FireFox !!!

Thursday, January 18, 2007

JavaScript Unobtrusive Security Form

In some cases JavaScript should be used to add more security during a client/servr interaction.

Paul Johnston knows this and tha's why He created md5 and sha1 hashing JavaScript implemntations.

You can choose to send just hashed form variables, to be sure, for example, that recieved stirngs are valid hash and they are present on db (removing sql injections problems).

You could even create special hashed strings too, to forget "man in the middle" problems, using a salt that will be generated and verified from server side code.

This hashed value could make your password more secure, requiring a kind of brute force that will be quite hard to do.

// man in the middle found the salt and the logging string
$try = 12345;
if(hash($salt.hash($try)))
echo 'Passwrod or collision found: '.$try;
else {
$try = 12346;
if(hash($salt.hash($try)))
// ... and again, again ..
// every time with a double hashed string ( slower than a single :D )
}


At the same time, this salt creates a collisions free hashed string, then a brute force operation should not be used to login in a form like this one because new salt , hashed with collision, will not produce a compatible authorizzation hashed string (or better, it's really difficult that a collision, hashed with a different string, will produce another collision).

This form is absolutely WAI-AAA WatchFire approved, valid W3C XHTML 1.1 and valid W3 CSS.
It's unobtrusive, works without JavaScript too (in a less secure way) and SecurityForm JavaScript function should be used in every kind of form, just modifing form and inputs id as You want.

This is a basic php example page, compatible with PHP 4.3 or 5 or 5.2, that shows how You should "drive correctly" login operation.

I hope code description is enought to understand this kind of form and I suggest to use sha1 instead of md5 (better security).

This is a short description:

  1. Client verify user and pass, if these are not empty call form.action page to recieve a new salt ($salt = uniqid(rand(), true)) sending just userName

  2. Server generates a new salt then it saves them on a simple table adding userName and time() so it sends them as SecurityForm onload callback

  3. Client recieves this new uniq string and generates a logging variable

    logging = choosedHash(salt + choosedHash(userPassword))

    and redirects client to authentication page sending uniqid recieved from server, userName and loging

  4. Server verify that salt table contains recieved salt and verify if found userName is the same of GET value, then verify that logging is a valid authorizzation string:

    // example query
    $query = 'SELECT * FROM user_list WHERE user = $user AND MD5(CONCAT($salt, pass)) = $logging';

    where pass is just hashed during registration

  5. server removes recieved salt from table and other salts with expire less than time() - 30 seconds



... and that's all.
Are You sure, now, that your user with JS enabled are a bit more protected ? :-)
(of course, SSL is absolutely the best way to "ensure privacy" ... but You could implement this kind of form with SSL too)


What about compatibility list ?
Well, every JavaScript compatible browser, starting from IE 5 and every JavaScript disabled or uncompatible browser too.

Monday, January 15, 2007

a little error choosing byte family plugin namespace :D

Well ... not much things to tell You .. just sorry for my last plugin namespace choice.

Now that I know What does it mean (thanks to Dean and Mario) I've changed namespace, Welcome overbyte plugin library :D

(probably the uniq plugin I need is one for my English, not for my libraries ... :E)

Friday, January 12, 2007

prototype, singleton, what else ?

A lot or JS developers use prototype style to write (extends) classes (functions) or singleton to have a private scope.

I often use different ways to create my classes (function) and I use prototype only to extend and not to create.

These are some examples:

/** prototype style */
// class Blog
function Blog(){};

// prototype to extend Blog
Blog.prototype = {
getName:function(){
return this.name;
},
setName:function(name){
this.name = name;
},
name:""
};


// how to use Blog class
var myblog = new Blog;
// new Blog() with parenthesis is not useful.
// full prototype style "doesn't accept"
// parameters on constructor
// (or better, it accepts but doesn't use them)

myblog.setName("WebReflection");
// setName is absolutely necessary to set public
// name parameter

/** prototype style */



/** singleton style */
function Blog(name){
return {
getName:function(){
return name;
// name has a global scope
// in this object, private
// for every other external scripts
}
};
};

// how to use this Blog function
var myblog = Blog("WebReflection");

// Singleton style should accept one or more
// arguments on fake constractor.
// myblog is an instanceof Object and
// is not a Blog class (I've not used new to set this var)

The first important difference is that with Singleton you don't need to create setName because a blog name shouldn't be modified from other scripts (in this example).
Then why You should declare public parameter (classVar.name) or public methods (classVar.setName) when a property shouldn't be changable ?

This is a common full prototype style problem, everything is public and everything should be modified from other scripts.

In the other hand, with above Singleton example You don't create an instance of Blog, just recieve everytime a new Object.

With prototype = {something} Your varible will be an instance of className but constructor will be an Object while if You declare every method "manually" variable constructor will be exactly the original function.

function Person1(){};
Person1.prototype = {
getClassName:function(){return "Person1"},
isPerson1:function(){return this instanceof Person1}
};
var p1 = new Person1;
document.write([
p1.getClassName(),
p1.isPerson1(),
p1.constructor,
p1.constructor === Person1
] + "
");
// Person1,true,function Object() { [native code] },false


function Person2(){};
Person2.prototype.getClassName = function(){return "Person1"};
Person2.prototype.isPerson2 = function(){return this instanceof Person2};
var p2 = new Person2;
document.write([
p2.getClassName(),
p2.isPerson2(),
p2.constructor,
p2.constructor === Person2
]);
// Person1,true,function Person2() { },true

For many developers it is a feature, because they think that native code is faster than function eveluation (that should be performed every time) ... however, I've never seen performance differences from prototype style and other styles.
Think that func by func prototype doesn't work as single object too, then I suppose there are a lot of scripts that clones prototype (or extends them) using a for in loop and that these scripts doesn't perform better (if it's true) than others.

This is another way, not native, to have both instanceof class and private scope on object You should do something like that:

function Blog(name){
this.getName = function(){
return name;
// as Singleton, name has
// a global scope inside this
// instance, private for
// every other script
};
};

// You could set private methods too ...
function Blog(name){

// private method, global scope
// inside this instance
function setName(){
selfname = arguments[0] || name;
};

// private variable
var selfname;

this.getName = function(){
setName(name);
return selfname;
};
};

var myblog = new Blog("WebReflection");
// You have an instanceof class Blog with
// a private internal scope and an external one


These kind of class instances are not possible to create with full prototype style and in this case evey instance will not be modified if other scripts changes Blog.prototype.getName with a new function.

function Blog(name){
function setName(){selfname = arguments[0] || name};
var selfname;
this.getName = function(){
setName(name);
return selfname;
};
};
Blog.prototype.getName = function(){
return "prototype doesn't change anything";
};

var myblog = new Blog("WebReflection");
document.write(myblog.getName()); // WebReflection

So this way should be thought as "more secure" than others because created instance will not be affected by prototype changes on constructor or on global Object, however, Singleton should be secure too.


function Blog(){
return {getName:function(){return "WebReflection"}}
};
Blog.prototype.getName = function(){
return "override";
};
Object.prototype.getName = function(){
return "override";
};

var myblog = new Blog;
document.write(myblog.getName()); // WebReflection

// if You don't use new ..
var myblog2 = Blog;
document.write(myblog2.getName()); // override

As I've said, the bad thing of singleton is that resulting variable will not be an instance of used className with or without new before declaration.


Last way, if You need a single object instance in your script, You should use this way too.

Blog = new function(){

// private method
function setName(){
selfname = arguments[0] || name;
};

// private variable
var selfname;

// public method
this.getName = function(){
return selfname;
};
this.setName = function(name){
setName(name);
};
};

Blog.setName("WebReflection");
document.write(Blog.getName());

// what kind of instance ? ... it's an "anonymous secret"
document.write(Blog instanceof Function); // false
document.write(Blog instanceof Blog.constructor);// true

This example is something like Singleton without the possibility to send arguments on constructor (and this one will not be a native Object code).
So this method has a "secret" constructor but You could extend them using Blog.constructor.prototype or extend another class using new Blog.constructor.
This example should be useful when You need a single instance of an anonymous function (a bit harder to be modified from other scripts) but remember that
to create a new instance You need GlobalObj.constructor and that other scripts should change a GlobalObj.construtor with prototype.

Now, this post is just to show different ways to create an "instance of something" ... but at this point I think that:

  1. if native code constructr is really faster to execute, Singleton should be the better choice (private scope too)
  2. if speed is important (and native code is really faster) but We don't need a private scope and We need to change every method/property of every className instance, prototype style is the better choice because We can know if a var is instance of a class and not only a generic instanceof Object.
  3. if extreme speed is not a problem (or native code doesn't perform faster), the best solution should be the simple function, to know both constructor and instanceof ... but We can't change every var in a single line.
  4. if we need a single anonymous instance, we could use the last example.

The third point limit, the possibility to change every instance of a class, should be solved with a simple Object proto

Object.prototype.syncronize = function(){
for(var key in this.constructor.prototype)
this[key] = this.constructor.prototype[key];
};

function Blog(name){
function setName(){
selfname = arguments[0] || name;
};
var selfname;
this.getName = function(){
setName(name);
return selfname;
};
};

var myblog = new Blog("WebReflection");
document.write([
myblog.constructor === Blog,
myblog instanceof Blog,
myblog.getName()
]);
// true,true,WebReflection


Blog.prototype.getName = function(){
return "override";
};

document.write([
myblog.constructor === Blog,
myblog instanceof Blog,
myblog.getName()
]);
// true,true,WebReflection


myblog.syncronize();

document.write([
myblog.constructor === Blog,
myblog instanceof Blog,
myblog.getName()
]);
// true,true,override


So, wich way do You like and Why ?

Thursday, January 11, 2007

Dojo source ? 39,09 Kb generated in 0.0006 seconds

It's true, less than 40Kb for dojo.js packed file without any packer, just using my overbyte Editor

How ?
Just open dojo.js file (146Kb) with one text editor (sure, Notepad too), select all, copy and past them inside overbyte Editor working area.

Now click on download, and choose the first option as showed on image:


Save the file as dojo.php and test on your host ... so view page informations, it's less than 40Kb with all gz compatible browsers ;-)

What a news ?
The beautyful thing is that my auto-generated php file (about 300Kb) decodes this js source in less than 1 millisecond, exactly 0.0006 seconds on my "old" centrino 1.6 Ghz with Apache 2.2 and PHP 5.2 running on PAMPA !

If You consider that generated file doesn't require zlib or gzencode function, as bootstrap js or php solution, and is compatible with every php hosting solution, You can think that JS size is not a big problem because You should decrease about 5X the final size.

I don't know how many Kbytes should be a packed packer version without comments of the same file, using my Editor to generate the php page ... but don't worry, result page will be generated in less than 0.0006 seconds :-)


I don't believe You and I don't want to view your damn Editor
Well, You could view dojo.php file using this link ...

P.S. Hey Ajaxians, Why didn't You find interesting my Editor expreiment ?

Wednesday, January 10, 2007

overbyte Editor, from Alpha to Beta

Update !!!
overbyte Editor now has a Suggest Panel inside textarea !
It doesn't contain every function or method but it has a kind of intelligent code interaction, do You like it ? :D

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

Just a little update about my last experiment, overbyte Editor.

I've fixed a lot of bugs and now it should work correctly on IE5.5, IE6, IE7, FireFox 2 (probably 1.5 too) and Opera 9 (probably 8 too).

I don't know why Safari has some problem with menu and I'm working to solve Safari incompatibility, however, now this Editor is version beta, so You could test them or use without problems ( I mean without every Alpha release problems :D ).

Please report me bugs or features You think should be cool and good JavaScripting ! :-)

[edit]
I forget a detail ... using my GzOutput.class.php with bootstrap.php solution, this component size is less than 14Kb without jsmin :-)

jhp is about 12 Kb without jsmin too ... but I'm working on, this project will not be available so soon.

Tuesday, January 09, 2007

JavaScript get_class and is_a functions

Update a new version of get_class, works with prototype classes too.

We often need to know the type of a variable with JavaScript but every dedicated function, such typeof or instanceof, are not always perfect.

For example, the typeof a string, that should be declared as both primitive and object value, should be "string" or should be "object".

var $1 = "test",
$2 = new String($1);

alert([
typeof($2), // object
typeof($1), // string
$2 == $1, // true
$2 === $1, // false
$2 instanceof String, // true
$1 instanceof String, // false

$2.constructor === $1.constructor
// true !!!
].join("\n"));

It's quite caotic ... but perfect, but every time We need to know if a variable is exactly that kind of variable We should
verify the typeof or the constructor and the instanceof ... little boring ?

With PHP We have two nice functions (... more than two, that's why I'm developing jhp) that are perfectly to know the class name of a variable or to know if that var "is a" class type.

These are my two proposal, one to know the generic class name of a variable and one to know if a variable is a class.

function get_class(obj){ // webreflection.blogspot.com
function get_class(obj){
return "".concat(obj).replace(/^.*function\s+([^\s]*|[^\(]*)\([^\x00]+$/, "$1") || "anonymous";
};
var result = "";
if(obj === null)
result = "null";
else if(obj === undefined)
result = "undefined";
else {
result = get_class(obj.constructor);
if(result === "Object" && obj.constructor.prototype) {
for(result in this) {
if(typeof(this[result]) === "function" && obj instanceof this[result]) {
result = get_class(this[result]);
break;
}
}
}
};
return result;
};
function is_a(obj, className){ // webreflection.blogspot.com
className = className.replace(/[^\w\$_]+/, ""); // paranoia
return get_class(obj) === className && {function:1}[eval("typeof(".concat(className,")"))] && obj instanceof eval(className)
};


With get_class function You could know the name of the constructor of a variable.
This means that if You need a string, both primitive and object, You could simply do a check like this

if(get_class(somevar) === "String")
// ... do stuff, the var is exactly a string


You could even use a switch

switch(get_class(somevar)) {
case "String":
alert(somevar);
break;
case "Number":
somevar += 1;
break;
case "Boolean":
somevar = !somevar;
break;
};

... or if You prefere, a portable object ...

var operations = {
String:function(v){document.write(v); return v},
Number:function(v){return v + 1}
};
somevar = operations[get_class(somevar)](somevar);


Finally, if You want to know if a variable is exaclty a type of class You could use is_a, that's a deeper check than instanceof because doesn't verify only the instance name.

document.write([
is_a(null, "Date"), // false
is_a(undefined, "Date"), // false
is_a(Date, "Date"), // false
is_a(new Date, "Date"), // true
is_a({}, "Object"), // true
is_a([], "Array"), // true
is_a("", "String"), // false
is_a(new String(""), "String"), // true
is_a(1, "Number"), // false
is_a(new Number(1), "Number"), // true
is_a(false, "Boolean"), // false
is_a(new Boolean(0), "Boolean"),// true
is_a(/re/, "RegExp"), // true
is_a(Math, "Math"), // false
is_a(Math, "Object") // true
].join("
"));

Monday, January 08, 2007

Simple JavaScript bootstrap solution

As WebSiteOptimization suggests external JavaScript files should be included "one time for all".
There are a lot of procedures to do that, using a server-side script to include and compress required files.
This simple anonymous function should do something like dynamic JavaScript inclusion, based on unobrtusive cross-browser function and really simple to use.

The concept is this one:
when You add a script on Your page this will be exactly the last script present on document so You could do some operation using its source.

bootstrap.js does it, and works as "includer" from first file name to last.


<script type="text/javascript" src="jsfolder/bootstrap.js?jsfile"></script>

In this example bootstrap will include jsfile.js that's inside jsfolder so You just need to include bootstrap.js file inside your dedicated JavaScript files folder.

You could load multiple JS too, using char "|" as separator

<script type="text/javascript" src="jsfolder/bootstrap.js?jsfile|otherfile|init"></script>

In this case bootstrap will load jsfile.js, then otherfile.js and finally init.js, everyone automatically from folder jsfolder.

// bootstrap resulting string for inclusion
jsfolder/jsfile.js
jsfolder/otherfile.js
jsfolder/init.js


If You need to include files with a different extension, You could simply add a suffix after last file name.

<script type="text/javascript" src="jsfolder/bootstrap.js?jsfile|otherfile|init#php"></script>

// bootstrap resulting string for inclusion
jsfolder/jsfile.php
jsfolder/otherfile.php
jsfolder/init.php


Then, for example, You could pack your js code using my overbyte Editor and call saved php files quickly.

You can use any kind of extension, then PHP is not required.

You can use more than one bootstrap too, copying bootstrap.js file inside every dedicated javascript folders.

Could be this an unobtrusive and alternative way to include dynamically your libraries and functions ? ... and it's less than 500 bytes :-)

Update
Now GzOutput php class supports something like bootstrap for JS, CSS and other kind of files.

You can test PHP 4 version or PHP 5, successful tested on E_ALL | E_STRICT error_reporting enviroment.

Thursday, January 04, 2007

overbyte Editor and jhp

Happy New Year :-)

I would like to present my last idea, jhp, that's absolutely alpha and that requires "a special" component to be tested quickly ... and that's the reason of this post, a work in progress plugin for my byte family library, called overbyte Editor.

It's alpha version too and for some strange reason it doesn't work on Safari browser (but it doesn't show any error too ... ) but it's a simple online runtime JavaScript editor / debugger with some funny features that I've never seen on the net.

It's not a FireBug alternative, it's just a "quick and dirty" enviroment to test rapidly your scripts, functions, html pages and probably other.

overbyte Editor has some Extra special function, based on syncronous php interatcions or using jsmin to parse and test your code in one step.

It could open your files, save them or inject into a dedicated php file that should solve definitely bandwidth problems using both jsmin and gz features even on hosts that haven't zlib enabled (adapted version of GzOutput class without gzencode or gz_hendler).

You can read more about overbyte and jhp directly on Editor page, using About menu to read these and other Editor informations.

I'm waiting for your suggests, bug reports or comments,
bye bye :-)

Friday, December 22, 2006

[PHP] New version of GzOutput class

I've just updated my recent GzOutput.class.php (more recent than last file published on Ajaxian :D) and tested successful on many browsers.

The difference from other cache-manager files, functions or classes is that GzOutput is totally indipendent from folders or page type, You could use them to increase JSON responses (using text/plain as Content-Type) as well as XML, (X)HTML, CSS or every kind of document You need.

You could combine this class with a JavaScript compressor (to improve download speed) and you don't need to care about output changes because ETag is based on sha1 and not on every mktime of each file (it means better server performances).

The only think that You need to remember is that You don't need to write everything before to use this class (empty spaces, some char or pages can't be write before its usage).

Four public methods are really simple to use:

create, sending an output string and a Content-Type type to use cache if it's available (if not, forces next download to use cache)

createNew, sending an output and a Content-Type to force everytime the download (it's a must for Ajax interactions with XML, JSON or serialized strings)

createFromList, sending an array of files and a Content-Type to create a single generic output file including each file content and using create properties for output

createNewFromList, sending an array of files and a Content-Type to create a single generic output file including each file content and using createNew properties for output

That's all, do You like it ? :-)

Wednesday, December 20, 2006

PHP API Manager for Notepad++

I've used fantastic Komodo IDE to develop for a lot of time my Python/PHP web/desktop applications but now that my portable PC "has been regenerated" from SONY I'm spendig a lot of time to re-install everything I need.

My first favourite editor was ConTEXT, a fantastic, fast and powerful editor for every kind of program language but "my last love" has been Komodo that I've won on phpclasses.org.

Difference is amazing but there's just a problem .... Komodo is too much powerful and wants a lot of resources (I've not an extremely powerful VAIO) then I've choosed to install ConTEXT one more time but I've found, inside a forum, another famous editor as Notepad++ is and I don't know why I didn't try them before.

It's exactly what I need, a fast, simple, scite based, auto-completition enabled editor, then it's fantastic because I can write PHP as JavaScript, C and many other languages too !!!

Auto-completition is just what ConTEXT doesn't have but hey, it's a must to remember perfectly each kind of function or method because You can use them with CTRL and SPACE where You want then php.api file, as javascript.api files are a perfect solution to develop quickly without an api search engine under your nose ;-)


That's why I've created two really stupid PHP files to manage PHP API, one to create a personal installation dedicated api and one to update and mantain an api with old, unused or deprecated method too.

This is the readme file:

PHP API Manager - Andrea Giammarchi [http://webreflection.blogspot.com/]

These two simple phpfiles overwrite or create php.api file for Notepad++ program [http://notepad-plus.sourceforge.net/]

Usage:

- notepad.dedicated.api.php

call this file to create your personal PHP configuration api.
This script create php.api file for Notepad++ program overwriting, if present, precedent php.api file version.
Use this application if You don't need other not loaded/present extensions of your php installation.


- notepad.update.api.php

call this file to update your personal PHP configuration api or original Notepad++ default php.api file.
This script create php.api file for Notepad++ program overwriting, if present, precedent php.api file version.
Use this application if You want every other php functions too that shouldn't be present on your php installation.
Please remember to copy old php.api file inside this folder before to launch this application.


And this is the link of downloadable zip file with these two php scripts (on title too).

Have fun with Notepad++ :-)

Firefox Multiple Vulnerabilities ? Update in few hours !

The Highly critical Secunia Advisory of 2006-12-19 is not a problem, FireFox 2.0.0.1 has been released in few hours !!!

You don't need to download this new version if you have auto update feature enabled because your FireFox will update by itself in a "couple of seconds".

I wonder when Microsoft Internet Explorer released an multiple patches update the day after after and then I wonder why You've not yet installed FireFox on your Windows, Mac or Linux computer!

This is quite a record for a browser and this is the complete FireFox 2 veulnerability report ... just 2 vulnerabilities and just one of them unpatched and it's a less critical problem.

This is "your" Internet Explorer 6 vulnerability report and this is the last version 7 of, again, Internet Explorer Browser vulnerability report with 3 bugs, one of them moderately critical and any of them patched.

So c'mon guys, what are You waiting for ? GetFirefox ;-)

Tuesday, December 19, 2006

IWA Italy didn't choose me !!!

The Web Skills Working Group selection is closed and the group is complete.

A lot of University members, a lot of Information Architect and a lot of IWA members ... but "any every day applications" certified or skilled developer, just people that write books, blog posts, do training courses every day and probably part of the same trainings that make italian ICT as is right now (unlikely often generally "ridi.culo.us" ...) ... well, I can't read about any skilled server and client (both!) developer in the Web 2.0 era (or probably I don't know Him/Her) ... but this group should tell us how should be a Web developer and what kind of certification He should have to be a real Web developer ... sure, one or more IWA certifications !

At this point, my first opinion is that V.U.E. certifications aren't a good start point (I've 2 official server and client certifications,PHP Engeener and AS2.0 - ECMAScript 3/4 Developer) and that my W3C/PHP/JavaScript/ActionScript skill and experience (about 8 years) isn't enought to be part of choosed professionists group ... I'm quite disappointed about that but I really ... really hope that next 3 months will be a revolution for italian Information and Communications Technology !

Well, Good Luck Web Skills Working Group, I hope you'll do an excellent work and I hope you'll find the right way to create real good Web developers and not just "fake Web Doctors" !!!

I'm waiting for your progresses, please respect our expectations, we believe in you ! :-)


[update]
this is just my opinion wrote in an italian forum

Sunday, December 17, 2006

Reset The Element CSS

Few days ago ajaxian posted a YUI solution to reset CSS in a page.

This is a really interesting way to solve inherit CSS problems when You need to create a personal widget or when a library would do it.
Dean Edwards did a WHATWG proposal for a <reset> element because
He *really* wants to turn off CSS inheritance
.

He's quite right for many reasons and that's mine proposal, a reset css that just use simply a class name.

.reset,.reset div,.reset dl,.reset dt,.reset dd,.reset ul,.reset ol,.reset li,.reset h1,.reset h2,.reset h3,.reset h4,.reset h5,.reset h6,.reset pre,.reset form,.reset fieldset,.reset input,.reset textarea,.reset p,.reset blockquote,.reset th,.reset td
{margin:0;padding:0;}

.reset table
{border-collapse:collapse;border-spacing:0;}

.reset fieldset,.reset img
{border:0;}

.reset address,.reset caption,.reset cite,.reset code,.reset dfn,.reset em,.reset strong,.reset th,.reset var
{font-style:normal;font-weight:normal;}

.reset ol,.reset ul
{list-style:none;}

.reset caption,.reset th
{text-align:left;}

.reset h1,.reset h2,.reset h3,.reset h4,.reset h5,.reset h6
{font-size:100%;font-weight:normal;}

.reset q:before,.reset q:after
{content:'';}

.reset abbr,.reset acronym
{border:0;}


The element with reset class name and every "resetted" elements seems to work fine and You could see an example using this page changing the href of the style element and changing, for example, the body element in this way

...
<link rel="stylesheet" type="text/css" href="reset.css">
</head>

<body class="reset">
...


This is just an example because You could use reset with every element to obtain the same result for each nested table, form and elements.

This isn't probably the best solution but should be one solution and You could use multiple class name to define Your style too

...
<element class="reset mywidgetstyle">
...


There's only some adjustment to do with headers and probably something else that You could set using a dedicated css

.reset h1 {
font-weigth: bold;
font-size: 1.2em;
}


It's just an example but it should work with every CSS based browser.

What do You think about this solution ?

Saturday, December 16, 2006

A stupid Ajax cache problem solution

One of the common problem using Ajax (Flash too) interactions is the cache.
There are a lot of valid PHP, Python, JSP and .NET solutions but browser compatibility is often a question mark.

You could implement easyly and directly a client solution and this is just another proposal.

function noCache(uri){return uri.concat(/\?/.test(uri)?"&":"?","noCache=",(new Date).getTime(),".",Math.random()*1234567)};

exactly 123 bytes to solve cache problems and this is the func description:

function noCache(
uri
// uri string to open
){

return uri.concat(
// concat String prototype,
// the fastest way to produce
// a complete string using multiple values

/\?/.test(uri) ?
// if uri has a query string

"&"
// add last value using & separator char
:

// else
"?",
// add a query string to this url

"noCache=",
// this should be a "cool name" for generated key

(new Date).getTime(),
// the noCache value will be milliseconds
// from 1970/01/01

".",
// plus a dot ...

Math.random()*1234567
// ... and a random value using
// a "big" integer as generator
);

// then this is a return example using uri: http://host.com/mypage.html
// http://host.com/mypage.html?noCache=1166301156233.332083.6663326991

// while this is an example using uri: http://host.com/mypage.html?v0=1&v2=a
// http://host.com/mypage.html?v0=1&v2=a&noCache=1166301168420.631416.7190624559
};


You could test directly in a loop, a benchmark that many other sites didn't test ...

for(var
i = 0, // many loops
max = 10000, // max i value
uri = document.location.href, // this href
obj = {}; // a generic object
i < max; // while i is less than max
i++ // increment the i value
) {
if(!obj[noCache(uri)]) // if obj has not a nocache(uri) key
obj[noCache(uri)] = true; // set them as true
else { // else if obj has just the returned nocache(uri) key
i = max;
alert("noCache doesn't work"); // this method is not so cool
}
};


A script that use Ajax requestes inside a loop is not a good script (I suppose) but this kind of demostration can show You that generated no-cache collisions probability are quite impossible.

A usage example should be this one:

XHR.open("get", noCache(myUri), true);
// or ...
XHR.open("post", noCache(myUri2), true);


Finally these are some F.A.Q.

Why there is a key and a value and not just a random value to perfom without caching problems ?
- because some server-side code should loop over GET or POST keys and in this way it should know that noCache is a not useful parameter to parse or to check. In other cases a server-side code should consider generated radom value as a key.

Why there is a getTime plus a random value and not just the first one ?
- because some client application should call more than a single request at the same time

Why there is a full stop between getDate and random value ?
- because if client date is modified there are less possibilities that generated value was just used (paranoia style)

I think these F.A.Q. are enought and I hope You'll find this simple function useful :-)

P.S. with ActionScript just change the regExp replacing with uri.indexOf("?") >= 0

Thursday, December 07, 2006

The byte family is now complete, welcome bytedom

another "$" dollar function ? elements prototypes ? no, just a simple library with its namespace that doesn't modify anything else !
This is my last creation to complete my lightweight low-level framework that should be everything You need for your Web 2.0 sites or to develop more complex libraries too.

I've found EJ idea great but I always look for my own solutions.
I've thought about bytedom since I've created btefx but btesonwas more important than simply dom management (P.S. new byteson version 2.0b is available) but now I've completed what I need to develop my projects.

This is the bytedom method list:

  • addClassName, to add if not present a class name to an element

  • addEvent, to add a standard name event such click, load, mouseover and every other, DOMContentLoaded too

  • clear, to remove empty textnode from an entire document (FireFox, for example, reads newlines as textnodes)

  • create, to create one or more elements (input, div, span .. and every other)

  • every, a method like Array.every official JS 1.5 method, usable with a list of elements and arrays too

  • filter, same style of every, to get only what You need with your dedicated filter function

  • forEach, as every and filter, to do something with a list of nodes / elements or arrays too

  • get, something like dollar function, to get one or more elements with specified ids, lists of nodes of specified types or a list of elements with specified classNames

  • getStyle, to know a property of a specified element style

  • pop, to get and remove an element from a parent node

  • preventDefault, to prevent events defaults

  • push, to get and add an element at the end of a parent node (something like appendChild)

  • remove, to get and remove an element from a parent node

  • removeClassName, to remove a className, if present, from an node / element

  • removeEvent, to remove a standard name event such click, load, mouseover and every other, DOMContentLoaded too

  • replace, to get and replace a new node from a parent

  • reverse, to reverse the order of every child found inside a parent node

  • shift, to get and remove the first element of a parent node

  • some, as every, filter and forEach

  • text, to get and create one or more text nodes

  • toggle, to hide an element storing its old visibility and display style values ... and to assign them if element is toggled again

  • unshift, to add one or more element at the top of a parent node


These useful methods (at least in my humil opinion) let you get, modify, filter or manage dom elements in a simple, funnny (?) and JS friendly way.

This is just one of examples present in this page while this is a new anti pixel logo for people that use every byte library:
byte family
that with every member is less than 10 Kbytes for packer version, less than 15 Kbytes for clean crunched version and finally less than 7 for memtronic version.

Please sorry for incomplete bytedom site, I'll update API section as soon as I can.
Now, You could read about every method and parameters directly inside Open Source file version.

I hope you'll like new bytedom library and please tell me if something doesn't work correclty or some browser is not compatible (successful tested with IE5+, FF1+, Opera8+, Safri2+, KDE3.4+).