<commit_before>$(function(){

  //example of how use to ranking curiosity
  var ranking  = new Ranking(); //create instance for ranking class
  var pdfs,videos;//variables for save data json of videos and pdfs
  var $pdfs,$videos;//variables for save html content element videos and pdfs
  ranking.init();
  sonRatesActivitiesCtrl.getMaxScoreAndHits(function(response){
    pdfs    = response.data.pdf;//get pdfs for server+
    videos  = response.data.videos;
    createElsementsVideos();//create element width video
    createElementsPdfs();//create element width pdf
    if(pdfs.length==0){
      $("#gst-materialPdf").prop("disabled",true);
    }else{
      $("#gst-materialPdf").prop("disabled",false);
    }
    if(videos.length==0){
      $("#gst-materialVideo").prop("disabled",true);
    }else{
      $("#gst-materialVideo").prop("disabled",false);
    }
  });
  ranking.setEventClick(function(event){//add event click to ranking
    var starAverage = $(this).index();// get value for set to ranking in data stars
    var these       = this;
    Curiosity.notyConfirm("Calificar actividad","¿Desas califcar esta actividad con "+starAverage+" estrellas?","question",function(){
      var data = {qualification: starAverage};
      ranking.uploadStars(these,starAverage);// update data stars of ranking
      sonRatesActivitiesCtrl.save(data);
    });
  });
  $("#gst-materialPdf").click(function(event){
    if(!$("#gst-modal-pdf-video").hasClass('gst-pdf-active')){
      $(".gst-information-list").empty();
      $(".gst-information-list").append($pdfs);
      //set information in modal
      $(".gst-information-list>div").children().first().addClass('active');
      var id = $(".gst-information-list>div>.media.active").data("id");
      addView(id,pdfs);
      $("#gst-modal-pdf-video").removeClass('gst-video-active');
      $("#gst-modal-pdf-video").addClass("gst-pdf-active");
      $(".gst-img-content").attr("src","/packages/assets/media/images/system/pdf-file.png");
      setInformationModal();
    }
  });
  $("#gst-materialVideo").click(function(event){
    if(!$("#gst-modal-pdf-video").hasClass('gst-video-active')){
      $(".gst-information-list").empty();
      $(".gst-information-list").append($videos);
      //set information in modal
      $(".gst-information-list>div").children().first().addClass('active');
      var id = $(".gst-information-list>div>.media.active").data("id");
      addView(id,videos);
      $("#gst-modal-pdf-video").removeClass("gst-pdf-active");
      $("#gst-modal-pdf-video").addClass('gst-video-active');
      $(".gst-img-content").attr("src","/packages/assets/media/images/teachersAsc/"+$(".gst-information-list>div>.media.active").data("foto"));
      setInformationModal();
    }
  });

  function setInformationModal(){//fumction for set information of item active in modal
    var $active = $(".gst-information-list>div>.media.active");
    //set data in modal
    if(!$("#gst-modal-pdf-video").hasClass('gst-video-active')){
      $("#gst-iframe-content").attr("src","/packages/assets/pdf/"+$active.data("name"));//set src of pdf in embed element
    }else{
      $("#gst-iframe-content").attr("src",$active.data("name"));//set src of pdf in embed element
      $(".gst-img-content").attr("src","/packages/assets/media/images/teachersAsc/"+$active.data("foto"));
    }
    $(".gst-tema-content").text($active.find(".media-heading").text());
    $(".gst-name-content").text($active.find("p.gst-name-content-list").text());
    $(".gst-views-content").text($active.find("p.gst-views-content-list").text());
  }
  $("#gst-modal-pdf-video").on("click",".media",function(event){//event click en item elemene of library pdf
    if(!$(this).hasClass("active")){
      $("#gst-modal-pdf-video .media").removeClass('active');
      if($("#gst-modal-pdf-video").hasClass("gst-video-active")){
         var id = $(this).data("id");
         addView(id,videos);
      }else{
         var id = $(this).data("id");
         addView(id,pdfs);
      }
      $(this).addClass('active');
      setInformationModal();
      }
  });
  $("#gst-back").click(function(event){
    window.history.back();//return to preview page
  });
  $('#gst-modal-pdf-video').on('hidden.bs.modal', function () {
    var data = {
      videos : videos,
      pdfs   : pdfs
    }
    activityCtrl.updateViews(data,function(response){
      console.log(response);
    });
  });
  function createElementsPdfs(){// function for create elements with pdf information and add in dom element
    $pdfs = $("
");
    $.each(pdfs,function(index,pdf){
      $pdfs.append($(
        '
'+
              ''+
                  ''+
              ''+
              '
'+
                  '
'+pdf.tema+'
'+
                  '
'+
                      '
Vistos: '+pdf.vistos+'
'+
                      '
'+pdf.nombre_real+'
'+
                  '
'+
              '
'+
          '
'
      ));
    });
  }
  function createElsementsVideos(){
    //all code here
    $videos = $("
");
    console.log(videos);
    $.each(videos,function(index,video){
           $videos.append('
'+
              ''+
                  ''+
              ''+
              '
'+
                  '
'+video.nombre+'
'+
                  '
'+
                      '
Escuela: '+video.escuela+'
'+
                      '
Profesor: '  +video.profesor+'
'+
                  '
'+
              '
'+
          '
');
    });
  }
  function addView(id,data){
    $.each(data,function(index,object){
      if(object.id == id){
        var vistos = parseInt(object.vistos);
        vistos +=1;
        object.vistos = vistos;
      }
    });
  }

  // animation
  var secuenceHp1 = StorageDB.table.getByAttr("secuences", "nombre", "festejo 1");
  var happy1 = StorageDB.table.getByAttr("spritesChild", "secuencia_id", secuenceHp1[0].id);
  var animation = new SpriteAnimator('gst-avCel', happy1[0].widthFrame, happy1[0].heightFrame, happy1[0].framesX, happy1[0].framesY, happy1[0].fps);
  animation.spreetsheet = "/packages/assets/media/images/avatar/sprites"+happy1[0].folder+happy1[0].imagen;
  setInterval(function(){ animation.play(); }, animation.speed);
});
<commit_msg>Cambios en la vista de juego jejeje.<commit_after>$(function(){

  //example of how use to ranking curiosity
  var ranking  = new Ranking(); //create instance for ranking class
  var pdfs,videos;//variables for save data json of videos and pdfs
  var $pdfs,$videos;//variables for save html content element videos and pdfs
  ranking.init();
  sonRatesActivitiesCtrl.getMaxScoreAndHits(function(response){
    pdfs    = response.data.pdf;//get pdfs for server+
    videos  = response.data.videos;
    createElsementsVideos();//create element width video
    createElementsPdfs();//create element width pdf
    if(pdfs.length==0){
      $("#gst-materialPdf").prop("disabled",true);
    }else{
      $("#gst-materialPdf").prop("disabled",false);
    }
    if(videos.length==0){
      $("#gst-materialVideo").prop("disabled",true);
    }else{
      $("#gst-materialVideo").prop("disabled",false);
    }
  });
  ranking.setEventClick(function(event){//add event click to ranking
    var starAverage = $(this).index();// get value for set to ranking in data stars
    var these       = this;
    Curiosity.notyConfirm("Calificar actividad","¿Desas califcar esta actividad con "+starAverage+" estrellas?","question",function(){
      var data = {qualification: starAverage};
      ranking.uploadStars(these,starAverage);// update data stars of ranking
      sonRatesActivitiesCtrl.save(data);
    });
  });
  $("#gst-materialPdf").click(function(event){
    if(!$("#gst-modal-pdf-video").hasClass('gst-pdf-active')){
      $(".gst-information-list").empty();
      $(".gst-information-list").append($pdfs);
      //set information in modal
      $(".gst-information-list>div").children().removeClass("active");
      $(".gst-information-list>div").children().first().addClass('active');
      var id = $(".gst-information-list>div>.media.active").data("id");
      addView(id,pdfs);
      $("#gst-modal-pdf-video").removeClass('gst-video-active');
      $("#gst-modal-pdf-video").addClass("gst-pdf-active");
      $(".gst-img-content").attr("src","/packages/assets/media/images/system/pdf-file.png");
      setInformationModal();
    }
  });
  $("#gst-materialVideo").click(function(event){
    if(!$("#gst-modal-pdf-video").hasClass('gst-video-active')){
      $(".gst-information-list").empty();
      $(".gst-information-list").append($videos);
      //set information in modal
      $(".gst-information-list>div").children().removeClass("active");
      $(".gst-information-list>div").children().first().addClass('active');
      var id = $(".gst-information-list>div>.media.active").data("id");
      addView(id,videos);
      $("#gst-modal-pdf-video").removeClass("gst-pdf-active");
      $("#gst-modal-pdf-video").addClass('gst-video-active');
      $(".gst-img-content").attr("src","/packages/assets/media/images/teachersAsc/"+$(".gst-information-list>div>.media.active").data("foto"));
      setInformationModal();
    }
  });

  function setInformationModal(){//fumction for set information of item active in modal
    var $active = $(".gst-information-list>div>.media.active");
    //set data in modal
    if(!$("#gst-modal-pdf-video").hasClass('gst-video-active')){
      $("#gst-iframe-content").attr("src","/packages/assets/pdf/"+$active.data("name"));//set src of pdf in embed element
    }else{
      $("#gst-iframe-content").attr("src",$active.data("name"));//set src of pdf in embed element
      $(".gst-img-content").attr("src","/packages/assets/media/images/teachersAsc/"+$active.data("foto"));
    }
    $(".gst-tema-content").text($active.find(".media-heading").text());
    $(".gst-name-content").text($active.find("p.gst-name-content-list").text());
    $(".gst-views-content").text($active.find("p.gst-views-content-list").text());
  }
  $("#gst-modal-pdf-video").on("click",".media",function(event){//event click en item elemene of library pdf
    if(!$(this).hasClass("active")){
      $("#gst-modal-pdf-video .media").removeClass('active');
      if($("#gst-modal-pdf-video").hasClass("gst-video-active")){
         var id = $(this).data("id");
         addView(id,videos);
      }else{
         var id = $(this).data("id");
         addView(id,pdfs);
      }
      $(this).addClass('active');
      setInformationModal();
      }
  });
  $("#gst-back").click(function(event){
    window.history.back();//return to preview page
  });
  $('#gst-modal-pdf-video').on('hidden.bs.modal', function () {
    var data = {
      videos : videos,
      pdfs   : pdfs
    }
    activityCtrl.updateViews(data,function(response){
      console.log(response);
    });
  });
  function createElementsPdfs(){// function for create elements with pdf information and add in dom element
    $pdfs = $("
");
    $.each(pdfs,function(index,pdf){
      $pdfs.append($(
        '
'+
              ''+
                  ''+
              ''+
              '
'+
                  '
'+pdf.tema+'
'+
                  '
'+
                      '
Vistos: '+pdf.vistos+'
'+
                      '
'+pdf.nombre_real+'
'+
                  '
'+
              '
'+
          '
'
      ));
    });
  }
  function createElsementsVideos(){
    //all code here
    $videos = $("
");
    console.log(videos);
    $.each(videos,function(index,video){
           $videos.append('
'+
              ''+
                  ''+
              ''+
              '
'+
                  '
'+video.nombre+'
'+
                  '
'+
                      '
Escuela: '+video.escuela+'
'+
                      '
Profesor: '  +video.profesor+'
'+
                  '
'+
              '
'+
          '
');
    });
  }
  function addView(id,data){
    $.each(data,function(index,object){
      if(object.id == id){
        var vistos = parseInt(object.vistos);
        vistos +=1;
        object.vistos = vistos;
      }
    });
  }

  // animation
  var secuenceHp1 = StorageDB.table.getByAttr("secuences", "nombre", "festejo 1");
  var happy1 = StorageDB.table.getByAttr("spritesChild", "secuencia_id", secuenceHp1[0].id);
  var animation = new SpriteAnimator('gst-avCel', happy1[0].widthFrame, happy1[0].heightFrame, happy1[0].framesX, happy1[0].framesY, happy1[0].fps);
  animation.spreetsheet = "/packages/assets/media/images/avatar/sprites"+happy1[0].folder+happy1[0].imagen;
  setInterval(function(){ animation.play(); }, animation.speed);
});
<|endoftext|>


<commit_before>var vueContentBeforeCreate = function(){};
var vueContentCreated = function(){};
var vueContentBeforeMount = function(){};
var vueContentMounted = function(){};
var vueContentBeforeUpdate = function(){};
var vueContentUpdated = function(){};
var vueContentBeforeDestroy = function(){};
var vueContentDestroyed = function(){};
var vueContentMethods = {};
var vueContentData = function() {};

var vueContentElementSelector = '#contentContainer';

//##########################################################//
vueContentData = function() {
	return {
    	pageTotal: pageTotal,
		pageCurrent: pageCurrent,
		pageSize: pageSize,

		modalAdd: modalAdd,
		modalUpdate: modalUpdate,
		modalDel: modalDel,

		modalDelSubmitLoading: modalDelSubmitLoading,
		modalDelMessage: '',
		modalDelRowIds: '',

	    tableColumns: tableColumnDatas,
	    tableData: [],
	    tableCheckedData: [],

        addForm: addFormContent,
        addFormValidate: addFormValidateContent,
        updateForm: updateFormContent,
        updateFormValidate: updateFormValidateContent,
        queryForm: queryFormContent,

    	self: this
    }
};
vueContentMethods = {

	loadPage:loadPageFn,
	changePage:changePageFn,

	addButton:addButtonFn,
	submitAdd:submitAddFn,

	updateButton:updateButtonFn,
	submitUpdate:submitUpdateFn,

	deleteButton:deleteButtonFn,
    submitDelete:submitDeleteFn,

	querySubmit:querySubmitFn,

	tableCheckboxSelectedData:tableCheckboxSelectedDataFn,

    rowUpdateButton:rowUpdateButtonFn,
    rowDeleteButton:rowDeleteButtonFn

}

function initializeContentOptions() {
	return {el: vueContentElementSelector, data: vueContentData, methods: vueContentMethods, beforeCreate: vueContentBeforeCreate, created: vueContentCreated, beforeMount: vueContentBeforeMount, mounted: vueContentMounted, beforeUpdate: vueContentBeforeUpdate, updated: vueContentUpdated, beforeDestroy: vueContentBeforeDestroy, destroyed: vueContentDestroyed};
}
//^^^^^^^^^^^^^^^^^^^^^^ 格式 顺序 不动 ^^^^^^^^^^^^^^^^^^^^^//<commit_msg>init 文件内容 转移到iview-utils 中<commit_after><|endoftext|>


<commit_before>var m = require('mithril');
var chessground = require('chessground');
var game = require('game').game;
var status = require('game').status;
var opposite = chessground.util.opposite;
var renderClock = require('../clock/view');
var renderReplay = require('../replay/view');
var renderStatus = require('./status');
var renderUser = require('game').view.user;
var button = require('./button');

function compact(x) {
  if (Object.prototype.toString.call(x) === '[object Array]') {
    var elems = x.filter(function(n) {
      return n !== undefined
    });
    return elems.length > 0 ? elems : null;
  }
  return x;
}

function renderPlayer(ctrl, player) {
  return player.ai ? m('div.username.on-game', [
    ctrl.trans('aiNameLevelAiLevel', 'Stockfish', player.ai),
    m('span.status')
  ]) : m('div', {
      class: 'username ' + player.color + (player.onGame ? ' on-game' : '')
    },
    renderUser(ctrl, player)
  );
}

var loader = m('div.loader', m('span'));

function renderKing(ctrl, color) {
  return m('div.no-square', (ctrl.vm.reloading || ctrl.vm.redirecting) ? loader : m('div.cg-piece.king.' + color));
}

function renderResult(ctrl) {
  var winner = game.getPlayer(ctrl.data, ctrl.data.game.winner);
  return winner ? m('div.player.' + winner.color, [
      renderKing(ctrl, winner.color),
      m('p', [
        renderStatus(ctrl),
        m('br'),
        ctrl.trans(winner.color == 'white' ? 'whiteIsVictorious' : 'blackIsVictorious')
      ])
    ]) :
    m('div.player', [
      (ctrl.vm.reloading || ctrl.vm.redirecting) ? m('div.no-square', loader) : null,
      m('p', renderStatus(ctrl))
    ]);
}

function renderTableEnd(ctrl) {
  var d = ctrl.data;
  var buttons = compact(ctrl.vm.redirecting ? null : (
    button.backToTournament(ctrl) || button.joinRematch(ctrl) || [
      button.answerOpponentRematch(ctrl) || button.cancelRematch(ctrl) || button.rematch(ctrl),
      button.newGame(ctrl)
    ]));
  return [
    buttons ? m('div.control.buttons', buttons) : null,
    renderReplay(ctrl.replay)
  ];
}

function renderTableWatch(ctrl) {
  var d = ctrl.data;
  var buttons = compact(ctrl.vm.redirecting ? null : [
    button.viewRematch(ctrl),
    button.viewTournament(ctrl)
  ]);
  return [
    buttons ? m('div.control.buttons', buttons) : null,
    renderReplay(ctrl.replay),
    renderPlayer(ctrl, d.player)
  ];
}

function renderTablePlay(ctrl) {
  var d = ctrl.data;
  var buttons = compact([
    button.forceResign(ctrl),
    button.threefoldClaimDraw(ctrl),
    button.cancelDrawOffer(ctrl),
    button.answerOpponentDrawOffer(ctrl),
    button.cancelTakebackProposition(ctrl),
    button.answerOpponentTakebackProposition(ctrl), (game.mandatory(d) && game.nbMoves(d, d.player.color) === 0) ? m('div[data-icon=j]',
      ctrl.trans('youHaveNbSecondsToMakeYourFirstMove', 30)
    ) : null
  ]);
  return [
    m('div.control.icons', [
      button.standard(ctrl, game.abortable, 'L', 'abortGame', 'abort'),
      button.standard(ctrl, game.takebackable, 'i', 'proposeATakeback', 'takeback-yes'),
      button.standard(ctrl, game.drawable, '2', 'offerDraw', 'draw-yes'),
      button.standard(ctrl, game.resignable, 'b', 'resign', 'resign')
    ]),
    buttons ? m('div.control.buttons', buttons) : null,
    renderReplay(ctrl.replay),
    m('div.whos_turn',
      ctrl.trans(d.game.player == d.player.color ? 'yourTurn' : 'waitingForOpponent'))
  ];
}

module.exports = function(ctrl) {
  var clockRunningColor = ctrl.isClockRunning() ? ctrl.data.game.player : null;
  return m('div.table_wrap', [
    (ctrl.clock && !ctrl.data.blind) ? renderClock(ctrl.clock, opposite(ctrl.data.player.color), "top", clockRunningColor) : null,
    m('div', {
      class: 'table' + (status.finished(ctrl.data) ? ' finished' : '')
    }, [
      renderPlayer(ctrl, ctrl.data.opponent),
      m('div.table_inner',
        ctrl.data.player.spectator ? renderTableWatch(ctrl) : (
          game.playable(ctrl.data) ? renderTablePlay(ctrl) : renderTableEnd(ctrl)
        )
      )
    ]), (ctrl.clock && !ctrl.data.blind) ? [
      renderClock(ctrl.clock, ctrl.data.player.color, "bottom", clockRunningColor),
      button.moretime(ctrl)
    ] : null
  ])
}
<commit_msg>Flip buttons, add player name<commit_after>var m = require('mithril');
var chessground = require('chessground');
var game = require('game').game;
var status = require('game').status;
var opposite = chessground.util.opposite;
var renderClock = require('../clock/view');
var renderReplay = require('../replay/view');
var renderStatus = require('./status');
var renderUser = require('game').view.user;
var button = require('./button');

function compact(x) {
  if (Object.prototype.toString.call(x) === '[object Array]') {
    var elems = x.filter(function(n) {
      return n !== undefined
    });
    return elems.length > 0 ? elems : null;
  }
  return x;
}

function renderPlayer(ctrl, player) {
  return player.ai ? m('div.username.on-game', [
    ctrl.trans('aiNameLevelAiLevel', 'Stockfish', player.ai),
    m('span.status')
  ]) : m('div', {
      class: 'username ' + player.color + (player.onGame ? ' on-game' : '')
    },
    renderUser(ctrl, player)
  );
}

var loader = m('div.loader', m('span'));

function renderKing(ctrl, color) {
  return m('div.no-square', (ctrl.vm.reloading || ctrl.vm.redirecting) ? loader : m('div.cg-piece.king.' + color));
}

function renderResult(ctrl) {
  var winner = game.getPlayer(ctrl.data, ctrl.data.game.winner);
  return winner ? m('div.player.' + winner.color, [
      renderKing(ctrl, winner.color),
      m('p', [
        renderStatus(ctrl),
        m('br'),
        ctrl.trans(winner.color == 'white' ? 'whiteIsVictorious' : 'blackIsVictorious')
      ])
    ]) :
    m('div.player', [
      (ctrl.vm.reloading || ctrl.vm.redirecting) ? m('div.no-square', loader) : null,
      m('p', renderStatus(ctrl))
    ]);
}

function renderTableEnd(ctrl) {
  var d = ctrl.data;
  var buttons = compact(ctrl.vm.redirecting ? null : (
    button.backToTournament(ctrl) || button.joinRematch(ctrl) || [
      button.answerOpponentRematch(ctrl) || button.cancelRematch(ctrl) || button.rematch(ctrl),
      button.newGame(ctrl)
    ]));
  return [
    renderReplay(ctrl.replay),
    buttons ? m('div.control.buttons', buttons) : null,
    renderPlayer(ctrl, d.player)
  ];
}

function renderTableWatch(ctrl) {
  var d = ctrl.data;
  var buttons = compact(ctrl.vm.redirecting ? null : [
    button.viewRematch(ctrl),
    button.viewTournament(ctrl)
  ]);
  return [
    renderReplay(ctrl.replay),
    buttons ? m('div.control.buttons', buttons) : null,
    renderPlayer(ctrl, d.player)
  ];
}

function renderTablePlay(ctrl) {
  var d = ctrl.data;
  var buttons = compact([
    button.forceResign(ctrl),
    button.threefoldClaimDraw(ctrl),
    button.cancelDrawOffer(ctrl),
    button.answerOpponentDrawOffer(ctrl),
    button.cancelTakebackProposition(ctrl),
    button.answerOpponentTakebackProposition(ctrl), (game.mandatory(d) && game.nbMoves(d, d.player.color) === 0) ? m('div[data-icon=j]',
      ctrl.trans('youHaveNbSecondsToMakeYourFirstMove', 30)
    ) : null
  ]);
  return [
    renderReplay(ctrl.replay),
    m('div.control.icons', [
      button.standard(ctrl, game.abortable, 'L', 'abortGame', 'abort'),
      button.standard(ctrl, game.takebackable, 'i', 'proposeATakeback', 'takeback-yes'),
      button.standard(ctrl, game.drawable, '2', 'offerDraw', 'draw-yes'),
      button.standard(ctrl, game.resignable, 'b', 'resign', 'resign')
    ]),
    buttons ? m('div.control.buttons', buttons) : null,
    renderPlayer(ctrl, d.player)
  ];
}

module.exports = function(ctrl) {
  var clockRunningColor = ctrl.isClockRunning() ? ctrl.data.game.player : null;
  return m('div.table_wrap', [
    (ctrl.clock && !ctrl.data.blind) ? renderClock(ctrl.clock, opposite(ctrl.data.player.color), "top", clockRunningColor) : null,
    m('div', {
      class: 'table' + (status.finished(ctrl.data) ? ' finished' : '')
    }, [
      renderPlayer(ctrl, ctrl.data.opponent),
      m('div.table_inner',
        ctrl.data.player.spectator ? renderTableWatch(ctrl) : (
          game.playable(ctrl.data) ? renderTablePlay(ctrl) : renderTableEnd(ctrl)
        )
      )
    ]), (ctrl.clock && !ctrl.data.blind) ? [
      renderClock(ctrl.clock, ctrl.data.player.color, "bottom", clockRunningColor),
      button.moretime(ctrl)
    ] : null
  ])
}
<|endoftext|>


<commit_before>/* eslint-disable no-useless-escape */
/* eslint-disable no-unused-expressions */
/* eslint-disable no-mixed-operators */

import Vue from 'vue'

export const isSSR = typeof window === 'undefined'
export let fromSSR = false
export let onSSR = isSSR

function getMatch (userAgent, platformMatch) {
  const match = /(edge)\/([\w.]+)/.exec(userAgent) ||
    /(opr)[\/]([\w.]+)/.exec(userAgent) ||
    /(vivaldi)[\/]([\w.]+)/.exec(userAgent) ||
    /(chrome)[\/]([\w.]+)/.exec(userAgent) ||
    /(iemobile)[\/]([\w.]+)/.exec(userAgent) ||
    /(version)(applewebkit)[\/]([\w.]+).*(safari)[\/]([\w.]+)/.exec(userAgent) ||
    /(webkit)[\/]([\w.]+).*(version)[\/]([\w.]+).*(safari)[\/]([\w.]+)/.exec(userAgent) ||
    /(webkit)[\/]([\w.]+)/.exec(userAgent) ||
    /(opera)(?:.*version|)[\/]([\w.]+)/.exec(userAgent) ||
    /(msie) ([\w.]+)/.exec(userAgent) ||
    userAgent.indexOf('trident') >= 0 && /(rv)(?::| )([\w.]+)/.exec(userAgent) ||
    userAgent.indexOf('compatible') < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(userAgent) ||
    []

  return {
    browser: match[5] || match[3] || match[1] || '',
    version: match[2] || match[4] || '0',
    versionNumber: match[4] || match[2] || '0',
    platform: platformMatch[0] || ''
  }
}

function getPlatformMatch (userAgent) {
  return /(ipad)/.exec(userAgent) ||
    /(ipod)/.exec(userAgent) ||
    /(windows phone)/.exec(userAgent) ||
    /(iphone)/.exec(userAgent) ||
    /(kindle)/.exec(userAgent) ||
    /(silk)/.exec(userAgent) ||
    /(android)/.exec(userAgent) ||
    /(win)/.exec(userAgent) ||
    /(mac)/.exec(userAgent) ||
    /(linux)/.exec(userAgent) ||
    /(cros)/.exec(userAgent) ||
    /(playbook)/.exec(userAgent) ||
    /(bb)/.exec(userAgent) ||
    /(blackberry)/.exec(userAgent) ||
    []
}

function getPlatform (userAgent) {
  userAgent = (userAgent || navigator.userAgent || navigator.vendor || window.opera).toLowerCase()

  const
    platformMatch = getPlatformMatch(userAgent),
    matched = getMatch(userAgent, platformMatch),
    browser = {}

  if (matched.browser) {
    browser[matched.browser] = true
    browser.version = matched.version
    browser.versionNumber = parseInt(matched.versionNumber, 10)
  }

  if (matched.platform) {
    browser[matched.platform] = true
  }

  const knownMobiles = browser.android ||
    browser.bb ||
    browser.blackberry ||
    browser.ipad ||
    browser.iphone ||
    browser.ipod ||
    browser.kindle ||
    browser.playbook ||
    browser.silk ||
    browser['windows phone']

  // These are all considered mobile platforms, meaning they run a mobile browser
  if (knownMobiles === true || /mobile|opera\s*mobi/i.test(userAgent) === true) {
    browser.mobile = true
  }
  // If it's not mobile we should consider it's desktop platform, meaning it runs a desktop browser
  // It's a workaround for anonymized user agents
  // (browser.cros || browser.mac || browser.linux || browser.win)
  else {
    browser.desktop = true
  }

  // Set iOS if on iPod, iPad or iPhone
  if (browser.ipod || browser.ipad || browser.iphone) {
    browser.ios = true
  }

  if (browser['windows phone']) {
    browser.winphone = true
    delete browser['windows phone']
  }

  // Chrome, Opera 15+, Vivaldi and Safari are webkit based browsers
  if (
    browser.chrome ||
    browser.opr ||
    browser.safari ||
    browser.vivaldi ||
    // we expect unknown, non iOS mobile browsers to be webkit based
    (
      browser.mobile === true &&
      browser.ios !== true &&
      knownMobiles !== true
    )
  ) {
    browser.webkit = true
  }

  // IE11 has a new token so we will assign it msie to avoid breaking changes
  if (browser.rv || browser.iemobile) {
    matched.browser = 'ie'
    browser.ie = true
  }

  // Edge is officially known as Microsoft Edge, so rewrite the key to match
  if (browser.edge) {
    matched.browser = 'edge'
    browser.edge = true
  }

  // Blackberry browsers are marked as Safari on BlackBerry
  if (browser.safari && browser.blackberry || browser.bb) {
    matched.browser = 'blackberry'
    browser.blackberry = true
  }

  // Playbook browsers are marked as Safari on Playbook
  if (browser.safari && browser.playbook) {
    matched.browser = 'playbook'
    browser.playbook = true
  }

  // Opera 15+ are identified as opr
  if (browser.opr) {
    matched.browser = 'opera'
    browser.opera = true
  }

  // Stock Android browsers are marked as Safari on Android.
  if (browser.safari && browser.android) {
    matched.browser = 'android'
    browser.android = true
  }

  // Kindle browsers are marked as Safari on Kindle
  if (browser.safari && browser.kindle) {
    matched.browser = 'kindle'
    browser.kindle = true
  }

  // Kindle Silk browsers are marked as Safari on Kindle
  if (browser.safari && browser.silk) {
    matched.browser = 'silk'
    browser.silk = true
  }

  if (browser.vivaldi) {
    matched.browser = 'vivaldi'
    browser.vivaldi = true
  }

  // Assign the name and platform variable
  browser.name = matched.browser
  browser.platform = matched.platform

  if (isSSR === false) {
    if (window.process && window.process.versions && window.process.versions.electron) {
      browser.electron = true
    }
    else if (document.location.href.indexOf('chrome-extension://') === 0) {
      browser.chromeExt = true
    }
    else if (window._cordovaNative || window.cordova) {
      browser.cordova = true
    }

    fromSSR = browser.cordova === void 0 &&
      browser.electron === void 0 &&
      !!document.querySelector('[data-server-rendered]')

    fromSSR === true && (onSSR = true)
  }

  return browser
}

let webStorage

export function hasWebStorage () {
  if (webStorage !== void 0) {
    return webStorage
  }

  try {
    if (window.localStorage) {
      webStorage = true
      return true
    }
  }
  catch (e) {}

  webStorage = false
  return false
}

function getClientProperties () {
  return {
    has: {
      touch: (() => !!('ontouchstart' in document.documentElement) || window.navigator.msMaxTouchPoints > 0)(),
      webStorage: hasWebStorage()
    },
    within: {
      iframe: window.self !== window.top
    }
  }
}

export default {
  has: {
    touch: false,
    webStorage: false
  },
  within: { iframe: false },

  parseSSR (/* ssrContext */ ssr) {
    return ssr ? {
      is: getPlatform(ssr.req.headers['user-agent']),
      has: this.has,
      within: this.within
    } : {
      is: getPlatform(),
      ...getClientProperties()
    }
  },

  install ($q, queues) {
    if (isSSR === true) {
      queues.server.push((q, ctx) => {
        q.platform = this.parseSSR(ctx.ssr)
      })
      return
    }

    this.is = getPlatform()

    if (fromSSR === true) {
      queues.takeover.push(q => {
        onSSR = fromSSR = false
        Object.assign(q.platform, getClientProperties())
      })
      Vue.util.defineReactive($q, 'platform', this)
    }
    else {
      Object.assign(this, getClientProperties())
      $q.platform = this
    }
  }
}
<commit_msg>fix(Platform): Touch support detection for IE/Edge #4215<commit_after>/* eslint-disable no-useless-escape */
/* eslint-disable no-unused-expressions */
/* eslint-disable no-mixed-operators */

import Vue from 'vue'

export const isSSR = typeof window === 'undefined'
export let fromSSR = false
export let onSSR = isSSR

function getMatch (userAgent, platformMatch) {
  const match = /(edge)\/([\w.]+)/.exec(userAgent) ||
    /(opr)[\/]([\w.]+)/.exec(userAgent) ||
    /(vivaldi)[\/]([\w.]+)/.exec(userAgent) ||
    /(chrome)[\/]([\w.]+)/.exec(userAgent) ||
    /(iemobile)[\/]([\w.]+)/.exec(userAgent) ||
    /(version)(applewebkit)[\/]([\w.]+).*(safari)[\/]([\w.]+)/.exec(userAgent) ||
    /(webkit)[\/]([\w.]+).*(version)[\/]([\w.]+).*(safari)[\/]([\w.]+)/.exec(userAgent) ||
    /(webkit)[\/]([\w.]+)/.exec(userAgent) ||
    /(opera)(?:.*version|)[\/]([\w.]+)/.exec(userAgent) ||
    /(msie) ([\w.]+)/.exec(userAgent) ||
    userAgent.indexOf('trident') >= 0 && /(rv)(?::| )([\w.]+)/.exec(userAgent) ||
    userAgent.indexOf('compatible') < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(userAgent) ||
    []

  return {
    browser: match[5] || match[3] || match[1] || '',
    version: match[2] || match[4] || '0',
    versionNumber: match[4] || match[2] || '0',
    platform: platformMatch[0] || ''
  }
}

function getPlatformMatch (userAgent) {
  return /(ipad)/.exec(userAgent) ||
    /(ipod)/.exec(userAgent) ||
    /(windows phone)/.exec(userAgent) ||
    /(iphone)/.exec(userAgent) ||
    /(kindle)/.exec(userAgent) ||
    /(silk)/.exec(userAgent) ||
    /(android)/.exec(userAgent) ||
    /(win)/.exec(userAgent) ||
    /(mac)/.exec(userAgent) ||
    /(linux)/.exec(userAgent) ||
    /(cros)/.exec(userAgent) ||
    /(playbook)/.exec(userAgent) ||
    /(bb)/.exec(userAgent) ||
    /(blackberry)/.exec(userAgent) ||
    []
}

function getPlatform (userAgent) {
  userAgent = (userAgent || navigator.userAgent || navigator.vendor || window.opera).toLowerCase()

  const
    platformMatch = getPlatformMatch(userAgent),
    matched = getMatch(userAgent, platformMatch),
    browser = {}

  if (matched.browser) {
    browser[matched.browser] = true
    browser.version = matched.version
    browser.versionNumber = parseInt(matched.versionNumber, 10)
  }

  if (matched.platform) {
    browser[matched.platform] = true
  }

  const knownMobiles = browser.android ||
    browser.bb ||
    browser.blackberry ||
    browser.ipad ||
    browser.iphone ||
    browser.ipod ||
    browser.kindle ||
    browser.playbook ||
    browser.silk ||
    browser['windows phone']

  // These are all considered mobile platforms, meaning they run a mobile browser
  if (knownMobiles === true || /mobile|opera\s*mobi/i.test(userAgent) === true) {
    browser.mobile = true
  }
  // If it's not mobile we should consider it's desktop platform, meaning it runs a desktop browser
  // It's a workaround for anonymized user agents
  // (browser.cros || browser.mac || browser.linux || browser.win)
  else {
    browser.desktop = true
  }

  // Set iOS if on iPod, iPad or iPhone
  if (browser.ipod || browser.ipad || browser.iphone) {
    browser.ios = true
  }

  if (browser['windows phone']) {
    browser.winphone = true
    delete browser['windows phone']
  }

  // Chrome, Opera 15+, Vivaldi and Safari are webkit based browsers
  if (
    browser.chrome ||
    browser.opr ||
    browser.safari ||
    browser.vivaldi ||
    // we expect unknown, non iOS mobile browsers to be webkit based
    (
      browser.mobile === true &&
      browser.ios !== true &&
      knownMobiles !== true
    )
  ) {
    browser.webkit = true
  }

  // IE11 has a new token so we will assign it msie to avoid breaking changes
  if (browser.rv || browser.iemobile) {
    matched.browser = 'ie'
    browser.ie = true
  }

  // Edge is officially known as Microsoft Edge, so rewrite the key to match
  if (browser.edge) {
    matched.browser = 'edge'
    browser.edge = true
  }

  // Blackberry browsers are marked as Safari on BlackBerry
  if (browser.safari && browser.blackberry || browser.bb) {
    matched.browser = 'blackberry'
    browser.blackberry = true
  }

  // Playbook browsers are marked as Safari on Playbook
  if (browser.safari && browser.playbook) {
    matched.browser = 'playbook'
    browser.playbook = true
  }

  // Opera 15+ are identified as opr
  if (browser.opr) {
    matched.browser = 'opera'
    browser.opera = true
  }

  // Stock Android browsers are marked as Safari on Android.
  if (browser.safari && browser.android) {
    matched.browser = 'android'
    browser.android = true
  }

  // Kindle browsers are marked as Safari on Kindle
  if (browser.safari && browser.kindle) {
    matched.browser = 'kindle'
    browser.kindle = true
  }

  // Kindle Silk browsers are marked as Safari on Kindle
  if (browser.safari && browser.silk) {
    matched.browser = 'silk'
    browser.silk = true
  }

  if (browser.vivaldi) {
    matched.browser = 'vivaldi'
    browser.vivaldi = true
  }

  // Assign the name and platform variable
  browser.name = matched.browser
  browser.platform = matched.platform

  if (isSSR === false) {
    if (window.process && window.process.versions && window.process.versions.electron) {
      browser.electron = true
    }
    else if (document.location.href.indexOf('chrome-extension://') === 0) {
      browser.chromeExt = true
    }
    else if (window._cordovaNative || window.cordova) {
      browser.cordova = true
    }

    fromSSR = browser.cordova === void 0 &&
      browser.electron === void 0 &&
      !!document.querySelector('[data-server-rendered]')

    fromSSR === true && (onSSR = true)
  }

  return browser
}

let webStorage

export function hasWebStorage () {
  if (webStorage !== void 0) {
    return webStorage
  }

  try {
    if (window.localStorage) {
      webStorage = true
      return true
    }
  }
  catch (e) {}

  webStorage = false
  return false
}

function getClientProperties () {
  return {
    has: {
      touch: (() => 'ontouchstart' in window ||
        window.navigator.maxTouchPoints > 0
      )(),
      webStorage: hasWebStorage()
    },
    within: {
      iframe: window.self !== window.top
    }
  }
}

export default {
  has: {
    touch: false,
    webStorage: false
  },
  within: { iframe: false },

  parseSSR (/* ssrContext */ ssr) {
    return ssr ? {
      is: getPlatform(ssr.req.headers['user-agent']),
      has: this.has,
      within: this.within
    } : {
      is: getPlatform(),
      ...getClientProperties()
    }
  },

  install ($q, queues) {
    if (isSSR === true) {
      queues.server.push((q, ctx) => {
        q.platform = this.parseSSR(ctx.ssr)
      })
      return
    }

    this.is = getPlatform()

    if (fromSSR === true) {
      queues.takeover.push(q => {
        onSSR = fromSSR = false
        Object.assign(q.platform, getClientProperties())
      })
      Vue.util.defineReactive($q, 'platform', this)
    }
    else {
      Object.assign(this, getClientProperties())
      $q.platform = this
    }
  }
}
<|endoftext|>


<commit_before>(function (templateLayout) {

    var compiler, log, rootTemplate;
    log = wef.logger("templateLayout.compiler");

    log.info("load compiler module");

    rootTemplate = function () {
        var that = {
            insert:insert,
            rows:[]
        };

        function insert(aTemplate) {
            log.info("add template ", aTemplate.selectorText);
            if (aTemplate.isRoot()) {
                log.debug("insert as root", aTemplate);
                that.rows.push(aTemplate);
                return true;
            } else {
                log.debug("search position :", aTemplate.position.position);
                return that.rows.some(function (element) {
                    return element.insert(aTemplate);
                });
            }
        }

        return that;
    }();

    function parseDisplay(displayValue) {
        /**
         * Name:    ‘display’
         * New value:    <display-type>? && [ [ <string> [ / <row-height> ]? ]+ ] <col-width>*
         * Percentages:    N/A
         * Computed value:    specified value
         *
         * The <display-type> is one of the following keywords. An omitted keyword is equivalent to ‘block’.
         * <display-type> = inline | block | list-item | inline-block | table | inline-table
         * | table-row-group | table-header-group | table-footer-group | table-row
         * | table-column-group | table-column | table-cell | table-caption | none
         *
         * Each <string> consist of one or more at signs (“@”), letters (or digits, see <letter> below),
         * periods (“.”) and spaces
         *
         * Each <row-height> sets the height of the preceding row. The default is ‘auto’.
         * The values can be as follows:
         * <length> An explicit height for that row. Negative values make the template illegal. If the length is
         * expressed in ‘gr’ units, these refer to the inherited grid, not the grid defined by the template itself.
         * auto The row's height is determined by its contents.
         * * (asterisk) All rows with an asterisk will be of equal height.
         *
         * Each <col-width> can be one of the following:
         * <length> An explicit width for that column. Negative values make the template illegal.
         * * (asterisk.) All columns with a ‘*’ have the same width. See the algorithm below.
         * max-content, min-content, minmax(p,q), fit-content
         */
        log.info("compiling display...");
        log.debug("display source: ", displayValue);
        var displayMetadata = {
            displayType:null,
            grid:null
        }, displayTypeRegExp = /^\s*(inline|block|list-item|inline-block|table|inline-table|table-row-group|table-header-group|table-footer-group|table-row|table-column-group|table-column|table-cell|table-caption|none)?/ig, stringRegExp = /\s*"([a-zA-Z0-9.@ ])+"/ig;
        if (displayValue !== undefined) {
            //TODO: check invalid values
            displayMetadata.displayType = displayValue.match(displayTypeRegExp);
            displayMetadata.grid = displayValue.match(stringRegExp).map(function (element) {
                return element.replace(/"/g, "").replace(/\s*/, "");
            });
        }
        log.info("display result: ", displayMetadata);
        return displayMetadata;
    }

    function parsePosition(positionValue) {
        var positionMetadata, matched, positionRegExp;
        /**
         * Name:    position
         * New value:    <letter> | same
         * Percentages:    N/A
         * Computed value:    ‘<letter>’ or ‘static’; see text
         *
         * <letter> must be a single letter or digit, with category Lu, Ll, Lt or Nd in Unicode [UNICODE]),
         * or a “@” symbol
         */
        log.info("compiling position...");
        log.debug("position source: ", positionValue);
        positionMetadata = {
            position:null
        };
        positionRegExp = /^\s*([a-zA-Z0-9]+|same)\s*/i;
        if (positionValue !== undefined) {
            matched = positionValue.match(positionRegExp);
            if (matched === null) {
                log.error("Unexpected value at ", positionValue);
                throw new Error("Unexpected value at ", positionValue);
            }
            positionMetadata.position = matched[1];
        }
        log.info("position result: ", positionMetadata);
        return positionMetadata;
    }

    function parseProperties(rule) {
        var preProcessTemplate = {};
        log.info("compiling properties...");
        log.debug("properties source: ", rule);

        preProcessTemplate.selectorText = rule.selectorText;
        preProcessTemplate.display = parseDisplay(rule.declaration[templateLayout.fn.constants.DISPLAY]);
        preProcessTemplate.position = parsePosition(rule.declaration[templateLayout.fn.constants.POSITION]);

        log.info("properties result: ", preProcessTemplate);
        return preProcessTemplate;
    }

    compiler = function () {
        return new compiler.prototype.init();
    };

    compiler.fn = compiler.prototype;

    compiler.prototype = {
        constructor:compiler,
        init:function () {
            return this;
        },
        compile:function (buffer) {
            var selectorText, preProcessTemplate, inserted, template;
            log.info("compile...");
            log.debug("buffer: ", buffer);

            for (selectorText in buffer) {

                if (buffer.hasOwnProperty(selectorText)) {
                    log.debug("next buffer element: ", selectorText);
                    log.group();
                    preProcessTemplate = parseProperties(buffer[selectorText]);
                    log.debug("preProcess: ", preProcessTemplate);
                    template = compiler.fn.templateBuilder().createTemplate(preProcessTemplate);
                    inserted = rootTemplate.insert(template);
                    log.groupEnd();
                    log.info("element insertion...", inserted ? "[OK]" : "ERROR!");
                }
            }
            log.debug("compile... OK");
            return rootTemplate;

        }
    };

    compiler.prototype.init.prototype = compiler.prototype;

    templateLayout.fn.compiler = compiler;

    (function (global) {
        var gridSlot;
        log.info("load gridSlot module...");
        gridSlot = function (slotText, rowIndex, colIndex, rowSpan, colSpan) {
            log.debug("slot...");
            return new gridSlot.prototype.init(slotText, rowIndex, colIndex, rowSpan, colSpan);
        };

        gridSlot.prototype = {
            constructor:gridSlot,
            slotText:undefined,
            rowIndex:undefined,
            colIndex:undefined,
            rowSpan:undefined,
            colSpan:undefined,
            init:function (slotText, rowIndex, colIndex, rowSpan, colSpan) {
                this.slotText = slotText;
                this.rowIndex = rowIndex;
                this.colIndex = colIndex;
                this.rowSpan = rowSpan;
                this.colSpan = colSpan;

            },
            toString:function () {
                return String(this.slotText, "cols:", this.colSpan);
            }
        };

        gridSlot.fn = gridSlot.prototype;
        gridSlot.prototype.init.prototype = gridSlot.prototype;

        global.gridSlot = gridSlot;
        log.info("load gridSlot module... [OK]");
    })(compiler.fn);

    (function (global) {
        var gridRow;
        log.info("load gridRow module...");
        gridRow = function (rowText, rowIndex, slots) {
            log.debug("row...");
            return new gridRow.prototype.init(rowText, rowIndex, slots);
        };
        gridRow.prototype = {
            constructor:gridRow,
            rowText:undefined,
            rowIndex:undefined,
            slotIdentifier:[],
            length:undefined,
            init:function (rowText, rowIndex, slots) {
                this.rowText = rowText;
                this.rowIndex = rowIndex;
                this.length = this.rowText.length;
                //valid reference if slots is not reused
                this.slotIdentifier = slots;
            }
        };

        gridRow.fn = gridRow.prototype;
        gridRow.prototype.init.prototype = gridRow.prototype;

        global.gridRow = gridRow;
        log.info("load gridRow module... [OK]");
    })(compiler.fn);

    (function (global) {
        var grid;
        log.info("load grid module...");
        grid = function (rows) {
            log.debug("grid...");
            return new grid.prototype.init(rows);
        };

        grid.prototype = {
            constructor:grid,
            rows:undefined,
            slots:undefined,
            init:function (rows) {
                this.rows = rows;
                this.slots = {};
            },
            hasSlot:function hasSlot(slotIdentifier) {
                var result;
                result = this.rows.some(function (row) {
                    var regExp = new RegExp(slotIdentifier);
                    return regExp.exec(row.rowText);
                });
                log.debug("hasSlot " + slotIdentifier + "?", result ? "yes" : "no");
                return result;
            },
            setTemplate:function (aTemplate) {
                var row, tmp, result;
                if (this.hasSlot(aTemplate.position.position)) {
                    //push template
                    tmp = this.slots[aTemplate.position.position] || [];
                    tmp.push(aTemplate);
                    this.slots[aTemplate.position.position] = tmp;
                    log.debug("grid [" + aTemplate.position.position + "] =", aTemplate);
                    return true;
                } else {
                    result = this.rows.some(function (row) {
                        var result;
                        result = row.slotIdentifier.some(function (slotId) {
                            var result;
                            result = this.slots[slotId] && this.slots[slotId].some(function (currentTemplate) {
                                return !currentTemplate.isLeaf() && currentTemplate.insert(aTemplate);
                            }, this);
                            if (!result) {
                                log.debug("not found, try another slot");
                            }
                            return result;
                        }, this);
                        if (!result) {
                            log.debug("not found, try another row");
                        }
                        return result;
                    }, this);
                    if (!result) {
                        log.debug("not found, try another branch");
                    }
                    return result;
                }
            }
        };

        grid.fn = grid.prototype;
        grid.prototype.init.prototype = grid.prototype;

        global.grid = grid;
        log.info("load grid module... [OK]");
    })(compiler.fn);

    (function (global) {
        var template;
        log.info("load template module...");
        template = function (selectorText, position, display, grid) {
            log.debug("template...");
            return new template.prototype.init(selectorText, position, display, grid);
        };

        template.prototype = {
            constructor:template,
            parentTemplate:undefined,
            selectorText:undefined,
            selector:undefined,
            display:undefined,
            position:undefined,
            grid:undefined,
            init:function (selectorText, position, display, grid) {
                this.selectorText = selectorText;
                this.display = display;
                this.position = position;
                this.grid = grid;
            },
            isRoot:function () {
                return this.position.position === null;
            },
            isLeaf:function () {
                return this.display.grid === null;
            },
            insert:function (aTemplate) {
                log.debug("trying to insert into ", this);
                return this.grid.setTemplate(aTemplate);
            }
        };

        template.fn = template.prototype;
        template.prototype.init.prototype = template.prototype;

        global.template = template;
        log.info("load template module... [OK]");
    })(compiler.fn);

    (function (global) {
        var templateBuilder;
        log.info("load templateBuilder module...");

        function Slots() {
            this.used = {};
            this.rows = [];
        }

        Slots.prototype = {
            constructor:Slots,
            used:{},
            rows:[],
            add:function (slot) {
                this.used[slot.slotText] = slot;
                if (!Array.isArray(this.rows[slot.rowIndex])) {
                    this.rows[slot.rowIndex] = [];
                }
                this.rows[slot.rowIndex][slot.colIndex] = slot;
            },
            getSlot:function (id) {
                return this.used[id];
            },
            getRows:function () {
                return this.rows;
            },
            deleteSlot:function (id) {
                delete this.used[id];
                this.rows[id.rowIndex].splice(id.colIndex, 1);
            }
        };

        templateBuilder = function () {
            log.debug("templateBuilder...");
            return new templateBuilder.prototype.init();
        };

        templateBuilder.prototype = {
            constructor:templateBuilder,
            slots:undefined,
            init:function () {
                this.slots = new Slots();
            },
            createTemplate:function (source) {
                var display, grid, gridRows;

                display = source.display;
                grid = null;
                if (display.grid !== null) {
                    this._addGrid(source.display);
                    gridRows = this.slots.getRows().map(function (row, index) {
                        return compiler.fn.gridRow(source.display.grid[index], index, row);
                    }, this);
                    grid = compiler.fn.grid(gridRows);
                }

                return compiler.fn.template(source.selectorText, source.position, display, grid);
            },
            _addGrid:function (display) {
                //TODO: grid !== null ???
                if (display.grid !== null) {
                    display.grid.forEach(function (rowText, rowIndex) {
                        this._addGridRow(rowText, rowIndex);
                    }, this);
                }
            },
            _addGridRow:function (rowText, rowIndex) {
                var identifiers;
                identifiers = Array.prototype.map.call(rowText, function (substring) {
                    return substring.charAt(0);
                });

                identifiers.forEach(function (slotText, colIndex) {
                    var slot;
                    if (!this.slots.getSlot(slotText)) {
                        this._addGridSlot(slotText, rowIndex, colIndex, 1, 1);
                    } else {
                    }

                    slot = this.slots.getSlot(slotText);
                    //validate row stub
                    //TODO: aba
                    slot.colSpan = (colIndex - slot.colIndex) + 1;
                    this.slots.add(slot);
                    //validate col stub
                    slot.rowSpan = (rowIndex - slot.rowIndex) + 1;
                    this.slots.add(slot);
                    //TODO: validate multiple
                }, this);
            },
            _addGridSlot:function (slotText, rowIndex, colIndex, rowSpan, colSpan) {
                this.slots.add(compiler.fn.gridSlot(slotText, rowIndex, colIndex, rowSpan, colSpan));
            }
        };

        templateBuilder.fn = templateBuilder.prototype;
        templateBuilder.prototype.init.prototype = templateBuilder.prototype;

        global.templateBuilder = templateBuilder;
        log.info("load templateBuilder module... [OK]");
    })(compiler.fn);

    log.info("compiler module load... [OK]");

})(window.templateLayout);
<commit_msg>Add height and width support. Refactor template elements<commit_after>(function (templateLayout) {
    var compiler, log, rootTemplate;
    log = wef.logger("templateLayout.compiler");
    log.info("load compiler module");

    rootTemplate = function () {
        var that = {
            insert:insert,
            rows:[]
        };

        function insert(aTemplate) {
            log.info("add template ", aTemplate.selectorText);
            if (aTemplate.isRoot()) {
                log.debug("insert as root", aTemplate);
                that.rows.push(aTemplate);
                return true;
            } else {
                log.debug("search position :", aTemplate.position.position);
                return that.rows.some(function (element) {
                    return element.insert(aTemplate);
                });
            }
        }

        return that;
    }();

    function parseDisplay(displayValue) {
        /**
         * Name:    ‘display’
         * New value:    <display-type>? && [ [ <string> [ / <row-height> ]? ]+ ] <col-width>*
         * Percentages:    N/A
         * Computed value:    specified value
         *
         * The <display-type> is one of the following keywords. An omitted keyword is equivalent to ‘block’.
         * <display-type> = inline | block | list-item | inline-block | table | inline-table
         * | table-row-group | table-header-group | table-footer-group | table-row
         * | table-column-group | table-column | table-cell | table-caption | none
         *
         * Each <string> consist of one or more at signs (“@”), letters (or digits, see <letter> below),
         * periods (“.”) and spaces
         *
         * Each <row-height> sets the height of the preceding row. The default is ‘auto’.
         * The values can be as follows:
         * <length> An explicit height for that row. Negative values make the template illegal. If the length is
         * expressed in ‘gr’ units, these refer to the inherited grid, not the grid defined by the template itself.
         * auto The row's height is determined by its contents.
         * * (asterisk) All rows with an asterisk will be of equal height.
         *
         * Each <col-width> can be one of the following:
         * <length> An explicit width for that column. Negative values make the template illegal.
         * * (asterisk.) All columns with a ‘*’ have the same width. See the algorithm below.
         * max-content, min-content, minmax(p,q), fit-content
         */
        log.info("compiling display...");
        log.debug("display source: ", displayValue);
        var displayMetadata = {
            displayType:undefined,
            grid:[],
            widths:[]
        },
            allRefExp = /\s*(none)?\s*(:?(\"[A-Za-z0-9\.@ ]+\")\s*(:?\/(\*|\d+(:?em|px|%)))?)\s*((:?(:?(:?\d+(:?em|px|%))|\*) *)*)/gi,
            found,
            displayTypeFound,
            gridNotFound,
            completed;
        //all without displayType   (:?(\"[A-Za-z0-9\.@ ]+\")\s*(:?\/(\*|\d+(:?em|px|%)))?\s*)((:?(:?(:?\d+(:?em|px|%))|\*) *)*)
        // /\s*(inline|block|list-item|inline-block|table|inline-table|table-row-group|table-header-group|table-footer-group|table-row|table-column-group|table-column|table-cell|table-caption|none)?\s*(:?(\"[A-Za-z0-9\.@ ]+\")\s*(:?\/(\*|\d+(:?em|px|%)))?\s*)((:?(:?(:?\d+(:?em|px|%))|\*) *)*)/g
        if (displayValue !== undefined) {
            while ((found = allRefExp.exec(displayValue)) !== null) {
                if (completed) {
                    log.error("Invalid template, invalid width definition");
                    throw new Error("Invalid template, width  definition");
                }
                if (found[1]) {
                    if (displayTypeFound) {
                        log.error("Invalid template, multiple display type");
                        throw new Error("Invalid template, multiple display type");
                    }
                    displayMetadata.displayType = found[1];
                    displayTypeFound = true;
                }
                if (found[3]) {
                    if (gridNotFound) {
                        log.error("Invalid template, invalid grid definition");
                        throw new Error("Invalid template, invalid grid definition");
                    }
                    displayMetadata.grid.push({rowText:found[3].replace(/"/g, "").replace(/\s*/, ""), height:undefined});
                } else {
                    gridNotFound = true;
                }
                if (found[5]) {
                    if (!displayMetadata.grid[found.index]) {
                        log.error("Invalid template, invalid height definition");
                        throw new Error("Invalid template, height definition");
                    }
                    displayMetadata.grid[found.index].height = found[5];
                }
                if (found[7]) {
                    displayMetadata.widths = found[7].split(/ /);
                    completed = true;
                }
            }
        }
        log.info("display result: ", displayMetadata);
        return displayMetadata;
    }

    function parsePosition(positionValue) {
        var positionMetadata, matched, positionRegExp;
        /**
         * Name:    position
         * New value:    <letter> | same
         * Percentages:    N/A
         * Computed value:    ‘<letter>’ or ‘static’; see text
         *
         * <letter> must be a single letter or digit, with category Lu, Ll, Lt or Nd in Unicode [UNICODE]),
         * or a “@” symbol
         */
        log.info("compiling position...");
        log.debug("position source: ", positionValue);
        positionMetadata = {
            position:null
        };
        positionRegExp = /^\s*([a-zA-Z0-9]+|same)\s*/i;
        if (positionValue !== undefined) {
            matched = positionValue.match(positionRegExp);
            if (matched === null) {
                log.error("Unexpected value at ", positionValue);
                throw new Error("Unexpected value at ", positionValue);
            }
            positionMetadata.position = matched[1];
        }
        log.info("position result: ", positionMetadata);
        return positionMetadata;
    }

    function parseProperties(rule) {
        var preProcessTemplate = {};
        log.info("compiling properties...");
        log.debug("properties source: ", rule);
        preProcessTemplate.selectorText = rule.selectorText;
        preProcessTemplate.display = parseDisplay(rule.declaration[templateLayout.fn.constants.DISPLAY]);
        preProcessTemplate.position = parsePosition(rule.declaration[templateLayout.fn.constants.POSITION]);
        log.info("properties result: ", preProcessTemplate);
        return preProcessTemplate;
    }

    compiler = function () {
        return new compiler.prototype.init();
    };

    compiler.fn = compiler.prototype;

    compiler.prototype = {
        constructor:compiler,
        init:function () {
            return this;
        },
        compile:function (buffer) {
            var selectorText, preProcessTemplate, inserted, template;
            log.info("compile...");
            log.debug("buffer: ", buffer);

            for (selectorText in buffer) {
                if (buffer.hasOwnProperty(selectorText)) {
                    log.debug("next buffer element: ", selectorText);
                    log.group();
                    preProcessTemplate = parseProperties(buffer[selectorText]);
                    log.debug("preProcess: ", preProcessTemplate);
                    template = compiler.fn.templateBuilder().createTemplate(preProcessTemplate);
                    inserted = rootTemplate.insert(template);
                    log.groupEnd();
                    log.info("element insertion...", inserted ? "[OK]" : "ERROR!");
                }
            }
            log.debug("compile... OK");
            return rootTemplate;
        }
    };

    compiler.prototype.init.prototype = compiler.prototype;

    templateLayout.fn.compiler = compiler;

    (function (global) {
        var gridSlot;
        log.info("load gridSlot module...");
        gridSlot = function (slotText, rowIndex, colIndex, options) {
            log.debug("slot...");
            return new gridSlot.prototype.init(slotText, rowIndex, colIndex, options);
        };

        gridSlot.prototype = {
            constructor:gridSlot,
            slotText:undefined,
            rowIndex:undefined,
            colIndex:undefined,
            rowSpan:undefined,
            colSpan:undefined,
            width:undefined,
            height:undefined,
            init:function (slotText, rowIndex, colIndex, options) {
                this.slotText = slotText;
                this.rowIndex = rowIndex;
                this.colIndex = colIndex;
                //options
                this.rowSpan = 1;
                this.colSpan = 1;
                this.height = undefined;
                this.width = undefined;
                wef.extend(this, options, ["rowSpan", "colSpan", "width", "height"]);
            }
        };

        gridSlot.fn = gridSlot.prototype;
        gridSlot.prototype.init.prototype = gridSlot.prototype;

        global.gridSlot = gridSlot;
        log.info("load gridSlot module... [OK]");
    })(compiler.fn);

    (function (global) {
        var gridRow;
        log.info("load gridRow module...");
        gridRow = function (rowText, rowIndex, slots, options) {
            log.debug("row...");
            return new gridRow.prototype.init(rowText, rowIndex, slots, options);
        };
        gridRow.prototype = {
            constructor:gridRow,
            rowText:undefined,
            rowIndex:undefined,
            slots:[],
            length:undefined,
            height:undefined,
            widths:[],
            init:function (rowText, rowIndex, slots, options) {
                this.rowText = rowText;
                this.rowIndex = rowIndex;
                this.slots = slots;
                this.length = this.rowText.length;
                //options
                this.height = undefined;
                this.widths = [];
                wef.extend(this, options, ["height", "widths"]);
            }
        };
        gridRow.fn = gridRow.prototype;
        gridRow.prototype.init.prototype = gridRow.prototype;

        global.gridRow = gridRow;
        log.info("load gridRow module... [OK]");
    })(compiler.fn);

    (function (global) {
        var grid;
        log.info("load grid module...");
        grid = function (rows, options) {
            log.debug("grid...");
            return new grid.prototype.init(rows, options);
        };

        grid.prototype = {
            constructor:grid,
            rows:undefined,
            filledSlots:undefined,
            widths:[],
            init:function (rows, options) {
                this.rows = rows;
                this.filledSlots = {};
                //options
                this.widths = [];
                wef.extend(this, options, ["widths"]);
            },
            hasSlot:function hasSlot(slotIdentifier) {
                var result;
                result = this.rows.some(function (row) {
                    var regExp = new RegExp(slotIdentifier);
                    return regExp.exec(row.rowText);
                });
                log.debug("hasSlot " + slotIdentifier + "?", result ? "yes" : "no");
                return result;
            },
            setTemplate:function (aTemplate) {
                var row, tmp, result;
                if (this.hasSlot(aTemplate.position.position)) {
                    //push template
                    tmp = this.filledSlots[aTemplate.position.position] || [];
                    tmp.push(aTemplate);
                    this.filledSlots[aTemplate.position.position] = tmp;
                    log.debug("grid [" + aTemplate.position.position + "] =", aTemplate);
                    return true;
                } else {
                    result = this.rows.some(function (row) {
                        var result;
                        result = row.slots.some(function (slotId) {
                            var result;
                            result = this.filledSlots[slotId] && this.filledSlots[slotId].some(function (currentTemplate) {
                                return !currentTemplate.isLeaf() && currentTemplate.insert(aTemplate);
                            }, this);
                            if (!result) {
                                log.debug("not found, try another slot");
                            }
                            return result;
                        }, this);
                        if (!result) {
                            log.debug("not found, try another row");
                        }
                        return result;
                    }, this);
                    if (!result) {
                        log.debug("not found, try another branch");
                    }
                    return result;
                }
            }
        };

        grid.fn = grid.prototype;
        grid.prototype.init.prototype = grid.prototype;

        global.grid = grid;
        log.info("load grid module... [OK]");
    })(compiler.fn);

    (function (global) {
        var template;
        log.info("load template module...");
        template = function (selectorText, position, display, grid) {
            log.debug("template...");
            return new template.prototype.init(selectorText, position, display, grid);
        };

        template.prototype = {
            constructor:template,
            parentTemplate:undefined,
            selectorText:undefined,
            selector:undefined,
            display:undefined,
            position:undefined,
            grid:undefined,
            init:function (selectorText, position, display, grid) {
                this.selectorText = selectorText;
                this.display = display;
                this.position = position;
                this.grid = grid;
            },
            isRoot:function () {
                return this.position.position === null;
            },
            isLeaf:function () {
                return this.display.grid.length === 0;
            },
            insert:function (aTemplate) {
                log.debug("trying to insert into ", this);
                return this.grid.setTemplate(aTemplate);
            }
        };
        template.fn = template.prototype;
        template.prototype.init.prototype = template.prototype;

        global.template = template;
        log.info("load template module... [OK]");
    })(compiler.fn);

    (function (global) {
        var templateBuilder;
        log.info("load templateBuilder module...");

        function GridBuffer() {
            this._used = {};
            this._rows = [];
        }

        GridBuffer.prototype = {
            constructor:GridBuffer,
            _used:{},
            _rows:[],
            add:function (slot) {
                this._used[slot.slotText] = slot;
                if (!Array.isArray(this._rows[slot.rowIndex])) {
                    this._rows[slot.rowIndex] = [];
                }
                this._rows[slot.rowIndex][slot.colIndex] = slot;
            },
            getSlot:function (id) {
                return this._used[id];
            },
            getRows:function () {
                return this._rows;
            },
            deleteSlot:function (id) {
                delete this._used[id];
                this._rows[id.rowIndex].splice(id.colIndex, 1);
            }
        };

        templateBuilder = function () {
            log.debug("templateBuilder...");
            return new templateBuilder.prototype.init();
        };

        templateBuilder.prototype = {
            constructor:templateBuilder,
            buffer:undefined,
            init:function () {
                this.buffer = new GridBuffer();
            },
            createTemplate:function (source) {
                var display, grid, gridRows;

                display = source.display;
                grid = null;
                if (display.grid.length > 0) {
                    this._addGrid(source.display);
                    gridRows = this.buffer.getRows().map(function (row, index) {
                        return compiler.fn.gridRow(source.display.grid[index].rowText, index, row, {height:source.display.grid[index].height});
                    }, this);
                    grid = compiler.fn.grid(gridRows, {widths:source.display.widths});
                }

                return compiler.fn.template(source.selectorText, source.position, display, grid);
            },
            _addGrid:function (display) {
                //TODO: grid !== null ???
                if (display.grid.length > 0) {
                    display.grid.forEach(function (row, rowIndex) {
                        this._addGridRow(row, rowIndex, display.widths);
                    }, this);
                }
            },
            _addGridRow:function (row, rowIndex, widths) {
                var identifiers;
                identifiers = Array.prototype.map.call(row.rowText, function (substring) {
                    return substring.charAt(0);
                });

                identifiers.forEach(function (slotText, colIndex) {
                    var slot;
                    if (!this.buffer.getSlot(slotText)) {
                        this._addGridSlot(slotText, rowIndex, colIndex, 1, 1, row.height, widths[colIndex]);
                    } else {
                    }

                    slot = this.buffer.getSlot(slotText);
                    //validate row stub
                    //TODO: aba
                    slot.colSpan = (colIndex - slot.colIndex) + 1;
                    this.buffer.add(slot);
                    //validate col stub
                    slot.rowSpan = (rowIndex - slot.rowIndex) + 1;
                    this.buffer.add(slot);
                    //TODO: validate multiple
                }, this);
            },
            _addGridSlot:function (slotText, rowIndex, colIndex, rowSpan, colSpan, height, width) {
                this.buffer.add(compiler.fn.gridSlot(slotText, rowIndex, colIndex, {rowSpan:rowSpan, colSpan:colSpan, height:height, width:width}));
            }
        };

        templateBuilder.fn = templateBuilder.prototype;
        templateBuilder.prototype.init.prototype = templateBuilder.prototype;

        global.templateBuilder = templateBuilder;
        log.info("load templateBuilder module... [OK]");
    })(compiler.fn);

    log.info("compiler module load... [OK]");

})(window.templateLayout);<|endoftext|>


<commit_before>var child_process = require('child_process');
var autils = require('../AUtils');
var GenericDiffReporterBase = require('./GenericDiffReporterBase');
var edge = require('edge');

var reporter = function () {
    this.name = "VisualStudio";

    // Use edge to execute some .net and go find the installed version of visual studio.
    var getVisualStudioPath =  edge.func(function () {/*
        async (input) => {
            // pulled this from https://github.com/approvals/ApprovalTests.Net/blob/master/ApprovalTests/Reporters/VisualStudioReporter.cs
            return (string)Microsoft.Win32.Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\devenv.exe", "", @"Microsoft Visual Studio 11.0\Common7\IDE\devenv.exe");
        }
    */});
    this.exePath = getVisualStudioPath(null /*no arguments*/, true);
};

reporter.prototype = new GenericDiffReporterBase();

reporter.prototype.report = function (approved, received, spawn) {
    spawn = spawn || child_process.spawn;
    autils.createEmptyFileIfNotExists(approved);

    var exe = this.exePath;

    var ps = spawn(exe, ["/diff", received, approved], {
        detached: true
    });

    ps.stdout.on('data', function (data) {
        console.log('reporter stdout: ' + data);
    });

    ps.stderr.on('data', function (data) {
        console.log('reporter stderr: ' + data);
    });

};

module.exports = reporter;
<commit_msg>fixing the visual studio reporter to play nicer on a mac<commit_after>var child_process = require('child_process');
var autils = require('../AUtils');
var GenericDiffReporterBase = require('./GenericDiffReporterBase');
var ostools = require('../osTools');

var reporter = function () {
    this.name = "VisualStudio";

    if(ostools.platform.isWindows){

        var edge = require('edge');

        // Use edge to execute some .net and go find the installed version of visual studio.
        var getVisualStudioPath =  edge.func(function () {/*
            async (input) => {
                // pulled this from https://github.com/approvals/ApprovalTests.Net/blob/master/ApprovalTests/Reporters/VisualStudioReporter.cs
                return (string)Microsoft.Win32.Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\devenv.exe", "", @"Microsoft Visual Studio 11.0\Common7\IDE\devenv.exe");
            }
        */});
        this.exePath = getVisualStudioPath(null /*no arguments*/, true);
    }

};

reporter.prototype = new GenericDiffReporterBase();

reporter.prototype.canReportOn = function(fileName){

    if(ostools.platform.isWindows){
        return GenericDiffReporterBase.prototype.canReportOn(fileName);
    }

    return false;
};

reporter.prototype.report = function (approved, received, spawn) {
    spawn = spawn || child_process.spawn;
    autils.createEmptyFileIfNotExists(approved);

    var exe = this.exePath;

    var ps = spawn(exe, ["/diff", received, approved], {
        detached: true
    });

    ps.stdout.on('data', function (data) {
        console.log('reporter stdout: ' + data);
    });

    ps.stderr.on('data', function (data) {
        console.log('reporter stderr: ' + data);
    });

};

module.exports = reporter;
<|endoftext|>


<commit_before>/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

/*
 * Copyright (c) 2015, Joyent, Inc.
 */

/*
 * Returns servers with more unreserved CPU than the CPU requested for this
 * allocation.
 */

function
filterMinCpu(log, state, servers, constraints)
{
	var reasons  = constraints.capacity ? null : {};
	var override = constraints.defaults.filter_min_resources;
	var filter;

	if (typeof (override) !== 'undefined' && !override)
		return ([servers]);

	/* VM allocation without a cpu_cap is also valid */
	if (!constraints.vm.cpu_cap)
		return ([servers]);

	if (constraints.pkg && constraints.pkg.overprovision_cpu) {
		var requestedCpu = constraints.vm.cpu_cap /
		    constraints.pkg.overprovision_cpu;

		filter = function (server) {
			if (server.unreserved_cpu >= requestedCpu)
				return (true);

			if (reasons) {
				var msg = 'VM\'s calculated ' +
				    requestedCpu + ' CPU is ' +
				    'less than server\'s spare ' +
				    server.unreserved_cpu;
				reasons[server.uuid] = msg;
			}

			return (false);
		};
	} else {
		filter = function (server) {
			var serverCpu = server.overprovision_ratios.cpu;

			if (!serverCpu)
				return (true);

			// if pkg was not provided, assume ratio does not matter
			if (!constraints.pkg)
				return (true);

			if (reasons) {
				var msg = 'Package gave no CPU overprovision ' +
				    'ratio, but server has ratio ' + serverCpu;
				reasons[server.uuid] = msg;
			}

			return (false);
		};
	}

	return ([servers.filter(filter), reasons]);
}

module.exports = {
	name: 'Servers with enough unreserved CPU',
	run: filterMinCpu,
	affectsCapacity: true
};
<commit_msg>DAPI-270 - hard-filter-min-cpu should handle cpu_cap only being in package as well; this is mainly for consistency. Also some trivial variable refactoring in that plugin.<commit_after>/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

/*
 * Copyright (c) 2015, Joyent, Inc.
 */

/*
 * Returns servers with more unreserved CPU than the CPU requested for this
 * allocation.
 */

function
filterMinCpu(log, state, servers, constraints)
{
	var reasons  = constraints.capacity ? null : {};
	var override = constraints.defaults.filter_min_resources;
	var vm       = constraints.vm;
	var pkg      = constraints.pkg;
	var filter;

	if (typeof (override) !== 'undefined' && !override)
		return ([servers]);

	if (!vm.cpu_cap && pkg && pkg.cpu_cap)
		vm.cpu_cap = pkg.cpu_cap;

	/* VM allocation without a cpu_cap is also valid */
	if (!vm.cpu_cap)
		return ([servers]);

	if (pkg && pkg.overprovision_cpu) {
		var requestedCpu = vm.cpu_cap / pkg.overprovision_cpu;

		filter = function (server) {
			if (server.unreserved_cpu >= requestedCpu)
				return (true);

			if (reasons) {
				var msg = 'VM\'s calculated ' +
				    requestedCpu + ' CPU is ' +
				    'less than server\'s spare ' +
				    server.unreserved_cpu;
				reasons[server.uuid] = msg;
			}

			return (false);
		};
	} else {
		filter = function (server) {
			var serverCpu = server.overprovision_ratios.cpu;

			if (!serverCpu)
				return (true);

			// if pkg was not provided, assume ratio does not matter
			if (!pkg)
				return (true);

			if (reasons) {
				var msg = 'Package gave no CPU overprovision ' +
				    'ratio, but server has ratio ' + serverCpu;
				reasons[server.uuid] = msg;
			}

			return (false);
		};
	}

	return ([servers.filter(filter), reasons]);
}

module.exports = {
	name: 'Servers with enough unreserved CPU',
	run: filterMinCpu,
	affectsCapacity: true
};
<|endoftext|>


<commit_before>var
  _ = require('lodash'),
  util = require('util');

function ResponseObject (requestObject, response) {

  this.data = null;
  this.protocol = null;
  this.action = null;
  this.collection = null;
  this.controller = null;
  this.requestId = null;
  this.error = null;
  this.timestamp = null;
  this.status = null;

  construct.call(this, requestObject, response);
}

/**
 * Format a response and add data from requestObject
 * @param {RequestObject} requestObject
 * @param {Object} response
 * @returns {Object}
 */
function construct (requestObject, response) {
  response = response || {};

  if (response.status) {
    this.status = response.status;
  } else if (util.isError(response)) {
    this.status = 500;
  } else {
    this.status = 200;
  }

  if (response.action && response.controller) {
    Object.keys(response).forEach(function (attr) {
      this[attr] = response[attr];
    }.bind(this));

    return this;
  }
  else if (util.isError(response)) {
    this.error = formatError.call(this, response);
  }

  this.protocol = requestObject.protocol;
  this.action = requestObject.action;
  this.collection = requestObject.collection;
  this.controller = requestObject.controller;
  this.requestId = requestObject.requestId;
  this.timestamp = requestObject.timestamp;

  // TODO: check if the  user want also data from requestObject or just response from Elasticsearch
  this.data = _.extend(requestObject.data, response);
}

/**
 * Format an error data
 * @param {Object} error Object
 * @returns {Object}
 */
function formatError(error) {
  var response = {
    message: 'Internal error',
    count: 1,
    stack: error
  };
  if (error.message) {
    response.message = error.message;
  }
  if (error.count) {
    response.count = error.count;
  }
  if (error.stack) {
    response.stack = error.stack;
  }
  else if (error.body) {
    response.stack = error.body;
  }
  return response;
}

/**
 * Construct an object that will be return to the client
 * The parameter blackList allow to exclude attributes from response
 * @param {Array?} blackList
 * @returns {Object} object sent to client
 */
ResponseObject.prototype.toJson = function (blackList) {
  var
    formattedData = {};

  blackList = blackList || [];

  if (!this.data) {
    return {
      status:this.status,
      error: this.error,
      result: null
    };
  }

  Object.keys(this.data).forEach(function (attr) {
    if (!blackList.length || _.indexOf(blackList,attr) === -1) {
      formattedData[attr] = this.data[attr];
    }
  }.bind(this));

  formattedData.requestId = this.requestId;
  formattedData.controller = this.controller;
  formattedData.action = this.action;
  formattedData.collection = this.collection;

  formattedData._source = formattedData._source || formattedData.body;
  delete formattedData.body;

  return {
    status: this.status,
    error: this.error,
    result: formattedData
  };
};

/**
 * Construct an object ResponseObject from a serializedObject
 * @param {Object} serializedObject
 * @returns {ResponseObject}
 */
ResponseObject.prototype.unserialize = function (serializedObject) {
  return new ResponseObject({}, serializedObject);
};

ResponseObject.prototype.addBody = function () {
  if (this.data._source) {
    this.data.body = this.data._source;
  }
};

module.exports = ResponseObject;<commit_msg>Fix reponseObject format : return the error.stack to client only in case of 500 Error<commit_after>var
  _ = require('lodash'),
  util = require('util');

function ResponseObject (requestObject, response) {

  this.data = null;
  this.protocol = null;
  this.action = null;
  this.collection = null;
  this.controller = null;
  this.requestId = null;
  this.error = null;
  this.timestamp = null;
  this.status = null;

  construct.call(this, requestObject, response);
}

/**
 * Format a response and add data from requestObject
 * @param {RequestObject} requestObject
 * @param {Object} response
 * @returns {Object}
 */
function construct (requestObject, response) {
  response = response || {};

  if (response.status) {
    this.status = response.status;
  } else if (util.isError(response)) {
    this.status = 500;
  } else {
    this.status = 200;
  }

  if (response.action && response.controller) {
    Object.keys(response).forEach(function (attr) {
      this[attr] = response[attr];
    }.bind(this));

    return this;
  }
  else if (util.isError(response)) {
    this.error = formatError.call(this, response);
  }

  this.protocol = requestObject.protocol;
  this.action = requestObject.action;
  this.collection = requestObject.collection;
  this.controller = requestObject.controller;
  this.requestId = requestObject.requestId;
  this.timestamp = requestObject.timestamp;

  // TODO: check if the  user want also data from requestObject or just response from Elasticsearch
  this.data = _.extend(requestObject.data, response);
}

/**
 * Format an error data
 * @param {Object} error Object
 * @returns {Object}
 */
function formatError(error) {
  var response = {
    message: 'Internal error',
    count: 1,
    stack: ''
  };
  if (error.message) {
    response.message = error.message;
  }
  if (error.count) {
    response.count = error.count;
  }
  if (error.status === 500) {
    if (error.stack) {
      response.stack = error.stack;
    }
    else if (error.body) {
      response.stack = error.body;
    } else {
      response.stack = error;
    }
  }
  return response;
}

/**
 * Construct an object that will be return to the client
 * The parameter blackList allow to exclude attributes from response
 * @param {Array?} blackList
 * @returns {Object} object sent to client
 */
ResponseObject.prototype.toJson = function (blackList) {
  var
    formattedData = {};

  blackList = blackList || [];

  if (!this.data) {
    return {
      status:this.status,
      error: this.error,
      result: null
    };
  }

  Object.keys(this.data).forEach(function (attr) {
    if (!blackList.length || _.indexOf(blackList,attr) === -1) {
      formattedData[attr] = this.data[attr];
    }
  }.bind(this));

  formattedData.requestId = this.requestId;
  formattedData.controller = this.controller;
  formattedData.action = this.action;
  formattedData.collection = this.collection;

  formattedData._source = formattedData._source || formattedData.body;
  delete formattedData.body;

  return {
    status: this.status,
    error: this.error,
    result: formattedData
  };
};

/**
 * Construct an object ResponseObject from a serializedObject
 * @param {Object} serializedObject
 * @returns {ResponseObject}
 */
ResponseObject.prototype.unserialize = function (serializedObject) {
  return new ResponseObject({}, serializedObject);
};

ResponseObject.prototype.addBody = function () {
  if (this.data._source) {
    this.data.body = this.data._source;
  }
};

module.exports = ResponseObject;<|endoftext|>


<commit_before>'use strict';

/**
 * Creates a Filter object referring to a collection of subfilters
 *
 * This allows V8 to convert this object to a pure
 * C++ class, with direct access to its members,
 * instead of a dictionary with b-search access time
 *
 * @typedef Filter
 * @type {Object}
 * @property {string} id
 * @property {string} index
 * @property {string} collection
 * @property {Array<Array<Object>>} canonical - filters in its canonical form
 * @property {Array<Subfilter>} subfilters
 * @property {Number} fidx - maps to the filters test table
 *
 * @param {string} id - filter unique id
 * @param {string} index
 * @param {string} collection
 * @param {Array<Array<Object>>} filters
 * @constructor
 */
function Filter(id, index, collection, filters) {
  this.id = id;
  this.index = index;
  this.collection = collection;
  this.filters = filters;
  this.subfilters = [];
  this.fidx = -1;

  return this;
}

module.exports = Filter;
<commit_msg>fix comment<commit_after>'use strict';

/**
 * Creates a Filter object referring to a collection of subfilters
 *
 * This allows V8 to convert this object to a pure
 * C++ class, with direct access to its members,
 * instead of a dictionary with b-search access time
 *
 * @typedef Filter
 * @type {Object}
 * @property {string} id
 * @property {string} index
 * @property {string} collection
 * @property {Array<Array<Object>>} filters in their canonical form
 * @property {Array<Subfilter>} subfilters
 * @property {Number} fidx - maps to the filters test table
 *
 * @param {string} id - filter unique id
 * @param {string} index
 * @param {string} collection
 * @param {Array<Array<Object>>} filters
 * @constructor
 */
function Filter(id, index, collection, filters) {
  this.id = id;
  this.index = index;
  this.collection = collection;
  this.filters = filters;
  this.subfilters = [];
  this.fidx = -1;

  return this;
}

module.exports = Filter;
<|endoftext|>


<commit_before>(function () {

	// @class Drop.Models.File extends Marbles.Model
	var File = Marbles.Model.createClass({
		displayName: 'Drop.Models.File',

		modelName: 'file',

		cidMappingScope: ['id', 'entity'],

		willInitialize: function () {
			this.type = Drop.config.POST_TYPES.file;

			this.on('change:attachments', this.handleChangeAttachments, this);
		},

		handleChangeAttachments: function (attachments) {
			if (!this.entity) {
				var _args = Array.prototype.slice.call(arguments, 0);
				this.once('change:entity', function () {
					this.handleChangeAttachments.apply(this, _args);
				}, this);
				return;
			}

			var i = attachments[0] || {};
			var _ref = i.name.split('.');
			var ext = _ref[_ref.length-1];
			if (!ext || ext === _ref[0]) {
				_ref = i.content_type.split('/');
				ext = _ref[_ref.length-1];
			}
			this.set('file_meta', {
				name: i.name,
				size: i.size,
				type: i.content_type,
				digest: i.digest,
				ext: ext
			});

			this.set('link', Drop.client.getNamedURL('attachment', [{entity: this.entity, digest: i.digest}]));
		},

		getSignedLink: function (ttl) {
			return Drop.client.getSignedURL('attachment', [{
				entity: this.entity,
				digest: this.get('file_meta.digest')
			}], { ttl: ttl });
		},

		save: function () {
			if (this.id === 'new') {
				// create
				this.trigger('save:start');
				Drop.client.createPost({
					entity: this.entity,
					type: this.type,
					permissions: {
						public: this.get('permissions.public') !== false
					}
				}, {
					attachments: [['file', this.file, this.name]],
					callback: {
						success: function (res, xhr) {
							this.set('file', null);
							this.parseAttributes(res.post);
							this.trigger('save:success', res, xhr);
						}.bind(this),

						failure: function (res, xhr) {
							this.trigger('save:failure', res, xhr);
						}.bind(this),

						complete: function (res, xhr) {
							this.trigger('save:complete', res, xhr);
						}.bind(this)
					}
				});
			} else {
				console.error(Error("You need to implement saving existing file with Drop.Models.File.prototype.save"));
			}
		},

		performDelete: function () {
			if (this.id === 'new') {
				this.detach();
				return;
			} else {
				Drop.client.deletePost({
					params: {
						entity: this.entity,
						post: this.id,
					},
					callback: {
						success: function (res, xhr) {
							this.trigger('delete:success', res, xhr);
							this.constructor.trigger('delete:success', this, res, xhr);
							this.detach();
						}.bind(this),

						failure: function (res, xhr) {
							this.trigger('delete:failure', res, xhr);
							this.constructor.trigger('delete:failure', this, res, xhr);
						}.bind(this),

						complete: function (res, xhr) {
							this.trigger('delete:complete', res, xhr);
							this.constructor.trigger('delete:complete', this, res, xhr);
						}.bind(this)
					}
				});
			}
		}
	});

	File.findOrInit = function (attrs) {
		return File.find(attrs, { fetch: false }) || new File(attrs);
	};

	Drop.Models.File = File;

})();
<commit_msg>Fix delete file<commit_after>(function () {

	// @class Drop.Models.File extends Marbles.Model
	var File = Marbles.Model.createClass({
		displayName: 'Drop.Models.File',

		modelName: 'file',

		cidMappingScope: ['id', 'entity'],

		willInitialize: function () {
			this.type = Drop.config.POST_TYPES.file;

			this.on('change:attachments', this.handleChangeAttachments, this);
		},

		handleChangeAttachments: function (attachments) {
			if (!this.entity) {
				var _args = Array.prototype.slice.call(arguments, 0);
				this.once('change:entity', function () {
					this.handleChangeAttachments.apply(this, _args);
				}, this);
				return;
			}

			var i = attachments[0] || {};
			var _ref = i.name.split('.');
			var ext = _ref[_ref.length-1];
			if (!ext || ext === _ref[0]) {
				_ref = i.content_type.split('/');
				ext = _ref[_ref.length-1];
			}
			this.set('file_meta', {
				name: i.name,
				size: i.size,
				type: i.content_type,
				digest: i.digest,
				ext: ext
			});

			this.set('link', Drop.client.getNamedURL('attachment', [{entity: this.entity, digest: i.digest}]));
		},

		getSignedLink: function (ttl) {
			return Drop.client.getSignedURL('attachment', [{
				entity: this.entity,
				digest: this.get('file_meta.digest')
			}], { ttl: ttl });
		},

		save: function () {
			if (this.id === 'new') {
				// create
				this.trigger('save:start');
				Drop.client.createPost({
					entity: this.entity,
					type: this.type,
					permissions: {
						public: this.get('permissions.public') !== false
					}
				}, {
					attachments: [['file', this.file, this.name]],
					callback: {
						success: function (res, xhr) {
							this.set('file', null);
							this.parseAttributes(res.post);
							this.trigger('save:success', res, xhr);
						}.bind(this),

						failure: function (res, xhr) {
							this.trigger('save:failure', res, xhr);
						}.bind(this),

						complete: function (res, xhr) {
							this.trigger('save:complete', res, xhr);
						}.bind(this)
					}
				});
			} else {
				console.error(Error("You need to implement saving existing file with Drop.Models.File.prototype.save"));
			}
		},

		performDelete: function () {
			if (this.id === 'new') {
				this.detach();
				return;
			} else {
				Drop.client.deletePost({
					params: [{
						entity: this.entity,
						post: this.id,
					}],
					callback: {
						success: function (res, xhr) {
							this.trigger('delete:success', res, xhr);
							this.constructor.trigger('delete:success', this, res, xhr);
							this.detach();
						}.bind(this),

						failure: function (res, xhr) {
							this.trigger('delete:failure', res, xhr);
							this.constructor.trigger('delete:failure', this, res, xhr);
						}.bind(this),

						complete: function (res, xhr) {
							this.trigger('delete:complete', res, xhr);
							this.constructor.trigger('delete:complete', this, res, xhr);
						}.bind(this)
					}
				});
			}
		}
	});

	File.findOrInit = function (attrs) {
		return File.find(attrs, { fetch: false }) || new File(attrs);
	};

	Drop.Models.File = File;

})();
<|endoftext|>