MediaWiki:EtymologyFanInOut.js

De Wikcionario, el diccionario libre

Nota: Después de publicar, quizás necesite actualizar la caché de su navegador para ver los cambios.

  • Firefox/Safari: Mantenga presionada la tecla Shift mientras pulsa el botón Actualizar, o presiona Ctrl+F5 o Ctrl+R (⌘+R en Mac)
  • Google Chrome: presione Ctrl+Shift+R (⌘+Shift+R en Mac)
  • Internet Explorer/Edge: mantenga presionada Ctrl mientras pulsa Actualizar, o presione Ctrl+F5
  • Opera: Presiona Ctrl+F5.
/********************************************
 * Muestra dos tablas con las aportaciones
 * de otras lenguas al destino y con las 
 * aportaciones del destino a otras lenguas
 *
 * Autor: Usuario:Juan_renombrado
 ********************************************
 */
 
 
if (typeof String.prototype.capitalize ==='undefined') {
     String.prototype.capitalize =function () {
         return this[0].toUpperCase() +this.slice(1);
    };
}
 
function EtymologyFanInOut() {}
EtymologyFanInOut.prototype.colour =function (element, ratio) {
     var rojo =255.0 *((100.0 -parseFloat(ratio)) / 100.0)
    , verde = (255.0 *parseFloat(ratio)) / 100.0;
     $(element).css('background-color', 'rgb(' +rojo.toFixed(0) +',' +verde.toFixed(0) +',0)');
};
 
EtymologyFanInOut.prototype.Pair =function (i, v) {
     this.i =i;
     this.v =v;
};
 
EtymologyFanInOut.prototype.addPageLayout = function(element){
   $('<table class="collapsible" style="border:dotted thin gray;width:100%;"><caption style="cursor:pointer;font-weight:bold;">Fan-In y Fan-Out</caption><tr><td><div id="etymfaninout" style="width:100%;"></div></td></tr></table>')
.appendTo(element);
   $('<span style="float:left;display:inline-block;"><input type="submit" id="etymfanin-aceptar" value="Aportes desde otras lenguas"><span id="etymfanin-contenido"></span></span>"').appendTo('#etymfaninout');
   $('<span style="float:right;display:inline-block;"><input type="submit" id="etymfanout-aceptar" value="Aportes a otras lenguas"><span id="etymfanout-contenido"></span></span>"').appendTo('#etymfaninout');
   $('<span id="etymfanin-cabecera"></span><span id="etymfanin-status"></span><table class="sortable wikitable" style="text-align:right;"><caption>Fan-in</caption><thead><tr style="text-align:center;"><th>idioma</th><th>peso</th><th>cantidad</th></tr></thead><tbody id="etymfanin-lista"></tbody></table>').appendTo('#etymfanin-contenido');
   $('<span id="etymfanout-cabecera"></span><span id="etymfanout-status"></span><table class="sortable wikitable" style="text-align:right;"><caption>Fan-out</caption><thead><tr style="text-align:center;"><th>idioma</th><th>aporte<br/>interno</th><th>aporte<br/>externo</th><th>confianza</th><th>peso</th><th>étimos</th><th>lemas</th></tr></thead><tbody id="etymfanout-lista"></tbody></table>').appendTo('#etymfanout-contenido');  
};
 
/**
 * EtymologyFanOut
 * The target language's contribution to other languages is calculated
 * 
 * Parameters:
 * isocode -> target's code language (iso 8859-[1,2,3,5,WikiMedia])
 * finishHandler -> this handler will be executed after the process is concluded (optional)
 * 
 * Methods:
 * populate()
 * 
 */
function EtymologyFanOut(isocode, finishHandler) {
     this.langCode =isocode;
     this.fanOutList =[];
     this.expandableString =['['];
     this.acumCardinal =0;
     this.acumCantidad =0;
     this.acumPuntuacion =0;
     this.stringPointer =0;
     this.nData =0;
     if (typeof finishHandler ==='function') {
        this.finishHandler =finishHandler;
    }
}
 
