<commit_before>
var contentstatus=0;
var count =1;
var timer;
var flag = 1 ;
var mapflag=1;
var page = 1;
////////////////////////////////random img start///////////////////////////////////
setInterval(function()
{
$(".hero").fadeOut( 1500, function() {
$(".hero").attr("style",'background:url("css/img/img'+count+'.jpg")');});
$('.hero').css('display', 'block');
$('.hero').animate({ opacity: 0 }, 0);
$('.hero').animate({ opacity: 1, top: "-10px" }, 2000);
    // Animation complete.
    if(count === 4)
    {
    	count=1;
    }
  count++ ;

}, 10000);

/////////////////////////////////script google analytics//////////////////////////////////////

  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-51359625-1', 'worldresident.net');
  ga('send', 'pageview');

///////////////////////////////////random img end///////////////////////////////////////

$(document).ready(function(){

///////////////init////////////////
$(".sel_district").attr('disabled','disabled');
$(".sel_provine").attr('disabled','disabled');
$(".sel_amphures").attr('disabled','disabled');

//////////////////////////////Moblie controller/////////////////////////////////////////////////////////////////////////
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
//alert(navigator.userAgent);
}

$$(".content1").swipeRight(function(){expandmap();});
$$(".content1").swipeLeft(function(){minimizemap();});
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////init page//////////////////////////////////////////////////////////
$(".auto_map_info").attr("height","0px");
$(".auto_map_info iframe").attr("height","0px");
$(".auto_map_info").attr("width","66%");
$(".auto_map_info iframe").attr("width","66%");
$("#loginopen").on("click",function(){
$(".loginfrm").css("visibility","visible");
$("#username_txt").focus();
});
/////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////function zone////////////////////////////////////////
function expandmap(){$(".auto_map_info").animate({height:window.screen.height-385+"px"});$(".auto_map_info iframe").animate({height:window.screen.height-385+"px"});$(".content1").animate({width:"100%"});$("#imgleftside").hide();};
function minimizemap(){$(".content1").animate({width:"23.23176%"});$("#imgleftside").show();$("#menu_index").show();};
function showlogin(){$(".loginfrm").css("visibility","visible");};
function hidelogin(){$(".loginfrm").css("visibility","hidden");};
/////////////////////////////////////////////////////////////////////////////////////////

$("#password_txt").focus(showlogin);
$("#username_txt").focus(showlogin);
$("#password_txt").focusout(hidelogin);
$("#username_txt").focusout(hidelogin);
$("#search_txt").focusout(function(){if(flag==0){minimizemap(); $("#menu_index").show();}});
$("#search_txt").on("click",function(){expandmap(); $("#menu_index").hide();});
$(".content1").on({
    'mouseover': function () {if(flag===1){timer = setTimeout(function () {contentstatus=1;expandmap();}, 1000);}},
    'mouseout' : function () {if(contentstatus===1){minimizemap(); contentstatus=0;}clearTimeout(timer);}
});
$(".pin").on({'mouseover': function () {flag=0;},'mouseout' : function () {flag=1;}});
$("#menu_index").on({'mouseover': function () {flag=0;},'mouseout' : function () {flag=1;}});
$(".content13").on({'mouseover': function () {flag=0;},'mouseout' : function () {flag=1;}});

$("#map_canvas").on("click",function(){$(".auto_map_info").animate({height:"0px"});$(".auto_map_info iframe").animate({height:"0px"});});
$("#tbrshow").html("");
$.ajax({type:'GET',url:'http://www.worldresident.net/getdb',success:function(data) {for(var i=0;i<10;i++){
					if(i==0)
					$("#tbrshow").append("

"+data[i].title+"
</ld>
");
					else
					$("#tbrshow").append("

"+data[i].title+"
</ld>
");
					}
                    $(".linkme").on({
    'mouseover': function () {$(this).addClass("hover");},
    'mouseout' : function () {$(this).removeClass("hover");}
});
                     $(".linkme").bind("tap",function(){window.open("http://www.worldresident.net/info.html?id="+$(this).attr('id'),"_blank");});

				},
				error:function(err) {
					//alert("Sorry, I can't get the feed");
				}
			});

});
///////////////////////zipcode request//////////////////////////////////////////////////////////
$('.sel_amphures_plus').change(function(){

  $('.txt_amphures').val($(this).val());
});

$('#txt_zipcode1').on('input',function(){fetchzip($('#txt_zipcode1'));});
$('#txt_zipcode2').on('input',function(){fetchzip($('#txt_zipcode2'));});
$('#txt_zipcode3').on('input',function(){fetchzip($('#txt_zipcode3'));});

function fetchzip(ele){

  if($(ele).val().length>=2)
{
$.ajax({
                type:'GET',
                url:'http://www.worldresident.net/zip?zip='+$(ele).val(),
                success:function(data) {
                    var pro = new Array();
                    var amp =new Array();
                    var dis = new Array();
                    var pos = new Array();
 $('.sel_district').html("");
  $('.sel_provine').html("");
  $('.sel_amphures_plus').html("");
   $('.sel_district_plus').html("");
  for(var i=0;i<data.length;i++)
  {
    pos.push(data[i].zipcode);
    pro.push(data[i].province_name);
    dis.push(data[i].amphur_name);
     amp.push(data[i].district_name);
  }
  pos = eliminateDuplicates(pos);
   pro = eliminateDuplicates(pro);
   amp = eliminateDuplicates(amp);
   dis = eliminateDuplicates(dis);

// globals
var rawTags = pos;
var inputField = $(ele);
var initInputFieldValue = inputField.value;
var dataList = document.getElementById('htmlListTags');
var initNbVirgules = (initInputFieldValue.match(/,/g)||[]).length;

fillDatalist("");

function fillDatalist(prefix) {
  var nbRawList = rawTags.length;
  // vide la liste initiale (pas utile si elle est vide au début) // FIXME
  while(dataList.childNodes.length > 0) {
    dataList.removeChild(dataList.childNodes[0]);
  }
  // la recréé avec les tags de l’array
  for (i=0; i < nbRawList; i++ ) {
    var nOpt = document.createElement("option");
    nOpt.value = prefix+rawTags[i];
    dataList.appendChild(nOpt);
  }
}

function mainLoop() {
  var currInputFieldValue = inputField.value;
  var currInputFieldValueTrimed = inputField.value.replace(/^\s+|\s+$/g, "");
  var currNbVirgules = (currInputFieldValue.match(/,/g)||[]).length;

  // renouvelle les "option" uniquement si le contenu de l’input à changé.
  if (currInputFieldValueTrimed != initInputFieldValue) {
    // renouvelle que si on a tout juste ajouté ou retiré une virgule depuis le dernier passage.
    if (initNbVirgules != currNbVirgules) {
      // récupère l’emplacement de la dernière virgule
      var lsIndex = currInputFieldValueTrimed.lastIndexOf(",");
      // récupère la chaine contenant jusqu’au dernier tag entier dans le contenu du champ
      var str = (lsIndex != -1) ? currInputFieldValueTrimed.substr(0, lsIndex)+", " : "";
      fillDatalist(str);
      initNbVirgules = currNbVirgules;
    }
    initInputFieldValue = currInputFieldValueTrimed;
  }
  setTimeout("mainLoop()", 100); // la fonction se redéclenchera dans 0,1s
  return true;
}
mainLoop();

   $.each(dis, function(key, value) {
     $('.sel_district_plus')
         .append($("<option></option>")
         .attr("value",value)
         .text(value));
});
     $.each(pro, function(key, value) {
     $('.sel_provine')
         .append($("<option></option>")
         .attr("value",value)
         .text(value));
});
       $.each(amp, function(key, value) {
     $('.sel_amphures_plus')
         .append($("<option></option>")
         .attr("value",value)
         .text(value));
});

                },
                error:function(err) {
                    alert("Something bad happend, IN " +url );

                }
            });
}
if($(ele).val().length==0)
{
  $('.sel_district').html("");
  $('.sel_provine').html("");
  $('.txt_amphures').html("");
    $('.sel_amphures_plus').html("");

}
}

function eliminateDuplicates(arr) {
  var i,
      len=arr.length,
      out=[],
      obj={};

  for (i=0;i<len;i++) {
    obj[arr[i]]=0;
  }
  for (i in obj) {
    out.push(i);
  }
  return out;
}

//$(".linkme").on('tap',window.location="/worldresiden/info?id="+$$(this).id);
/////////////////////////////////////////////////for info request////////////////////////////////
var parameter = window.location.search.replace( "?", "" );
var values = parameter.split("=");
 var lat ;
                    var loong ;
 if(values[0]==="id"&&values[1]!=null)
 {

    $.ajax({
                type:'GET',
                url:'http://www.worldresident.net/info?'+values[0]+"="+values[1],
                success:function(data) {
                     lat = data.location[0];
                     loong = data.location[1];
                     console.log(data.location[1]);
                    $("#nameaprt").html(data.title);
                    $("#detailaprt").html(data.detail);
                       if(data.location!=null)
                       {
                    $("#locationaprt").html('');
                   }
                   else
                   {
                    $("#locationaprt").html(" ")
                   }
                    $("#imageaprt").html(data.image);
                },
                error:function(err) {
                    alert("Something bad happend, IN " +url );

                }
            });
 }
if(values[0]==="page"&&values[1]!=null)
{
   $.ajax({
                type:'GET',
                url:'http://www.worldresident.net/page?'+values[0]+"="+values[1],
                success:function(data) {

            for(var i=0;i<15;i++)
				{
					var stat = 0;
				for(var j =0;j<20;j++)
					{
					try{	if(data[i].images[j].match(/jpg/g)||data[i].images[j].match(/png/g))
						{
						$("#columns").append('

'+data[i].title+'

');
              						j=20;
									stat=1;
						}
					   }
					catch(ex){}
					}

					if(stat===0)
					{
						$("#columns").append('

'+data[i].title+'

');

						}

                }
                 $(".pin").on("click",function(){window.open("http://www.worldresident.net/info.html?id="+$(this).attr('id'),"_blank")});

                },
                error:function(err) {
                    alert("Something bad happend, IN " +url );

                }
            });

}
/////////////////////////////////////////check page action ////////////////////////////////////////
$(window).scroll(function() {
   if($(window).scrollTop() + $(window).height() == $(document).height()) {
	   page++;
        $.ajax({
                type:'GET',
                url:'http://www.worldresident.net/page?page='+page,
                success:function(data) {

            for(var i=0;i<15;i++)
				{
					var stat = 0;
				for(var j =0;j<20;j++)
					{ try{
						if(data[i].images[j].match(/jpg/g)||data[i].images[j].match(/png/g))
						{
						$("#columns").append('

'+data[i].title+'

');
              						j=20;
									stat=1;
						}
						}
					catch(ex){}
					}
					if(stat===0)
					{
						$("#columns").append('

'+data[i].title+'

');

						}

                }

          $(".pin").unbind();
           $(".pin").bind("click",function(){window.open("http://www.worldresident.net/info.html?id="+$(this).attr('id'))});

                },
                error:function(err) {
                    alert("Something bad happend, IN " +url );

                }

            });
   }
});
<commit_msg>select plus<commit_after>
var contentstatus=0;
var count =1;
var timer;
var flag = 1 ;
var mapflag=1;
var page = 1;
////////////////////////////////random img start///////////////////////////////////
setInterval(function()
{
$(".hero").fadeOut( 1500, function() {
$(".hero").attr("style",'background:url("css/img/img'+count+'.jpg")');});
$('.hero').css('display', 'block');
$('.hero').animate({ opacity: 0 }, 0);
$('.hero').animate({ opacity: 1, top: "-10px" }, 2000);
    // Animation complete.
    if(count === 4)
    {
    	count=1;
    }
  count++ ;

}, 10000);

/////////////////////////////////script google analytics//////////////////////////////////////

  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-51359625-1', 'worldresident.net');
  ga('send', 'pageview');

///////////////////////////////////random img end///////////////////////////////////////

$(document).ready(function(){

///////////////init////////////////
$(".sel_district").attr('disabled','disabled');
$(".sel_provine").attr('disabled','disabled');
$(".sel_amphures").attr('disabled','disabled');

//////////////////////////////Moblie controller/////////////////////////////////////////////////////////////////////////
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
//alert(navigator.userAgent);
}

$$(".content1").swipeRight(function(){expandmap();});
$$(".content1").swipeLeft(function(){minimizemap();});
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////init page//////////////////////////////////////////////////////////
$(".auto_map_info").attr("height","0px");
$(".auto_map_info iframe").attr("height","0px");
$(".auto_map_info").attr("width","66%");
$(".auto_map_info iframe").attr("width","66%");
$("#loginopen").on("click",function(){
$(".loginfrm").css("visibility","visible");
$("#username_txt").focus();
});
/////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////function zone////////////////////////////////////////
function expandmap(){$(".auto_map_info").animate({height:window.screen.height-385+"px"});$(".auto_map_info iframe").animate({height:window.screen.height-385+"px"});$(".content1").animate({width:"100%"});$("#imgleftside").hide();};
function minimizemap(){$(".content1").animate({width:"23.23176%"});$("#imgleftside").show();$("#menu_index").show();};
function showlogin(){$(".loginfrm").css("visibility","visible");};
function hidelogin(){$(".loginfrm").css("visibility","hidden");};
/////////////////////////////////////////////////////////////////////////////////////////

$("#password_txt").focus(showlogin);
$("#username_txt").focus(showlogin);
$("#password_txt").focusout(hidelogin);
$("#username_txt").focusout(hidelogin);
$("#search_txt").focusout(function(){if(flag==0){minimizemap(); $("#menu_index").show();}});
$("#search_txt").on("click",function(){expandmap(); $("#menu_index").hide();});
$(".content1").on({
    'mouseover': function () {if(flag===1){timer = setTimeout(function () {contentstatus=1;expandmap();}, 1000);}},
    'mouseout' : function () {if(contentstatus===1){minimizemap(); contentstatus=0;}clearTimeout(timer);}
});
$(".pin").on({'mouseover': function () {flag=0;},'mouseout' : function () {flag=1;}});
$("#menu_index").on({'mouseover': function () {flag=0;},'mouseout' : function () {flag=1;}});
$(".content13").on({'mouseover': function () {flag=0;},'mouseout' : function () {flag=1;}});

$("#map_canvas").on("click",function(){$(".auto_map_info").animate({height:"0px"});$(".auto_map_info iframe").animate({height:"0px"});});
$("#tbrshow").html("");
$.ajax({type:'GET',url:'http://www.worldresident.net/getdb',success:function(data) {for(var i=0;i<10;i++){
					if(i==0)
					$("#tbrshow").append("

"+data[i].title+"
</ld>
");
					else
					$("#tbrshow").append("

"+data[i].title+"
</ld>
");
					}
                    $(".linkme").on({
    'mouseover': function () {$(this).addClass("hover");},
    'mouseout' : function () {$(this).removeClass("hover");}
});
                     $(".linkme").bind("tap",function(){window.open("http://www.worldresident.net/info.html?id="+$(this).attr('id'),"_blank");});

				},
				error:function(err) {
					//alert("Sorry, I can't get the feed");
				}
			});

});
///////////////////////zipcode request//////////////////////////////////////////////////////////
$('.sel_amphures_plus').change(function(){

  $('.txt_amphures').val($(this).val());
});

$('#txt_zipcode1').on('input',function(){fetchzip($('#txt_zipcode1'));});
$('#txt_zipcode2').on('input',function(){fetchzip($('#txt_zipcode2'));});
$('#txt_zipcode3').on('input',function(){fetchzip($('#txt_zipcode3'));});

function fetchzip(ele){

  if($(ele).val().length>=2)
{
$.ajax({
                type:'GET',
                url:'http://www.worldresident.net/zip?zip='+$(ele).val(),
                success:function(data) {
                    var pro = new Array();
                    var amp =new Array();
                    var dis = new Array();
                    var pos = new Array();
 $('.sel_district').html("");
  $('.sel_provine').html("");
  $('.sel_amphures_plus').html("");
   $('.sel_district_plus').html("");
  for(var i=0;i<data.length;i++)
  {
    pos.push(data[i].zipcode);
    pro.push(data[i].province_name);
    dis.push(data[i].amphur_name);
     amp.push(data[i].district_name);
  }
  pos = eliminateDuplicates(pos);
   pro = eliminateDuplicates(pro);
   amp = eliminateDuplicates(amp);
   dis = eliminateDuplicates(dis);

// globals
var rawTags = pos;

var initInputFieldValue = $(ele).val();
var dataList = document.getElementById('htmlListTags');
var initNbVirgules = (initInputFieldValue.match(/,/g)||[]).length;

fillDatalist("");

function fillDatalist(prefix) {
  var nbRawList = rawTags.length;
  // vide la liste initiale (pas utile si elle est vide au début) // FIXME
  while(dataList.childNodes.length > 0) {
    dataList.removeChild(dataList.childNodes[0]);
  }
  // la recréé avec les tags de l’array
  for (i=0; i < nbRawList; i++ ) {
    var nOpt = document.createElement("option");
    nOpt.value = prefix+rawTags[i];
    dataList.appendChild(nOpt);
  }
}

function mainLoop() {
  var currInputFieldValue = $(ele).val();
  var currInputFieldValueTrimed = $(ele).val().replace(/^\s+|\s+$/g, "");
  var currNbVirgules = (currInputFieldValue.match(/,/g)||[]).length;

  // renouvelle les "option" uniquement si le contenu de l’input à changé.
  if (currInputFieldValueTrimed != initInputFieldValue) {
    // renouvelle que si on a tout juste ajouté ou retiré une virgule depuis le dernier passage.
    if (initNbVirgules != currNbVirgules) {
      // récupère l’emplacement de la dernière virgule
      var lsIndex = currInputFieldValueTrimed.lastIndexOf(",");
      // récupère la chaine contenant jusqu’au dernier tag entier dans le contenu du champ
      var str = (lsIndex != -1) ? currInputFieldValueTrimed.substr(0, lsIndex)+", " : "";
      fillDatalist(str);
      initNbVirgules = currNbVirgules;
    }
    initInputFieldValue = currInputFieldValueTrimed;
  }
  setTimeout("mainLoop()", 100); // la fonction se redéclenchera dans 0,1s
  return true;
}
mainLoop();

   $.each(dis, function(key, value) {
     $('.sel_district_plus')
         .append($("<option></option>")
         .attr("value",value)
         .text(value));
});
     $.each(pro, function(key, value) {
     $('.sel_provine')
         .append($("<option></option>")
         .attr("value",value)
         .text(value));
});
       $.each(amp, function(key, value) {
     $('.sel_amphures_plus')
         .append($("<option></option>")
         .attr("value",value)
         .text(value));
});

                },
                error:function(err) {
                    alert("Something bad happend, IN " +url );

                }
            });
}
if($(ele).val().length==0)
{
  $('.sel_district').html("");
  $('.sel_provine').html("");
  $('.txt_amphures').html("");
    $('.sel_amphures_plus').html("");

}
}

function eliminateDuplicates(arr) {
  var i,
      len=arr.length,
      out=[],
      obj={};

  for (i=0;i<len;i++) {
    obj[arr[i]]=0;
  }
  for (i in obj) {
    out.push(i);
  }
  return out;
}

//$(".linkme").on('tap',window.location="/worldresiden/info?id="+$$(this).id);
/////////////////////////////////////////////////for info request////////////////////////////////
var parameter = window.location.search.replace( "?", "" );
var values = parameter.split("=");
 var lat ;
                    var loong ;
 if(values[0]==="id"&&values[1]!=null)
 {

    $.ajax({
                type:'GET',
                url:'http://www.worldresident.net/info?'+values[0]+"="+values[1],
                success:function(data) {
                     lat = data.location[0];
                     loong = data.location[1];
                     console.log(data.location[1]);
                    $("#nameaprt").html(data.title);
                    $("#detailaprt").html(data.detail);
                       if(data.location!=null)
                       {
                    $("#locationaprt").html('');
                   }
                   else
                   {
                    $("#locationaprt").html(" ")
                   }
                    $("#imageaprt").html(data.image);
                },
                error:function(err) {
                    alert("Something bad happend, IN " +url );

                }
            });
 }
if(values[0]==="page"&&values[1]!=null)
{
   $.ajax({
                type:'GET',
                url:'http://www.worldresident.net/page?'+values[0]+"="+values[1],
                success:function(data) {

            for(var i=0;i<15;i++)
				{
					var stat = 0;
				for(var j =0;j<20;j++)
					{
					try{	if(data[i].images[j].match(/jpg/g)||data[i].images[j].match(/png/g))
						{
						$("#columns").append('

'+data[i].title+'

');
              						j=20;
									stat=1;
						}
					   }
					catch(ex){}
					}

					if(stat===0)
					{
						$("#columns").append('

'+data[i].title+'

');

						}

                }
                 $(".pin").on("click",function(){window.open("http://www.worldresident.net/info.html?id="+$(this).attr('id'),"_blank")});

                },
                error:function(err) {
                    alert("Something bad happend, IN " +url );

                }
            });

}
/////////////////////////////////////////check page action ////////////////////////////////////////
$(window).scroll(function() {
   if($(window).scrollTop() + $(window).height() == $(document).height()) {
	   page++;
        $.ajax({
                type:'GET',
                url:'http://www.worldresident.net/page?page='+page,
                success:function(data) {

            for(var i=0;i<15;i++)
				{
					var stat = 0;
				for(var j =0;j<20;j++)
					{ try{
						if(data[i].images[j].match(/jpg/g)||data[i].images[j].match(/png/g))
						{
						$("#columns").append('

'+data[i].title+'

');
              						j=20;
									stat=1;
						}
						}
					catch(ex){}
					}
					if(stat===0)
					{
						$("#columns").append('

'+data[i].title+'

');

						}

                }

          $(".pin").unbind();
           $(".pin").bind("click",function(){window.open("http://www.worldresident.net/info.html?id="+$(this).attr('id'))});

                },
                error:function(err) {
                    alert("Something bad happend, IN " +url );

                }

            });
   }
});
<|endoftext|>


<commit_before>(function (context, factory) {
  if (typeof module === 'object' && typeof module.exports === 'object') {
    module.exports = function (context, GM) {
      var _ = require('lodash');
      var core = require('./core.js');
      var misc = require('./misc.js');
      var dispatcher = require('./dispatcher.js');
      var modules = [misc, dispatcher].map(function (v) {
        return v.call(null, context, GM);
      });
      var $ = _.assign.apply(null, modules);
      return factory(context, GM, core, $);
    };
  } else {
    factory(context, {
      getValue: GM_getValue,
      setValue: GM_setValue,
    }, context._, context.$);
  }
}(this, function (context, GM, _, $) {
  'use strict';

  var MANIFEST = [
    {
      name: 'version',
      key: 'version',
      default_: 0,
      verify: function (v) {
        return typeof v === 'number' && v >= 0;
      },
    },
    {
      name: 'alignCenter',
      key: 'align_center',
      default_: true,
      verify: isBoolean,
    },
    {
      name: 'changeBackground',
      key: 'change_background',
      default_: true,
      verify: isBoolean,
    },
    {
      name: 'externalServerSupport',
      key: 'external_server_support',
      default_: false,
      verify: isBoolean,
    },
    {
      name: 'redirectImage',
      key: 'redirect_image',
      default_: true,
      verify: isBoolean,
    },
    {
      name: 'scaleImage',
      key: 'scale_image',
      default_: true,
      verify: isBoolean,
    },
    {
      name: 'logLevel',
      key: 'log_level',
      default_: 1,
      verify: function (v) {
        return typeof v === 'number' && v >= 0 && v <= 2;
      },
    },
  ];
  var PATCHES = [
    function (c) {
      var ac = typeof c.alignCenter === 'boolean';
      if (typeof c.changeBackground !== 'boolean') {
        c.changeBackground = ac ? c.alignCenter : true;
      }
      if (typeof c.scaleImage !== 'boolean') {
        c.scaleImage = ac ? c.alignCenter : true;
      }
      if (!ac) {
        c.alignCenter = true;
      }
      if (typeof c.redirectImage !== 'boolean') {
        c.redirectImage = true;
      }
    },
    function (c) {
      if (typeof c.externalServerSupport !== 'boolean') {
        c.externalServerSupport = false;
      }
    },
    function (c) {
      if (typeof c.logLevel !== 'number') {
        c.logLevel = 1;
      }
    },
  ];

  var window = context.window;

  function isBoolean(v) {
    return typeof v === 'boolean';
  }

  function createConfig () {
    var c = {};
    _.C(MANIFEST).each(function (m) {
      Object.defineProperty(c, m.name, {
        configurable: true,
        enumerable: true,
        get: function () {
          return GM.getValue(m.key, m.default_);
        },
        set: function (v) {
          GM.setValue(m.key, v);
        },
      });
    });
    return c;
  }

  function senityCheck (c) {
    var ok = _.C(MANIFEST).all(function (m) {
      return m.verify(c[m.name]);
    });
    if (!ok) {
      c.version = 0;
    }
    return c;
  }

  function migrate (c) {
    while (c.version < PATCHES.length) {
      PATCHES[c.version](c);
      ++c.version;
    }
    return c;
  }

  $.config = migrate(senityCheck(createConfig()));

  $.register({
    rule: {
      host: /^adsbypasser\.github\.io$/,
      path: /^\/configure\.html$/,
    },
    ready: function () {

      $.window.commit = function (data) {
        data.version = $.config.version;
        _.C(data).each(function (v, k) {
          $.config[k] = v;
        });
      };

      // TODO: i18n
      $.window.render({
        version: $.config.version,
        options: {
          alignCenter: {
            type: 'checkbox',
            value: $.config.alignCenter,
            label: 'Align Center',
            help: 'Align image to the center if possible. (default: enabled)',
          },
          changeBackground: {
            type: 'checkbox',
            value: $.config.changeBackground,
            label: 'Change Background',
            help: 'Use Firefox-like image background if possible. (default: enabled)',
          },
          redirectImage: {
            type: 'checkbox',
            value: $.config.redirectImage,
            label: 'Redirect Image',
            help: [
              'Directly open image link if possible. (default: enabled)',
              'If disabled, redirection will only works on link shortener sites.',
            ].join('
\n'),
          },
          scaleImage: {
            type: 'checkbox',
            value: $.config.scaleImage,
            label: 'Scale Image',
            help: 'When image loaded, scale it to fit window if possible. (default: enabled)',
          },
          externalServerSupport: {
            type: 'checkbox',
            value: $.config.externalServerSupport,
            label: 'External Server Support',
            help: [
              'Send URL information to external server to enhance features (e.g.: captcha resolving). (default: disabled)',
              'Affected sites:',
              'setlinks.us (captcha)',
            ].join('
\n'),
          },
          logLevel: {
            type: 'select',
            value: $.config.logLevel,
            menu: [
              [0, '0 (quiet)'],
              [1, '1 (default)'],
              [2, '2 (verbose)'],
            ],
            label: 'Log Level',
            help: [
              'Log level in developer console. (default: 1)',
              '0 will not print anything in console.',
              '1 will only print logs on affected sites.',
              '2 will print on any sites.',
            ].join('
\n'),
          },
        },
      });

    },
  });

  return $;

}));

// ex: ts=2 sts=2 sw=2 et
// sublime: tab_size 2; translate_tabs_to_spaces true; detect_indentation false; use_tab_stops true;
// kate: space-indent on; indent-width 2;
<commit_msg>Defence type error.<commit_after>(function (context, factory) {
  if (typeof module === 'object' && typeof module.exports === 'object') {
    module.exports = function (context, GM) {
      var _ = require('lodash');
      var core = require('./core.js');
      var misc = require('./misc.js');
      var dispatcher = require('./dispatcher.js');
      var modules = [misc, dispatcher].map(function (v) {
        return v.call(null, context, GM);
      });
      var $ = _.assign.apply(null, modules);
      return factory(context, GM, core, $);
    };
  } else {
    factory(context, {
      getValue: GM_getValue,
      setValue: GM_setValue,
    }, context._, context.$);
  }
}(this, function (context, GM, _, $) {
  'use strict';

  var MANIFEST = [
    {
      name: 'version',
      key: 'version',
      default_: 0,
      verify: function (v) {
        return typeof v === 'number' && v >= 0;
      },
    },
    {
      name: 'alignCenter',
      key: 'align_center',
      default_: true,
      verify: isBoolean,
    },
    {
      name: 'changeBackground',
      key: 'change_background',
      default_: true,
      verify: isBoolean,
    },
    {
      name: 'externalServerSupport',
      key: 'external_server_support',
      default_: false,
      verify: isBoolean,
    },
    {
      name: 'redirectImage',
      key: 'redirect_image',
      default_: true,
      verify: isBoolean,
    },
    {
      name: 'scaleImage',
      key: 'scale_image',
      default_: true,
      verify: isBoolean,
    },
    {
      name: 'logLevel',
      key: 'log_level',
      default_: 1,
      verify: function (v) {
        return typeof v === 'number' && v >= 0 && v <= 2;
      },
    },
  ];
  var PATCHES = [
    function (c) {
      var ac = typeof c.alignCenter === 'boolean';
      if (typeof c.changeBackground !== 'boolean') {
        c.changeBackground = ac ? c.alignCenter : true;
      }
      if (typeof c.scaleImage !== 'boolean') {
        c.scaleImage = ac ? c.alignCenter : true;
      }
      if (!ac) {
        c.alignCenter = true;
      }
      if (typeof c.redirectImage !== 'boolean') {
        c.redirectImage = true;
      }
    },
    function (c) {
      if (typeof c.externalServerSupport !== 'boolean') {
        c.externalServerSupport = false;
      }
    },
    function (c) {
      if (typeof c.logLevel !== 'number') {
        c.logLevel = 1;
      }
    },
  ];

  var window = context.window;

  function isBoolean(v) {
    return typeof v === 'boolean';
  }

  function createConfig () {
    var c = {};
    _.C(MANIFEST).each(function (m) {
      Object.defineProperty(c, m.name, {
        configurable: true,
        enumerable: true,
        get: function () {
          return GM.getValue(m.key, m.default_);
        },
        set: function (v) {
          GM.setValue(m.key, v);
        },
      });
    });
    return c;
  }

  function senityCheck (c) {
    var ok = _.C(MANIFEST).all(function (m) {
      return m.verify(c[m.name]);
    });
    if (!ok) {
      c.version = 0;
    }
    return c;
  }

  function migrate (c) {
    if (typeof c.version !== 'number' || c.version < 0) {
      throw new _.AdsBypasserError('wrong config version: ' + c.version);
    }
    while (c.version < PATCHES.length) {
      PATCHES[c.version](c);
      ++c.version;
    }
    return c;
  }

  $.config = migrate(senityCheck(createConfig()));

  $.register({
    rule: {
      host: /^adsbypasser\.github\.io$/,
      path: /^\/configure\.html$/,
    },
    ready: function () {

      $.window.commit = function (data) {
        data.version = $.config.version;
        _.C(data).each(function (v, k) {
          $.config[k] = v;
        });
      };

      // TODO: i18n
      $.window.render({
        version: $.config.version,
        options: {
          alignCenter: {
            type: 'checkbox',
            value: $.config.alignCenter,
            label: 'Align Center',
            help: 'Align image to the center if possible. (default: enabled)',
          },
          changeBackground: {
            type: 'checkbox',
            value: $.config.changeBackground,
            label: 'Change Background',
            help: 'Use Firefox-like image background if possible. (default: enabled)',
          },
          redirectImage: {
            type: 'checkbox',
            value: $.config.redirectImage,
            label: 'Redirect Image',
            help: [
              'Directly open image link if possible. (default: enabled)',
              'If disabled, redirection will only works on link shortener sites.',
            ].join('
\n'),
          },
          scaleImage: {
            type: 'checkbox',
            value: $.config.scaleImage,
            label: 'Scale Image',
            help: 'When image loaded, scale it to fit window if possible. (default: enabled)',
          },
          externalServerSupport: {
            type: 'checkbox',
            value: $.config.externalServerSupport,
            label: 'External Server Support',
            help: [
              'Send URL information to external server to enhance features (e.g.: captcha resolving). (default: disabled)',
              'Affected sites:',
              'setlinks.us (captcha)',
            ].join('
\n'),
          },
          logLevel: {
            type: 'select',
            value: $.config.logLevel,
            menu: [
              [0, '0 (quiet)'],
              [1, '1 (default)'],
              [2, '2 (verbose)'],
            ],
            label: 'Log Level',
            help: [
              'Log level in developer console. (default: 1)',
              '0 will not print anything in console.',
              '1 will only print logs on affected sites.',
              '2 will print on any sites.',
            ].join('
\n'),
          },
        },
      });

    },
  });

  return $;

}));

// ex: ts=2 sts=2 sw=2 et
// sublime: tab_size 2; translate_tabs_to_spaces true; detect_indentation false; use_tab_stops true;
// kate: space-indent on; indent-width 2;
<|endoftext|>


<commit_before>'use strict'

import React, {PropTypes} from 'react'
import Component          from 'react-pure-render/component'
import ReactDOM           from 'react-dom'

// ROUTING
import {
    BrowserRouter as Router,
    Match,
    Route,
    Switch,
    IndexRoute
}                           from 'react-router-dom'
// import CreateBrowserHistory from 'history/lib/createBrowserHistory'

// nothing

// MOBX
import { Provider } from 'mobx-react'
import store, {stores}     from './stores'
import autorun      from './stores/lib/autorunWrapper.js'
autorun(stores)

// import Routes            from './Routes'
import App                  from './App'
import HomePage             from './pages/HomePage'
import SearchPage           from './pages/SearchPage'
import NotFoundPage         from './pages/NotFoundPage'

if (module.hot) module.hot.accept()

if (process.env.NODE_ENV !== 'production' && process.env.IS_BROWSER) {
    // Enable React devtools
    window.React = React
}

class RootTest extends Component {

    render() {
        return
RouteTest-render()

    }

}

const createRoutes = () => (
    <Switch>
        <Route exact path="/" component={App} />
        <Route path="/test" component={RootTest} />
        <Route path="*" component={NotFoundPage} />
    </Switch>
)
// refactor: export = debugging helper
export const routes = createRoutes()

export class Root extends Component {

    constructor(props) {
        super(props)

        console.log('process.env.IS_BROWSER?', process.env.IS_BROWSER)

        // console.log('store (default)', store)
        // console.log('stores (fm)', store)
    }

    render() {
        console.log('[Root->render()]')

        return (
            <Provider store={store}>
                {/* <App /> */}
                <Router>
                    {routes}
                </Router>
            </Provider>
        )
    }

}

if (process.env.IS_BROWSER) {
    ReactDOM.render(
        <Root />,
        document.getElementById('app')
    )
}
<commit_msg>nothing<commit_after>'use strict'

import React, {PropTypes} from 'react'
import Component          from 'react-pure-render/component'
import ReactDOM           from 'react-dom'

// ROUTING
import {
    BrowserRouter as Router,
    Match,
    Route,
    Switch,
    IndexRoute
}                           from 'react-router-dom'
// import CreateBrowserHistory from 'history/lib/createBrowserHistory'

// nothing

// MOBX
import { Provider } from 'mobx-react'
import store, {stores}     from './stores'
import autorun      from './stores/lib/autorunWrapper.js'
autorun(stores)

// import Routes            from './Routes'
import App                  from './App'
import HomePage             from './pages/HomePage'
import SearchPage           from './pages/SearchPage'
import NotFoundPage         from './pages/NotFoundPage'

if (module.hot) module.hot.accept()

if (process.env.NODE_ENV !== 'production' && process.env.IS_BROWSER) {
    // Enable React devtools
    window.React = React
}

// nothing

class RootTest extends Component {

    render() {
        return
RouteTest-render()

    }

}

const createRoutes = () => (
    <Switch>
        <Route exact path="/" component={App} />
        <Route path="/test" component={RootTest} />
        <Route path="*" component={NotFoundPage} />
    </Switch>
)
// refactor: export = debugging helper
export const routes = createRoutes()

export class Root extends Component {

    constructor(props) {
        super(props)

        console.log('process.env.IS_BROWSER?', process.env.IS_BROWSER)

        // console.log('store (default)', store)
        // console.log('stores (fm)', store)
    }

    render() {
        console.log('[Root->render()]')

        return (
            <Provider store={store}>
                {/* <App /> */}
                <Router>
                    {routes}
                </Router>
            </Provider>
        )
    }

}

if (process.env.IS_BROWSER) {
    ReactDOM.render(
        <Root />,
        document.getElementById('app')
    )
}
<|endoftext|>


<commit_before>var q = require('q');
var hbs = require('hbs');
var fs = require('fs');
var path = require('path');
var _ = require('lodash');

function View(path, data) {
  this.path = path;
  this.data = {};
  this.helpers = {
    json: function(context, options) {
      return JSON.stringify(context);
    }
  };
  this.setData(data);
  this.registerHelpers();
}

View.globalData = {};

View.prototype.registerHelpers = function() {
  Object.keys(this.helpers).forEach(function(key) {
    hbs.registerHelper(key, this.helpers[key]);
  }.bind(this));
};

View.prototype.setData = function(data) {
  _.merge(this.data, data || {});
};

View.prototype.setGlobalData = function(data) {
  _.merge(View.globalData, data || {});
};

View.prototype.getData = function(key) {
  if (key) {
    return this.data[key] || View.globalData[key];
  }
  return this.data;
};

View.prototype.renderHtml = function(html, callback) {

  // Merge the global and view data
  var data = _.merge({}, View.globalData, this.getData());

  return hbs.compile(html)(data);
};

View.prototype.render = function() {
  var html = fs.readFileSync(path.join('app', 'views', this.path + '.hbs'), 'utf8');
  return this.compile().then(function() {
    return this.renderHtml(html);
  }.bind(this));
};

View.prototype.compile = function() {
  return this.resolveDependencies();
};

View.prototype.resolveDependencies = function() {
  return this.resolvePromises();
};

View.prototype.resolvePromises = function() {

  var data = {};
  var promises = this.getPromises();

  return q.allResolved(promises.objects).spread(function() {

    Array.prototype.slice.call(arguments).forEach(function(output, i) {
      data[promises.keys[i]] = output;
    });

    this.setData(data);

  }.bind(this));
};

View.prototype.getPromises = function() {

  var data = this.getData();
  var promises = Object.keys(data).filter(function(prop) {
    return (typeof data[prop] === 'object' && q.isPromise(data[prop]));
  });

  return {
    keys: promises.map(function(prop) {
      return prop;
    }),
    objects: promises.map(function(prop) {
      return data[prop];
    })
  };
};

module.exports = View;
<commit_msg>Simplified view<commit_after>var q = require('q');
var hbs = require('hbs');
var fs = require('fs');
var path = require('path');
var _ = require('lodash');

function View(path, data) {
  this.path = path;
  this.data = {};
  this.helpers = {
    json: function(context, options) {
      return JSON.stringify(context);
    }
  };
  this.setData(data);
  this.registerHelpers();
}

View.globalData = {};

View.prototype.registerHelpers = function() {
  Object.keys(this.helpers).forEach(function(key) {
    hbs.registerHelper(key, this.helpers[key]);
  }.bind(this));
};

View.prototype.setData = function(data) {
  _.merge(this.data, data || {});
};

View.prototype.setGlobalData = function(data) {
  _.merge(View.globalData, data || {});
};

View.prototype.getData = function(key) {
  if (key) {
    return this.data[key] || View.globalData[key];
  }
  return this.data;
};

View.prototype.compileTemplate = function(template, callback) {

  // Merge the global and view data
  var data = _.merge({}, View.globalData, this.getData());

  return hbs.compile(template)(data);
};

View.prototype.render = function() {
  var template = fs.readFileSync(path.join('app', 'views', this.path + '.hbs'), 'utf8');
  return this.resolvePromises().then(function() {
    return this.compileTemplate(template);
  }.bind(this));
};

View.prototype.resolvePromises = function() {

  var data = {};
  var promises = this.getPromises();

  return q.allSettled(promises).spread(function() {

    Array.prototype.slice.call(arguments).forEach(function(output, i) {
      data[promises.keys[i]] = output;
    });

    this.setData(data);

  }.bind(this));
};

View.prototype.getPromises = function() {

  var data = this.getData();

  var promises = Object.keys(data).filter(function(prop) {
    return (typeof data[prop] === 'object' && q.isPromise(data[prop]));
  });

  return {
    keys: promises.map(function(prop) {
      return prop;
    }),
    objects: promises.map(function(prop) {
      return data[prop];
    })
  };
};

module.exports = View;
<|endoftext|>


<commit_before>define(["CM/Frontend/JsonSerializable"], function() {

  QUnit.module('CM/Frontend/JsonSerializable:flat', {
    beforeEach: function() {
      var FooDefaults = CM_Frontend_JsonSerializable.extend({
        defaults: function() {
          return {
            foo: 'defaultValue'
          };
        }
      });

      var models = {
        foo: new CM_Frontend_JsonSerializable({val1: 1}),
        bar: new CM_Frontend_JsonSerializable({val1: 1}),
        fooWithDefaults: new FooDefaults({val1: 1})
      };

      var synced = [];
      models.foo.on('sync', function(model, syncAttributes) {
        synced.push(syncAttributes);
      });

      this.models = models;
      this.synced = synced;
    },

    afterEach: function() {
      this.models.foo.off();
      this.models.bar.off();
      this.models = null;
      this.synced = null;
    }
  });

  QUnit.test("compatible", function(assert) {
    var foo = this.models.foo;
    var bar = this.models.bar;
    assert.ok(foo.compatible(bar) && bar.compatible(foo));
    assert.ok(!foo.compatible({val1: 1}));
    assert.ok(!bar.compatible({val1: 1}));
  });

  QUnit.test("toJSON", function(assert) {
    var foo = this.models.foo;

    assert.deepEqual(foo.toJSON(), {val1: 1});
    foo.set({
      val1: 1,
      val2: {foo: 1}
    });
    assert.deepEqual(foo.toJSON(), {val1: 1, val2: {foo: 1}});
  });

  QUnit.test("equals", function(assert) {
    var foo = this.models.foo;
    var bar = this.models.bar;

    assert.ok(foo.equals(bar) && bar.equals(foo));
    assert.ok(!foo.equals());
    assert.ok(!foo.equals(null));
    assert.ok(!foo.equals({val1: 1}));
    assert.ok(!foo.equals(new CM_Frontend_JsonSerializable()));

    foo.set({val1: 2});
    assert.ok(!foo.equals(bar) && !bar.equals(foo));

    foo.set({
      val1: 1,
      val2: new CM_Frontend_JsonSerializable({val: 2})
    });
    bar.set({
      val1: 1,
      val2: new CM_Frontend_JsonSerializable({val: 2})
    });
    assert.ok(foo.equals(bar) && bar.equals(foo));

    foo.get('val2').set({val: 1});
    assert.ok(!foo.equals(bar) && !bar.equals(foo));

    foo.get('val2').set({val: 2});
    foo.set('val3', 3);
    assert.ok(!foo.equals(bar) && !bar.equals(foo));

    foo.unset('val1');
    foo.unset('val3');
    assert.ok(!foo.equals(bar) && !bar.equals(foo));

    foo.set('val1', 1);
    assert.ok(foo.equals(bar) && bar.equals(foo));

    bar.set('val3', 3);
    assert.ok(!foo.equals(bar) && !bar.equals(foo));

    bar.unset('val1');
    bar.unset('val3');
    assert.ok(!foo.equals(bar) && !bar.equals(foo));
  });

  QUnit.test("sync", function(assert) {
    var foo = this.models.foo;
    var bar = this.models.bar;
    var synced = this.synced;
    var result = null;

    assert.throws(function() {
      foo.sync({val1: 1});
    }, /Failed to update the model, incompatible parameter/);

    result = foo.sync(bar);
    assert.equal(result, null);
    assert.deepEqual(synced, []);

    bar.set({val1: 3, val2: 1});
    result = foo.sync(bar);
    assert.equal(foo.get('val1'), 3);
    assert.equal(foo.get('val2'), 1);
    assert.deepEqual(result, {updated: {val1: 3}, added: {val2: 1}});
    assert.deepEqual(synced, [{updated: {val1: 3}, added: {val2: 1}}]);

    bar.unset('val2');
    result = foo.sync(bar);
    assert.equal(foo.get('val2'), undefined);
    assert.deepEqual(result, {removed: ['val2']});
    assert.deepEqual(synced, [
      {updated: {val1: 3}, added: {val2: 1}},
      {removed: ['val2']}
    ]);
  });

  QUnit.test("sync with defaults", function(assert) {
    var foo = this.models.fooWithDefaults;
    var bar = this.models.bar;
    var result = null;

    result = foo.sync(bar);
    assert.equal(result, null);
    assert.equal(foo.get('foo'), 'defaultValue');

    bar.set({val1: 3, val2: 1, foo: 'newValue'});
    result = foo.sync(bar);
    assert.equal(foo.get('val1'), 3);
    assert.equal(foo.get('val2'), 1);
    assert.equal(foo.get('foo'), 'newValue');
    assert.deepEqual(result, {updated: {val1: 3, foo: 'newValue'}, added: {val2: 1}});
  });

  // Nested CM_Frontend_JsonSerializable instances

  QUnit.module('CM/Frontend/JsonSerializable:nested', {
    beforeEach: function() {
      var foo001 = new CM_Frontend_JsonSerializable({name: '1'});
      var foo011 = new CM_Frontend_JsonSerializable({name: '1.1'});
      var foo111 = new CM_Frontend_JsonSerializable({name: '1.1.1'});
      foo001.set('1.1', foo011);
      foo011.set('1.1.1', foo111);

      var clone001 = foo001.clone();
      var clone011 = foo011.clone();
      var clone111 = foo111.clone();
      clone001.set('1.1', clone011);
      clone011.set('1.1.1', clone111);

      var synced = {foo001: null, foo011: null, foo111: null};

      foo001.on('sync', function(model, syncAttributes) {
        synced.foo001 = syncAttributes;
      });
      foo011.on('sync', function(model, syncAttributes) {
        synced.foo011 = syncAttributes;
      });
      foo111.on('sync', function(model, syncAttributes) {
        synced.foo111 = syncAttributes;
      });

      this.models = {
        foo: {foo001: foo001, foo011: foo011, foo111: foo111},
        clone: {clone001: clone001, clone011: clone011, clone111: clone111}
      };
      this.synced = synced;
    },

    afterEach: function() {
      _.each(this.models.foo, function(model) {
        model.off();
      });
      this.models = null;
      this.synced = null;
    }
  });

  QUnit.test("toJSON", function(assert) {
    assert.deepEqual(this.models.foo.foo001.toJSON(), {
      'name': '1',
      '1.1': {
        'name': '1.1',
        '1.1.1': {
          'name': '1.1.1'
        }
      }
    });
  });

  QUnit.test("toJSON with array", function(assert) {
    var foo001 = this.models.foo.foo001;
    var foo011 = this.models.foo.foo011;
    var clone111 = this.models.clone.clone111;

    foo011.set('list', [
      clone111.clone(), [clone111.clone()], null, 1, {foo: 1, bar: clone111.clone()}
    ]);

    assert.deepEqual(foo001.toJSON(), {
      'name': '1',
      '1.1': {
        'name': '1.1',
        '1.1.1': {
          'name': '1.1.1'
        },
        'list': [
          {name: '1.1.1'}, [{name: '1.1.1'}], null, 1, {foo: 1, bar: {name: '1.1.1'}}
        ]
      }
    });
  });

  QUnit.test("sync: change higher level child attribute", function(assert) {
    var foo001 = this.models.foo.foo001;
    var clone001 = this.models.clone.clone001;
    var clone111 = this.models.clone.clone111;
    var synced = this.synced;
    var result = null;

    clone111.set('name', 'clone 1.1.1');
    result = foo001.sync(clone001);
    assert.equal(foo001.get('1.1').get('1.1.1').get('name'), 'clone 1.1.1');
    assert.deepEqual(result, {
      updated: {
        '1.1': {
          updated: {
            '1.1.1': {
              updated: {'name': 'clone 1.1.1'}
            }
          }
        }
      }
    });
    assert.deepEqual(synced.foo001, {
      updated: {
        '1.1': {
          updated: {
            '1.1.1': {
              updated: {'name': 'clone 1.1.1'}
            }
          }
        }
      }
    });
    assert.deepEqual(synced.foo011, {
      updated: {
        '1.1.1': {
          updated: {'name': 'clone 1.1.1'}
        }
      }
    });
    assert.deepEqual(synced.foo111, {
      updated: {
        'name': 'clone 1.1.1'
      }
    });
  });

  QUnit.test("sync: change middle level child attribute", function(assert) {
    var foo001 = this.models.foo.foo001;
    var clone001 = this.models.clone.clone001;
    var clone011 = this.models.clone.clone011;
    var synced = this.synced;
    var result = null;

    clone011.set('name', 'clone 1.1');

    result = foo001.sync(clone001);
    assert.equal(foo001.get('1.1').get('name'), 'clone 1.1');
    assert.deepEqual(result, {
      updated: {
        '1.1': {
          updated: {'name': 'clone 1.1'}
        }
      }
    });
    assert.deepEqual(synced.foo001, {
      updated: {
        '1.1': {
          updated: {'name': 'clone 1.1'}
        }
      }
    });
    assert.deepEqual(synced.foo011, {
      updated: {'name': 'clone 1.1'}
    });
    assert.deepEqual(synced.foo111, null);
  });

  QUnit.test("sync: add child attribute", function(assert) {
    var foo001 = this.models.foo.foo001;
    var clone001 = this.models.clone.clone001;
    var clone011 = this.models.clone.clone011;
    var synced = this.synced;
    var result = null;

    clone011.set('val1', 1);

    result = foo001.sync(clone001);
    assert.equal(foo001.get('1.1').get('val1'), 1);
    assert.deepEqual(result, {
      updated: {
        '1.1': {
          added: {'val1': 1}
        }
      }
    });
    assert.deepEqual(synced.foo001, {
      updated: {
        '1.1': {
          added: {'val1': 1}
        }
      }
    });
    assert.deepEqual(synced.foo011, {
      added: {'val1': 1}
    });
    assert.deepEqual(synced.foo111, null);
  });

  QUnit.test("sync: add child JsonSerialized attribute", function(assert) {
    var foo001 = this.models.foo.foo001;
    var clone001 = this.models.clone.clone001;
    var clone011 = this.models.clone.clone011;
    var synced = this.synced;
    var result = null;

    clone011.set('val1', new CM_Frontend_JsonSerializable({foo: 1}));

    result = foo001.sync(clone001);
    assert.ok(foo001.get('1.1').get('val1') instanceof CM_Frontend_JsonSerializable);
    assert.deepEqual(result, {
      updated: {
        '1.1': {
          added: {
            'val1': {foo: 1}
          }
        }
      }
    });
    assert.deepEqual(synced.foo001, {
      updated: {
        '1.1': {
          added: {
            'val1': {foo: 1}
          }
        }
      }
    });
    assert.deepEqual(synced.foo011, {
      added: {
        'val1': {foo: 1}
      }
    });
    assert.deepEqual(synced.foo111, null);
  });

  QUnit.test("sync: remove child attribute", function(assert) {
    var foo001 = this.models.foo.foo001;
    var clone001 = this.models.clone.clone001;
    var clone011 = this.models.clone.clone011;
    var synced = this.synced;
    var result = null;

    clone011.unset('name');

    result = foo001.sync(clone001);
    assert.equal(foo001.get('1.1').get('name'), undefined);
    assert.deepEqual(result, {
      updated: {
        '1.1': {
          removed: ['name']
        }
      }
    });
    assert.deepEqual(synced.foo001, {
      updated: {
        '1.1': {
          removed: ['name']
        }
      }
    });
    assert.deepEqual(synced.foo011, {
      removed: ['name']
    });
    assert.deepEqual(synced.foo111, null);
  });

  QUnit.test("sync: remove child JsonSerialized attribute", function(assert) {
    var foo001 = this.models.foo.foo001;
    var foo111 = this.models.foo.foo111;
    var clone001 = this.models.clone.clone001;
    var clone011 = this.models.clone.clone011;
    var synced = this.synced;
    var result = null;

    clone011.unset('1.1.1');

    var isFoo111Removed = false;
    foo111.on('remove', function() {
      isFoo111Removed = true;
    });

    result = foo001.sync(clone001);
    assert.equal(foo001.get('1.1').get('1.1.1'), undefined);
    assert.deepEqual(result, {
      updated: {
        '1.1': {
          removed: ['1.1.1']
        }
      }
    });
    assert.deepEqual(synced.foo001, {
      updated: {
        '1.1': {
          removed: ['1.1.1']
        }
      }
    });
    assert.deepEqual(synced.foo011, {
      removed: ['1.1.1']
    });
    assert.deepEqual(synced.foo111, null);
    assert.ok(isFoo111Removed);
  });
});
<commit_msg>Add assertions for JsonSerializable::toJSON<commit_after>define(["CM/Frontend/JsonSerializable"], function() {

  QUnit.module('CM/Frontend/JsonSerializable:flat', {
    beforeEach: function() {
      var FooDefaults = CM_Frontend_JsonSerializable.extend({
        defaults: function() {
          return {
            foo: 'defaultValue'
          };
        }
      });

      var models = {
        foo: new CM_Frontend_JsonSerializable({val1: 1}),
        bar: new CM_Frontend_JsonSerializable({val1: 1}),
        fooWithDefaults: new FooDefaults({val1: 1})
      };

      var synced = [];
      models.foo.on('sync', function(model, syncAttributes) {
        synced.push(syncAttributes);
      });

      this.models = models;
      this.synced = synced;
    },

    afterEach: function() {
      this.models.foo.off();
      this.models.bar.off();
      this.models = null;
      this.synced = null;
    }
  });

  QUnit.test("compatible", function(assert) {
    var foo = this.models.foo;
    var bar = this.models.bar;
    assert.ok(foo.compatible(bar) && bar.compatible(foo));
    assert.ok(!foo.compatible({val1: 1}));
    assert.ok(!bar.compatible({val1: 1}));
  });

  QUnit.test("toJSON", function(assert) {
    var foo = this.models.foo;

    assert.deepEqual(foo.toJSON(), {val1: 1});
    foo.set({
      val1: 1,
      val2: {foo: 1}
    });
    assert.deepEqual(foo.toJSON(), {val1: 1, val2: {foo: 1}});
  });

  QUnit.test("equals", function(assert) {
    var foo = this.models.foo;
    var bar = this.models.bar;

    assert.ok(foo.equals(bar) && bar.equals(foo));
    assert.ok(!foo.equals());
    assert.ok(!foo.equals(null));
    assert.ok(!foo.equals({val1: 1}));
    assert.ok(!foo.equals(new CM_Frontend_JsonSerializable()));

    foo.set({val1: 2});
    assert.ok(!foo.equals(bar) && !bar.equals(foo));

    foo.set({
      val1: 1,
      val2: new CM_Frontend_JsonSerializable({val: 2})
    });
    bar.set({
      val1: 1,
      val2: new CM_Frontend_JsonSerializable({val: 2})
    });
    assert.ok(foo.equals(bar) && bar.equals(foo));

    foo.get('val2').set({val: 1});
    assert.ok(!foo.equals(bar) && !bar.equals(foo));

    foo.get('val2').set({val: 2});
    foo.set('val3', 3);
    assert.ok(!foo.equals(bar) && !bar.equals(foo));

    foo.unset('val1');
    foo.unset('val3');
    assert.ok(!foo.equals(bar) && !bar.equals(foo));

    foo.set('val1', 1);
    assert.ok(foo.equals(bar) && bar.equals(foo));

    bar.set('val3', 3);
    assert.ok(!foo.equals(bar) && !bar.equals(foo));

    bar.unset('val1');
    bar.unset('val3');
    assert.ok(!foo.equals(bar) && !bar.equals(foo));
  });

  QUnit.test("sync", function(assert) {
    var foo = this.models.foo;
    var bar = this.models.bar;
    var synced = this.synced;
    var result = null;

    assert.throws(function() {
      foo.sync({val1: 1});
    }, /Failed to update the model, incompatible parameter/);

    result = foo.sync(bar);
    assert.equal(result, null);
    assert.deepEqual(synced, []);

    bar.set({val1: 3, val2: 1});
    result = foo.sync(bar);
    assert.equal(foo.get('val1'), 3);
    assert.equal(foo.get('val2'), 1);
    assert.deepEqual(result, {updated: {val1: 3}, added: {val2: 1}});
    assert.deepEqual(synced, [{updated: {val1: 3}, added: {val2: 1}}]);

    bar.unset('val2');
    result = foo.sync(bar);
    assert.equal(foo.get('val2'), undefined);
    assert.deepEqual(result, {removed: ['val2']});
    assert.deepEqual(synced, [
      {updated: {val1: 3}, added: {val2: 1}},
      {removed: ['val2']}
    ]);
  });

  QUnit.test("sync with defaults", function(assert) {
    var foo = this.models.fooWithDefaults;
    var bar = this.models.bar;
    var result = null;

    result = foo.sync(bar);
    assert.equal(result, null);
    assert.equal(foo.get('foo'), 'defaultValue');

    bar.set({val1: 3, val2: 1, foo: 'newValue'});
    result = foo.sync(bar);
    assert.equal(foo.get('val1'), 3);
    assert.equal(foo.get('val2'), 1);
    assert.equal(foo.get('foo'), 'newValue');
    assert.deepEqual(result, {updated: {val1: 3, foo: 'newValue'}, added: {val2: 1}});
  });

  // Nested CM_Frontend_JsonSerializable instances

  QUnit.module('CM/Frontend/JsonSerializable:nested', {
    beforeEach: function() {
      var foo001 = new CM_Frontend_JsonSerializable({name: '1'});
      var foo011 = new CM_Frontend_JsonSerializable({name: '1.1'});
      var foo111 = new CM_Frontend_JsonSerializable({name: '1.1.1'});
      foo001.set('1.1', foo011);
      foo011.set('1.1.1', foo111);

      var clone001 = foo001.clone();
      var clone011 = foo011.clone();
      var clone111 = foo111.clone();
      clone001.set('1.1', clone011);
      clone011.set('1.1.1', clone111);

      var synced = {foo001: null, foo011: null, foo111: null};

      foo001.on('sync', function(model, syncAttributes) {
        synced.foo001 = syncAttributes;
      });
      foo011.on('sync', function(model, syncAttributes) {
        synced.foo011 = syncAttributes;
      });
      foo111.on('sync', function(model, syncAttributes) {
        synced.foo111 = syncAttributes;
      });

      this.models = {
        foo: {foo001: foo001, foo011: foo011, foo111: foo111},
        clone: {clone001: clone001, clone011: clone011, clone111: clone111}
      };
      this.synced = synced;
    },

    afterEach: function() {
      _.each(this.models.foo, function(model) {
        model.off();
      });
      this.models = null;
      this.synced = null;
    }
  });

  QUnit.test("toJSON", function(assert) {
    assert.deepEqual(this.models.foo.foo001.toJSON(), {
      'name': '1',
      '1.1': {
        'name': '1.1',
        '1.1.1': {
          'name': '1.1.1'
        }
      }
    });
  });

  QUnit.test("toJSON with array", function(assert) {
    var foo001 = this.models.foo.foo001;
    var foo011 = this.models.foo.foo011;
    var clone111 = this.models.clone.clone111;

    foo011.set('list', [
      clone111.clone(), [clone111.clone()], null, 1, {foo: 1, bar: clone111.clone()}
    ]);

    assert.deepEqual(foo001.toJSON(), {
      'name': '1',
      '1.1': {
        'name': '1.1',
        '1.1.1': {
          'name': '1.1.1'
        },
        'list': [
          {name: '1.1.1'}, [{name: '1.1.1'}], null, 1, {foo: 1, bar: {name: '1.1.1'}}
        ]
      }
    });
    assert.equal(JSON.stringify(foo001), '{"name":"1","1.1":{"name":"1.1","1.1.1":{"name":"1.1.1"},"list":[{"name":"1.1.1"},[{"name":"1.1.1"}],null,1,{"foo":1,"bar":{"name":"1.1.1"}}]}}');
  });

  QUnit.test("sync: change higher level child attribute", function(assert) {
    var foo001 = this.models.foo.foo001;
    var clone001 = this.models.clone.clone001;
    var clone111 = this.models.clone.clone111;
    var synced = this.synced;
    var result = null;

    clone111.set('name', 'clone 1.1.1');
    result = foo001.sync(clone001);
    assert.equal(foo001.get('1.1').get('1.1.1').get('name'), 'clone 1.1.1');
    assert.deepEqual(result, {
      updated: {
        '1.1': {
          updated: {
            '1.1.1': {
              updated: {'name': 'clone 1.1.1'}
            }
          }
        }
      }
    });
    assert.deepEqual(synced.foo001, {
      updated: {
        '1.1': {
          updated: {
            '1.1.1': {
              updated: {'name': 'clone 1.1.1'}
            }
          }
        }
      }
    });
    assert.deepEqual(synced.foo011, {
      updated: {
        '1.1.1': {
          updated: {'name': 'clone 1.1.1'}
        }
      }
    });
    assert.deepEqual(synced.foo111, {
      updated: {
        'name': 'clone 1.1.1'
      }
    });
  });

  QUnit.test("sync: change middle level child attribute", function(assert) {
    var foo001 = this.models.foo.foo001;
    var clone001 = this.models.clone.clone001;
    var clone011 = this.models.clone.clone011;
    var synced = this.synced;
    var result = null;

    clone011.set('name', 'clone 1.1');

    result = foo001.sync(clone001);
    assert.equal(foo001.get('1.1').get('name'), 'clone 1.1');
    assert.deepEqual(result, {
      updated: {
        '1.1': {
          updated: {'name': 'clone 1.1'}
        }
      }
    });
    assert.deepEqual(synced.foo001, {
      updated: {
        '1.1': {
          updated: {'name': 'clone 1.1'}
        }
      }
    });
    assert.deepEqual(synced.foo011, {
      updated: {'name': 'clone 1.1'}
    });
    assert.deepEqual(synced.foo111, null);
  });

  QUnit.test("sync: add child attribute", function(assert) {
    var foo001 = this.models.foo.foo001;
    var clone001 = this.models.clone.clone001;
    var clone011 = this.models.clone.clone011;
    var synced = this.synced;
    var result = null;

    clone011.set('val1', 1);

    result = foo001.sync(clone001);
    assert.equal(foo001.get('1.1').get('val1'), 1);
    assert.deepEqual(result, {
      updated: {
        '1.1': {
          added: {'val1': 1}
        }
      }
    });
    assert.deepEqual(synced.foo001, {
      updated: {
        '1.1': {
          added: {'val1': 1}
        }
      }
    });
    assert.deepEqual(synced.foo011, {
      added: {'val1': 1}
    });
    assert.deepEqual(synced.foo111, null);
  });

  QUnit.test("sync: add child JsonSerialized attribute", function(assert) {
    var foo001 = this.models.foo.foo001;
    var clone001 = this.models.clone.clone001;
    var clone011 = this.models.clone.clone011;
    var synced = this.synced;
    var result = null;

    clone011.set('val1', new CM_Frontend_JsonSerializable({foo: 1}));

    result = foo001.sync(clone001);
    assert.ok(foo001.get('1.1').get('val1') instanceof CM_Frontend_JsonSerializable);
    assert.deepEqual(result, {
      updated: {
        '1.1': {
          added: {
            'val1': {foo: 1}
          }
        }
      }
    });
    assert.deepEqual(synced.foo001, {
      updated: {
        '1.1': {
          added: {
            'val1': {foo: 1}
          }
        }
      }
    });
    assert.deepEqual(synced.foo011, {
      added: {
        'val1': {foo: 1}
      }
    });
    assert.deepEqual(synced.foo111, null);
  });

  QUnit.test("sync: remove child attribute", function(assert) {
    var foo001 = this.models.foo.foo001;
    var clone001 = this.models.clone.clone001;
    var clone011 = this.models.clone.clone011;
    var synced = this.synced;
    var result = null;

    clone011.unset('name');

    result = foo001.sync(clone001);
    assert.equal(foo001.get('1.1').get('name'), undefined);
    assert.deepEqual(result, {
      updated: {
        '1.1': {
          removed: ['name']
        }
      }
    });
    assert.deepEqual(synced.foo001, {
      updated: {
        '1.1': {
          removed: ['name']
        }
      }
    });
    assert.deepEqual(synced.foo011, {
      removed: ['name']
    });
    assert.deepEqual(synced.foo111, null);
  });

  QUnit.test("sync: remove child JsonSerialized attribute", function(assert) {
    var foo001 = this.models.foo.foo001;
    var foo111 = this.models.foo.foo111;
    var clone001 = this.models.clone.clone001;
    var clone011 = this.models.clone.clone011;
    var synced = this.synced;
    var result = null;

    clone011.unset('1.1.1');

    var isFoo111Removed = false;
    foo111.on('remove', function() {
      isFoo111Removed = true;
    });

    result = foo001.sync(clone001);
    assert.equal(foo001.get('1.1').get('1.1.1'), undefined);
    assert.deepEqual(result, {
      updated: {
        '1.1': {
          removed: ['1.1.1']
        }
      }
    });
    assert.deepEqual(synced.foo001, {
      updated: {
        '1.1': {
          removed: ['1.1.1']
        }
      }
    });
    assert.deepEqual(synced.foo011, {
      removed: ['1.1.1']
    });
    assert.deepEqual(synced.foo111, null);
    assert.ok(isFoo111Removed);
  });
});
<|endoftext|>


<commit_before>
import { expect } from 'chai';

const {Quest, QuestGen, QuestPopulate}
    = require('../../../client/src/quest-gen');

const FactoryWorld = require('../../../client/src/factory.world');

const questGram1 = '<QUEST> ::= "goto" "kill";';

const questGram2 =
`<QUEST> ::= <goto> "kill";
<goto> ::= <subquest> "goto" | "goto";
<subquest> ::= "goto" | "goto" <QUEST>;`;

const questGram3 =
`<QUEST> ::= <goto> <get> <learn>;
<goto> ::= <learn> "goto_there";
<get> ::= <goto> "get_it";
<learn> ::= "learn_it";`;

describe('QuestGen', () => {
    let questGen = null;

    beforeEach(() => {
        questGen = new QuestGen();
    });

    it('can create simple quests', () => {
        const rules = QuestGen.parse(questGram1);
        const conf = {rules};

        const quest = questGen.genQuestWithConf(conf);
        expect(quest).to.be.instanceof(Quest);
        expect(quest.numQuests()).to.equal(1);
        expect(quest.numTasks()).to.equal(2);
        console.log(JSON.stringify(quest));
    });

    it('can create quests with sub-quests', () => {
        const rules = QuestGen.parse(questGram2);
        const conf = {rules, minQuests: 2};
        const quest = questGen.genQuestWithConf(conf);
        console.log(JSON.stringify(quest));
        expect(quest.numQuests()).to.be.above(1);
    });

    it('creates a single task from each term', () => {
        const rules = QuestGen.parse(questGram3);
        const conf = {debug: true, rules};
        const quest = questGen.genQuestWithConf(conf);
        console.log(JSON.stringify(quest));
        expect(quest.numTasks()).to.equal(6);
    });
});

describe('QuestPopulate', () => {

    it('is used to map quests to resources', () => {
        const questPopul = new QuestPopulate();
        const factWorld = new FactoryWorld();
        const city = factWorld.createCity({
            name: 'QuestCity', nQuarters: 1,
            quarter: [
                {name: 'QuestQuarter', nLevels: 1}
            ]
        });
        const taskList = ['<goto>already_there', '<kill>kill'];
        const quest = new Quest('Kill an actor', taskList);
        questPopul.mapQuestToResources(quest, city, null);
        questPopul.addQuestComponents(city);

        const level = city.getLevels()[0]; // Only one
        const actors = level.getActors();

        let hasGiver = false;
        let hasTarget = false;
        actors.forEach(actor => {
            console.log('Checking actor', actor.getName());
            if (actor.has('QuestTarget')) {hasTarget = true;}
            if (actor.has('QuestGiver')) {hasGiver = true;}
        });

        expect(hasGiver).to.equal(true);
        expect(hasTarget).to.equal(true);
    });
});
<commit_msg>Added more unit tests for quests.<commit_after>
import { expect } from 'chai';

const {Quest, QuestGen, QuestPopulate}
    = require('../../../client/src/quest-gen');
const FactoryWorld = require('../../../client/src/factory.world');
const RGTest = require('../../roguetest');

const questGram1 = '<QUEST> ::= "goto" "kill";';

const questGram2 =
`<QUEST> ::= <goto> "kill";
<goto> ::= <subquest> "goto" | "goto";
<subquest> ::= "goto" | "goto" <QUEST>;`;

const questGram3 =
`<QUEST> ::= <goto> <get> <learn>;
<goto> ::= <learn> "goto_there";
<get> ::= <goto> "get_it";
<learn> ::= "learn_it";`;

describe('QuestGen', () => {
    let questGen = null;

    beforeEach(() => {
        questGen = new QuestGen();
    });

    it('can create simple quests', () => {
        const rules = QuestGen.parse(questGram1);
        const conf = {rules};

        const quest = questGen.genQuestWithConf(conf);
        expect(quest).to.be.instanceof(Quest);
        expect(quest.numQuests()).to.equal(1);
        expect(quest.numTasks()).to.equal(2);
        console.log(JSON.stringify(quest));
    });

    it('can create quests with sub-quests', () => {
        const rules = QuestGen.parse(questGram2);
        const conf = {rules, minQuests: 2};
        const quest = questGen.genQuestWithConf(conf);
        console.log(JSON.stringify(quest));
        expect(quest.numQuests()).to.be.above(1);
    });

    it('creates a single task from each term', () => {
        const rules = QuestGen.parse(questGram3);
        const conf = {debug: true, rules};
        const quest = questGen.genQuestWithConf(conf);
        console.log(JSON.stringify(quest));
        expect(quest.numTasks()).to.equal(6);
    });
});

describe('QuestPopulate', () => {
    let questPopul = null;

    beforeEach(() => {
        questPopul = new QuestPopulate();
    });

    it('is used to map quests to resources', () => {
        const factWorld = new FactoryWorld();
        const city = factWorld.createCity({
            name: 'QuestCity', nQuarters: 1,
            quarter: [
                {name: 'QuestQuarter', nLevels: 1}
            ]
        });
        const taskList = ['<goto>already_there', '<kill>kill'];
        const quest = new Quest('Kill an actor', taskList);
        questPopul.mapQuestToResources(quest, city, null);
        questPopul.addQuestComponents(city);

        const level = city.getLevels()[0]; // Only one
        const actors = level.getActors();

        let hasGiver = false;
        let hasTarget = false;
        actors.forEach(actor => {
            console.log('Checking actor', actor.getName());
            if (actor.has('QuestTarget')) {hasTarget = true;}
            if (actor.has('QuestGiver')) {hasGiver = true;}
        });

        expect(hasGiver).to.equal(true);
        expect(hasTarget).to.equal(true);
    });

    it('can map learn/goto/get/give task', () => {
        const area = RGTest.createTestArea();
        const taskList = [
            '<goto>already_there',
            'listen',
            '<goto>goto',
            '<get>gather',
            '<goto>goto',
            'give'
        ];
        const quest = new Quest('Learn item loc and give it', taskList);
        const areaTile = area.getTileXY(0, 0);
        const city = areaTile.getZones('City')[0];
        const ok = questPopul.mapQuestToResources(quest, city, areaTile);
        expect(ok, 'Quest mapped OK').to.equal(true);
        questPopul.addQuestComponents(city);

        const level = city.getLevels()[0]; // Only one
        const giver = level.getActors().find(a => a.has('QuestGiver'));
        expect(giver).to.not.be.empty;
        const giverComp = giver.get('QuestGiver');
        const questTargets = giverComp.getQuestTargets();
        expect(questTargets.length).to.equal(6);

    });

    it('can map any arbitrary quest without sub-quests to resources', () => {
        for (let i = 0; i < 5; i++) {
            const area = RGTest.createTestArea();
            const numCreated = questPopul.createQuests({}, area, 0, 0);
            expect(numCreated).to.equal(1);
        }
    });

    it('can map any arbitrary quest to resources/tasks/subquests', () => {
        // const area = RGTest.createTestArea();
    });
});
<|endoftext|>


<commit_before>var async            = require('async');
var _                = require('underscore');
var sha1             = require('sha1');
var merkle           = require('merkle');
var vucoin           = require('vucoin');
var eventStream      = require('event-stream');
var inquirer         = require('inquirer');
var dos2unix         = require('./dos2unix');
var parsers          = require('./streams/parsers/doc');
var extractSignature = require('./streams/extractSignature');
var localValidator   = require('./localValidator');
var logger           = require('./logger')('sync');

var CONST_FORCE_TX_PROCESSING = false;

module.exports = function Synchroniser (server, host, port, conf) {
  var that = this;

  // Services
  var TransactionService = server.TransactionsService;
  var PeeringService     = server.PeeringService;
  var ParametersService  = server.ParametersService;
  var BlockchainService  = server.BlockchainService;

  // Models
  var Block      = server.conn.model('Block');
  var Merkle        = server.conn.model('Merkle');
  var Membership    = server.conn.model('Membership');
  var Transaction   = server.conn.model('Transaction');
  var Peer          = server.conn.model('Peer');
  var Configuration = server.conn.model('Configuration');

  this.remoteFingerprint = null;

  this.sync = function (done) {
    logger.info('Connecting remote host...');
    vucoin(host, port, function (err, node) {
      if(err){
        done('Cannot sync: ' + err);
        return;
      }

      // Global sync vars
      var remotePeer = new Peer({});
      var remoteJsonPeer = {};
      var remoteCurrentNumber;
      var remotePubkey;

      async.waterfall([
        function (next){
          logger.info('Sync started.');
          next();
        },

        //============
        // Blockchain
        //============
        function (next){
          logger.info('Downloading Blockchain...');
          async.parallel({
            localCurrent: function (next) {
              BlockchainService.current(function (err, current) {
                next(null, err ? null : current);
              });
            },
            remoteCurrent: function (next) {
              node.blockchain.current(function (err, current) {
                next(null, err ? null : current);
              });
            }
          }, next);
        },
        function (res, next) {
          var lCurrent = res.localCurrent;
          var rCurrent = res.remoteCurrent;
          var i = lCurrent ? lCurrent.number + 1 : 0;
          if (!rCurrent) {
            next('No block found on remote node');
            return;
          }
          async.whilst(
            function () { return rCurrent ? i <= rCurrent.number : false; },
            function (callback) {
                async.waterfall([
                  function (next) {
                    node.blockchain.block(i, next);
                  },
                  function (block, next) {
                    // Rawification of transactions
                    block.transactions.forEach(function (tx) {
                      tx.raw = ["TX", "1", tx.signatories.length, tx.inputs.length, tx.outputs.length, tx.comment ? '1' : '0'].join(':') + '\n';
                      tx.raw += tx.signatories.join('\n') + '\n';
                      tx.raw += tx.inputs.join('\n') + '\n';
                      tx.raw += tx.outputs.join('\n') + '\n';
                      if (tx.comment)
                        tx.raw += tx.comment + '\n';
                      tx.raw += tx.signatures.join('\n') + '\n';
                    });
                    BlockchainService.submitBlock(block, next);
                  },
                  function (block, next) {
                    i++;
                    next();
                  }
                ], callback);
            }, next);
        },

        //============
        // Peer
        //============
        function (next){
          node.network.peering.get(next);
        },
        function (json, next){
          remotePubkey = json.pubkey;
          remotePeer.copyValuesFrom(json);
          var entry = remotePeer.getRaw();
          var signature = dos2unix(remotePeer.signature);
          // Parameters
          if(!(entry && signature)){
            callback('Requires a peering entry + signature');
            return;
          }

          remoteJsonPeer = json;
          remoteJsonPeer.pub = json.pubkey;
          remoteJsonPeer.status = "NOTHING";
          localValidator().checkPeerSignature(remoteJsonPeer, next);
        },
        function (next) {
          async.waterfall([
            function (next){
              PeeringService.submit(remoteJsonPeer, function (err) {
                next(err == 'Peer document is older than currently recorded' ? null : err);
              });
            },
          ], function (err) {
            next(err);
          });
        },

        //==============
        // Transactions
        //==============
        // function (next){
        //   Key.find({ managed: true }, next);
        // },
        // function (keys, next) {
        //   async.forEachSeries(keys, function (key, onKeyDone) {
        //     syncTransactionsOfKey(node, key.fingerprint, onKeyDone);
        //   }, next);
        // },

        //=======
        // Peers
        //=======
        function (next){
          Merkle.peers(next);
        },
        function (merkle, next) {
          node.network.peering.peers.get({}, function (err, json) {
            var rm = new NodesMerkle(json);
            if(rm.root() != merkle.root()){
              var leavesToAdd = [];
              node.network.peering.peers.get({ leaves: true }, function (err, json) {
                _(json.leaves).forEach(function(leaf){
                  if(merkle.leaves().indexOf(leaf) == -1){
                    leavesToAdd.push(leaf);
                  }
                });
                var hashes = [];
                async.forEachSeries(leavesToAdd, function(leaf, callback){
                  async.waterfall([
                    function (cb) {
                      node.network.peering.peers.get({ "leaf": leaf }, cb);
                    },
                    function (json, cb) {
                      var jsonEntry = json.leaf.value;
                      var sign = json.leaf.value.signature;
                      var entry = {};
                      ["version", "currency", "fingerprint", "endpoints"].forEach(function (key) {
                        entry[key] = jsonEntry[key];
                      });
                      entry.signature = sign;
                      entry.pubkey = { fingerprint: entry.fingerprint };
                      logger.info('Peer 0x' + entry.fingerprint);
                      PeeringService.submit(entry, function (err) {
                        cb();
                      });
                    }
                  ], callback);
                }, function(err, result){
                  next(err);
                });
              });
            }
            else next();
          });
        },
      ], function (err, result) {
        logger.info('Sync finished.');
        done(err);
      });
    })
  }
}

function NodesMerkle (json) {

  var that = this;
  var merkleRoot = null;
  ["depth", "nodesCount", "leavesCount"].forEach(function (key) {
    that[key] = json[key];
  });

  this.merkleRoot = json["root"];

  // var i = 0;
  // this.levels = [];
  // while(json && json.levels[i]){
  //   this.levels.push(json.levels[i]);
  //   i++;
  // }

  this.root = function () {
    return this.merkleRoot;
  }
}

function choose (question, defaultValue, ifOK, ifNotOK) {
  inquirer.prompt([{
    type: "confirm",
    name: "q",
    message: question,
    default: defaultValue,
  }], function (answer) {
    answer.q ? ifOK() : ifNotOK();
  });
}
<commit_msg>Sync: refactoring<commit_after>var async            = require('async');
var _                = require('underscore');
var sha1             = require('sha1');
var merkle           = require('merkle');
var vucoin           = require('vucoin');
var eventStream      = require('event-stream');
var inquirer         = require('inquirer');
var dos2unix         = require('./dos2unix');
var parsers          = require('./streams/parsers/doc');
var extractSignature = require('./streams/extractSignature');
var localValidator   = require('./localValidator');
var logger           = require('./logger')('sync');

var CONST_FORCE_TX_PROCESSING = false;

module.exports = function Synchroniser (server, host, port, conf) {
  var that = this;

  // Services
  var TransactionService = server.TransactionsService;
  var PeeringService     = server.PeeringService;
  var ParametersService  = server.ParametersService;
  var BlockchainService  = server.BlockchainService;

  // Models
  var Block      = server.conn.model('Block');
  var Merkle        = server.conn.model('Merkle');
  var Membership    = server.conn.model('Membership');
  var Transaction   = server.conn.model('Transaction');
  var Peer          = server.conn.model('Peer');
  var Configuration = server.conn.model('Configuration');

  this.remoteFingerprint = null;

  this.sync = function (done) {
    logger.info('Connecting remote host...');
    vucoin(host, port, function (err, node) {
      if(err){
        done('Cannot sync: ' + err);
        return;
      }

      async.waterfall([
        function (next){
          logger.info('Sync started.');
          next();
        },

        //============
        // Blockchain
        //============
        function (next){
          logger.info('Downloading Blockchain...');
          async.parallel({
            localCurrent: function (next) {
              BlockchainService.current(function (err, current) {
                next(null, err ? null : current);
              });
            },
            remoteCurrent: function (next) {
              node.blockchain.current(function (err, current) {
                next(null, err ? null : current);
              });
            }
          }, next);
        },
        function (res, next) {
          var lCurrent = res.localCurrent;
          var rCurrent = res.remoteCurrent;
          var i = lCurrent ? lCurrent.number + 1 : 0;
          if (!rCurrent) {
            next('No block found on remote node');
            return;
          }
          async.whilst(
            function () { return rCurrent ? i <= rCurrent.number : false; },
            function (callback) {
                async.waterfall([
                  function (next) {
                    node.blockchain.block(i, next);
                  },
                  function (block, next) {
                    // Rawification of transactions
                    block.transactions.forEach(function (tx) {
                      tx.raw = ["TX", "1", tx.signatories.length, tx.inputs.length, tx.outputs.length, tx.comment ? '1' : '0'].join(':') + '\n';
                      tx.raw += tx.signatories.join('\n') + '\n';
                      tx.raw += tx.inputs.join('\n') + '\n';
                      tx.raw += tx.outputs.join('\n') + '\n';
                      if (tx.comment)
                        tx.raw += tx.comment + '\n';
                      tx.raw += tx.signatures.join('\n') + '\n';
                    });
                    BlockchainService.submitBlock(block, next);
                  },
                  function (block, next) {
                    i++;
                    next();
                  }
                ], callback);
            }, next);
        },

        function (next) {
          syncPeer(node, next);
        },

        //==============
        // Transactions
        //==============
        // function (next){
        //   Key.find({ managed: true }, next);
        // },
        // function (keys, next) {
        //   async.forEachSeries(keys, function (key, onKeyDone) {
        //     syncTransactionsOfKey(node, key.fingerprint, onKeyDone);
        //   }, next);
        // },

        //=======
        // Peers
        //=======
        function (next){
          Merkle.peers(next);
        },
        function (merkle, next) {
          node.network.peering.peers.get({}, function (err, json) {
            var rm = new NodesMerkle(json);
            if(rm.root() != merkle.root()){
              var leavesToAdd = [];
              node.network.peering.peers.get({ leaves: true }, function (err, json) {
                _(json.leaves).forEach(function(leaf){
                  if(merkle.leaves().indexOf(leaf) == -1){
                    leavesToAdd.push(leaf);
                  }
                });
                var hashes = [];
                async.forEachSeries(leavesToAdd, function(leaf, callback){
                  async.waterfall([
                    function (cb) {
                      node.network.peering.peers.get({ "leaf": leaf }, cb);
                    },
                    function (json, cb) {
                      var jsonEntry = json.leaf.value;
                      var sign = json.leaf.value.signature;
                      var entry = {};
                      ["version", "currency", "fingerprint", "endpoints"].forEach(function (key) {
                        entry[key] = jsonEntry[key];
                      });
                      entry.signature = sign;
                      entry.pubkey = { fingerprint: entry.fingerprint };
                      logger.info('Peer 0x' + entry.fingerprint);
                      PeeringService.submit(entry, function (err) {
                        cb();
                      });
                    }
                  ], callback);
                }, function(err, result){
                  next(err);
                });
              });
            }
            else next();
          });
        },
      ], function (err, result) {
        logger.info('Sync finished.');
        done(err);
      });
    })
  }

  //============
  // Peer
  //============
  function syncPeer (node, done) {

    // Global sync vars
    var remotePeer = new Peer({});
    var remoteJsonPeer = {};
    var remotePubkey;

    async.waterfall([
      function (next){
        node.network.peering.get(next);
      },
      function (json, next){
        remotePubkey = json.pubkey;
        remotePeer.copyValuesFrom(json);
        var entry = remotePeer.getRaw();
        var signature = dos2unix(remotePeer.signature);
        // Parameters
        if(!(entry && signature)){
          callback('Requires a peering entry + signature');
          return;
        }

        remoteJsonPeer = json;
        remoteJsonPeer.pub = json.pubkey;
        remoteJsonPeer.status = "NOTHING";
        localValidator().checkPeerSignature(remoteJsonPeer, next);
      },
      function (next) {
        async.waterfall([
          function (next){
            PeeringService.submit(remoteJsonPeer, function (err) {
              next(err == 'Peer document is older than currently recorded' ? null : err);
            });
          },
        ], function (err) {
          next(err);
        });
      },
    ], done);
  }
}

function NodesMerkle (json) {

  var that = this;
  var merkleRoot = null;
  ["depth", "nodesCount", "leavesCount"].forEach(function (key) {
    that[key] = json[key];
  });

  this.merkleRoot = json["root"];

  // var i = 0;
  // this.levels = [];
  // while(json && json.levels[i]){
  //   this.levels.push(json.levels[i]);
  //   i++;
  // }

  this.root = function () {
    return this.merkleRoot;
  }
}

function choose (question, defaultValue, ifOK, ifNotOK) {
  inquirer.prompt([{
    type: "confirm",
    name: "q",
    message: question,
    default: defaultValue,
  }], function (answer) {
    answer.q ? ifOK() : ifNotOK();
  });
}
<|endoftext|>


<commit_before>var express = require("express");
var app = express();
var port = 80;

//app.set('port',process.env.PORT || 80);

app.set('view engine', "jade");
app.engine('jade', require('jade').__express);

app.set('views', __dirname + '/views');
app.use(express.static(__dirname + '/public'));

app.use(express.cookieParser());
app.use(express.session({
	secret : 'esto es secreto'
}));
app.use(express.bodyParser());
app.use(express.methodOverride());

app.get("/", function(req, res) {
	res.render("index");
});

var io = require('socket.io').listen(app.listen(port));

/*
io.configure('production', function(){
  io.enable('browser client etag');
  io.set('log level', 1);

  io.set('transports', [
    'websocket',
    'flashsocket'
  ]);
});*/
process.env.NODE_ENV = 'production';
io.configure('development', function(){
  io.set('transports', ['websocket']);
});

var playerIDCounter = 0;
var fps = 30;
var speed = 10;

io.sockets.on('connection', function(socket) {
	//socket.set('id',playerIDCounter);
	playerIDCounter++;

	socket.emit('draw', {
		//id : socket.get('id')
	});

	socket.on('play', function(data) {
		console.log(data);
	});

	socket.on('disconnect', function() {
		io.sockets.emit('user disconnected');
	});
});

console.log("Listening on port " + port); <commit_msg>Definiendo objetos y motor de juego<commit_after>var express = require("express");
var app = express();
var port = 80;

//app.set('port',process.env.PORT || 80);

app.set('view engine', "jade");
app.engine('jade', require('jade').__express);

app.set('views', __dirname + '/views');
app.use(express.static(__dirname + '/public'));

app.use(express.cookieParser());
app.use(express.session({
	secret : 'esto es secreto'
}));
app.use(express.bodyParser());
app.use(express.methodOverride());

app.get("/", function(req, res) {
	res.render("index");
});

var io = require('socket.io').listen(app.listen(port));

/*
 io.configure('production', function(){
 io.enable('browser client etag');
 io.set('log level', 1);

 io.set('transports', [
 'websocket',
 'flashsocket'
 ]);
 });*/

process.env.NODE_ENV = 'development';
io.configure('development', function() {
	io.set('transports', ['websocket']);
});

var playerIDCounter = 0;
var FPS = 30;
var speed = 10;
var scenaryWithd=1000;
var scenaryHeight=500;

var Actor = (function(velocidad, xIni, yIni) {
	this.v = velocidad;
	this.x = xIni;
	this.y = yIni;
});

var Jugador=(function() {

	this.mover=(function (dir) {
		switch(dir) {
			case 1:
				this.y+=this.v;
				break;
			case 2:
				this.y-=this.v;
				break;
			default:

		}
	});
});

var Bola=(function(angulo) {
	this.angulo=angulo;// en radianes

	this.mover = (function() {
		vy = (float)(v * Math.sin(angulo));
		vx = (float)(v * Math.cos(angulo));
		x += vx;
		y -= vy;
	});

	this.chocar = (function() {

	});
});

Jugador.prototype = new Actor();
Bola.prototype = new Actor();

function update(){

}

setInterval(function() {
    update();
    player.draw();
}, 1000/FPS);

io.sockets.on('connection', function(socket) {
	//socket.set('id',playerIDCounter);
	playerIDCounter++;

	socket.emit('draw', {
		//id : socket.get('id')
	});

	socket.on('play', function(data) {
		console.log(data);
	});

	socket.on('disconnect', function() {
		io.sockets.emit('user disconnected');
	});
});

console.log("Listening on port " + port);
<|endoftext|>