<commit_before>'use strict';

var globalHours = ['6:00am', '7:00am', '8:00am','9:00am','10:00am','11:00am','12:00pm','1:00pm','2:00pm','3:00pm','4:00pm','5:00pm','6:00pm','7:00pm'];
// Store 1
var firstAndPike = {
  locationName: 'First and Pike',
  minCustPerHour: 23,
  maxCustPerHour: 65,
  avgCookiesPerCust: 6.3,
  custEachHourArray: [],
  cookiesEachHourArray: [],
  totalDailyCookieSales: 0
};
firstAndPike.calcCustEachHour = function (){
 // This method will generate a random number of customer for each hour and push
 //  them into the array.
  for (var i = 0; i < globalHours.length; i++) {
    var singleHourCust = Math.floor(Math.random() * (this.maxCustPerHour - this.minCustPerHour + 1)) + this.minCustPerHour;
    //console.log(this.maxCustPerHour);
    this.custEachHourArray.push(singleHourCust);
  }
  //console.log(this.custEachHourArray);
};
firstAndPike.calcCookiesEachHour = function(){
//  // This method will use the array of customers for each hours, multipy each of those hoursly values by the average cookies per customer.
//  // and generate an array of hourly cookie sales
//   //this.calcCustEachHour();
  for (var i = 0; i < globalHours.length; i++) {
    var singleHourCookies = Math.ceil(this.custEachHourArray[i] * this.avgCookiesPerCust);
  //  console.log(Math.ceil(this.custEachHourArray[i] * this.avgCookiesPerCust));
    //;
    this.cookiesEachHourArray.push(singleHourCookies);
    this.totalDailyCookieSales += singleHourCookies;
  }
  //console.log(this.cookiesEachHourArray);
};
firstAndPike.render = function() {
  //This method will take the array of thoursly cookie sales and display the data as an unordered list
  // };
  var pikeList = document.getElementById('Pike');
  for (var i = 0; i < globalHours.length; i++){
    var listElement = document.createElement('li');
    listElement.textContent = globalHours[i] + ': ' + this.cookiesEachHourArray[i] + ' cookies';
    pikeList.appendChild(listElement);
  }
  var totalElement = document.createElement('li');
  totalElement.textContent = 'Total: ' + this.totalDailyCookieSales + ' cookies';
  pikeList.appendChild(totalElement);
};
firstAndPike.calcCustEachHour();
firstAndPike.calcCookiesEachHour();
firstAndPike.render();
//Store2
var seaTacAirport = {
  locationName: 'SeaTac Airport',
  minCustPerHour: 3,
  maxCustPerHour: 24,
  avgCookiesPerCust: 1.2,
  custEachHourArray: [],
  cookiesEachHourArray: [],
  totalDailyCookieSales: 0
};
seaTacAirport.calcCustEachHour = function (){
  for (var i = 0; i < globalHours.length; i++) {
    var singleHourCust = Math.floor(Math.random() * (this.maxCustPerHour - this.minCustPerHour + 1)) + this.minCustPerHour;
    this.custEachHourArray.push(singleHourCust);
  }
};
seaTacAirport.calcCookiesEachHour = function(){
  for (var i = 0; i < globalHours.length; i++) {
    var singleHourCookies = Math.ceil(this.custEachHourArray[i] * this.avgCookiesPerCust);
    this.cookiesEachHourArray.push(singleHourCookies);
    this.totalDailyCookieSales += singleHourCookies;
  }
};
seaTacAirport.render = function() {
  var airportList = document.getElementById('SeaTac Airport');
  for (var i = 0; i < globalHours.length; i++){
    var listElement = document.createElement('li');
    listElement.textContent = globalHours[i] + ': ' + this.cookiesEachHourArray[i] + ' cookies';
    airportList.appendChild(listElement);
  }
  var totalElement = document.createElement('li');
  totalElement.textContent = 'Total: ' + this.totalDailyCookieSales + ' cookies';
  airportList.appendChild(totalElement);
};
seaTacAirport.calcCustEachHour();
seaTacAirport.calcCookiesEachHour();
seaTacAirport.render();
//store3
var seattleCenter = {
  locationName: 'Seattle Center',
  minCustPerHour: 11,
  maxCustPerHour: 38,
  avgCookiesPerCust: 3.7,
  custEachHourArray: [],
  cookiesEachHourArray: [],
  totalDailyCookieSales: 0
};
seattleCenter.calcCustEachHour = function (){
  for (var i = 0; i < globalHours.length; i++) {
    var singleHourCust = Math.floor(Math.random() * (this.maxCustPerHour - this.minCustPerHour + 1)) + this.minCustPerHour;
    this.custEachHourArray.push(singleHourCust);
  }
};
seattleCenter.calcCookiesEachHour = function(){
  for (var i = 0; i < globalHours.length; i++) {
    var singleHourCookies = Math.ceil(this.custEachHourArray[i] * this.avgCookiesPerCust);
    this.cookiesEachHourArray.push(singleHourCookies);
    this.totalDailyCookieSales += singleHourCookies;
  }
};
seattleCenter.render = function() {
  var centerList = document.getElementById('Seattle Center');
  for (var i = 0; i < globalHours.length; i++){
    var listElement = document.createElement('li');
    listElement.textContent = globalHours[i] + ': ' + this.cookiesEachHourArray[i] + ' cookies';
    centerList.appendChild(listElement);
  }
  var totalElement = document.createElement('li');
  totalElement.textContent = 'Total: ' + this.totalDailyCookieSales + ' cookies';
  centerList.appendChild(totalElement);
};
seattleCenter.calcCustEachHour();
seattleCenter.calcCookiesEachHour();
seattleCenter.render();
//store4
var capitolHill = {
  locationName: 'Capitol Hill',
  minCustPerHour: 11,
  maxCustPerHour: 38,
  avgCookiesPerCust: 3.7,
  custEachHourArray: [],
  cookiesEachHourArray: [],
  totalDailyCookieSales: 0
};
capitolHill.calcCustEachHour = function (){
  for (var i = 0; i < globalHours.length; i++) {
    var singleHourCust = Math.floor(Math.random() * (this.maxCustPerHour - this.minCustPerHour + 1)) + this.minCustPerHour;
    this.custEachHourArray.push(singleHourCust);
  }
};
capitolHill.calcCookiesEachHour = function(){
  for (var i = 0; i < globalHours.length; i++) {
    var singleHourCookies = Math.ceil(this.custEachHourArray[i] * this.avgCookiesPerCust);
    this.cookiesEachHourArray.push(singleHourCookies);
    this.totalDailyCookieSales += singleHourCookies;
  }
};
capitolHill.render = function() {
  var capitalList = document.getElementById('Capitol Hill');
  for (var i = 0; i < globalHours.length; i++){
    var listElement = document.createElement('li');
    listElement.textContent = globalHours[i] + ': ' + this.cookiesEachHourArray[i] + ' cookies';
    capitalList.appendChild(listElement);
  }
  var totalElement = document.createElement('li');
  totalElement.textContent = 'Total: ' + this.totalDailyCookieSales + ' cookies';
  capitalList.appendChild(totalElement);
};
capitolHill.calcCustEachHour();
capitolHill.calcCookiesEachHour();
capitolHill.render();
//store5
var alki = {
  locationName: 'Alki',
  minCustPerHour: 11,
  maxCustPerHour: 38,
  avgCookiesPerCust: 3.7,
  custEachHourArray: [],
  cookiesEachHourArray: [],
  totalDailyCookieSales: 0
};
alki.calcCustEachHour = function (){
  for (var i = 0; i < globalHours.length; i++) {
    var singleHourCust = Math.floor(Math.random() * (this.maxCustPerHour - this.minCustPerHour + 1)) + this.minCustPerHour;
    this.custEachHourArray.push(singleHourCust);
  }
};
alki.calcCookiesEachHour = function(){
  for (var i = 0; i < globalHours.length; i++) {
    var singleHourCookies = Math.ceil(this.custEachHourArray[i] * this.avgCookiesPerCust);
    this.cookiesEachHourArray.push(singleHourCookies);
    this.totalDailyCookieSales += singleHourCookies;
  }
};
alki.render = function() {
  var alkiList = document.getElementById('Alki');
  for (var i = 0; i < globalHours.length; i++){
    var listElement = document.createElement('li');
    listElement.textContent = globalHours[i] + ': ' + this.cookiesEachHourArray[i] + ' cookies';
    alkiList.appendChild(listElement);
  }
  var totalElement = document.createElement('li');
  totalElement.textContent = 'Total: ' + this.totalDailyCookieSales + ' cookies';
  alkiList.appendChild(totalElement);
};
alki.calcCustEachHour();
alki.calcCookiesEachHour();
alki.render();
<commit_msg>working on constructors<commit_after>'use strict';

var globalHours = ['6:00am', '7:00am', '8:00am','9:00am','10:00am','11:00am','12:00pm','1:00pm','2:00pm','3:00pm','4:00pm','5:00pm','6:00pm','7:00pm'];
var allStores = [];
function Store(locationName, minCustPerHour, maxCustPerHour, avgCookiesPerCust){
  this.locationName = locationName;
  this.minCustPerHour = minCustPerHour;
  this.maxCustPerHour = maxCustPerHour;
  this.avgCookiesPerCust = avgCookiesPerCust;
  this.custEachHourArray = [];
  this.cookiesEachHourArray = [];
  this.totalDailyCookieSales = 0;
  this.calCustEachHour = function () {
    for (var i = 0; i < globalHours.length; i++) {
      var singleHourCust = Math.floor(Math.random() * (this.maxCustPerHour - this.minCustPerHour + 1)) + this.minCustPerHour;
      this.custEachHourArray.push(singleHourCust);
    }
  };
  this.calcCookiesEachHour = function (){
    this.calCustEachHour();
    for (var i = 0; i < globalHours.length; i++){
      var singleHourCookies = Math.ceil(this.custEachHourArray[i] * this.avgCookiesPerCust);
      this.cookiesEachHourArray.push(singleHourCookies);
      this.totalDailyCookieSales += singleHourCookies;
    }
  };
  this.calcCookiesEachHour();
  allStores.push(this);

};

var firstAndPike = new Store('First And Pike',23,65,6.3);
var seaTacAirport = new Store('SeaTac Airport',3,24,1.2);
var seattleCenter = new Store('Seattle Center',11,38,3.7);
var capitolHill = new Store('Capitol Hill',20,38,2.3);
var alki = new Store('Alki',2,16,4.6);
console.log(firstAndPike);
console.log(seaTacAirport);
console.log(seattleCenter);
console.log(capitolHill);
console.log(alki);
//End of constructors
var dataset = document.getElementById('cookiez');
function makeHeaderRow(){
  for( var i = 0; i < globalHours.length; i++){
    var tableRow = document.createElement('tr');
    var thElement = document.createElement('th');
    thElement.textContent = globalHours[i];
    tableRow.appenChild(thElement);
  }
};
//this.calcCookiesEachHour = function(){
  //return Math.floor(this.calCustEachHour() * this.avgCookiesPerCust);
  //}

  //var firstAndPike = new store('First And Pike',23,65,6.3);