EtymologyFanOut.prototype =new EtymologyFanInOut();
 
EtymologyFanOut.prototype.populateView =function () {
     var that =this;
     $.each(this.fanOutList, function () {
         var porcentaje =100 *this.p / that.acumPuntuacion
        , interno = 100 *this.inn
        , externo = 100 *this.out
        , elemento = $('<tr><th>' +this.n +'</th><td class="interno">' +interno.toFixed(2) +'%</td><td class="externo">' +externo.toFixed(2) +'%</td><td class="fiel">' +this.fiel.toFixed(2) +'</td><td class="pct">' +porcentaje.toFixed(2) +'%</td><td class="num">' +this.c +'</td><td>' +this.t +'</td></tr>').appendTo('#etymfanout-lista');
         that.colour($(elemento).children('.pct').first(), porcentaje);
    });
     if (typeof this.finishHandler ==='function') {
         //console.log('llamando al finalizador');
         this.finishHandler();
    }
};
 
EtymologyFanOut.prototype.retrieveExpansion =function (n) {
     var that =this;
     $('#etymfanout-status').text('[ recuperando cantidades ' +n +']');
     //console.log('-----------retrieveExpansion ['+n+']--------------------');
     $.getJSON('//es.wiktionary.org/w/api.php?callback=?', {
         action: "expandtemplates"
        , format: "json"
        , text: this.expandableString[n]
    }
    , function (obj) {
         if (!obj ||!obj.expandtemplates ||obj.error) {
             $('#etymfanout-status').text("error recuperando objeto");
        }else {
             //console.log(obj.expandtemplates['*']);
             var listData = JSON.parse(obj.expandtemplates['*']);
             $.each(listData, function () {
                 that.acumCardinal +=this.c;
                 that.acumCantidad +=this.t;
                 var o ={
                     "n": this.n, "c": this.c, "t": this.t, "inn": 0, "out": 0, "fiel": Math.log(this.t), "p": 0
                };
                 that.fanOutList.push(o);
                 //that.total += value;
 
            });
            if (n <that.stringPointer) {
                 that.retrieveExpansion(Number(n)+1);
            }else {
	         $('#etymfanout-status').hide();
                 $.each(that.fanOutList, function () {
                     this.inn =this.c / this.t;
                     this.out =this.c / that.acumCardinal;
                     that.acumPuntuacion +=(this.p =(this.inn +this.out) *this.fiel);
                     //console.log(value);
 
                });
                 that.fanOutList.sort(function (a, b) {
                     return b.p -a.p;
                });
                that.populateView();
            }
        }
    });
};
 
EtymologyFanOut.prototype.retrieveCategoryList =function (data) {
     var that =this,
     eS = that.expandableString,
     ii = that.stringPointer;
     
     $('#etymfanout-status').text('[ recuperando lista de idiomas ' +this.nData +']');
     //console.log('recuperando lista de categorías');
     $.getJSON('//es.wiktionary.org/w/api.php?callback=?', data, function (obj) {
         if (!obj ||!obj.query ||obj.error) {
             $('#etymfanout-status').text("error recuperando objeto");
        }else {
             //console.log(obj.expandtemplates['*']);
             $.each(obj.query.categorymembers, function () {
                 //console.log(index+': '+value.title);
                 // va creando la cadena expandible con el cardinal de cada categoría, el nombre del idioma y el número de lemas del idioma
                 //console.log(value.title);
                 var nombre =this.title
                , filtro = nombre.replace(/Categoría:\S+:Palabras de origen\s.+/, '');
                 if (filtro.length >0) {
                    return;
                }
                 nombre =nombre.replace('Categoría:', '').replace(/:Palabras de origen\s.*/, '').toLowerCase();
                 // GET method has a maximum length, so we need to split the string into manageable parts
                 eS[ii] +='{"n":"{{'+nombre+'|texto=x}}","c":{{formatnum:{{PAGESINCATEGORY:'+this.title.substring('Categoría:'.length) +'}}|R}},"t":{{formatnum:{{PAGESINCATEGORY:{{ucfirst:{{'+nombre+'|texto=x}}}}'+(nombre !=='es' ? '-Español' : '') +'}}|R}} },';
                 if (eS[ii].length >4000) {                   
                     eS[ii] = eS[ii].replace(/,$/,'') +']';
                     ii = (++that.stringPointer);
                     eS.push('[');
                }
            });
            if (obj['query-continue']) {
                 data.cmcontinue =obj['query-continue'].categorymembers.cmcontinue;
                 ++that.nData;
                 that.retrieveCategoryList(data);
            }else {
		 eS[ii] = eS[ii].replace(/,$/,'') +']';
                 that.retrieveExpansion(0);
            }
        }
    });
};
 
EtymologyFanOut.prototype.populate =function () {
     // recupera nombre de normalizar_categoría
     var that =this;
     $('#etymfanout-status').text('[ recuperando nombre canónico ]');
     $.getJSON('//es.wiktionary.org/w/api.php?callback=?', {
         action: "expandtemplates"
        , format: "json"
        , text: "{{normalizar categoría|" +this.langCode +"}}"
    }
    , function (obj) {
         if (!obj ||!obj.expandtemplates ||obj.error) {
             $('#etymfanout-status').text("error recuperando objeto");
        }else {
             $('#etymfanout-status').text('');
             //console.log(obj.expandtemplates['*']);
             var queryData ={
                 action: "query"
                , format: "json"
                , list: 'categorymembers'
                , cmnamespace: 14
                , cmtitle: 'Categoría:Palabras de origen ' +obj.expandtemplates['*']
            };
             that.retrieveCategoryList(queryData);
        }
    });
};
 
/**
 * EtymologyFanIn
 * The external and internal contribution to the target language is calculated
 * 
 * Parameters:
 * isocode -> target's code language (iso 8859-[1,2,3,5,WikiMedia])
 * finishHandler -> this handler will be executed after the process is concluded (optional)
 * 
 * Methods:
 * populate()
 * 
 */
function EtymologyFanIn(isocode, finishHandler) {
     this.langCode =isocode;
     this.prefix ='Categoría:' +this.langCode.toUpperCase() +':Palabras';
     this.total =0;
     this.fanInSize =0;
     this.fanInList =[];
     this.expandableString =['{"idiomas":['];
     this.stringPointer = 0;
     this.retrieved = 0;
     if (typeof finishHandler ==='function') {
        this.finishHandler =finishHandler;
    }
}
 
EtymologyFanIn.prototype =new EtymologyFanInOut();
 
EtymologyFanIn.prototype.populateView =function (nombre, cantidad) {
     $('#etymfanin-cabecera').prepend('<span id="idioma">' +nombre +': ' +this.total +' etimologías de </span><span id="total">~' +cantidad +'</span>');
     var that =this;
     $.each(this.fanInList, function () {
         var porcentaje =100.0 *parseFloat(this.v) / parseFloat(that.total)
        , elemento = $('<tr><th>' +this.i +'</th><td class="pct">' +porcentaje.toFixed(2) +'%</td><td class="num">' +this.v +'</td></tr>').appendTo('#etymfanin-lista');
         that.colour($(elemento).children('.pct').first(), porcentaje);
    });
     if (typeof this.finishHandler ==='function') {
         //console.log('llamando al finalizador');
         this.finishHandler();
    }
};
 
EtymologyFanIn.prototype.retrieveExpansion =function (n) {
     var that =this;
     $('#etymfanin-status').text('[ recuperando cantidades '+n+']');
     $.getJSON('//es.wiktionary.org/w/api.php?callback=?', {
         action: "expandtemplates"
        , format: "json"
        , text: this.expandableString[n]
    }
    , function (obj) {
         if (!obj ||!obj.expandtemplates ||obj.error) {
             $('#etymfanin-status').text("error recuperando objeto");
        }else {
             var retrievedObj = JSON.parse(obj.expandtemplates['*'])
            , listNum = retrievedObj.idiomas;
             $.each(listNum, function () {
                 that.fanInList[that.retrieved].v =this;
		 ++that.retrieved;
                 that.total +=this;
            });
             that.fanInList.sort(function (a, b) {
                 return b.v -a.v;
            });
            if (n <that.stringPointer) {
                 that.retrieveExpansion(Number(n)+1);
            }else {
	         $('#etymfanin-status').hide();
		 that.populateView(retrievedObj.nombre, retrievedObj.cantidad);
            }
        }
    });
};
 