/* Store 1
var firstAndPike = {
  locationName: 'First and Pike',
  minCustPerHour: 23,
  maxCustPerHour: 65,
  avgCookiesPerCust: 6.3,
  custEachHourArray: [],
  cookiesEachHourArray: [],
  totalDailyCookieSales: 0
};
firstAndPike.calcCustEachHour = function (){
 // This method will generate a random number of customer for each hour and push
 //  them into the array.
  for (var i = 0; i < globalHours.length; i++) {
    var singleHourCust = Math.floor(Math.random() * (this.maxCustPerHour - this.minCustPerHour + 1)) + this.minCustPerHour;
    //console.log(this.maxCustPerHour);
    this.custEachHourArray.push(singleHourCust);
  }
  //console.log(this.custEachHourArray);
};
firstAndPike.calcCookiesEachHour = function(){
//  // This method will use the array of customers for each hours, multipy each of those hoursly values by the average cookies per customer.
//  // and generate an array of hourly cookie sales
//   //this.calcCustEachHour();
  for (var i = 0; i < globalHours.length; i++) {
    var singleHourCookies = Math.ceil(this.custEachHourArray[i] * this.avgCookiesPerCust);
  //  console.log(Math.ceil(this.custEachHourArray[i] * this.avgCookiesPerCust));
    //;
    this.cookiesEachHourArray.push(singleHourCookies);
    this.totalDailyCookieSales += singleHourCookies;
  }
  //console.log(this.cookiesEachHourArray);
};
firstAndPike.render = function() {
  //This method will take the array of thoursly cookie sales and display the data as an unordered list
  // };
  var pikeList = document.getElementById('Pike');
  for (var i = 0; i < globalHours.length; i++){
    var listElement = document.createElement('li');
    listElement.textContent = globalHours[i] + ': ' + this.cookiesEachHourArray[i] + ' cookies';
    pikeList.appendChild(listElement);
  }
  var totalElement = document.createElement('li');
  totalElement.textContent = 'Total: ' + this.totalDailyCookieSales + ' cookies';
  pikeList.appendChild(totalElement);
};
firstAndPike.calcCustEachHour();
firstAndPike.calcCookiesEachHour();
firstAndPike.render();
//Store2
var seaTacAirport = {
  locationName: 'SeaTac Airport',
  minCustPerHour: 3,
  maxCustPerHour: 24,
  avgCookiesPerCust: 1.2,
  custEachHourArray: [],
  cookiesEachHourArray: [],
  totalDailyCookieSales: 0
};
seaTacAirport.calcCustEachHour = function (){
  for (var i = 0; i < globalHours.length; i++) {
    var singleHourCust = Math.floor(Math.random() * (this.maxCustPerHour - this.minCustPerHour + 1)) + this.minCustPerHour;
    this.custEachHourArray.push(singleHourCust);
  }
};
seaTacAirport.calcCookiesEachHour = function(){
  for (var i = 0; i < globalHours.length; i++) {
    var singleHourCookies = Math.ceil(this.custEachHourArray[i] * this.avgCookiesPerCust);
    this.cookiesEachHourArray.push(singleHourCookies);
    this.totalDailyCookieSales += singleHourCookies;
  }
};
seaTacAirport.render = function() {
  var airportList = document.getElementById('SeaTac Airport');
  for (var i = 0; i < globalHours.length; i++){
    var listElement = document.createElement('li');
    listElement.textContent = globalHours[i] + ': ' + this.cookiesEachHourArray[i] + ' cookies';
    airportList.appendChild(listElement);
  }
  var totalElement = document.createElement('li');
  totalElement.textContent = 'Total: ' + this.totalDailyCookieSales + ' cookies';
  airportList.appendChild(totalElement);
};
seaTacAirport.calcCustEachHour();
seaTacAirport.calcCookiesEachHour();
seaTacAirport.render();
//store3
var seattleCenter = {
  locationName: 'Seattle Center',
  minCustPerHour: 11,
  maxCustPerHour: 38,
  avgCookiesPerCust: 3.7,
  custEachHourArray: [],
  cookiesEachHourArray: [],
  totalDailyCookieSales: 0
};
seattleCenter.calcCustEachHour = function (){
  for (var i = 0; i < globalHours.length; i++) {
    var singleHourCust = Math.floor(Math.random() * (this.maxCustPerHour - this.minCustPerHour + 1)) + this.minCustPerHour;
    this.custEachHourArray.push(singleHourCust);
  }
};
seattleCenter.calcCookiesEachHour = function(){
  for (var i = 0; i < globalHours.length; i++) {
    var singleHourCookies = Math.ceil(this.custEachHourArray[i] * this.avgCookiesPerCust);
    this.cookiesEachHourArray.push(singleHourCookies);
    this.totalDailyCookieSales += singleHourCookies;
  }
};
seattleCenter.render = function() {
  var centerList = document.getElementById('Seattle Center');
  for (var i = 0; i < globalHours.length; i++){
    var listElement = document.createElement('li');
    listElement.textContent = globalHours[i] + ': ' + this.cookiesEachHourArray[i] + ' cookies';
    centerList.appendChild(listElement);
  }
  var totalElement = document.createElement('li');
  totalElement.textContent = 'Total: ' + this.totalDailyCookieSales + ' cookies';
  centerList.appendChild(totalElement);
};
seattleCenter.calcCustEachHour();
seattleCenter.calcCookiesEachHour();
seattleCenter.render();
//store4
var capitolHill = {
  locationName: 'Capitol Hill',
  minCustPerHour: 20,
  maxCustPerHour: 38,
  avgCookiesPerCust: 2.3,
  custEachHourArray: [],
  cookiesEachHourArray: [],
  totalDailyCookieSales: 0
};
capitolHill.calcCustEachHour = function (){
  for (var i = 0; i < globalHours.length; i++) {
    var singleHourCust = Math.floor(Math.random() * (this.maxCustPerHour - this.minCustPerHour + 1)) + this.minCustPerHour;
    this.custEachHourArray.push(singleHourCust);
  }
};
capitolHill.calcCookiesEachHour = function(){
  for (var i = 0; i < globalHours.length; i++) {
    var singleHourCookies = Math.ceil(this.custEachHourArray[i] * this.avgCookiesPerCust);
    this.cookiesEachHourArray.push(singleHourCookies);
    this.totalDailyCookieSales += singleHourCookies;
  }
};
capitolHill.render = function() {
  var capitalList = document.getElementById('Capitol Hill');
  for (var i = 0; i < globalHours.length; i++){
    var listElement = document.createElement('li');
    listElement.textContent = globalHours[i] + ': ' + this.cookiesEachHourArray[i] + ' cookies';
    capitalList.appendChild(listElement);
  }
  var totalElement = document.createElement('li');
  totalElement.textContent = 'Total: ' + this.totalDailyCookieSales + ' cookies';
  capitalList.appendChild(totalElement);
};
capitolHill.calcCustEachHour();
capitolHill.calcCookiesEachHour();
capitolHill.render();
//store5
var alki = {
  locationName: 'Alki',
  minCustPerHour: 2,
  maxCustPerHour: 16,
  avgCookiesPerCust: 4.6,
  custEachHourArray: [],
  cookiesEachHourArray: [],
  totalDailyCookieSales: 0
};
alki.calcCustEachHour = function (){
  for (var i = 0; i < globalHours.length; i++) {
    var singleHourCust = Math.floor(Math.random() * (this.maxCustPerHour - this.minCustPerHour + 1)) + this.minCustPerHour;
    this.custEachHourArray.push(singleHourCust);
  }
};
alki.calcCookiesEachHour = function(){
  for (var i = 0; i < globalHours.length; i++) {
    var singleHourCookies = Math.ceil(this.custEachHourArray[i] * this.avgCookiesPerCust);
    this.cookiesEachHourArray.push(singleHourCookies);
    this.totalDailyCookieSales += singleHourCookies;
  }
};
alki.render = function() {
  var alkiList = document.getElementById('Alki');
  for (var i = 0; i < globalHours.length; i++){
    var listElement = document.createElement('li');
    listElement.textContent = globalHours[i] + ': ' + this.cookiesEachHourArray[i] + ' cookies';
    alkiList.appendChild(listElement);
  }
  var totalElement = document.createElement('li');
  totalElement.textContent = 'Total: ' + this.totalDailyCookieSales + ' cookies';
  alkiList.appendChild(totalElement);
};
alki.calcCustEachHour();
alki.calcCookiesEachHour();
alki.render();
*/
<|endoftext|>


<commit_before>'use strict';

var Command         = require('./-command');
var IconTask        = require('splicon/lib/icon-task');
var chalk           = require('chalk');

module.exports = Command.extend({
  name: 'cordova:make-icons',
  aliases: ['cordova:icons', 'cdv:icon', 'cdv:make-icons'],
  description: 'Generates cordova icon files and updates config',
  works: 'insideProject',

  availableOptions: [{
    name: 'source',
    type: String,
    default: 'ember-cordova/icon.svg'
  }, {
    name: 'platform',
    type: Array,
    default: ['all']
  }],

  run: function(options) {
    this._super.apply(this, arguments);

    this.ui.writeLine(chalk.green(
      'ember-cordova: generating-icons'
    ));

    return new IconTask({
      source: options.source,
      platforms: options.platform,
      projectPath: 'ember-cordova/cordova'
    }).then(function() {
      this.ui.writeLine(chalk.green(
        'ember-cordova: icons generated'
      ));
    }).catch(function(err) {
      this.ui.writeLine(chalk.red(
        'ember-cordova: Error generating icons ' + err
      ));
    });
  }
});
<commit_msg>fix(make icon): assign `this` when returning new IconTask<commit_after>'use strict';

var Command         = require('./-command');
var IconTask        = require('splicon/lib/icon-task');
var chalk           = require('chalk');

module.exports = Command.extend({
  name: 'cordova:make-icons',
  aliases: ['cordova:icons', 'cdv:icon', 'cdv:make-icons'],
  description: 'Generates cordova icon files and updates config',
  works: 'insideProject',

  availableOptions: [{
    name: 'source',
    type: String,
    default: 'ember-cordova/icon.svg'
  }, {
    name: 'platform',
    type: Array,
    default: ['all']
  }],

  run: function(options) {
    this._super.apply(this, arguments);

    this.ui.writeLine(chalk.green(
      'ember-cordova: generating-icons'
    ));

    let _this = this;
    return new IconTask({
      source: options.source,
      platforms: options.platform,
      projectPath: 'ember-cordova/cordova'
    }).then(function() {
      _this.ui.writeLine(chalk.green(
        'ember-cordova: icons generated'
      ));
    }).catch(function(err) {
      _this.ui.writeLine(chalk.red(
        'ember-cordova: Error generating icons ' + err
      ));
    });
  }
});
<|endoftext|>


<commit_before>module.exports = {
  'Unit': require('./unit'),
  'Lexer': require('./lexer'),
};
<commit_msg>Add math & clean up.<commit_after>module.exports = {
  // Objects
  'Unit': require('./unit'),
  'Lexer': require('./lexer'),

  // Methods
  'math': require('./math'),
};
<|endoftext|>


<commit_before>const ostb = require('os-toolbox');
const q = require('q');

exports.getInfos = function () {
    let deferred = q.defer();
    q.all([
        ostb.cpuLoad(),
        ostb.memoryUsage()
    ]).then(function (results) {
        deferred.resolve({
            cpu: results[0],
            mem: results[1]
        });
    });
    return deferred.promise;
}

exports.getInfosFull = function () {
    let deferred = q.defer();
    q.all([
        ostb.cpuLoad(),
        ostb.memoryUsage(),
        ostb.platform(),
        ostb.uptime(),
        ostb.currentProcesses()
    ]).then(function (results) {
        deferred.resolve({
            cpu: results[0],
            mem: results[1],
            platform: results[2],
            uptime: results[3],
            processes: results[4]
        });
    });
    return deferred.promise;
}

exports.uptime = function () {
    let uptime = ostb.uptime();
    let secondsInAMinute = 60;
    let secondsInAnHour = 60 * secondsInAMinute;
    let secondsInADay = 24 * secondsInAnHour;

    // extract days
    let days = Math.round(uptime / secondsInADay);

    // extract hours
    let hourSeconds = uptime % secondsInADay;
    let hours = Math.round(hourSeconds / secondsInAnHour);

    // extract minutes
    let minuteSeconds = hourSeconds % secondsInAnHour;
    let minutes = Math.round(minuteSeconds / secondsInAMinute);
    return {
        days: days,
        hours: hours,
        minutes: minutes
    };
}

exports.freecache = function () {
    let deferred = q.defer();
    childProcess.exec('echo 3 > /proc/sys/vm/drop_caches', (err) => {
        if (err) {
            deffered.reject(err);
        }
    });
    return deferred.promise;
}<commit_msg>[FIX] Memory cleanup job<commit_after>const ostb = require('os-toolbox');
const q = require('q');
const childProcess = require('child_process');

exports.getInfos = function () {
    let deferred = q.defer();
    q.all([
        ostb.cpuLoad(),
        ostb.memoryUsage()
    ]).then(function (results) {
        deferred.resolve({
            cpu: results[0],
            mem: results[1]
        });
    });
    return deferred.promise;
}