EtymologyFanIn.prototype.retrieveCategoryList =function (data) {
     $('#etymfanin-status').text('[ recuperando idiomas ]');
     var that =this,
     eS = that.expandableString,
     ii = that.stringPointer;
     $.getJSON('//es.wiktionary.org/w/api.php?callback=?', data, function (obj) {
         if (!obj ||!obj.query ||obj.error) {
             $('#etymfanin-status').text("error recuperando objeto");
        }else {
             //console.log(obj.query.categorymembers.length);
             $.each(obj.query.categorymembers, function () {
                 var nombre =this.title.substring(that.prefix.length);
                 nombre =nombre.replace('de origen ', '').replace(/(incierto|epónimo|onomatopéyico)/, '*$1').replace('formadas por ', '*');
                 that.fanInList.push(new that.Pair(nombre, 0));
                 eS[ii] +="{{formatnum:{{PAGESINCATEGORY:" +this.title.substring('Categoría:'.length) +"}}|R}},";
                 ++that.fanInSize;
		 if(eS[ii].length >4000){
		     eS[ii] = eS[ii].replace(/,$/,'') +"]}";
                     ii = (++that.stringPointer);
                     eS.push('{"idiomas":[');
		 }
            });
             $('#etymfanin-status').text('[ recuperados ' +that.fanInSize +' ]');
             if (obj['query-continue']) {
                 data.cmcontinue =obj['query-continue'].categorymembers.cmcontinue;
                 that.retrieveCategoryList(data);
            }else {
		 eS[ii] = eS[ii].replace(/,$/,'');
                 eS[ii] +='],"nombre":"{{'+that.langCode+'|texto=x}}","cantidad": {{formatnum:{{PAGESINCATEGORY:{{ucfirst:{{'+that.langCode +'|texto=x}}}}'+(that.langCode !=='es' ? '-Español' : '') +' }}|R}} }';
                 // expand mediawiki templates
		 that.retrieveExpansion(0);
            }
        }
    });
};

EtymologyFanIn.prototype.populate =function () {
     var queryData ={
         action: "query"
        , format: "json"
        , list: 'categorymembers'
        , cmnamespace: 14
        , cmtitle: 'Categoría:' +this.langCode.toUpperCase() +':Palabras por origen'
        , rawcontinue: true
    };
     this.retrieveCategoryList(queryData);
};

$(document).ready(function () {
    if (!etymFanInOutCode || !etymFanInOutLayoutParent) {
        return;
    }
    (new EtymologyFanInOut).addPageLayout(etymFanInOutLayoutParent);
    $('#etymfanout-aceptar').click(function () {
         //if($('#codigo').val()){
         var that =this
        , fanOut; //$(this).prop('disabled', true);
         $(this).hide();
         //langCode = $('#codigo').val().toLowerCase();
         $('#etymfanout-lista').empty();
         $('#etymfanout-cabecera').empty();
         $('#etymfanout-status').show();
         fanOut =new EtymologyFanOut(etymFanInOutCode/*, function(){$(that).prop('disabled', false);}*/ );
         fanOut.populate();
         //}
        
    });
     $('#etymfanin-aceptar').click(function () {
         //if($('#codigo').val()){
         var that =this
        , fanIn; //$(this).prop('disabled', true);
         $(this).hide();
         //langCode = $('#codigo').val().toLowerCase();
         $('#etymfanin-lista').empty();
         $('#etymfanin-cabecera').empty();
         $('#etymfanin-status').show();
         fanIn =new EtymologyFanIn(etymFanInOutCode/*, function(){$(that).prop('disabled', false);}*/ );
         fanIn.populate();
         //}
        
    });
});