exports.getInfosFull = function () {
    let deferred = q.defer();
    q.all([
        ostb.cpuLoad(),
        ostb.memoryUsage(),
        ostb.platform(),
        ostb.uptime(),
        ostb.currentProcesses()
    ]).then(function (results) {
        deferred.resolve({
            cpu: results[0],
            mem: results[1],
            platform: results[2],
            uptime: results[3],
            processes: results[4]
        });
    });
    return deferred.promise;
}

exports.uptime = function () {
    let uptime = ostb.uptime();
    let secondsInAMinute = 60;
    let secondsInAnHour = 60 * secondsInAMinute;
    let secondsInADay = 24 * secondsInAnHour;

    // extract days
    let days = Math.round(uptime / secondsInADay);

    // extract hours
    let hourSeconds = uptime % secondsInADay;
    let hours = Math.round(hourSeconds / secondsInAnHour);

    // extract minutes
    let minuteSeconds = hourSeconds % secondsInAnHour;
    let minutes = Math.round(minuteSeconds / secondsInAMinute);
    return {
        days: days,
        hours: hours,
        minutes: minutes
    };
}

exports.freecache = function () {
    let deferred = q.defer();
    childProcess.exec('echo 3 > /proc/sys/vm/drop_caches', (err) => {
        if (err) {
            deferred.reject(err);
        }
    });
    return deferred.promise;
}<|endoftext|>


<commit_before>/**
 * Creates static pages' JSON
 * @param collectionId
 * @param releaseDate
 * @param pageType
 * @param parentUrl
 */

function loadT7Creator(collectionId, releaseDate, pageType, parentUrl) {
  var releaseDate = null;             //overwrite scheduled collection date
  var pageName, pageNameTrimmed, newUri, pageData, isNumber;
  if (parentUrl === '/') {        //to check home page
    parentUrl = '';
  }
  var parentUrlData = parentUrl + "/data";
  $.ajax({
    url: parentUrlData,
    dataType: 'json',
    crossDomain: true,
    success: function (checkData) {
      if (pageType === 'static_landing_page' && checkData.type === 'home_page' ||
        (pageType === 'static_qmi' || pageType === 'static_adhoc' || pageType === 'static_methodology' || pageType === 'static_methodology_download') && checkData.type === 'product_page') {
        submitFormHandler();
        return true;
      } else if ((pageType === 'static_foi' || pageType === 'static_page' || pageType === 'static_landing_page') && checkData.type.match(/static_.+/)) {
        submitFormHandler();
        return true;
      } else {
        sweetAlert("This is not a valid place to create this page.");
        loadCreateScreen(collectionId);
      }
    },
    error: function () {
      console.log('No page data returned');
    }
  });

  function submitFormHandler() {
    if (pageType === 'static_qmi' || pageType === 'static_methodology') {
      $('.edition').append(
        '
' +
        'Last revised' +
        '<input id="releaseDate" type="text" placeholder="day month year" />'
      );

      $('#releaseDate').datepicker({dateFormat: 'dd MM yy'});
    } else if (pageType === 'static_adhoc') {
      $('.edition').append(
        'Release date' +
        '<input id="releaseDate" type="text" placeholder="day month year" />' +
        '
' +
        'Reference' +
        '<input id="adhoc-reference" type="text" placeholder="Reference number" />'
      );
      $('#releaseDate').datepicker({dateFormat: 'dd MM yy'});
      $('#adhoc-reference').on('input', function () {
        isNumber = $(this).val();
        if (!isNumber.match(/^\d+$/)) {
          sweetAlert('This needs to be a number');
          $(this).val('');
        }
      });
    }
    else if (!releaseDate && !(pageType === 'static_page' || pageType === 'static_landing_page')) {
      $('.edition').append(
        '
' +
        'Release date' +
        '<input id="releaseDate" type="text" placeholder="day month year" />'
      );
      $('#releaseDate').datepicker({dateFormat: 'dd MM yy'});
    }

    $('form').submit(function (e) {
      e.preventDefault();
      //Check for reserved words
      if ($('#pagename').val().toLowerCase() === 'current' || $('#pagename').val().toLowerCase() === 'latest' || $('#pagename').val().toLowerCase() === 'data') {
        alert('That is not an accepted value for a title');
        $('#pagename').val('');
        return false;
      }
      pageData = pageTypeDataT7(pageType);
      pageName = $('#pagename').val().trim();
      pageData.description.title = pageName;
      pageNameTrimmed = pageName.replace(/[^A-Z0-9]+/ig, "").toLowerCase();
      pageData.fileName = pageNameTrimmed;
      pageData.description.reference = isNumber;
      var adHocUrl = isNumber + pageNameTrimmed;
      if (pageType === 'static_qmi' && !Florence.globalVars.welsh) {
        newUri = makeUrl(parentUrl, 'qmis', pageNameTrimmed);
      } else if (pageType === 'static_adhoc' && !Florence.globalVars.welsh) {
        newUri = makeUrl(parentUrl, 'adhocs', adHocUrl);
      } else if ((pageType === 'static_methodology' || pageType === 'static_methodology_download') && !Florence.globalVars.welsh) {
        newUri = makeUrl(parentUrl, 'methodologies', pageNameTrimmed);
      } else if (!Florence.globalVars.welsh) {
        newUri = makeUrl(parentUrl, pageNameTrimmed);
      } else {
        sweetAlert('You can not perform that operation in Welsh.');
      }
      var safeNewUri = checkPathSlashes(newUri);
      if (releaseDate && (pageType === 'static_qmi')) {
        date = new Date(releaseDate);
        pageData.description.lastRevised = $.datepicker.formatDate('dd/mm/yy', date);
      } else if (releaseDate && (pageType !== 'static_page' || pageType !== 'static_landing_page')) {
        date = new Date(releaseDate);
        pageData.description.releaseDate = $.datepicker.formatDate('dd/mm/yy', date);
      } else if (!releaseDate && (pageType === 'static_qmi' || pageType === 'static_methodology')) {
        pageData.description.lastRevised = new Date($('#releaseDate').val()).toISOString();
      } else if (!releaseDate && !(pageType === 'static_page' || pageType === 'static_landing_page')) {
        pageData.description.releaseDate = new Date($('#releaseDate').val()).toISOString();
      }

      if (pageName.length < 5) {
        sweetAlert("This is not a valid file name");
      } else {
        saveContent(collectionId, safeNewUri, pageData);
      }
    });
  }
}

function pageTypeDataT7(pageType) {

  if (pageType === "static_page") {
    return {
      "description": {
        "title": "",
        "summary": "",
        "keywords": [],
        "metaDescription": ""
      },
      "markdown": [],
      "downloads": [],
      type: pageType,
      "links": []
    };
  } else if (pageType === "static_landing_page") {
    return {
      "description": {
        "title": "",
        "summary": "",
        "keywords": [],
        "metaDescription": "",
      },
      "sections": [],
      "markdown": [],
      type: pageType,
      "links": []
    };
  }
  else if (pageType === "static_methodology") {
    return {
      "description": {
        "title": "",
        "summary": "",
        "releaseDate": "",
        "contact": {
          "name": "",
          "email": "",
          "telephone": ""
        },
        "keywords": [],
        "metaDescription": ""
      },
      "sections": [],
      "accordion": [],
      "relatedDocuments": [],
      "relatedDatasets": [],
      "charts": [],
      "tables": [],
      "images": [],
      "downloads": [],
      "links": [],
      "alerts": [],
      type: pageType
    };
  } else if (pageType === "static_methodology_download") {
    return {
      "description": {
        "title": "",
        "contact": {
          "name": "",
          "email": "",
          "phone": ""
        },
        "releaseDate": "",
        "keywords": [],
        "metaDescription": ""
      },
      "markdown": [],
      "downloads": [],
      "relatedDocuments": [],
      "relatedDatasets": [],
      "links": [],
      "alerts": [],
      type: pageType
    };
  } else if (pageType === "static_qmi") {
    return {
      "description": {
        "title": "",
        "contact": {
          "name": "",
          "email": "",
          "phone": ""
        },
        "surveyName": "",
        "frequency": "",
        "compilation": "",
        "geographicCoverage": "",
        "sampleSize": null,
        "lastRevised": "",
        "nationalStatistic": false,
        "keywords": [],
        "metaDescription": ""
      },
      "markdown": [],
      "downloads": [],
      "relatedDocuments": [],
      "relatedDatasets": [],
      "links": [],
      type: pageType
    };
  } else if (pageType === "static_foi") {
    return {
      "description": {
        "title": "",
        "releaseDate": "",
        "keywords": [],
        "metaDescription": ""
      },
      "downloads": [],
      "markdown": [],
      "links": [],
      type: pageType
    };
  } else if (pageType === "static_adhoc") {
    return {
      "description": {
        "title": "",
        "releaseDate": "",
        "reference": null,
        "keywords": [],
        "metaDescription": ""
      },
      "downloads": [],
      "markdown": [],
      "links": [],
      type: pageType
    };
  } else {
    sweetAlert('Unsupported page type', 'This is not a static page', "info");
  }
}<commit_msg>Change length of filename to allow four characters<commit_after>/**
 * Creates static pages' JSON
 * @param collectionId
 * @param releaseDate
 * @param pageType
 * @param parentUrl
 */

function loadT7Creator(collectionId, releaseDate, pageType, parentUrl) {
  var releaseDate = null;             //overwrite scheduled collection date
  var pageName, pageNameTrimmed, newUri, pageData, isNumber;
  if (parentUrl === '/') {        //to check home page
    parentUrl = '';
  }
  var parentUrlData = parentUrl + "/data";
  $.ajax({
    url: parentUrlData,
    dataType: 'json',
    crossDomain: true,
    success: function (checkData) {
      if (pageType === 'static_landing_page' && checkData.type === 'home_page' ||
        (pageType === 'static_qmi' || pageType === 'static_adhoc' || pageType === 'static_methodology' || pageType === 'static_methodology_download') && checkData.type === 'product_page') {
        submitFormHandler();
        return true;
      } else if ((pageType === 'static_foi' || pageType === 'static_page' || pageType === 'static_landing_page') && checkData.type.match(/static_.+/)) {
        submitFormHandler();
        return true;
      } else {
        sweetAlert("This is not a valid place to create this page.");
        loadCreateScreen(collectionId);
      }
    },
    error: function () {
      console.log('No page data returned');
    }
  });

  function submitFormHandler() {
    if (pageType === 'static_qmi' || pageType === 'static_methodology') {
      $('.edition').append(
        '
' +
        'Last revised' +
        '<input id="releaseDate" type="text" placeholder="day month year" />'
      );

      $('#releaseDate').datepicker({dateFormat: 'dd MM yy'});
    } else if (pageType === 'static_adhoc') {
      $('.edition').append(
        'Release date' +
        '<input id="releaseDate" type="text" placeholder="day month year" />' +
        '
' +
        'Reference' +
        '<input id="adhoc-reference" type="text" placeholder="Reference number" />'
      );
      $('#releaseDate').datepicker({dateFormat: 'dd MM yy'});
      $('#adhoc-reference').on('input', function () {
        isNumber = $(this).val();
        if (!isNumber.match(/^\d+$/)) {
          sweetAlert('This needs to be a number');
          $(this).val('');
        }
      });
    }
    else if (!releaseDate && !(pageType === 'static_page' || pageType === 'static_landing_page')) {
      $('.edition').append(
        '
' +
        'Release date' +
        '<input id="releaseDate" type="text" placeholder="day month year" />'
      );
      $('#releaseDate').datepicker({dateFormat: 'dd MM yy'});
    }

    $('form').submit(function (e) {
      e.preventDefault();
      //Check for reserved words
      if ($('#pagename').val().toLowerCase() === 'current' || $('#pagename').val().toLowerCase() === 'latest' || $('#pagename').val().toLowerCase() === 'data') {
        alert('That is not an accepted value for a title');
        $('#pagename').val('');
        return false;
      }
      pageData = pageTypeDataT7(pageType);
      pageName = $('#pagename').val().trim();
      pageData.description.title = pageName;
      pageNameTrimmed = pageName.replace(/[^A-Z0-9]+/ig, "").toLowerCase();
      pageData.fileName = pageNameTrimmed;
      pageData.description.reference = isNumber;
      var adHocUrl = isNumber + pageNameTrimmed;
      if (pageType === 'static_qmi' && !Florence.globalVars.welsh) {
        newUri = makeUrl(parentUrl, 'qmis', pageNameTrimmed);
      } else if (pageType === 'static_adhoc' && !Florence.globalVars.welsh) {
        newUri = makeUrl(parentUrl, 'adhocs', adHocUrl);
      } else if ((pageType === 'static_methodology' || pageType === 'static_methodology_download') && !Florence.globalVars.welsh) {
        newUri = makeUrl(parentUrl, 'methodologies', pageNameTrimmed);
      } else if (!Florence.globalVars.welsh) {
        newUri = makeUrl(parentUrl, pageNameTrimmed);
      } else {
        sweetAlert('You can not perform that operation in Welsh.');
      }
      var safeNewUri = checkPathSlashes(newUri);
      if (releaseDate && (pageType === 'static_qmi')) {
        date = new Date(releaseDate);
        pageData.description.lastRevised = $.datepicker.formatDate('dd/mm/yy', date);
      } else if (releaseDate && (pageType !== 'static_page' || pageType !== 'static_landing_page')) {
        date = new Date(releaseDate);
        pageData.description.releaseDate = $.datepicker.formatDate('dd/mm/yy', date);
      } else if (!releaseDate && (pageType === 'static_qmi' || pageType === 'static_methodology')) {
        pageData.description.lastRevised = new Date($('#releaseDate').val()).toISOString();
      } else if (!releaseDate && !(pageType === 'static_page' || pageType === 'static_landing_page')) {
        pageData.description.releaseDate = new Date($('#releaseDate').val()).toISOString();
      }

      if (pageName.length < 4) {
        sweetAlert("This is not a valid file name");
      } else {
        saveContent(collectionId, safeNewUri, pageData);
      }
    });
  }
}

function pageTypeDataT7(pageType) {

  if (pageType === "static_page") {
    return {
      "description": {
        "title": "",
        "summary": "",
        "keywords": [],
        "metaDescription": ""
      },
      "markdown": [],
      "downloads": [],
      type: pageType,
      "links": []
    };
  } else if (pageType === "static_landing_page") {
    return {
      "description": {
        "title": "",
        "summary": "",
        "keywords": [],
        "metaDescription": "",
      },
      "sections": [],
      "markdown": [],
      type: pageType,
      "links": []
    };
  }
  else if (pageType === "static_methodology") {
    return {
      "description": {
        "title": "",
        "summary": "",
        "releaseDate": "",
        "contact": {
          "name": "",
          "email": "",
          "telephone": ""
        },
        "keywords": [],
        "metaDescription": ""
      },
      "sections": [],
      "accordion": [],
      "relatedDocuments": [],
      "relatedDatasets": [],
      "charts": [],
      "tables": [],
      "images": [],
      "downloads": [],
      "links": [],
      "alerts": [],
      type: pageType
    };
  } else if (pageType === "static_methodology_download") {
    return {
      "description": {
        "title": "",
        "contact": {
          "name": "",
          "email": "",
          "phone": ""
        },
        "releaseDate": "",
        "keywords": [],
        "metaDescription": ""
      },
      "markdown": [],
      "downloads": [],
      "relatedDocuments": [],
      "relatedDatasets": [],
      "links": [],
      "alerts": [],
      type: pageType
    };
  } else if (pageType === "static_qmi") {
    return {
      "description": {
        "title": "",
        "contact": {
          "name": "",
          "email": "",
          "phone": ""
        },
        "surveyName": "",
        "frequency": "",
        "compilation": "",
        "geographicCoverage": "",
        "sampleSize": null,
        "lastRevised": "",
        "nationalStatistic": false,
        "keywords": [],
        "metaDescription": ""
      },
      "markdown": [],
      "downloads": [],
      "relatedDocuments": [],
      "relatedDatasets": [],
      "links": [],
      type: pageType
    };
  } else if (pageType === "static_foi") {
    return {
      "description": {
        "title": "",
        "releaseDate": "",
        "keywords": [],
        "metaDescription": ""
      },
      "downloads": [],
      "markdown": [],
      "links": [],
      type: pageType
    };
  } else if (pageType === "static_adhoc") {
    return {
      "description": {
        "title": "",
        "releaseDate": "",
        "reference": null,
        "keywords": [],
        "metaDescription": ""
      },
      "downloads": [],
      "markdown": [],
      "links": [],
      type: pageType
    };
  } else {
    sweetAlert('Unsupported page type', 'This is not a static page', "info");
  }
}<|endoftext|>


<commit_before>module("tinymce.plugins.Fullscreen", {
	setupModule: function() {
		QUnit.stop();

		tinymce.init({
			selector: "textarea",
			plugins: "fullscreen link",
			add_unload_trigger: false,
			skin: false,
			init_instance_callback: function(ed) {
				window.editor = ed;
				QUnit.start();
			}
		});
	}
});

test('Fullscreen class on html and body tag', function() {
	var bodyTag = document.body;
	var htmlTag = document.documentElement;

	equal(tinymce.DOM.hasClass(bodyTag, "mce-fullscreen"), false, 'Body tag should not have "mce-fullscreen" class before fullscreen command');
	equal(tinymce.DOM.hasClass(htmlTag, "mce-fullscreen"), false, 'Html tag should not have "mce-fullscreen" class before fullscreen command');

	editor.execCommand('mceFullScreen');

	equal(tinymce.DOM.hasClass(bodyTag, "mce-fullscreen"), true, 'Body tag should have "mce-fullscreen" class after fullscreen command');
	equal(tinymce.DOM.hasClass(htmlTag, "mce-fullscreen"), true, 'Html tag should have "mce-fullscreen" class after fullscreen command');

	editor.execCommand('mceLink', true);

	var windows = editor.windowManager.getWindows();
	var linkWindow = windows[0];

	equal(typeof linkWindow, 'object', 'Link window is an object');

	linkWindow.close();

	equal(windows.length, 0, 'No windows exist');

	equal(tinymce.DOM.hasClass(bodyTag, "mce-fullscreen"), true, 'Body tag should still have "mce-fullscreen" class after window is closed');
	equal(tinymce.DOM.hasClass(htmlTag, "mce-fullscreen"), true, 'Html tag should still have "mce-fullscreen" class after window is closed');
});
<commit_msg>fix fullscreen test bug<commit_after>module("tinymce.plugins.Fullscreen", {
	setupModule: function() {
		QUnit.stop();

		tinymce.init({
			selector: "textarea",
			plugins: "fullscreen link",
			add_unload_trigger: false,
			skin: false,
			init_instance_callback: function(ed) {
				window.editor = ed;
				QUnit.start();
			}
		});
	}
});

test('Fullscreen class on html and body tag', function() {
	var bodyTag = document.body;
	var htmlTag = document.documentElement;

	equal(tinymce.DOM.hasClass(bodyTag, "mce-fullscreen"), false, 'Body tag should not have "mce-fullscreen" class before fullscreen command');
	equal(tinymce.DOM.hasClass(htmlTag, "mce-fullscreen"), false, 'Html tag should not have "mce-fullscreen" class before fullscreen command');

	editor.execCommand('mceFullScreen');

	equal(tinymce.DOM.hasClass(bodyTag, "mce-fullscreen"), true, 'Body tag should have "mce-fullscreen" class after fullscreen command');
	equal(tinymce.DOM.hasClass(htmlTag, "mce-fullscreen"), true, 'Html tag should have "mce-fullscreen" class after fullscreen command');

	editor.execCommand('mceLink', true);

	var windows = editor.windowManager.getWindows();
	var linkWindow = windows[0];

	equal(typeof linkWindow, 'object', 'Link window is an object');

	linkWindow.close();

	equal(windows.length, 0, 'No windows exist');

	equal(tinymce.DOM.hasClass(bodyTag, "mce-fullscreen"), true, 'Body tag should still have "mce-fullscreen" class after window is closed');
	equal(tinymce.DOM.hasClass(htmlTag, "mce-fullscreen"), true, 'Html tag should still have "mce-fullscreen" class after window is closed');

	editor.execCommand('mceFullScreen');
});
<|endoftext|>


<commit_before>"use strict";

var messages = require("../../../messages");
var t        = require("../../../types");

exports.check = t.isPattern;

function DestructuringTransformer(opts) {
  this.blockHoist = opts.blockHoist;
  this.operator   = opts.operator;
  this.nodes      = opts.nodes;
  this.scope      = opts.scope;
  this.file       = opts.file;
  this.kind       = opts.kind;
}

DestructuringTransformer.prototype.buildVariableAssignment = function (id, init) {
  var op = this.operator;
  if (t.isMemberExpression(id)) op = "=";

  var node;

  if (op) {
    node = t.expressionStatement(t.assignmentExpression(op, id, init));
  } else {
    node = t.variableDeclaration(this.kind, [
      t.variableDeclarator(id, init)
    ]);
  }

  node._blockHoist = this.blockHoist;

  return node;
};

DestructuringTransformer.prototype.buildVariableDeclaration = function (id, init) {
  var declar = t.variableDeclaration("var", [
    t.variableDeclarator(id, init)
  ]);
  declar._blockHoist = this.blockHoist;
  return declar;
};

DestructuringTransformer.prototype.push = function (id, init) {
  if (t.isObjectPattern(id)) {
    this.pushObjectPattern(id, init);
  } else if (t.isArrayPattern(id)) {
    this.pushArrayPattern(id, init);
  } else if (t.isAssignmentPattern(id)) {
    this.pushAssignmentPattern(id, init);
  } else {
    this.nodes.push(this.buildVariableAssignment(id, init));
  }
};

DestructuringTransformer.prototype.get = function () {

};

DestructuringTransformer.prototype.pushAssignmentPattern = function (pattern, valueRef) {
  // we need to assign the current value of the assignment to avoid evaluating
  // it more than once

  var tempValueRef = this.scope.generateUidBasedOnNode(valueRef);

  var declar = t.variableDeclaration("var", [
    t.variableDeclarator(tempValueRef, valueRef)
  ]);
  declar._blockHoist = this.blockHoist;
  this.nodes.push(declar);

  //

  this.nodes.push(this.buildVariableAssignment(
    pattern.left,
    t.conditionalExpression(
      t.binaryExpression("===", tempValueRef, t.identifier("undefined")),
      pattern.right,
      tempValueRef
    )
  ));
};

DestructuringTransformer.prototype.pushObjectSpread = function (pattern, objRef, spreadProp, spreadPropIndex) {
  // get all the keys that appear in this object before the current spread

  var keys = [];

  for (var i = 0; i < pattern.properties.length; i++) {
    var prop = pattern.properties[i];

    // we've exceeded the index of the spread property to all properties to the
    // right need to be ignored
    if (i >= spreadPropIndex) break;

    // ignore other spread properties
    if (t.isSpreadProperty(prop)) continue;

    var key = prop.key;
    if (t.isIdentifier(key)) key = t.literal(prop.key.name);
    keys.push(key);
  }

  keys = t.arrayExpression(keys);

  //

  var value = t.callExpression(this.file.addHelper("object-without-properties"), [objRef, keys]);
  this.nodes.push(this.buildVariableAssignment(spreadProp.argument, value));
};

DestructuringTransformer.prototype.pushObjectProperty = function (prop, propRef) {
  if (t.isLiteral(prop.key)) prop.computed = true;

  var pattern = prop.value;
  var objRef  = t.memberExpression(propRef, prop.key, prop.computed);

  if (t.isPattern(pattern)) {
    this.push(pattern, objRef);
  } else {
    this.nodes.push(this.buildVariableAssignment(pattern, objRef));
  }
};

DestructuringTransformer.prototype.pushObjectPattern = function (pattern, objRef) {
  // https://github.com/babel/babel/issues/681

  if (!pattern.properties.length) {
    this.nodes.push(t.expressionStatement(
      t.callExpression(this.file.addHelper("object-destructuring-empty"), [objRef])
    ));
  }

  // if we have more than one properties in this pattern and the objectRef is a
  // member expression then we need to assign it to a temporary variable so it's
  // only evaluated once

  if (pattern.properties.length > 1 && t.isMemberExpression(objRef)) {
    var temp = this.scope.generateUidBasedOnNode(objRef, this.file);
    this.nodes.push(this.buildVariableDeclaration(temp, objRef));
    objRef = temp;
  }

  //

  for (var i = 0; i < pattern.properties.length; i++) {
    var prop = pattern.properties[i];
    if (t.isSpreadProperty(prop)) {
      this.pushObjectSpread(pattern, objRef, prop, i);
    } else {
      this.pushObjectProperty(prop, objRef);
    }
  }
};

var hasRest = function (pattern) {
  for (var i = 0; i < pattern.elements.length; i++) {
    if (t.isRestElement(pattern.elements[i])) {
      return true;
    }
  }
  return false;
};

DestructuringTransformer.prototype.canUnpackArrayPattern = function (pattern, arr) {
  // not an array so there's no way we can deal with this
  if (!t.isArrayExpression(arr)) return false;

  // pattern has less elements than the array and doesn't have a rest so some
  // elements wont be evaluated
  if (pattern.elements.length < arr.elements.length && !hasRest(pattern)) return false;

  // deopt on holes
  for (var i = 0; i < pattern.elements.length; i++) {
    if (!pattern.elements[i]) return false;
  }

  return true;
};

DestructuringTransformer.prototype.pushUnpackedArrayPattern = function (pattern, arr) {
  for (var i = 0; i < pattern.elements.length; i++) {
    var elem = pattern.elements[i];
    if (t.isRestElement(elem)) {
      this.push(elem.argument, t.arrayExpression(arr.elements.slice(i)));
    } else {
      this.push(elem, arr.elements[i]);
    }
  }
};

DestructuringTransformer.prototype.pushArrayPattern = function (pattern, arrayRef) {
  if (!pattern.elements) return;

  // optimise basic array destructuring of an array expression
  //
  // we can't do this to a pattern of unequal size to it's right hand
  // array expression as then there will be values that wont be evaluated
  //
  // eg: var [a, b] = [1, 2];

  if (this.canUnpackArrayPattern(pattern, arrayRef)) {
    return this.pushUnpackedArrayPattern(pattern, arrayRef);
  }

  // if we have a rest then we need all the elements so don't tell
  // `scope.toArray` to only get a certain amount

  var count = !hasRest(pattern) && pattern.elements.length;

  // so we need to ensure that the `arrayRef` is an array, `scope.toArray` will
  // return a locally bound identifier if it's been inferred to be an array,
  // otherwise it'll be a call to a helper that will ensure it's one

  var toArray = this.scope.toArray(arrayRef, count);

  if (t.isIdentifier(toArray)) {
    // we've been given an identifier so it must have been inferred to be an
    // array
    arrayRef = toArray;
  } else {
    arrayRef = this.scope.generateUidBasedOnNode(arrayRef);
    this.nodes.push(this.buildVariableDeclaration(arrayRef, toArray));
    this.scope.assignTypeGeneric(arrayRef.name, "Array");
  }

  //

  for (var i = 0; i < pattern.elements.length; i++) {
    var elem = pattern.elements[i];

    // hole
    if (!elem) continue;

    var elemRef;

    if (t.isRestElement(elem)) {
      elemRef = this.scope.toArray(arrayRef);

      if (i > 0) {
        elemRef = t.callExpression(t.memberExpression(elemRef, t.identifier("slice")), [t.literal(i)]);
      }

      // set the element to the rest element argument since we've dealt with it
      // being a rest already
      elem = elem.argument;
    } else {
      elemRef = t.memberExpression(arrayRef, t.literal(i), true);
    }

    this.push(elem, elemRef);
  }
};

DestructuringTransformer.prototype.init = function (pattern, ref) {
  // trying to destructure a value that we can't evaluate more than once so we
  // need to save it to a variable

  if (!t.isArrayExpression(ref) && !t.isMemberExpression(ref) && !t.isIdentifier(ref)) {
    var key = this.scope.generateUidBasedOnNode(ref);
    this.nodes.push(this.buildVariableDeclaration(key, ref));
    ref = key;
  }

  //

  this.push(pattern, ref);
};

exports.ForInStatement =
exports.ForOfStatement = function (node, parent, scope, file) {
  var left = node.left;

  if (t.isPattern(left)) {
    // for ({ length: k } in { abc: 3 });

    var temp = scope.generateUidIdentifier("ref");

    node.left = t.variableDeclaration("var", [
      t.variableDeclarator(temp)
    ]);

    t.ensureBlock(node);

    node.body.body.unshift(t.variableDeclaration("var", [
      t.variableDeclarator(left, temp)
    ]));

    return;
  }

  if (!t.isVariableDeclaration(left)) return;

  var pattern = left.declarations[0].id;
  if (!t.isPattern(pattern)) return;

  var key = scope.generateUidIdentifier("ref");
  node.left = t.variableDeclaration(left.kind, [
    t.variableDeclarator(key, null)
  ]);

  var nodes = [];

  var destructuring = new DestructuringTransformer({
    kind: left.kind,
    file: file,
    scope: scope,
    nodes: nodes
  });

  destructuring.init(pattern, key);

  t.ensureBlock(node);

  var block = node.body;
  block.body = nodes.concat(block.body);
};

exports.Function = function (node, parent, scope, file) {
  var nodes = [];

  var hasDestructuringTransformer = false;

  node.params = node.params.map(function (pattern, i) {
    if (!t.isPattern(pattern)) return pattern;

    hasDestructuringTransformer = true;
    var ref = scope.generateUidIdentifier("ref");

    var destructuring = new DestructuringTransformer({
      blockHoist: node.params.length - i,
      nodes:      nodes,
      scope:      scope,
      file:       file,
      kind:       "var",
    });
    destructuring.init(pattern, ref);

    return ref;
  });

  if (!hasDestructuringTransformer) return;

  t.ensureBlock(node);

  var block = node.body;
  block.body = nodes.concat(block.body);
};

exports.CatchClause = function (node, parent, scope, file) {
  var pattern = node.param;
  if (!t.isPattern(pattern)) return;

  var ref = scope.generateUidIdentifier("ref");
  node.param = ref;

  var nodes = [];

  var destructuring = new DestructuringTransformer({
    kind: "let",
    file: file,
    scope: scope,
    nodes: nodes
  });
  destructuring.init(pattern, ref);

  node.body.body = nodes.concat(node.body.body);

  return node;
};

exports.ExpressionStatement = function (node, parent, scope, file) {
  var expr = node.expression;
  if (expr.type !== "AssignmentExpression") return;
  if (!t.isPattern(expr.left)) return;
  if (file.isConsequenceExpressionStatement(node)) return;

  var nodes = [];

  var ref = scope.generateUidIdentifier("ref");
  nodes.push(t.variableDeclaration("var", [
    t.variableDeclarator(ref, expr.right)
  ]));

  var destructuring = new DestructuringTransformer({
    operator: expr.operator,
    file: file,
    scope: scope,
    nodes: nodes
  });
  destructuring.init(expr.left, ref);

  return nodes;
};

exports.AssignmentExpression = function (node, parent, scope, file) {
  if (!t.isPattern(node.left)) return;

  var ref = scope.generateUidIdentifier("temp");
  scope.push({
    key: ref.name,
    id: ref
  });

  var nodes = [];
  nodes.push(t.assignmentExpression("=", ref, node.right));

  var destructuring = new DestructuringTransformer({
    operator: node.operator,
    file: file,
    scope: scope,
    nodes: nodes
  });
  destructuring.init(node.left, ref);

  nodes.push(ref);

  return t.toSequenceExpression(nodes, scope);
};

var variableDeclarationhasPattern = function (node) {
  for (var i = 0; i < node.declarations.length; i++) {
    if (t.isPattern(node.declarations[i].id)) {
      return true;
    }
  }
  return false;
};

exports.VariableDeclaration = function (node, parent, scope, file) {
  if (t.isForInStatement(parent) || t.isForOfStatement(parent)) return;
  if (!variableDeclarationhasPattern(node)) return;

  var nodes = [];
  var declar;

  for (var i = 0; i < node.declarations.length; i++) {
    declar = node.declarations[i];

    var patternId = declar.init;
    var pattern   = declar.id;

    var destructuring = new DestructuringTransformer({
      nodes: nodes,
      scope: scope,
      kind:  node.kind,
      file:  file
    });

    if (t.isPattern(pattern) && patternId) {
      destructuring.init(pattern, patternId);

      if (+i !== node.declarations.length - 1) {
        // we aren't the last declarator so let's just make the
        // last transformed node inherit from us
        t.inherits(nodes[nodes.length - 1], declar);
      }
    } else {
      nodes.push(t.inherits(destructuring.buildVariableAssignment(declar.id, declar.init), declar));
    }
  }

  if (!t.isProgram(parent) && !t.isBlockStatement(parent)) {
    // https://github.com/babel/babel/issues/113
    // for (let [x] = [0]; false;) {}

    declar = null;

    for (i = 0; i < nodes.length; i++) {
      node = nodes[i];
      declar = declar || t.variableDeclaration(node.kind, []);

      if (!t.isVariableDeclaration(node) && declar.kind !== node.kind) {
        throw file.errorWithNode(node, messages.get("invalidParentForThisNode"));
      }

      declar.declarations = declar.declarations.concat(node.declarations);
    }

    return declar;
  }

  return nodes;
};
<commit_msg>don't unpack array when the pattern contains more elements than the corresponding array expression<commit_after>"use strict";

var messages = require("../../../messages");
var t        = require("../../../types");

exports.check = t.isPattern;

function DestructuringTransformer(opts) {
  this.blockHoist = opts.blockHoist;
  this.operator   = opts.operator;
  this.nodes      = opts.nodes;
  this.scope      = opts.scope;
  this.file       = opts.file;
  this.kind       = opts.kind;
}

DestructuringTransformer.prototype.buildVariableAssignment = function (id, init) {
  var op = this.operator;
  if (t.isMemberExpression(id)) op = "=";

  var node;

  if (op) {
    node = t.expressionStatement(t.assignmentExpression(op, id, init));
  } else {
    node = t.variableDeclaration(this.kind, [
      t.variableDeclarator(id, init)
    ]);
  }

  node._blockHoist = this.blockHoist;

  return node;
};

DestructuringTransformer.prototype.buildVariableDeclaration = function (id, init) {
  var declar = t.variableDeclaration("var", [
    t.variableDeclarator(id, init)
  ]);
  declar._blockHoist = this.blockHoist;
  return declar;
};

DestructuringTransformer.prototype.push = function (id, init) {
  if (t.isObjectPattern(id)) {
    this.pushObjectPattern(id, init);
  } else if (t.isArrayPattern(id)) {
    this.pushArrayPattern(id, init);
  } else if (t.isAssignmentPattern(id)) {
    this.pushAssignmentPattern(id, init);
  } else {
    this.nodes.push(this.buildVariableAssignment(id, init));
  }
};

DestructuringTransformer.prototype.get = function () {

};

DestructuringTransformer.prototype.pushAssignmentPattern = function (pattern, valueRef) {
  // we need to assign the current value of the assignment to avoid evaluating
  // it more than once

  var tempValueRef = this.scope.generateUidBasedOnNode(valueRef);

  var declar = t.variableDeclaration("var", [
    t.variableDeclarator(tempValueRef, valueRef)
  ]);
  declar._blockHoist = this.blockHoist;
  this.nodes.push(declar);

  //

  this.nodes.push(this.buildVariableAssignment(
    pattern.left,
    t.conditionalExpression(
      t.binaryExpression("===", tempValueRef, t.identifier("undefined")),
      pattern.right,
      tempValueRef
    )
  ));
};

DestructuringTransformer.prototype.pushObjectSpread = function (pattern, objRef, spreadProp, spreadPropIndex) {
  // get all the keys that appear in this object before the current spread

  var keys = [];

  for (var i = 0; i < pattern.properties.length; i++) {
    var prop = pattern.properties[i];

    // we've exceeded the index of the spread property to all properties to the
    // right need to be ignored
    if (i >= spreadPropIndex) break;

    // ignore other spread properties
    if (t.isSpreadProperty(prop)) continue;

    var key = prop.key;
    if (t.isIdentifier(key)) key = t.literal(prop.key.name);
    keys.push(key);
  }

  keys = t.arrayExpression(keys);

  //

  var value = t.callExpression(this.file.addHelper("object-without-properties"), [objRef, keys]);
  this.nodes.push(this.buildVariableAssignment(spreadProp.argument, value));
};

DestructuringTransformer.prototype.pushObjectProperty = function (prop, propRef) {
  if (t.isLiteral(prop.key)) prop.computed = true;

  var pattern = prop.value;
  var objRef  = t.memberExpression(propRef, prop.key, prop.computed);

  if (t.isPattern(pattern)) {
    this.push(pattern, objRef);
  } else {
    this.nodes.push(this.buildVariableAssignment(pattern, objRef));
  }
};

DestructuringTransformer.prototype.pushObjectPattern = function (pattern, objRef) {
  // https://github.com/babel/babel/issues/681

  if (!pattern.properties.length) {
    this.nodes.push(t.expressionStatement(
      t.callExpression(this.file.addHelper("object-destructuring-empty"), [objRef])
    ));
  }

  // if we have more than one properties in this pattern and the objectRef is a
  // member expression then we need to assign it to a temporary variable so it's
  // only evaluated once

  if (pattern.properties.length > 1 && t.isMemberExpression(objRef)) {
    var temp = this.scope.generateUidBasedOnNode(objRef, this.file);
    this.nodes.push(this.buildVariableDeclaration(temp, objRef));
    objRef = temp;
  }

  //

  for (var i = 0; i < pattern.properties.length; i++) {
    var prop = pattern.properties[i];
    if (t.isSpreadProperty(prop)) {
      this.pushObjectSpread(pattern, objRef, prop, i);
    } else {
      this.pushObjectProperty(prop, objRef);
    }
  }
};

var hasRest = function (pattern) {
  for (var i = 0; i < pattern.elements.length; i++) {
    if (t.isRestElement(pattern.elements[i])) {
      return true;
    }
  }
  return false;
};

DestructuringTransformer.prototype.canUnpackArrayPattern = function (pattern, arr) {
  // not an array so there's no way we can deal with this
  if (!t.isArrayExpression(arr)) return false;

  // pattern has less elements than the array and doesn't have a rest so some
  // elements wont be evaluated
  if (pattern.elements.length > arr.elements.length) return;
  if (pattern.elements.length < arr.elements.length && !hasRest(pattern)) return false;

  // deopt on holes
  for (var i = 0; i < pattern.elements.length; i++) {
    if (!pattern.elements[i]) return false;
  }

  return true;
};

DestructuringTransformer.prototype.pushUnpackedArrayPattern = function (pattern, arr) {
  for (var i = 0; i < pattern.elements.length; i++) {
    var elem = pattern.elements[i];
    if (t.isRestElement(elem)) {
      this.push(elem.argument, t.arrayExpression(arr.elements.slice(i)));
    } else {
      this.push(elem, arr.elements[i]);
    }
  }
};

DestructuringTransformer.prototype.pushArrayPattern = function (pattern, arrayRef) {
  if (!pattern.elements) return;

  // optimise basic array destructuring of an array expression
  //
  // we can't do this to a pattern of unequal size to it's right hand
  // array expression as then there will be values that wont be evaluated
  //
  // eg: var [a, b] = [1, 2];

  if (this.canUnpackArrayPattern(pattern, arrayRef)) {
    return this.pushUnpackedArrayPattern(pattern, arrayRef);
  }

  // if we have a rest then we need all the elements so don't tell
  // `scope.toArray` to only get a certain amount

  var count = !hasRest(pattern) && pattern.elements.length;

  // so we need to ensure that the `arrayRef` is an array, `scope.toArray` will
  // return a locally bound identifier if it's been inferred to be an array,
  // otherwise it'll be a call to a helper that will ensure it's one

  var toArray = this.scope.toArray(arrayRef, count);

  if (t.isIdentifier(toArray)) {
    // we've been given an identifier so it must have been inferred to be an
    // array
    arrayRef = toArray;
  } else {
    arrayRef = this.scope.generateUidBasedOnNode(arrayRef);
    this.nodes.push(this.buildVariableDeclaration(arrayRef, toArray));
    this.scope.assignTypeGeneric(arrayRef.name, "Array");
  }

  //

  for (var i = 0; i < pattern.elements.length; i++) {
    var elem = pattern.elements[i];

    // hole
    if (!elem) continue;

    var elemRef;

    if (t.isRestElement(elem)) {
      elemRef = this.scope.toArray(arrayRef);

      if (i > 0) {
        elemRef = t.callExpression(t.memberExpression(elemRef, t.identifier("slice")), [t.literal(i)]);
      }

      // set the element to the rest element argument since we've dealt with it
      // being a rest already
      elem = elem.argument;
    } else {
      elemRef = t.memberExpression(arrayRef, t.literal(i), true);
    }

    this.push(elem, elemRef);
  }
};

DestructuringTransformer.prototype.init = function (pattern, ref) {
  // trying to destructure a value that we can't evaluate more than once so we
  // need to save it to a variable

  if (!t.isArrayExpression(ref) && !t.isMemberExpression(ref) && !t.isIdentifier(ref)) {
    var key = this.scope.generateUidBasedOnNode(ref);
    this.nodes.push(this.buildVariableDeclaration(key, ref));
    ref = key;
  }

  //

  this.push(pattern, ref);
};

exports.ForInStatement =
exports.ForOfStatement = function (node, parent, scope, file) {
  var left = node.left;

  if (t.isPattern(left)) {
    // for ({ length: k } in { abc: 3 });

    var temp = scope.generateUidIdentifier("ref");

    node.left = t.variableDeclaration("var", [
      t.variableDeclarator(temp)
    ]);

    t.ensureBlock(node);

    node.body.body.unshift(t.variableDeclaration("var", [
      t.variableDeclarator(left, temp)
    ]));

    return;
  }

  if (!t.isVariableDeclaration(left)) return;

  var pattern = left.declarations[0].id;
  if (!t.isPattern(pattern)) return;

  var key = scope.generateUidIdentifier("ref");
  node.left = t.variableDeclaration(left.kind, [
    t.variableDeclarator(key, null)
  ]);

  var nodes = [];

  var destructuring = new DestructuringTransformer({
    kind: left.kind,
    file: file,
    scope: scope,
    nodes: nodes
  });

  destructuring.init(pattern, key);

  t.ensureBlock(node);

  var block = node.body;
  block.body = nodes.concat(block.body);
};

exports.Function = function (node, parent, scope, file) {
  var nodes = [];

  var hasDestructuringTransformer = false;

  node.params = node.params.map(function (pattern, i) {
    if (!t.isPattern(pattern)) return pattern;

    hasDestructuringTransformer = true;
    var ref = scope.generateUidIdentifier("ref");

    var destructuring = new DestructuringTransformer({
      blockHoist: node.params.length - i,
      nodes:      nodes,
      scope:      scope,
      file:       file,
      kind:       "var",
    });
    destructuring.init(pattern, ref);

    return ref;
  });

  if (!hasDestructuringTransformer) return;

  t.ensureBlock(node);

  var block = node.body;
  block.body = nodes.concat(block.body);
};

exports.CatchClause = function (node, parent, scope, file) {
  var pattern = node.param;
  if (!t.isPattern(pattern)) return;

  var ref = scope.generateUidIdentifier("ref");
  node.param = ref;

  var nodes = [];

  var destructuring = new DestructuringTransformer({
    kind: "let",
    file: file,
    scope: scope,
    nodes: nodes
  });
  destructuring.init(pattern, ref);

  node.body.body = nodes.concat(node.body.body);

  return node;
};

exports.ExpressionStatement = function (node, parent, scope, file) {
  var expr = node.expression;
  if (expr.type !== "AssignmentExpression") return;
  if (!t.isPattern(expr.left)) return;
  if (file.isConsequenceExpressionStatement(node)) return;

  var nodes = [];

  var ref = scope.generateUidIdentifier("ref");
  nodes.push(t.variableDeclaration("var", [
    t.variableDeclarator(ref, expr.right)
  ]));

  var destructuring = new DestructuringTransformer({
    operator: expr.operator,
    file: file,
    scope: scope,
    nodes: nodes
  });
  destructuring.init(expr.left, ref);

  return nodes;
};

exports.AssignmentExpression = function (node, parent, scope, file) {
  if (!t.isPattern(node.left)) return;

  var ref = scope.generateUidIdentifier("temp");
  scope.push({
    key: ref.name,
    id: ref
  });

  var nodes = [];
  nodes.push(t.assignmentExpression("=", ref, node.right));

  var destructuring = new DestructuringTransformer({
    operator: node.operator,
    file: file,
    scope: scope,
    nodes: nodes
  });
  destructuring.init(node.left, ref);

  nodes.push(ref);

  return t.toSequenceExpression(nodes, scope);
};

var variableDeclarationHasPattern = function (node) {
  for (var i = 0; i < node.declarations.length; i++) {
    if (t.isPattern(node.declarations[i].id)) {
      return true;
    }
  }
  return false;
};

exports.VariableDeclaration = function (node, parent, scope, file) {
  if (t.isForInStatement(parent) || t.isForOfStatement(parent)) return;
  if (!variableDeclarationHasPattern(node)) return;

  var nodes = [];
  var declar;

  for (var i = 0; i < node.declarations.length; i++) {
    declar = node.declarations[i];

    var patternId = declar.init;
    var pattern   = declar.id;

    var destructuring = new DestructuringTransformer({
      nodes: nodes,
      scope: scope,
      kind:  node.kind,
      file:  file
    });

    if (t.isPattern(pattern) && patternId) {
      destructuring.init(pattern, patternId);

      if (+i !== node.declarations.length - 1) {
        // we aren't the last declarator so let's just make the
        // last transformed node inherit from us
        t.inherits(nodes[nodes.length - 1], declar);
      }
    } else {
      nodes.push(t.inherits(destructuring.buildVariableAssignment(declar.id, declar.init), declar));
    }
  }

  if (!t.isProgram(parent) && !t.isBlockStatement(parent)) {
    // https://github.com/babel/babel/issues/113
    // for (let [x] = [0]; false;) {}

    declar = null;

    for (i = 0; i < nodes.length; i++) {
      node = nodes[i];
      declar = declar || t.variableDeclaration(node.kind, []);

      if (!t.isVariableDeclaration(node) && declar.kind !== node.kind) {
        throw file.errorWithNode(node, messages.get("invalidParentForThisNode"));
      }

      declar.declarations = declar.declarations.concat(node.declarations);
    }

    return declar;
  }

  return nodes;
};
<|endoftext|>


<commit_before>define([
	'goo/loaders/handlers/ConfigHandler',
	'goo/util/ObjectUtil',
	'goo/entities/SystemBus',
	'goo/renderer/shaders/ShaderBuilder',
	'goo/util/Snow', // TODO Should move!
	'goo/util/rsvp'
], function(
	ConfigHandler,
	_,
	SystemBus,
	ShaderBuilder,
	Snow,
	RSVP
) {
	'use strict';

	var defaults = {
		backgroundColor: [0.3,0.3,0.3,1],
		globalAmbient: [0,0,0,1],
		fog: {
			enabled: false,
			color: [1,1,1],
			near: 10,
			far: 1000
		}
	};
	var soundDefaults = {
		volume: 1,
		reverb: 0,
		dopplerFactor: 1,
		rolloffFactor: 0.4,
		maxDistance: 100
	};

	/**
	 * @class Handling environments
	 * @param {World} world
	 * @param {Function} getConfig
	 * @param {Function} updateObject
	 * @private
	 */
	function EnvironmentHandler() {
		ConfigHandler.apply(this, arguments);
		this._cache = {};
	}

	EnvironmentHandler.prototype = Object.create(ConfigHandler.prototype);
	EnvironmentHandler.prototype.constructor = EnvironmentHandler;
	ConfigHandler._registerClass('environment', EnvironmentHandler);

	EnvironmentHandler.prototype._prepare = function(config) {
		_.defaults(config, defaults);
	};

	EnvironmentHandler.prototype._create = function() {
		return {
			weatherState: {}
		};
	};

	EnvironmentHandler.prototype._remove = function(ref) {
		var object = this._objects[ref];
		delete this._objects[ref];

		// Remove weather
		for (var key in object.weatherState) {
			EnvironmentHandler.weatherHandlers[key].remove(object.weatherState);
		}

		// Reset environment
		SystemBus.emit('goo.setClearColor', defaults.backgroundColor);
		ShaderBuilder.GLOBAL_AMBIENT = defaults.globalAmbient;
		ShaderBuilder.USE_FOG = defaults.fog.enabled;
		ShaderBuilder.FOG_COLOR = defaults.fog.color.slice(0,3);
		ShaderBuilder.FOG_SETTINGS = [defaults.fog.near, defaults.fog.far];

		// Reset Sound
		var soundSystem = this.world.getSystem('SoundSystem');
		if (soundSystem) {
			soundSystem.updateConfig(soundDefaults);
			soundSystem.setReverb(null);
		}
	};

	/**
	 * Adds/updates/removes an environment
	 * @param {string} ref
	 * @param {object|null} config
	 * @param {object} options
	 * @returns {RSVP.Promise} Resolves with the updated environment or null if removed
	 */
	EnvironmentHandler.prototype._update = function(ref, config, options) {
		var that = this;
		return ConfigHandler.prototype._update.call(this, ref, config, options).then(function(object) {
			if (!object) { return; }
			object.backgroundColor = config.backgroundColor.slice(0);
			object.globalAmbient = config.globalAmbient.slice(0,3);

			object.fog = _.deepClone(config.fog);

			// Background color
			SystemBus.emit('goo.setClearColor', object.backgroundColor);

			// Fog and ambient
			ShaderBuilder.GLOBAL_AMBIENT = object.globalAmbient;
			ShaderBuilder.USE_FOG = object.fog.enabled;
			ShaderBuilder.FOG_COLOR = object.fog.color.slice(0,3);
			ShaderBuilder.FOG_SETTINGS = [object.fog.near, config.fog.far];

			// Weather
			for (var key in config.weather) {
				var handler = EnvironmentHandler.weatherHandlers[key];
				if (handler) {
					handler.update.call(that, config.weather[key], object.weatherState);
				}
			}

			var promises = [];
			// Skybox
			if(config.skyboxRef && config.skyboxRef !== that._cache.skyboxRef) {
				var p = that._load(config.skyboxRef, options).then(function(/*skybox*/) {
					that._cache.skyboxRef = config.skyboxRef;
				});
				promises.push(p);
			}

			// Sound
			var soundSystem = that.world.getSystem('SoundSystem');
			if (config.sound && soundSystem) {
				soundSystem.updateConfig(config.sound);
				if (config.sound.reverbRef) {
					var p = that._load(config.sound.reverbRef).then(function(sound) {
						soundSystem.setReverb(sound._buffer);
					});
					promises.push(p);
				} else {
					soundSystem.setReverb(null);
				}
			}
			return RSVP.all(promises).then(function() { return object; });
		});
	};

	EnvironmentHandler.weatherHandlers = {
		snow: {
			update: function(config, weatherState) {
				if (config.enabled) {
					if (weatherState.snow && weatherState.snow.enabled) {
						// adjust snow
						weatherState.snow.snow.setEmissionVelocity(config.velocity);
						weatherState.snow.snow.setReleaseRatePerSecond(config.rate);
						weatherState.snow.snow.setEmissionHeight(config.height);
					} else {
						// add snow
						weatherState.snow = weatherState.snow || {};
						weatherState.snow.enabled = true;
						weatherState.snow.snow = new Snow(this.world.gooRunner);
					}
				} else {
					if (weatherState.snow && weatherState.snow.enabled) {
						// remove snow
						weatherState.snow.snow.remove();
						weatherState.snow.enabled = false;
						delete weatherState.snow.snow;
					}
				}
			},
			remove: function(weatherState) {
				if (weatherState.snow.snow) {
					weatherState.snow.snow.remove();
					weatherState.snow.enabled = false;
					delete weatherState.snow.snow;
				}
			}
		}
	};

	return EnvironmentHandler;
});<commit_msg>Post review bugfix on #941<commit_after>define([
	'goo/loaders/handlers/ConfigHandler',
	'goo/util/ObjectUtil',
	'goo/entities/SystemBus',
	'goo/renderer/shaders/ShaderBuilder',
	'goo/util/Snow', // TODO Should move!
	'goo/util/rsvp'
], function(
	ConfigHandler,
	_,
	SystemBus,
	ShaderBuilder,
	Snow,
	RSVP
) {
	'use strict';

	var defaults = {
		backgroundColor: [0.3,0.3,0.3,1],
		globalAmbient: [0,0,0,1],
		fog: {
			enabled: false,
			color: [1,1,1],
			near: 10,
			far: 1000
		}
	};
	var soundDefaults = {
		volume: 1,
		reverb: 0,
		dopplerFactor: 1,
		rolloffFactor: 0.4,
		maxDistance: 100
	};

	/**
	 * @class Handling environments
	 * @param {World} world
	 * @param {Function} getConfig
	 * @param {Function} updateObject
	 * @private
	 */
	function EnvironmentHandler() {
		ConfigHandler.apply(this, arguments);
	}

	EnvironmentHandler.prototype = Object.create(ConfigHandler.prototype);
	EnvironmentHandler.prototype.constructor = EnvironmentHandler;
	ConfigHandler._registerClass('environment', EnvironmentHandler);

	EnvironmentHandler.prototype._prepare = function(config) {
		_.defaults(config, defaults);
	};

	EnvironmentHandler.prototype._create = function() {
		return {
			weatherState: {}
		};
	};

	EnvironmentHandler.prototype._remove = function(ref) {
		var object = this._objects[ref];
		delete this._objects[ref];

		// Remove weather
		for (var key in object.weatherState) {
			EnvironmentHandler.weatherHandlers[key].remove(object.weatherState);
		}

		// Reset environment
		SystemBus.emit('goo.setClearColor', defaults.backgroundColor);
		ShaderBuilder.GLOBAL_AMBIENT = defaults.globalAmbient;
		ShaderBuilder.USE_FOG = defaults.fog.enabled;
		ShaderBuilder.FOG_COLOR = defaults.fog.color.slice(0,3);
		ShaderBuilder.FOG_SETTINGS = [defaults.fog.near, defaults.fog.far];

		// Reset Sound
		var soundSystem = this.world.getSystem('SoundSystem');
		if (soundSystem) {
			soundSystem.updateConfig(soundDefaults);
			soundSystem.setReverb(null);
		}
	};

	/**
	 * Adds/updates/removes an environment
	 * @param {string} ref
	 * @param {object|null} config
	 * @param {object} options
	 * @returns {RSVP.Promise} Resolves with the updated environment or null if removed
	 */
	EnvironmentHandler.prototype._update = function(ref, config, options) {
		var that = this;
		return ConfigHandler.prototype._update.call(this, ref, config, options).then(function(object) {
			if (!object) { return; }
			object.backgroundColor = config.backgroundColor.slice(0);
			object.globalAmbient = config.globalAmbient.slice(0,3);

			object.fog = _.deepClone(config.fog);

			// Background color
			SystemBus.emit('goo.setClearColor', object.backgroundColor);

			// Fog and ambient
			ShaderBuilder.GLOBAL_AMBIENT = object.globalAmbient;
			ShaderBuilder.USE_FOG = object.fog.enabled;
			ShaderBuilder.FOG_COLOR = object.fog.color.slice(0,3);
			ShaderBuilder.FOG_SETTINGS = [object.fog.near, config.fog.far];

			// Weather
			for (var key in config.weather) {
				var handler = EnvironmentHandler.weatherHandlers[key];
				if (handler) {
					handler.update.call(that, config.weather[key], object.weatherState);
				}
			}

			var promises = [];
			// Skybox
			if(config.skyboxRef) {
				var p = that._load(config.skyboxRef, options);
				promises.push(p);
			}

			// Sound
			var soundSystem = that.world.getSystem('SoundSystem');
			if (config.sound && soundSystem) {
				soundSystem.updateConfig(config.sound);
				if (config.sound.reverbRef) {
					var p = that._load(config.sound.reverbRef).then(function(sound) {
						soundSystem.setReverb(sound._buffer);
					});
					promises.push(p);
				} else {
					soundSystem.setReverb(null);
				}
			}
			return RSVP.all(promises).then(function() { return object; });
		});
	};

	EnvironmentHandler.weatherHandlers = {
		snow: {
			update: function(config, weatherState) {
				if (config.enabled) {
					if (weatherState.snow && weatherState.snow.enabled) {
						// adjust snow
						weatherState.snow.snow.setEmissionVelocity(config.velocity);
						weatherState.snow.snow.setReleaseRatePerSecond(config.rate);
						weatherState.snow.snow.setEmissionHeight(config.height);
					} else {
						// add snow
						weatherState.snow = weatherState.snow || {};
						weatherState.snow.enabled = true;
						weatherState.snow.snow = new Snow(this.world.gooRunner);
					}
				} else {
					if (weatherState.snow && weatherState.snow.enabled) {
						// remove snow
						weatherState.snow.snow.remove();
						weatherState.snow.enabled = false;
						delete weatherState.snow.snow;
					}
				}
			},
			remove: function(weatherState) {
				if (weatherState.snow.snow) {
					weatherState.snow.snow.remove();
					weatherState.snow.enabled = false;
					delete weatherState.snow.snow;
				}
			}
		}
	};

	return EnvironmentHandler;
});<|endoftext|>


<commit_before>// DecentCMS (c) 2014 Bertrand Le Roy, under MIT. See LICENSE.txt for licensing details.
'use strict';

/**
 * @description
 * The ContentRenderer is responsible for the content item rendering lifecycle.
 */
function ContentRenderer(scope) {
  this.scope = scope;
  scope.shapes = scope.shapes || [];
}
ContentRenderer.feature = 'content';
ContentRenderer.service = 'renderer';
ContentRenderer.scope = 'request';
ContentRenderer.isScopeSingleton = true;

/**
 * @description
 * Adds a shape or a content item to the list of shapes for the request.
 * @param options
 * @param {string} [options.id]
 * The id of an item to fetch and add as a shape.
 * @param {object} [options.shape]
 * A shape to add to the list of shapes to render.
 * @param {string} [options.displayType]
 * The display type to use when rendering the shape.
 */
ContentRenderer.prototype.promiseToRender = function promiseToRender(options) {
  var scope = this.scope;
  if (!scope.shapes) {
    scope.shapes = [];
  }
  if (options.id) {
    scope.require('storage-manager').promiseToGet(options.id);
    if (options.displayType === 'main') {
      scope.itemId = options.id;
    }
    scope.shapes.push({
      meta: {
        type: 'shape-item-promise',
        place: options.place
      },
      temp: {
        displayType: options.displayType || 'details'
      },
      id: options.id
    });
  }
  else if (options.shape) {
    scope.shapes.push(options.shape);
  }
};

/**
 * @description
 * Builds the rendered page from the list of shapes that was prepared
 * so far. This method defines the rendering lifecycle, by emitting
 * events and service calls:
 * * 'placement-strategy'.placeShapes({shape, shapes, renderStream}, done)
 * * 'shape-handler'.handle({shape, shapes, renderStream}, done)
 * * decent.core.register-meta
 * * decent.core.register-style
 * * decent.core.register-script
 * * 'rendering-strategy'.render({shape, shapes, renderStream}, done)
 * @param context
 * @param {object}          [context.scope] The scope, which is normally the current request.
 * @param {IncomingMessage} [context.request] The request.
 * @param {ServerResponse}  [context.response] The response.
 * @param {Function} pageBuilt The function to call when the page has been rendered.
 */
ContentRenderer.prototype.render = function render(context, pageBuilt) {
  var scope = this.scope;
  if (scope.handled) {
    pageBuilt();
    return;
  }
  var log = scope.require('log');
  var response = context.response;
  var shapes = scope.shapes;
  var layout = scope.layout = {
    meta: {type: 'layout'},
    site: scope.require('shell')
  };
  var renderStream = scope.require('render-stream');
  // TODO: add filters, that are just additional pipes before res.
  renderStream
    .on('data', function(data) {
      response.write(data);
    });
  if (renderStream.onError) {
    renderStream.onError(function (err) {
      pageBuilt(err);
      return;
    });
  }
  if (scope.itemId) {
    var item = scope.require('storage-manager').getAvailableItem(scope.itemId);
    if (!item) {
      response.statusCode = 404;
      renderStream.title = scope.title = layout.title =
        scope.require('localization')('404 - Not Found');
      scope.require('shape')
        .place(layout, 'main', {
          meta: {type: 'not-found'},
          notFoundId: scope.itemId
        }, 'before');
    }
  }
  var lifecycle = scope.lifecycle(
    // Build the shape tree through placement strategies
    'placement-strategy', 'placeShapes',
    // Let handlers manipulate items and shapes
    // Handlers are responsible for drilling into the tree according to
    // their knowledge of the shapes they are handling.
    'shape-handler', 'handle',
    // Call for meta, script, and style sheet registration
    function registerMetaStyleAndScript(options, done) {
      scope.emit(ContentRenderer.registerMetaEvent, {renderStream: renderStream});
      scope.emit(ContentRenderer.registerStyleEvent, {renderStream: renderStream});
      scope.emit(ContentRenderer.registerScriptEvent, {renderStream: renderStream});
      done();
    },
    // Render
    'rendering-strategy', 'render'
  );
  lifecycle({
    scope: scope,
    shape: layout,
    shapes: shapes,
    renderStream: renderStream
  }, function contentRenderingDone(err) {
    if (err) {
      log.error('Error during content rendering', err);
      pageBuilt(err);
      return;
    }
    // Tear down
    renderStream.end();
    pageBuilt();
  });
};

/**
 * Calls for meta tag registering.
 */
ContentRenderer.registerMetaEvent = 'decent.core.register-meta';
ContentRenderer.registerMetaEvent_payload = {
  /**
   * The render stream that handles the html to render.
   */
  renderStream: 'RenderStream'
};

/**
 * Calls for style sheet registering.
 */
ContentRenderer.registerStyleEvent = 'decent.core.register-style';
ContentRenderer.registerStyleEvent_payload = {
  /**
   * The render stream that handles the html to render.
   */
  renderStream: 'RenderStream'
};

/**
 * Calls for script registering.
 */
ContentRenderer.registerScriptEvent = 'decent.core.register-script';
ContentRenderer.registerScriptEvent_payload = {
  /**
   * The render stream that handles the html to render.
   */
  renderStream: 'RenderStream'
};

module.exports = ContentRenderer;<commit_msg>Add the main item to layout.temp.<commit_after>// DecentCMS (c) 2014 Bertrand Le Roy, under MIT. See LICENSE.txt for licensing details.
'use strict';

/**
 * @description
 * The ContentRenderer is responsible for the content item rendering lifecycle.
 */
function ContentRenderer(scope) {
  this.scope = scope;
  scope.shapes = scope.shapes || [];
}
ContentRenderer.feature = 'content';
ContentRenderer.service = 'renderer';
ContentRenderer.scope = 'request';
ContentRenderer.isScopeSingleton = true;

/**
 * @description
 * Adds a shape or a content item to the list of shapes for the request.
 * @param options
 * @param {string} [options.id]
 * The id of an item to fetch and add as a shape.
 * @param {object} [options.shape]
 * A shape to add to the list of shapes to render.
 * @param {string} [options.displayType]
 * The display type to use when rendering the shape.
 */
ContentRenderer.prototype.promiseToRender = function promiseToRender(options) {
  var scope = this.scope;
  if (!scope.shapes) {
    scope.shapes = [];
  }
  if (options.id) {
    scope.require('storage-manager').promiseToGet(options.id);
    if (options.displayType === 'main') {
      scope.itemId = options.id;
    }
    scope.shapes.push({
      meta: {
        type: 'shape-item-promise',
        place: options.place
      },
      temp: {
        displayType: options.displayType || 'details'
      },
      id: options.id
    });
  }
  else if (options.shape) {
    scope.shapes.push(options.shape);
  }
};

/**
 * @description
 * Builds the rendered page from the list of shapes that was prepared
 * so far. This method defines the rendering lifecycle, by emitting
 * events and service calls:
 * * 'placement-strategy'.placeShapes({shape, shapes, renderStream}, done)
 * * 'shape-handler'.handle({shape, shapes, renderStream}, done)
 * * decent.core.register-meta
 * * decent.core.register-style
 * * decent.core.register-script
 * * 'rendering-strategy'.render({shape, shapes, renderStream}, done)
 * @param context
 * @param {object}          [context.scope] The scope, which is normally the current request.
 * @param {IncomingMessage} [context.request] The request.
 * @param {ServerResponse}  [context.response] The response.
 * @param {Function} pageBuilt The function to call when the page has been rendered.
 */
ContentRenderer.prototype.render = function render(context, pageBuilt) {
  var scope = this.scope;
  if (scope.handled) {
    pageBuilt();
    return;
  }
  var log = scope.require('log');
  var response = context.response;
  var shapes = scope.shapes;
  var layout = scope.layout = {
    meta: {type: 'layout'},
    site: scope.require('shell'),
    temp: {}
  };
  var renderStream = scope.require('render-stream');
  // TODO: add filters, that are just additional pipes before res.
  renderStream
    .on('data', function(data) {
      response.write(data);
    });
  if (renderStream.onError) {
    renderStream.onError(function (err) {
      pageBuilt(err);
      return;
    });
  }
  if (scope.itemId) {
    var item = scope.require('storage-manager').getAvailableItem(scope.itemId);
    if (item) {
      layout.temp.item = item;
    }
    else {
      response.statusCode = 404;
      renderStream.title = scope.title = layout.title =
        scope.require('localization')('404 - Not Found');
      scope.require('shape')
        .place(layout, 'main', {
          meta: {type: 'not-found'},
          notFoundId: scope.itemId
        }, 'before');
    }
  }
  var lifecycle = scope.lifecycle(
    // Build the shape tree through placement strategies
    'placement-strategy', 'placeShapes',
    // Let handlers manipulate items and shapes
    // Handlers are responsible for drilling into the tree according to
    // their knowledge of the shapes they are handling.
    'shape-handler', 'handle',
    // Call for meta, script, and style sheet registration
    function registerMetaStyleAndScript(options, done) {
      scope.emit(ContentRenderer.registerMetaEvent, {renderStream: renderStream});
      scope.emit(ContentRenderer.registerStyleEvent, {renderStream: renderStream});
      scope.emit(ContentRenderer.registerScriptEvent, {renderStream: renderStream});
      done();
    },
    // Render
    'rendering-strategy', 'render'
  );
  lifecycle({
    scope: scope,
    shape: layout,
    shapes: shapes,
    renderStream: renderStream
  }, function contentRenderingDone(err) {
    if (err) {
      log.error('Error during content rendering', err);
      pageBuilt(err);
      return;
    }
    // Tear down
    renderStream.end();
    pageBuilt();
  });
};

/**
 * Calls for meta tag registering.
 */
ContentRenderer.registerMetaEvent = 'decent.core.register-meta';
ContentRenderer.registerMetaEvent_payload = {
  /**
   * The render stream that handles the html to render.
   */
  renderStream: 'RenderStream'
};

/**
 * Calls for style sheet registering.
 */
ContentRenderer.registerStyleEvent = 'decent.core.register-style';
ContentRenderer.registerStyleEvent_payload = {
  /**
   * The render stream that handles the html to render.
   */
  renderStream: 'RenderStream'
};

/**
 * Calls for script registering.
 */
ContentRenderer.registerScriptEvent = 'decent.core.register-script';
ContentRenderer.registerScriptEvent_payload = {
  /**
   * The render stream that handles the html to render.
   */
  renderStream: 'RenderStream'
};

module.exports = ContentRenderer;<|endoftext|>


<commit_before>/**
 *
 * Copyright (c) Chong-U Lim
 * http://github.com/chongdashu
 */
this.chongdashu = this.chongdashu||{};

(function() {
    "use strict";

/**
 * GameState
 * @class GameState
 * @constructor
 **/
var GameState = function(game) {
};
var p = GameState.prototype;

    p.prototypes = null;
    p.dataIndex = 0;

    // @phaser
    p.preload = function() {

    };

    // @phaser
    p.create = function() {
        this.createGroups();
        this.createBackground();
        this.createGround();
    };

    p.createGroups = function() {
        this.backgroundGroup = this.game.add.group();
        this.groundGroup = this.game.add.group();
    };

    p.createBackground = function() {
        this.background = this.backgroundGroup.create(0,0, "background");
        this.background.anchor.set(0.5, 0.5);
    };

    p.createGround = function() {
        var x = 0;
        var y = GLOBAL_GAME_HEIGHT/2 - GLOBAL_TILE_HEIGHT/2;

        var tile = null;
        for (x=0; x < GLOBAL_GAME_WIDTH/GLOBAL_TILE_WIDTH; x++) {
            tile = this.groundGroup.create(-GLOBAL_GAME_WIDTH/2 + GLOBAL_TILE_WIDTH/2 + x*GLOBAL_TILE_WIDTH, y, "tile-brown");
            tile.anchor.set(0.5, 0.5);
        }
    };

    // @phaser
    p.update = function() {

    };

    // render
    p.render = function() {
        pixel.context.drawImage(game.canvas, 0, 0, game.width, game.height, 0, 0, pixel.width, pixel.height);
    };

// Link
// ----
chongdashu.GameState = GameState;

}());

<commit_msg>Add debug height lines<commit_after>/**
 *
 * Copyright (c) Chong-U Lim
 * http://github.com/chongdashu
 */
this.chongdashu = this.chongdashu||{};

(function() {
    "use strict";

/**
 * GameState
 * @class GameState
 * @constructor
 **/
var GameState = function(game) {
};
var p = GameState.prototype;

    p.prototypes = null;
    p.dataIndex = 0;

    // @phaser
    p.preload = function() {

    };

    // @phaser
    p.create = function() {
        this.createGroups();
        this.createBackground();
        this.createGround();
        this.createDebug();
    };

    p.createGroups = function() {
        this.backgroundGroup = this.game.add.group();
        this.groundGroup = this.game.add.group();
    };

    p.createBackground = function() {
        this.background = this.backgroundGroup.create(0,0, "background");
        this.background.anchor.set(0.5, 0.5);
    };

    p.createGround = function() {
        var x = 0;
        var y = GLOBAL_GAME_HEIGHT/2 - GLOBAL_TILE_HEIGHT/2;

        var tile = null;
        for (x=0; x < GLOBAL_GAME_WIDTH/GLOBAL_TILE_WIDTH; x++) {
            tile = this.groundGroup.create(-GLOBAL_GAME_WIDTH/2 + GLOBAL_TILE_WIDTH/2 + x*GLOBAL_TILE_WIDTH, y, "tile-brown");
            tile.anchor.set(0.5, 0.5);
        }
    };

    p.createDebug = function() {
        // Create a bitmap the same size as the stage
        var bitmap = this.game.add.bitmapData(this.game.width, this.game.height);

        // These functions use the canvas context to draw lines using the canvas API
        for(var y = this.game.height-GLOBAL_TILE_HEIGHT; y >= 0; y -= GLOBAL_TILE_HEIGHT) {
            bitmap.context.beginPath();
            bitmap.context.strokeStyle = 'rgba(255, 255, 255, 0.5)';
            bitmap.context.moveTo(0, y);
            bitmap.context.lineTo(this.game.width, y);
            bitmap.context.stroke();
        }

        this.game.add.image(-GLOBAL_GAME_WIDTH/2, -GLOBAL_GAME_HEIGHT/2, bitmap);
    };

    // @phaser
    p.update = function() {

    };

    // render
    p.render = function() {
        pixel.context.drawImage(game.canvas, 0, 0, game.width, game.height, 0, 0, pixel.width, pixel.height);
    };

// Link
// ----
chongdashu.GameState = GameState;

}());

<|endoftext|>