<commit_before>'use strict';

var openHours = ['6am', '7am', '8am', '9am', '10am', '11am', '12pm', '1pm', '2pm', '3pm', '4pm', '5pm', '6pm', '7pm'];
var locationNames = [];
//
//CONSTRUCTOR FUNCTION
//
function CreateNewStore (storeName, minCustHour, maxCustHour, avgCookiesCustomer) {
  //PROPERTIES
  this.storeName = storeName;
  this.minCustHour = minCustHour;
  this.maxCustHour = maxCustHour;
  this.avgCookiesCustomer = avgCookiesCustomer;
  this.randomCustHour = [];
  this.projCookiesPerHour = [];
  this.totalDailyCookies = 0;
  // this.totalHourlyCookies = 0;
  locationNames.push(this);
  // this.renderLists();

  this.calcRandomCustHour();
  this.calcCookiesPerHour();
};

//METHOD to calculate random customers per hour
CreateNewStore.prototype.calcRandomCustHour = function() {
  for (var i = 0; i < openHours.length; i++) {
    this.randomCustHour.push(Math.floor(Math.random() * (this.maxCustHour - this.minCustHour + 1) + this.minCustHour));
  }
};

//METHOD to calculate projected number of cookies each hour AND total daily cookes
CreateNewStore.prototype.calcCookiesPerHour = function() {
  for (var i = 0; i < this.randomCustHour.length; i++) {
    var singleHourCookies = Math.ceil(this.randomCustHour[i] * this.avgCookiesCustomer);
    this.projCookiesPerHour.push(singleHourCookies);
    this.totalDailyCookies += singleHourCookies;
  }
};

// METHOD TO CREATE SALES TABLE DATA CELLS
CreateNewStore.prototype.createSalesDataCells = function () {
  var salesDataTable = document.getElementById('salesDataTable');

  var salesDataRow = document.createElement('tr');
  var salesDataNameCell = document.createElement('td');
  salesDataNameCell.textContent = this.storeName;
  salesDataRow.appendChild(salesDataNameCell);

  for (var i = 0; i < this.projCookiesPerHour.length; i++) {
    var salesDataCell = document.createElement('td');
    salesDataCell.textContent = this.projCookiesPerHour[i];
    salesDataRow.appendChild(salesDataCell);
  }

  var salesDataTotalCell = document.createElement('td');
  salesDataTotalCell.textContent = this.totalDailyCookies;
  salesDataRow.appendChild(salesDataTotalCell);

  salesDataTable.appendChild(salesDataRow);
};

//STAND ALONE FUNCTION FOR HEADER ROW
function makeHeaderRow () {
  var salesDataTable = document.getElementById('salesDataTable');

  var salesDataRow = document.createElement('tr');
  var salesDataEmptyHeader = document.createElement('th');
  salesDataEmptyHeader.textContent = '';
  salesDataRow.appendChild(salesDataEmptyHeader);

  for (var i = 0; i < openHours.length; i++) {
    var salesDataHeader = document.createElement('th');
    salesDataHeader.textContent = openHours[i];
    salesDataRow.appendChild(salesDataHeader);
  }
  salesDataEmptyHeader = document.createElement('th');
  salesDataEmptyHeader.textContent = 'Daily Total';
  salesDataRow.appendChild(salesDataEmptyHeader);

  salesDataTable.appendChild(salesDataRow);
};

// STAND-ALONE FUNCTION FOR FOOTER
function makeFooterRow () {
  var salesDataTable = document.getElementById('salesDataTable');

  var salesFooterRow = document.createElement('tr');
  var salesDataEmptyFooter = document.createElement('td');
  salesDataEmptyFooter.textContent = '';
  salesFooterRow.appendChild(salesDataEmptyFooter);

  for (var i = 0; i < openHours.length; i++) {
    var salesDataFooter = document.createElement('td');
    salesDataFooter.textContent = 'total';
    salesFooterRow.appendChild(salesDataFooter);
  }
  var salesDataFooterTotal = document.createElement('td');
  salesDataFooterTotal.textContent = 'TOTAL';
  salesFooterRow.appendChild(salesDataFooterTotal);
  salesDataTable.appendChild(salesFooterRow);
};

function renderSalesDataCells () {
  for (var i = 0; i < locationNames.length; i++) {
    locationNames[i].createSalesDataCells();
  }
};

new CreateNewStore('First and Pike', 23, 65, 6.3); //eslint-disable-line
new CreateNewStore('Seatac Airport', 3, 24, 1.2);
new CreateNewStore('Seattle Center', 11, 38, 3.7);
new CreateNewStore('Capital Hill', 20, 38, 2.3);
new CreateNewStore('Alki', 2, 16, 4.6);

var formSubmit = document.getElementById('salesProjectionForm');
var formStoreName = document.getElementById('storeLocation');
var formMinCustHour = document.getElementById('minCustHour');
var formMaxCustHour = document.getElementById('maxCustHour');
var formAvgCookies = document.getElementById('avgCookiesCustomer');

function AddNewStore(event) {

  event.preventDefault();

  var cookieStore = event.target.storeLocation.value;
  var minCust = event.target.minCustHour.value;
  var maxCust = event.target.maxCustHour.value;
  var avgCookies = event.target.avgCookiesCustomer.value;

  if (!cookieStore || !minCust || !maxCust || !avgCookies) {
    return alert('Must enter data in all fields');
  }

  var newStore = new CreateNewStore(cookieStore, minCust, maxCust, avgCookies);
  console.log(newStore);
  locationNames.push(newStore);

};

makeHeaderRow();
renderSalesDataCells();
makeFooterRow();

formSubmit.addEventListener('submit', AddNewStore);
<commit_msg>Adding new store, new store row is printing to a table, but still not all correct but making progress<commit_after>'use strict';

var openHours = ['6am', '7am', '8am', '9am', '10am', '11am', '12pm', '1pm', '2pm', '3pm', '4pm', '5pm', '6pm', '7pm'];
var locationNames = [];
//
//CONSTRUCTOR FUNCTION
//
function CreateNewStore (storeName, minCustHour, maxCustHour, avgCookiesCustomer) {
  //PROPERTIES
  this.storeName = storeName;
  this.minCustHour = minCustHour;
  this.maxCustHour = maxCustHour;
  this.avgCookiesCustomer = avgCookiesCustomer;
  this.randomCustHour = [];
  this.projCookiesPerHour = [];
  this.totalDailyCookies = 0;
  // this.totalHourlyCookies = 0;
  locationNames.push(this);
  // this.renderLists();

  this.calcRandomCustHour();
  this.calcCookiesPerHour();
};

//METHOD to calculate random customers per hour
CreateNewStore.prototype.calcRandomCustHour = function() {
  for (var i = 0; i < openHours.length; i++) {
    this.randomCustHour.push(Math.floor(Math.random() * (this.maxCustHour - this.minCustHour + 1) + this.minCustHour));
  }
};

//METHOD to calculate projected number of cookies each hour AND total daily cookes
CreateNewStore.prototype.calcCookiesPerHour = function() {
  for (var i = 0; i < this.randomCustHour.length; i++) {
    var singleHourCookies = Math.ceil(this.randomCustHour[i] * this.avgCookiesCustomer);
    this.projCookiesPerHour.push(singleHourCookies);
    this.totalDailyCookies += singleHourCookies;
  }
};

// METHOD TO CREATE SALES TABLE DATA CELLS
CreateNewStore.prototype.createSalesDataCells = function () {
  var salesDataTable = document.getElementById('salesDataTable');

  var salesDataRow = document.createElement('tr');
  var salesDataNameCell = document.createElement('td');
  salesDataNameCell.textContent = this.storeName;
  salesDataRow.appendChild(salesDataNameCell);

  for (var i = 0; i < this.projCookiesPerHour.length; i++) {
    var salesDataCell = document.createElement('td');
    salesDataCell.textContent = this.projCookiesPerHour[i];
    salesDataRow.appendChild(salesDataCell);
  }

  var salesDataTotalCell = document.createElement('td');
  salesDataTotalCell.textContent = this.totalDailyCookies;
  salesDataRow.appendChild(salesDataTotalCell);

  salesDataTable.appendChild(salesDataRow);
};

//STAND ALONE FUNCTION FOR HEADER ROW
function makeHeaderRow () {
  var salesDataTable = document.getElementById('salesDataTable');

  var salesDataRow = document.createElement('tr');
  var salesDataEmptyHeader = document.createElement('th');
  salesDataEmptyHeader.textContent = '';
  salesDataRow.appendChild(salesDataEmptyHeader);

  for (var i = 0; i < openHours.length; i++) {
    var salesDataHeader = document.createElement('th');
    salesDataHeader.textContent = openHours[i];
    salesDataRow.appendChild(salesDataHeader);
  }
  salesDataEmptyHeader = document.createElement('th');
  salesDataEmptyHeader.textContent = 'Daily Total';
  salesDataRow.appendChild(salesDataEmptyHeader);

  salesDataTable.appendChild(salesDataRow);
};

// STAND-ALONE FUNCTION FOR FOOTER
function makeFooterRow () {
  var salesDataTable = document.getElementById('salesDataTable');

  var salesFooterRow = document.createElement('tr');
  var salesDataEmptyFooter = document.createElement('td');
  salesDataEmptyFooter.textContent = '';
  salesFooterRow.appendChild(salesDataEmptyFooter);

  for (var i = 0; i < openHours.length; i++) {
    var salesDataFooter = document.createElement('td');
    salesDataFooter.textContent = 'total';
    salesFooterRow.appendChild(salesDataFooter);
  }
  var salesDataFooterTotal = document.createElement('td');
  salesDataFooterTotal.textContent = 'TOTAL';
  salesFooterRow.appendChild(salesDataFooterTotal);
  salesDataTable.appendChild(salesFooterRow);
};

function renderSalesDataCells () {
  for (var i = 0; i < locationNames.length; i++) {
    locationNames[i].createSalesDataCells();
  }
};

var formSubmit = document.getElementById('salesProjectionForm');
// var formStoreName = document.getElementById('storeLocation');
// var formMinCustHour = document.getElementById('minCustHour');
// var formMaxCustHour = document.getElementById('maxCustHour');
// var formAvgCookies = document.getElementById('avgCookiesCustomer');

function AddNewStore(event) {

  event.preventDefault();

  var cookieStore = event.target.storeLocation.value;
  var minCust = event.target.minCustHour.value;
  var maxCust = event.target.maxCustHour.value;
  var avgCookies = event.target.avgCookiesCustomer.value;

  if (!cookieStore || !minCust || !maxCust || !avgCookies) {
    return alert('Must enter data in all fields');
  };

  var newStore = new CreateNewStore(cookieStore, minCust, maxCust, avgCookies);
  console.log(newStore);
  locationNames.push(newStore);

  function renderAddedRows () {
    for (var i = 0; i < locationNames.length; i++) {
      locationNames[i].createSalesDataCells();
    }
  };

  renderAddedRows();

};

formSubmit.addEventListener('submit', AddNewStore);

new CreateNewStore('First and Pike', 23, 65, 6.3); //eslint-disable-line
new CreateNewStore('Seatac Airport', 3, 24, 1.2);
new CreateNewStore('Seattle Center', 11, 38, 3.7);
new CreateNewStore('Capital Hill', 20, 38, 2.3);
new CreateNewStore('Alki', 2, 16, 4.6);

makeHeaderRow();
renderSalesDataCells();
makeFooterRow();
<|endoftext|>


<commit_before>const assert = require('assert')
const sinon = require('sinon')
import GameTimerListener from '../../src/models/GameTimerListener'
import TimeEvent from '../../src/view/TimeEvent'

describe('Game timer listener tests', () => {
  var gtListener, player, menuController, topBarController, city, gameEvents
  var isGameOverSpy, tbcRedrawSpy, mcRedrawSpy, countPointsSpy

  beforeEach(() => {
    isGameOverSpy = sinon.spy()
    tbcRedrawSpy = sinon.spy()
    mcRedrawSpy = sinon.spy()
    countPointsSpy = sinon.spy()

    menuController = {
      redraw: mcRedrawSpy
    }

    topBarController = {
      redraw: tbcRedrawSpy
    }

    gameEvents = {
      isGameOver: isGameOverSpy
    }

    player = {
      structures: 74,
      cash: 788,
      addPoints: countPointsSpy
    }

    city = {
      buyTurnips: () => 1
    }

    gtListener = new GameTimerListener({
      player: player,
      menuController: menuController,
      city: city,
      topBarController: topBarController,
      gameEvents: gameEvents
    })
  })

  it('Constructor works', () => {
    assert.equal(player, gtListener.player)
    assert.equal(menuController, gtListener.menuController)
    assert.equal(city, gtListener.city)
    assert.equal(topBarController, gtListener.topBarController)
    assert.equal(gameEvents, gtListener.gameEvents)
  })

  it('onTimer works correctly', () => {
    var timerEvent = { year: 2 }
    var countProdStub = sinon.stub()
    countProdStub.withArgs(timerEvent).returns(37)
    var doTransactionSpy = sinon.spy()
    var redrawControllersSpy = sinon.spy()

    gtListener.countProductionFromStructures = countProdStub
    gtListener.doTransaction = doTransactionSpy
    gtListener.redrawControllers = redrawControllersSpy
    gtListener.checkBuildingRuining = sinon.spy()
    gtListener.onTimer(timerEvent)

    assert(doTransactionSpy.calledWith(37, timerEvent))
    assert(redrawControllersSpy.calledWith())
    assert(isGameOverSpy.calledWith(timerEvent))
    assert(gtListener.checkBuildingRuining.calledWith(timerEvent))
  })

  it('countProductionFromStructures works correctly', () => {
    var timerEvent = 4
    var str = { produce: function (timerEvent) {return 3 + timerEvent}, structureType : {name: "not a farm"}}
    var structures = [str, str, str]
    player.structures = structures

    var result = gtListener.countProductionFromStructures(timerEvent)
    assert.equal(21, result)
  })

  it('doTransaction works correctly', () => {
    gtListener.doTransaction(6, {endOfTheYear: true})
    assert(countPointsSpy.calledWith(1))
    assert.equal(789, player.cash)
  })

  it('redrawControllers works correctly', () => {
    gtListener.redrawControllers()
    assert(mcRedrawSpy.calledWith())
    assert(tbcRedrawSpy.calledWith())
  })
})
<commit_msg>testi<commit_after>const assert = require('assert')
const sinon = require('sinon')
import GameTimerListener from '../../src/models/GameTimerListener'
import TimeEvent from '../../src/view/TimeEvent'

describe('Game timer listener tests', () => {
  var gtListener, player, menuController, topBarController, city, gameEvents
  var isGameOverSpy, tbcRedrawSpy, mcRedrawSpy, countPointsSpy

  beforeEach(() => {
    isGameOverSpy = sinon.spy()
    tbcRedrawSpy = sinon.spy()
    mcRedrawSpy = sinon.spy()
    countPointsSpy = sinon.spy()

    menuController = {
      redraw: mcRedrawSpy
    }

    topBarController = {
      redraw: tbcRedrawSpy
    }

    gameEvents = {
      isGameOver: isGameOverSpy
    }

    player = {
      structures: 74,
      cash: 788,
      addPoints: countPointsSpy
    }

    city = {
      buyTurnips: () => 1
    }

    gtListener = new GameTimerListener({
      player: player,
      menuController: menuController,
      city: city,
      topBarController: topBarController,
      gameEvents: gameEvents
    })
  })

  it('Constructor works', () => {
    assert.equal(player, gtListener.player)
    assert.equal(menuController, gtListener.menuController)
    assert.equal(city, gtListener.city)
    assert.equal(topBarController, gtListener.topBarController)
    assert.equal(gameEvents, gtListener.gameEvents)
  })

  it('onTimer works correctly', () => {
    var timerEvent = { year: 2 }
    var countProdStub = sinon.stub()
    countProdStub.withArgs(timerEvent).returns(37)
    var doTransactionSpy = sinon.spy()
    var redrawControllersSpy = sinon.spy()

    gtListener.countProductionFromStructures = countProdStub
    gtListener.doTransaction = doTransactionSpy
    gtListener.redrawControllers = redrawControllersSpy
    gtListener.checkBuildingRuining = sinon.spy()
    gtListener.onTimer(timerEvent)

    assert(doTransactionSpy.calledWith(37, timerEvent))
    assert(redrawControllersSpy.calledWith())
    assert(isGameOverSpy.calledWith(timerEvent))
    assert(gtListener.checkBuildingRuining.calledWith(timerEvent))
  })

  it('countProductionFromStructures works correctly', () => {
    var timerEvent = 4
    var str = { produce: function (timerEvent) {return 3 + timerEvent}, structureType : {name: "not a farm"}}
    var structures = [str, str, str]
    player.structures = structures

    var result = gtListener.countProductionFromStructures(timerEvent)
    assert.equal(21, result)
  })

  it('Ruining calls ruinign functions', ()=>{
    var str = {healthManager: {checkRuin: sinon.spy()}}
    player.structures = [str, str, str]

    gtListener.checkBuildingRuining(1)
    assert.equal(3, str.healthManager.checkRuin.callCount)
    assert(str.healthManager.checkRuin.calledWith(1))
  })

  it('doTransaction works correctly', () => {
    gtListener.doTransaction(6, {endOfTheYear: true})
    assert(countPointsSpy.calledWith(1))
    assert.equal(789, player.cash)
  })

  it('redrawControllers works correctly', () => {
    gtListener.redrawControllers()
    assert(mcRedrawSpy.calledWith())
    assert(tbcRedrawSpy.calledWith())
  })
})
<|endoftext|>


<commit_before>import { Migrations } from 'meteor/percolate:migrations';
import { backupMongo } from '../mongoBackup';
import { Meteor} from 'meteor/meteor';

import moment from 'moment/moment';
import path from 'path';

const LAST_MIGRATION = 23;

for (let i=1; i<=LAST_MIGRATION; i++) {
    const migration = require(`./migrate_v${i}`)[`MigrateV${i}`];
    Migrations.add({version: i, up() {migration.up();}, down() {migration.down();}});
}

// ----------------------------------------------------------------
function findLatestVersion() {
    let max = 0;

    Migrations._list.forEach((entry) => {
        max = Math.max(entry.version, max);
    });

    return max;
}

export const handleMigration = function () {
    const latestVersion = findLatestVersion(),
        currentVersion = Migrations.getVersion();

    if (currentVersion < latestVersion) {
        let basePath = Meteor.settings && Meteor.settings.db && Meteor.settings.db.mongodumpTargetDirectory || '';

        if (basePath !== '') {
            let backupPath = path.join(basePath, 'mongobackup_' + moment().format('YYYY-MM-DD'));
            backupMongo(process.env.MONGO_URL, backupPath);
        } else {
            console.warn('db.mongodumpTargetDirectory is not configured in settings.json. Skipping database backup!');
        }

        Migrations.migrateTo('latest');
    }
};
<commit_msg>Hotfix: ignore migration 23.<commit_after>import { Migrations } from 'meteor/percolate:migrations';
import { backupMongo } from '../mongoBackup';
import { Meteor} from 'meteor/meteor';

import moment from 'moment/moment';
import path from 'path';

const LAST_MIGRATION = 22;

for (let i=1; i<=LAST_MIGRATION; i++) {
    const migration = require(`./migrate_v${i}`)[`MigrateV${i}`];
    Migrations.add({version: i, up() {migration.up();}, down() {migration.down();}});
}

// ----------------------------------------------------------------
function findLatestVersion() {
    let max = 0;

    Migrations._list.forEach((entry) => {
        max = Math.max(entry.version, max);
    });

    return max;
}

export const handleMigration = function () {
    const latestVersion = findLatestVersion(),
        currentVersion = Migrations.getVersion();

    if (currentVersion < latestVersion) {
        let basePath = Meteor.settings && Meteor.settings.db && Meteor.settings.db.mongodumpTargetDirectory || '';

        if (basePath !== '') {
            let backupPath = path.join(basePath, 'mongobackup_' + moment().format('YYYY-MM-DD'));
            backupMongo(process.env.MONGO_URL, backupPath);
        } else {
            console.warn('db.mongodumpTargetDirectory is not configured in settings.json. Skipping database backup!');
        }

        Migrations.migrateTo('latest');
    }
};
<|endoftext|>


<commit_before>// ==========================================================================
// Project:   metamorph
// Copyright: ©2011 My Company Inc. All rights reserved.
// ==========================================================================

(function(window) {

  var K = function(){},
      guid = 0,
      document = window.document,

      // Feature-detect the W3C range API, the extended check is for IE9 which only partially supports ranges
      supportsRange = ('createRange' in document) && (typeof Range !== 'undefined') && Range.prototype.createContextualFragment,

      // Internet Explorer prior to 9 does not allow setting innerHTML if the first element
      // is a "zero-scope" element. This problem can be worked around by making
      // the first node an invisible text node. We, like Modernizr, use
      needsShy = (function(){
        var testEl = document.createElement('div');
        testEl.innerHTML = "

";
        testEl.firstChild.innerHTML = "";
        return testEl.firstChild.innerHTML === '';
      })(),

      // IE 8 (and likely earlier) likes to move whitespace preceeding
      // a script tag to appear after it. This means that we can
      // accidentally remove whitespace when updating a morph.
      movesWhitespace = (function() {
        var testEl = document.createElement('div');
        testEl.innerHTML = "Test: Value";
        return testEl.childNodes[0].nodeValue === 'Test:' &&
                testEl.childNodes[2].nodeValue === ' Value';
      })();

  // Constructor that supports either Metamorph('foo') or new
  // Metamorph('foo');
  //
  // Takes a string of HTML as the argument.

  var Metamorph = function(html) {
    var self;

    if (this instanceof Metamorph) {
      self = this;
    } else {
      self = new K();
    }

    self.innerHTML = html;
    var myGuid = 'metamorph-'+(guid++);
    self.start = myGuid + '-start';
    self.end = myGuid + '-end';

    return self;
  };

  K.prototype = Metamorph.prototype;

  var rangeFor, htmlFunc, removeFunc, outerHTMLFunc, appendToFunc, afterFunc, prependFunc, startTagFunc, endTagFunc;

  outerHTMLFunc = function() {
    return this.startTag() + this.innerHTML + this.endTag();
  };

  startTagFunc = function() {
    /*
     * We replace chevron by its hex code in order to prevent escaping problems.
     * Check this thread for more explaination:
     * http://stackoverflow.com/questions/8231048/why-use-x3c-instead-of-when-generating-html-from-javascript
     */
    return "
hi

";
     *     div.firstChild.firstChild.tagName //=> ""
     *
     * If our script markers are inside such a node, we need to find that
     * node and use *it* as the marker.
     **/
    var realNode = function(start) {
      while (start.parentNode.tagName === "") {
        start = start.parentNode;
      }

      return start;
    };

    /**
     * When automatically adding a tbody, Internet Explorer inserts the
     * tbody immediately before the first
. Other browsers create it
     * before the first node, no matter what.
     *
     * This means the the following code:
     *
     *     div = document.createElement("div");
     *     div.innerHTML = "

hi

     *
     * Generates the following DOM in IE:
     *
     *     + div
     *       + table
     *         - script id='first'
     *         + tbody
     *           + tr
     *             + td
     *               - "hi"
     *           - script id='last'
     *
     * Which means that the two script tags, even though they were
     * inserted at the same point in the hierarchy in the original
     * HTML, now have different parents.
     *
     * This code reparents the first script tag by making it the tbody's
     * first child.
     **/
    var fixParentage = function(start, end) {
      if (start.parentNode !== end.parentNode) {
        end.parentNode.insertBefore(start, end.parentNode.firstChild);
      }
    };

    htmlFunc = function(html, outerToo) {
      // get the real starting node. see realNode for details.
      var start = realNode(document.getElementById(this.start));
      var end = document.getElementById(this.end);
      var parentNode = end.parentNode;
      var node, nextSibling, last;

      // make sure that the start and end nodes share the same
      // parent. If not, fix it.
      fixParentage(start, end);

      // remove all of the nodes after the starting placeholder and
      // before the ending placeholder.
      node = start.nextSibling;
      while (node) {
        nextSibling = node.nextSibling;
        last = node === end;

        // if this is the last node, and we want to remove it as well,
        // set the `end` node to the next sibling. This is because
        // for the rest of the function, we insert the new nodes
        // before the end (note that insertBefore(node, null) is
        // the same as appendChild(node)).
        //
        // if we do not want to remove it, just break.
        if (last) {
          if (outerToo) { end = node.nextSibling; } else { break; }
        }

        node.parentNode.removeChild(node);

        // if this is the last node and we didn't break before
        // (because we wanted to remove the outer nodes), break
        // now.
        if (last) { break; }

        node = nextSibling;
      }

      // get the first node for the HTML string, even in cases like
      // tables and lists where a simple innerHTML on a div would
      // swallow some of the content.
      node = firstNodeFor(start.parentNode, html);

      // copy the nodes for the HTML between the starting and ending
      // placeholder.
      while (node) {
        nextSibling = node.nextSibling;
        parentNode.insertBefore(node, end);
        node = nextSibling;
      }
    };

    // remove the nodes in the DOM representing this metamorph.
    //
    // this includes the starting and ending placeholders.
    removeFunc = function() {
      var start = realNode(document.getElementById(this.start));
      var end = document.getElementById(this.end);

      this.html('');
      start.parentNode.removeChild(start);
      end.parentNode.removeChild(end);
    };

    appendToFunc = function(parentNode) {
      var node = firstNodeFor(parentNode, this.outerHTML());
      var nextSibling;

      while (node) {
        nextSibling = node.nextSibling;
        parentNode.appendChild(node);
        node = nextSibling;
      }
    };

    afterFunc = function(html) {
      // get the real starting node. see realNode for details.
      var end = document.getElementById(this.end);
      var insertBefore = end.nextSibling;
      var parentNode = end.parentNode;
      var nextSibling;
      var node;

      // get the first node for the HTML string, even in cases like
      // tables and lists where a simple innerHTML on a div would
      // swallow some of the content.
      node = firstNodeFor(parentNode, html);

      // copy the nodes for the HTML between the starting and ending
      // placeholder.
      while (node) {
        nextSibling = node.nextSibling;
        parentNode.insertBefore(node, insertBefore);
        node = nextSibling;
      }
    };

    prependFunc = function(html) {
      var start = document.getElementById(this.start);
      var parentNode = start.parentNode;
      var nextSibling;
      var node;

      node = firstNodeFor(parentNode, html);
      var insertBefore = start.nextSibling;

      while (node) {
        nextSibling = node.nextSibling;
        parentNode.insertBefore(node, insertBefore);
        node = nextSibling;
      }
    };
  }

  Metamorph.prototype.html = function(html) {
    this.checkRemoved();
    if (html === undefined) { return this.innerHTML; }

    htmlFunc.call(this, html);

    this.innerHTML = html;
  };

  Metamorph.prototype.replaceWith = function(html) {
    this.checkRemoved();
    htmlFunc.call(this, html, true);
  };

  Metamorph.prototype.remove = removeFunc;
  Metamorph.prototype.outerHTML = outerHTMLFunc;
  Metamorph.prototype.appendTo = appendToFunc;
  Metamorph.prototype.after = afterFunc;
  Metamorph.prototype.prepend = prependFunc;
  Metamorph.prototype.startTag = startTagFunc;
  Metamorph.prototype.endTag = endTagFunc;

  Metamorph.prototype.isRemoved = function() {
    var before = document.getElementById(this.start);
    var after = document.getElementById(this.end);

    return !before || !after;
  };

  Metamorph.prototype.checkRemoved = function() {
    if (this.isRemoved()) {
      throw new Error("Cannot perform operations on a Metamorph that is not in the DOM.");
    }
  };

  window.Metamorph = Metamorph;
})(this);

<commit_msg>don't require document just to require metamorph<commit_after>// ==========================================================================
// Project:   metamorph
// Copyright: ©2011 My Company Inc. All rights reserved.
// ==========================================================================

(function(window) {

  var K = function(){},
      guid = 0,
      document = window.document,

      // Feature-detect the W3C range API, the extended check is for IE9 which only partially supports ranges
      supportsRange = document && ('createRange' in document) && (typeof Range !== 'undefined') && Range.prototype.createContextualFragment,

      // Internet Explorer prior to 9 does not allow setting innerHTML if the first element
      // is a "zero-scope" element. This problem can be worked around by making
      // the first node an invisible text node. We, like Modernizr, use
      needsShy = document && (function(){
        var testEl = document.createElement('div');
        testEl.innerHTML = "

";
        testEl.firstChild.innerHTML = "";
        return testEl.firstChild.innerHTML === '';
      })(),

      // IE 8 (and likely earlier) likes to move whitespace preceeding
      // a script tag to appear after it. This means that we can
      // accidentally remove whitespace when updating a morph.
      movesWhitespace = document && (function() {
        var testEl = document.createElement('div');
        testEl.innerHTML = "Test: Value";
        return testEl.childNodes[0].nodeValue === 'Test:' &&
                testEl.childNodes[2].nodeValue === ' Value';
      })();

  // Constructor that supports either Metamorph('foo') or new
  // Metamorph('foo');
  //
  // Takes a string of HTML as the argument.

  var Metamorph = function(html) {
    var self;

    if (this instanceof Metamorph) {
      self = this;
    } else {
      self = new K();
    }

    self.innerHTML = html;
    var myGuid = 'metamorph-'+(guid++);
    self.start = myGuid + '-start';
    self.end = myGuid + '-end';

    return self;
  };

  K.prototype = Metamorph.prototype;

  var rangeFor, htmlFunc, removeFunc, outerHTMLFunc, appendToFunc, afterFunc, prependFunc, startTagFunc, endTagFunc;

  outerHTMLFunc = function() {
    return this.startTag() + this.innerHTML + this.endTag();
  };

  startTagFunc = function() {
    /*
     * We replace chevron by its hex code in order to prevent escaping problems.
     * Check this thread for more explaination:
     * http://stackoverflow.com/questions/8231048/why-use-x3c-instead-of-when-generating-html-from-javascript
     */
    return "
hi

";
     *     div.firstChild.firstChild.tagName //=> ""
     *
     * If our script markers are inside such a node, we need to find that
     * node and use *it* as the marker.
     **/
    var realNode = function(start) {
      while (start.parentNode.tagName === "") {
        start = start.parentNode;
      }

      return start;
    };

    /**
     * When automatically adding a tbody, Internet Explorer inserts the
     * tbody immediately before the first
. Other browsers create it
     * before the first node, no matter what.
     *
     * This means the the following code:
     *
     *     div = document.createElement("div");
     *     div.innerHTML = "

hi

     *
     * Generates the following DOM in IE:
     *
     *     + div
     *       + table
     *         - script id='first'
     *         + tbody
     *           + tr
     *             + td
     *               - "hi"
     *           - script id='last'
     *
     * Which means that the two script tags, even though they were
     * inserted at the same point in the hierarchy in the original
     * HTML, now have different parents.
     *
     * This code reparents the first script tag by making it the tbody's
     * first child.
     **/
    var fixParentage = function(start, end) {
      if (start.parentNode !== end.parentNode) {
        end.parentNode.insertBefore(start, end.parentNode.firstChild);
      }
    };

    htmlFunc = function(html, outerToo) {
      // get the real starting node. see realNode for details.
      var start = realNode(document.getElementById(this.start));
      var end = document.getElementById(this.end);
      var parentNode = end.parentNode;
      var node, nextSibling, last;

      // make sure that the start and end nodes share the same
      // parent. If not, fix it.
      fixParentage(start, end);

      // remove all of the nodes after the starting placeholder and
      // before the ending placeholder.
      node = start.nextSibling;
      while (node) {
        nextSibling = node.nextSibling;
        last = node === end;

        // if this is the last node, and we want to remove it as well,
        // set the `end` node to the next sibling. This is because
        // for the rest of the function, we insert the new nodes
        // before the end (note that insertBefore(node, null) is
        // the same as appendChild(node)).
        //
        // if we do not want to remove it, just break.
        if (last) {
          if (outerToo) { end = node.nextSibling; } else { break; }
        }

        node.parentNode.removeChild(node);

        // if this is the last node and we didn't break before
        // (because we wanted to remove the outer nodes), break
        // now.
        if (last) { break; }

        node = nextSibling;
      }

      // get the first node for the HTML string, even in cases like
      // tables and lists where a simple innerHTML on a div would
      // swallow some of the content.
      node = firstNodeFor(start.parentNode, html);

      // copy the nodes for the HTML between the starting and ending
      // placeholder.
      while (node) {
        nextSibling = node.nextSibling;
        parentNode.insertBefore(node, end);
        node = nextSibling;
      }
    };

    // remove the nodes in the DOM representing this metamorph.
    //
    // this includes the starting and ending placeholders.
    removeFunc = function() {
      var start = realNode(document.getElementById(this.start));
      var end = document.getElementById(this.end);

      this.html('');
      start.parentNode.removeChild(start);
      end.parentNode.removeChild(end);
    };

    appendToFunc = function(parentNode) {
      var node = firstNodeFor(parentNode, this.outerHTML());
      var nextSibling;

      while (node) {
        nextSibling = node.nextSibling;
        parentNode.appendChild(node);
        node = nextSibling;
      }
    };

    afterFunc = function(html) {
      // get the real starting node. see realNode for details.
      var end = document.getElementById(this.end);
      var insertBefore = end.nextSibling;
      var parentNode = end.parentNode;
      var nextSibling;
      var node;

      // get the first node for the HTML string, even in cases like
      // tables and lists where a simple innerHTML on a div would
      // swallow some of the content.
      node = firstNodeFor(parentNode, html);

      // copy the nodes for the HTML between the starting and ending
      // placeholder.
      while (node) {
        nextSibling = node.nextSibling;
        parentNode.insertBefore(node, insertBefore);
        node = nextSibling;
      }
    };

    prependFunc = function(html) {
      var start = document.getElementById(this.start);
      var parentNode = start.parentNode;
      var nextSibling;
      var node;

      node = firstNodeFor(parentNode, html);
      var insertBefore = start.nextSibling;

      while (node) {
        nextSibling = node.nextSibling;
        parentNode.insertBefore(node, insertBefore);
        node = nextSibling;
      }
    };
  }

  Metamorph.prototype.html = function(html) {
    this.checkRemoved();
    if (html === undefined) { return this.innerHTML; }

    htmlFunc.call(this, html);

    this.innerHTML = html;
  };

  Metamorph.prototype.replaceWith = function(html) {
    this.checkRemoved();
    htmlFunc.call(this, html, true);
  };

  Metamorph.prototype.remove = removeFunc;
  Metamorph.prototype.outerHTML = outerHTMLFunc;
  Metamorph.prototype.appendTo = appendToFunc;
  Metamorph.prototype.after = afterFunc;
  Metamorph.prototype.prepend = prependFunc;
  Metamorph.prototype.startTag = startTagFunc;
  Metamorph.prototype.endTag = endTagFunc;

  Metamorph.prototype.isRemoved = function() {
    var before = document.getElementById(this.start);
    var after = document.getElementById(this.end);

    return !before || !after;
  };

  Metamorph.prototype.checkRemoved = function() {
    if (this.isRemoved()) {
      throw new Error("Cannot perform operations on a Metamorph that is not in the DOM.");
    }
  };

  window.Metamorph = Metamorph;
})(this);

<|endoftext|>


<commit_before>import React, { useRef, useState, useEffect } from "react";

import Header from "./Header";
import ActionButton from "./ActionButton";
import ContentWrapper from "./ContentWrapper";

import backgroundImage from "../assets/img/backgrounds/landingBG2.png";
import graphicMobile from "../assets/img/backgrounds/backgroundMobile.png";
import waveLineRed from "../assets/img/backgrounds/waveLineRed.png";
import logo from "../assets/img/logo/qhacksCrown-colored.svg";
import word from "../assets/img/logo/qhacksWordmark-colored.svg";

const landingCSS = {
  width: "100%",
  height: "730px",
  marginTop: "120px",
  background: `url(${backgroundImage}) no-repeat center center`,
  backgroundColor: "#fff",
  backgroundSize: "auto 650px",
  "@media (min-width: 820px) and (max-width: 1200px)": {
    backgroundSize: "auto 550px"
  },
  "@media(max-width: 820px)": {
    height: "900px",
    marginTop: "50px",
    background: `url(${waveLineRed}) no-repeat center bottom`
  }
};

const applyButtonCSS = {
  alignItems: "center",
  position: "relative",
  margin: "40px 0 40px auto",
  "@media(max-width: 820px)": {
    margin: "30px auto 45px auto",
    padding: "5px 10px 5px 10px"
  }
};

function Landing() {

  const [timerDays, setTimerDays] = useState("00");
  const [timerHours, setTimerHours] = useState("00");
  const [timerMinutes, setTimerMinutes] = useState("00");
  const [timerSeconds, setTimerSeconds] = useState("00");

  let interval = useRef;

  const startTimer = () => {
      const countDownDate = new Date('November 25 2020 17:00:00').getTime();

      interval = setInterval(()=>{
        const now = new Date().getTime();
        const distance = countDownDate - now;

        const days = Math.floor(distance/(1000*60*60*24));
        const hours = Math.floor((distance%(1000*60*60*24)/(1000*60*60)));
        const minutes = Math.floor((distance%(1000*60*60)/(1000*60)));
        const seconds = Math.floor((distance%(1000*60)) / 1000);

        if (distance < 0){
          clearInterval(interval.current);
        }else{
          setTimerDays(days);
          setTimerHours(hours);
          setTimerMinutes(minutes);
          setTimerSeconds(seconds);
        }

      }, 1000);
  };

useEffect(()=>{
  startTimer();
  return() =>{
    clearInterval(interval.current);
  };
});

  return (

      <ContentWrapper>

          <h2
            data-cy="qhacks-information"
            css={{
              zIndex: "2",
              color: "#000000",
              fontWeight: 600,
              fontSize: "22px",
              marginTop: "20px",
              marginBottom: "20px",
              "@media (min-width: 820px) and (max-width: 1200px)": {
                fontSize: "20px"
              },
              "@media(max-width: 820px)": {
                fontSize: "15px",
                fontWeight: 600,
                paddingBottom: "20px"
              }
            }}
          >
            Queen’s University • January 22nd - 24th, 2021

            Queen’s University’s annual hackathon.

            Join us for an unforgettable experience!

          {/*<ActionButton
            dataCy="apply-button"
            backgroundColor="#00205B"
            foregroundColor="#ffffff"
            hoverBackgroundColor="#00205B"
            hoverForegroundColor="#ffffff"
            style={applyButtonCSS}
            type="rounded"
          >

Applications Opening in

{timerDays}

days

              :

{timerHours}

hours

              :

{timerMinutes}

minutes

              :

{timerSeconds}

seconds

              </ActionButton>*/}
           <ActionButton
            dataCy="apply-button"
            backgroundColor="#00205B"
            foregroundColor="#ffffff"
            hoverBackgroundColor="#16498c"
            hoverForegroundColor="#ffffff"
            style={applyButtonCSS}
            link="https://app.qhacks.io/"
            type="rounded"
          >
            Apply Now
          </ActionButton>

      </ContentWrapper>

  );
}

export default Landing;
<commit_msg>remove comments<commit_after>import React, { useRef, useState, useEffect } from "react";

import Header from "./Header";
import ActionButton from "./ActionButton";
import ContentWrapper from "./ContentWrapper";

import backgroundImage from "../assets/img/backgrounds/landingBG2.png";
import graphicMobile from "../assets/img/backgrounds/backgroundMobile.png";
import waveLineRed from "../assets/img/backgrounds/waveLineRed.png";
import logo from "../assets/img/logo/qhacksCrown-colored.svg";
import word from "../assets/img/logo/qhacksWordmark-colored.svg";

const landingCSS = {
  width: "100%",
  height: "730px",
  marginTop: "120px",
  background: `url(${backgroundImage}) no-repeat center center`,
  backgroundColor: "#fff",
  backgroundSize: "auto 650px",
  "@media (min-width: 820px) and (max-width: 1200px)": {
    backgroundSize: "auto 550px"
  },
  "@media(max-width: 820px)": {
    height: "900px",
    marginTop: "50px",
    background: `url(${waveLineRed}) no-repeat center bottom`
  }
};

const applyButtonCSS = {
  alignItems: "center",
  position: "relative",
  margin: "40px 0 40px auto",
  "@media(max-width: 820px)": {
    margin: "30px auto 45px auto",
    padding: "5px 10px 5px 10px"
  }
};

function Landing() {

  const [timerDays, setTimerDays] = useState("00");
  const [timerHours, setTimerHours] = useState("00");
  const [timerMinutes, setTimerMinutes] = useState("00");
  const [timerSeconds, setTimerSeconds] = useState("00");

  let interval = useRef;

  const startTimer = () => {
      const countDownDate = new Date('November 25 2020 17:00:00').getTime();

      interval = setInterval(()=>{
        const now = new Date().getTime();
        const distance = countDownDate - now;

        const days = Math.floor(distance/(1000*60*60*24));
        const hours = Math.floor((distance%(1000*60*60*24)/(1000*60*60)));
        const minutes = Math.floor((distance%(1000*60*60)/(1000*60)));
        const seconds = Math.floor((distance%(1000*60)) / 1000);

        if (distance < 0){
          clearInterval(interval.current);
        }else{
          setTimerDays(days);
          setTimerHours(hours);
          setTimerMinutes(minutes);
          setTimerSeconds(seconds);
        }

      }, 1000);
  };

useEffect(()=>{
  startTimer();
  return() =>{
    clearInterval(interval.current);
  };
});

  return (

      <ContentWrapper>

          <h2
            data-cy="qhacks-information"
            css={{
              zIndex: "2",
              color: "#000000",
              fontWeight: 600,
              fontSize: "22px",
              marginTop: "20px",
              marginBottom: "20px",
              "@media (min-width: 820px) and (max-width: 1200px)": {
                fontSize: "20px"
              },
              "@media(max-width: 820px)": {
                fontSize: "15px",
                fontWeight: 600,
                paddingBottom: "20px"
              }
            }}
          >
            Queen’s University • January 22nd - 24th, 2021

            Queen’s University’s annual hackathon.

            Join us for an unforgettable experience!

           <ActionButton
            dataCy="apply-button"
            backgroundColor="#00205B"
            foregroundColor="#ffffff"
            hoverBackgroundColor="#16498c"
            hoverForegroundColor="#ffffff"
            style={applyButtonCSS}
            link="https://app.qhacks.io/"
            type="rounded"
          >
            Apply Now
          </ActionButton>

      </ContentWrapper>

  );
}

export default Landing;
<|endoftext|>


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

'use strict'

const assert = require('insist')
var TestServer = require('../test_server')
const Client = require('../client')()

var config = require('../../config').getProperties()

function makeMockOAuthHeader(opts) {
  var token = Buffer.from(JSON.stringify(opts)).toString('hex')
  return 'Bearer ' + token
}

describe('remote account profile', function() {
  this.timeout(15000)

  let server
  before(() => {
    config.oauth.url = 'http://localhost:9010'
    return TestServer.start(config)
      .then(s => {
        server = s
      })
  })

  it(
    'account profile authenticated with session returns profile data',
    () => {
      return Client.create(config.publicUrl, server.uniqueEmail(), 'password', { lang: 'en-US' })
        .then(
          function (c) {
            return c.api.accountProfile(c.sessionToken)
          }
        )
        .then(
          function (response) {
            assert.ok(response.email, 'email address is returned')
            assert.equal(response.locale, 'en-US', 'locale is returned')
          }
        )
    }
  )

  it(
    'account profile authenticated with oauth returns profile data',
    () => {
      return Client.create(config.publicUrl, server.uniqueEmail(), 'password', { lang: 'en-US' })
        .then(
          function (c) {
            return c.api.accountProfile(null, {
              Authorization: makeMockOAuthHeader({
                user: c.uid,
                scope: ['profile']
              })
            })
          }
        )
        .then(
          function (response) {
            assert.ok(response.email, 'email address is returned')
            assert.equal(response.locale, 'en-US', 'locale is returned')
          }
        )
    }
  )

  it(
    'account profile authenticated with invalid oauth token returns an error',
    () => {
      return Client.create(config.publicUrl, server.uniqueEmail(), 'password', { lang: 'en-US' })
        .then(
          function (c) {
            return c.api.accountProfile(null, {
              Authorization: makeMockOAuthHeader({
                code: 401,
                errno: 108
              })
            })
          }
        )
        .then(
          function () {
            assert(false, 'should get an error')
          },
          function (e) {
            assert.equal(e.code, 401, 'correct error status code')
            assert.equal(e.errno, 110, 'correct errno')
          }
        )
    }
  )

  it(
    'account status authenticated with oauth for unknown uid returns an error',
    () => {
      return Client.create(config.publicUrl, server.uniqueEmail(), 'password', { lang: 'en-US' })
        .then(
          function (c) {
            var UNKNOWN_UID = 'abcdef123456'
            assert.notEqual(c.uid, UNKNOWN_UID)
            return c.api.accountProfile(null, {
              Authorization: makeMockOAuthHeader({
                user: UNKNOWN_UID,
                scope: ['profile']
              })
            })
          }
        )
        .then(
          function () {
            assert(false, 'should get an error')
          },
          function (e) {
            assert.equal(e.code, 400, 'correct error status code')
            assert.equal(e.errno, 102, 'correct errno')
          }
        )
    }
  )

  it(
    'account status authenticated with oauth for wrong scope returns no info',
    () => {
      return Client.create(config.publicUrl, server.uniqueEmail(), 'password', { lang: 'en-US' })
        .then(
          function (c) {
            return c.api.accountProfile(null, {
              Authorization: makeMockOAuthHeader({
                user: c.uid,
                scope: ['readinglist', 'payments']
              })
            })
          }
        )
        .then(
          function (response) {
            assert.deepEqual(response, {}, 'no info should be returned')
          }
        )
    }
  )

  it(
    'account profile authenticated with limited oauth scopes returns limited profile data',
    () => {
      var client
      return Client.create(config.publicUrl, server.uniqueEmail(), 'password', { lang: 'en-US' })
        .then(
          function (c) {
            client = c
            return client.api.accountProfile(null, {
              Authorization: makeMockOAuthHeader({
                user: client.uid,
                scope: ['profile:email']
              })
            })
          }
        )
        .then(
          function (response) {
            assert.ok(response.email, 'email address is returned')
            assert.ok(! response.locale, 'locale should not be returned')
          }
        )
        .then(
          function () {
            return client.api.accountProfile(null, {
              Authorization: makeMockOAuthHeader({
                user: client.uid,
                scope: ['profile:locale']
              })
            })
          }
        )
        .then(
          function (response) {
            assert.ok(! response.email, 'email address should not be returned')
            assert.equal(response.locale, 'en-US', 'locale is returned')
          }
        )
    }
  )

  it(
    'account profile authenticated with oauth :write scopes returns profile data',
    () => {
      var client
      return Client.create(config.publicUrl, server.uniqueEmail(), 'password', { lang: 'en-US' })
        .then(
          function (c) {
            client = c
            return client.api.accountProfile(null, {
              Authorization: makeMockOAuthHeader({
                user: client.uid,
                scope: ['profile:write']
              })
            })
          }
        )
        .then(
          function (response) {
            assert.ok(response.email, 'email address is returned')
            assert.ok(response.locale, 'locale is returned')
          }
        )
        .then(
          function () {
            return client.api.accountProfile(null, {
              Authorization: makeMockOAuthHeader({
                user: client.uid,
                scope: ['profile:locale:write', 'readinglist']
              })
            })
          }
        )
        .then(
          function (response) {
            assert.ok(! response.email, 'email address should not be returned')
            assert.ok(response.locale, 'locale is returned')
          }
        )
        .then(
          function () {
            return client.api.accountProfile(null, {
              Authorization: makeMockOAuthHeader({
                user: client.uid,
                scope: ['storage', 'profile:email:write']
              })
            })
          }
        )
        .then(
          function (response) {
            assert.ok(response.email, 'email address is returned')
            assert.ok(! response.locale, 'locale should not be returned')
          }
        )
    }
  )

  it(
    'account profile works with unicode email address',
    () => {
      var email = server.uniqueUnicodeEmail()
      return Client.create(config.publicUrl, email, 'password')
        .then(
          function (c) {
            return c.api.accountProfile(c.sessionToken)
          }
        )
        .then(
          function (response) {
            assert.equal(response.email, email, 'email address is returned')
          }
        )
    }
  )

  after(() => {
    return TestServer.stop(server)
  })
})
<commit_msg>fix(tests): Test that unauthenticated /account/profile rejects cleanly. (#2296) r=@philbooth,@vladikoff<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

'use strict'

const assert = require('insist')
var TestServer = require('../test_server')
const Client = require('../client')()

var config = require('../../config').getProperties()

function makeMockOAuthHeader(opts) {
  var token = Buffer.from(JSON.stringify(opts)).toString('hex')
  return 'Bearer ' + token
}

describe('remote account profile', function() {
  this.timeout(15000)

  let server
  before(() => {
    config.oauth.url = 'http://localhost:9010'
    return TestServer.start(config)
      .then(s => {
        server = s
      })
  })

  it(
    'account profile authenticated with session returns profile data',
    () => {
      return Client.create(config.publicUrl, server.uniqueEmail(), 'password', { lang: 'en-US' })
        .then(
          function (c) {
            return c.api.accountProfile(c.sessionToken)
          }
        )
        .then(
          function (response) {
            assert.ok(response.email, 'email address is returned')
            assert.equal(response.locale, 'en-US', 'locale is returned')
          }
        )
    }
  )

  it(
    'account profile authenticated with oauth returns profile data',
    () => {
      return Client.create(config.publicUrl, server.uniqueEmail(), 'password', { lang: 'en-US' })
        .then(
          function (c) {
            return c.api.accountProfile(null, {
              Authorization: makeMockOAuthHeader({
                user: c.uid,
                scope: ['profile']
              })
            })
          }
        )
        .then(
          function (response) {
            assert.ok(response.email, 'email address is returned')
            assert.equal(response.locale, 'en-US', 'locale is returned')
          }
        )
    }
  )

  it(
    'account profile with no authentication returns a 401',
    () => {
      return Client.create(config.publicUrl, server.uniqueEmail(), 'password', { lang: 'en-US' })
        .then(c => {
          return c.api.accountProfile(null, {})
        })
        .then(
          (response) => { assert.fail('request should have failed') },
          (err) => {
            assert.equal(err.code, 401, 'request failed with a 401')
          }
        )
    }
  )

  it(
    'account profile authenticated with invalid oauth token returns an error',
    () => {
      return Client.create(config.publicUrl, server.uniqueEmail(), 'password', { lang: 'en-US' })
        .then(
          function (c) {
            return c.api.accountProfile(null, {
              Authorization: makeMockOAuthHeader({
                code: 401,
                errno: 108
              })
            })
          }
        )
        .then(
          function () {
            assert(false, 'should get an error')
          },
          function (e) {
            assert.equal(e.code, 401, 'correct error status code')
            assert.equal(e.errno, 110, 'correct errno')
          }
        )
    }
  )

  it(
    'account status authenticated with oauth for unknown uid returns an error',
    () => {
      return Client.create(config.publicUrl, server.uniqueEmail(), 'password', { lang: 'en-US' })
        .then(
          function (c) {
            var UNKNOWN_UID = 'abcdef123456'
            assert.notEqual(c.uid, UNKNOWN_UID)
            return c.api.accountProfile(null, {
              Authorization: makeMockOAuthHeader({
                user: UNKNOWN_UID,
                scope: ['profile']
              })
            })
          }
        )
        .then(
          function () {
            assert(false, 'should get an error')
          },
          function (e) {
            assert.equal(e.code, 400, 'correct error status code')
            assert.equal(e.errno, 102, 'correct errno')
          }
        )
    }
  )

  it(
    'account status authenticated with oauth for wrong scope returns no info',
    () => {
      return Client.create(config.publicUrl, server.uniqueEmail(), 'password', { lang: 'en-US' })
        .then(
          function (c) {
            return c.api.accountProfile(null, {
              Authorization: makeMockOAuthHeader({
                user: c.uid,
                scope: ['readinglist', 'payments']
              })
            })
          }
        )
        .then(
          function (response) {
            assert.deepEqual(response, {}, 'no info should be returned')
          }
        )
    }
  )

  it(
    'account profile authenticated with limited oauth scopes returns limited profile data',
    () => {
      var client
      return Client.create(config.publicUrl, server.uniqueEmail(), 'password', { lang: 'en-US' })
        .then(
          function (c) {
            client = c
            return client.api.accountProfile(null, {
              Authorization: makeMockOAuthHeader({
                user: client.uid,
                scope: ['profile:email']
              })
            })
          }
        )
        .then(
          function (response) {
            assert.ok(response.email, 'email address is returned')
            assert.ok(! response.locale, 'locale should not be returned')
          }
        )
        .then(
          function () {
            return client.api.accountProfile(null, {
              Authorization: makeMockOAuthHeader({
                user: client.uid,
                scope: ['profile:locale']
              })
            })
          }
        )
        .then(
          function (response) {
            assert.ok(! response.email, 'email address should not be returned')
            assert.equal(response.locale, 'en-US', 'locale is returned')
          }
        )
    }
  )

  it(
    'account profile authenticated with oauth :write scopes returns profile data',
    () => {
      var client
      return Client.create(config.publicUrl, server.uniqueEmail(), 'password', { lang: 'en-US' })
        .then(
          function (c) {
            client = c
            return client.api.accountProfile(null, {
              Authorization: makeMockOAuthHeader({
                user: client.uid,
                scope: ['profile:write']
              })
            })
          }
        )
        .then(
          function (response) {
            assert.ok(response.email, 'email address is returned')
            assert.ok(response.locale, 'locale is returned')
          }
        )
        .then(
          function () {
            return client.api.accountProfile(null, {
              Authorization: makeMockOAuthHeader({
                user: client.uid,
                scope: ['profile:locale:write', 'readinglist']
              })
            })
          }
        )
        .then(
          function (response) {
            assert.ok(! response.email, 'email address should not be returned')
            assert.ok(response.locale, 'locale is returned')
          }
        )
        .then(
          function () {
            return client.api.accountProfile(null, {
              Authorization: makeMockOAuthHeader({
                user: client.uid,
                scope: ['storage', 'profile:email:write']
              })
            })
          }
        )
        .then(
          function (response) {
            assert.ok(response.email, 'email address is returned')
            assert.ok(! response.locale, 'locale should not be returned')
          }
        )
    }
  )

  it(
    'account profile works with unicode email address',
    () => {
      var email = server.uniqueUnicodeEmail()
      return Client.create(config.publicUrl, email, 'password')
        .then(
          function (c) {
            return c.api.accountProfile(c.sessionToken)
          }
        )
        .then(
          function (response) {
            assert.equal(response.email, email, 'email address is returned')
          }
        )
    }
  )

  after(() => {
    return TestServer.stop(server)
  })
})
<|endoftext|>


<commit_before>/**
 * @license
 * Code City: Server
 *
 * Copyright 2017 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Load ES5 for tests.
 * @author fraser@google.com (Neil Fraser)
 */

'use strict';

const fs = require('fs');
module.exports = fs.readFileSync('es5.js', 'utf8');
<commit_msg>Fix server tests<commit_after>/**
 * @license
 * Code City: Server
 *
 * Copyright 2017 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Load ES5 for tests.
 * @author fraser@google.com (Neil Fraser)
 */

'use strict';

const fs = require('fs');
module.exports = fs.readFileSync('startup/es5.js', 'utf8');
<|endoftext|>


<commit_before>import React, { useRef, useState, useEffect } from "react";

import Header from "./Header";
import ActionButton from "./ActionButton";
import ContentWrapper from "./ContentWrapper";

import backgroundImage from "../assets/img/backgrounds/landingBG2.png";
import graphicMobile from "../assets/img/backgrounds/backgroundMobile.png";
import waveLineRed from "../assets/img/backgrounds/waveLineRed.png";
import logo from "../assets/img/logo/qhacksCrown-colored.svg";
import word from "../assets/img/logo/qhacksWordmark-colored.svg";

const landingCSS = {
  width: "100%",
  height: "730px",
  marginTop: "120px",
  background: `url(${backgroundImage}) no-repeat center center`,
  backgroundColor: "#fff",
  backgroundSize: "auto 650px",
  "@media (min-width: 820px) and (max-width: 1200px)": {
    backgroundSize: "auto 550px"
  },
  "@media(max-width: 820px)": {
    height: "900px",
    marginTop: "50px",
    background: `url(${waveLineRed}) no-repeat center bottom`
  }
};

const applyButtonCSS = {
  alignItems: "center",
  position: "relative",
  margin: "40px 0 40px auto",
  "@media(max-width: 820px)": {
    margin: "30px auto 45px auto",
    padding: "5px 10px 5px 10px"
  }
};

function Landing() {

  const [timerDays, setTimerDays] = useState("00");
  const [timerHours, setTimerHours] = useState("00");
  const [timerMinutes, setTimerMinutes] = useState("00");
  const [timerSeconds, setTimerSeconds] = useState("00");

  let interval = useRef;

  const startTimer = () => {
      const countDownDate = new Date('November 25 2020 17:00:00').getTime();

      interval = setInterval(()=>{
        const now = new Date().getTime();
        const distance = countDownDate - now;

        const days = Math.floor(distance/(1000*60*60*24));
        const hours = Math.floor((distance%(1000*60*60*24)/(1000*60*60)));
        const minutes = Math.floor((distance%(1000*60*60)/(1000*60)));
        const seconds = Math.floor((distance%(1000*60)) / 1000);

        if (distance < 0){
          clearInterval(interval.current);
        }else{
          setTimerDays(days);
          setTimerHours(hours);
          setTimerMinutes(minutes);
          setTimerSeconds(seconds);
        }

      }, 1000);
  };

useEffect(()=>{
  startTimer();
  return() =>{
    clearInterval(interval.current);
  };
});

  return (

      <ContentWrapper>

          <h2
            data-cy="qhacks-information"
            css={{
              zIndex: "2",
              color: "#000000",
              fontWeight: 600,
              fontSize: "22px",
              marginTop: "20px",
              marginBottom: "20px",
              "@media (min-width: 820px) and (max-width: 1200px)": {
                fontSize: "20px"
              },
              "@media(max-width: 820px)": {
                fontSize: "15px",
                fontWeight: 600,
                paddingBottom: "20px"
              }
            }}
          >
            Queen’s University • January 22nd - 24th, 2021

            Queen’s University’s annual hackathon.

            Join us for an unforgettable experience!

          {/*<ActionButton
            dataCy="apply-button"
            backgroundColor="#00205B"
            foregroundColor="#ffffff"
            hoverBackgroundColor="#00205B"
            hoverForegroundColor="#ffffff"
            style={applyButtonCSS}
            type="rounded"
          >

Applications Opening in

{timerDays}

days

              :

{timerHours}

hours

              :

{timerMinutes}

minutes

              :

{timerSeconds}

seconds

              </ActionButton>*/}
           <ActionButton
            dataCy="apply-button"
            backgroundColor="#00205B"
            foregroundColor="#ffffff"
            hoverBackgroundColor="#16498c"
            hoverForegroundColor="#ffffff"
            style={applyButtonCSS}
            type="rounded"
          >
            Applications Have Been Closed
          </ActionButton>

      </ContentWrapper>

  );
}

export default Landing;
<commit_msg>reverted change<commit_after>import React, { useRef, useState, useEffect } from "react";

import Header from "./Header";
import ActionButton from "./ActionButton";
import ContentWrapper from "./ContentWrapper";

import backgroundImage from "../assets/img/backgrounds/landingBG2.png";
import graphicMobile from "../assets/img/backgrounds/backgroundMobile.png";
import waveLineRed from "../assets/img/backgrounds/waveLineRed.png";
import logo from "../assets/img/logo/qhacksCrown-colored.svg";
import word from "../assets/img/logo/qhacksWordmark-colored.svg";

const landingCSS = {
  width: "100%",
  height: "730px",
  marginTop: "120px",
  background: `url(${backgroundImage}) no-repeat center center`,
  backgroundColor: "#fff",
  backgroundSize: "auto 650px",
  "@media (min-width: 820px) and (max-width: 1200px)": {
    backgroundSize: "auto 550px"
  },
  "@media(max-width: 820px)": {
    height: "900px",
    marginTop: "50px",
    background: `url(${waveLineRed}) no-repeat center bottom`
  }
};

const applyButtonCSS = {
  alignItems: "center",
  position: "relative",
  margin: "40px 0 40px auto",
  "@media(max-width: 820px)": {
    margin: "30px auto 45px auto",
    padding: "5px 10px 5px 10px"
  }
};

function Landing() {

  const [timerDays, setTimerDays] = useState("00");
  const [timerHours, setTimerHours] = useState("00");
  const [timerMinutes, setTimerMinutes] = useState("00");
  const [timerSeconds, setTimerSeconds] = useState("00");

  let interval = useRef;

  const startTimer = () => {
      const countDownDate = new Date('November 25 2020 17:00:00').getTime();

      interval = setInterval(()=>{
        const now = new Date().getTime();
        const distance = countDownDate - now;

        const days = Math.floor(distance/(1000*60*60*24));
        const hours = Math.floor((distance%(1000*60*60*24)/(1000*60*60)));
        const minutes = Math.floor((distance%(1000*60*60)/(1000*60)));
        const seconds = Math.floor((distance%(1000*60)) / 1000);

        if (distance < 0){
          clearInterval(interval.current);
        }else{
          setTimerDays(days);
          setTimerHours(hours);
          setTimerMinutes(minutes);
          setTimerSeconds(seconds);
        }

      }, 1000);
  };

useEffect(()=>{
  startTimer();
  return() =>{
    clearInterval(interval.current);
  };
});

  return (

      <ContentWrapper>

          <h2
            data-cy="qhacks-information"
            css={{
              zIndex: "2",
              color: "#000000",
              fontWeight: 600,
              fontSize: "22px",
              marginTop: "20px",
              marginBottom: "20px",
              "@media (min-width: 820px) and (max-width: 1200px)": {
                fontSize: "20px"
              },
              "@media(max-width: 820px)": {
                fontSize: "15px",
                fontWeight: 600,
                paddingBottom: "20px"
              }
            }}
          >
            Queen’s University • January 22nd - 24th, 2021

            Queen’s University’s annual hackathon.

            Join us for an unforgettable experience!

          {/*<ActionButton
            dataCy="apply-button"
            backgroundColor="#00205B"
            foregroundColor="#ffffff"
            hoverBackgroundColor="#00205B"
            hoverForegroundColor="#ffffff"
            style={applyButtonCSS}
            type="rounded"
          >

Applications Opening in

{timerDays}

days

              :

{timerHours}

hours

              :

{timerMinutes}

minutes

              :

{timerSeconds}

seconds

              </ActionButton>*/}
           <ActionButton
            dataCy="apply-button"
            backgroundColor="#00205B"
            foregroundColor="#ffffff"
            hoverBackgroundColor="#16498c"
            hoverForegroundColor="#ffffff"
            style={applyButtonCSS}
            link="https://app.qhacks.io/"
            type="rounded"
          >
            Apply Now
          </ActionButton>

      </ContentWrapper>

  );
}

export default Landing;
<|endoftext|>


<commit_before>"use strict";

// Use the fastest possible means to execute a task in a future turn
// of the event loop.

// linked list of tasks (single, with head node)
var head = {task: void 0, next: null};
var tail = head;
var flushing = false;
var requestFlush = void 0;
var hasSetImmediate = typeof setImmediate === "function";
var domain;

// Avoid shims from browserify.
// The existence of `global` in browsers is guaranteed by browserify.
var process = global.process;

// Note that some fake-Node environments,
// like the Mocha test runner, introduce a `process` global.
var isNodeJS = !!process && ({}).toString.call(process) === "[object process]";

function flush() {
    /* jshint loopfunc: true */

    while (head.next) {
        head = head.next;
        var task = head.task;
        head.task = void 0;

        try {
            task();

        } catch (e) {
            if (isNodeJS) {
                // In node, uncaught exceptions are considered fatal errors.
                // Re-throw them to interrupt flushing!

                // Ensure continuation if an uncaught exception is suppressed
                // listening process.on("uncaughtException") or domain("error").
                requestFlush();

                throw e;

            } else {
                // In browsers, uncaught exceptions are not fatal.
                // Re-throw them asynchronously to avoid slow-downs.
                setTimeout(function () {
                    throw e;
                }, 0);
            }
        }
    }

    flushing = false;
}

if (isNodeJS) {
    // Node.js
    requestFlush = function () {
        // Ensure flushing is not bound to any domain.
        var currentDomain = process.domain;
        if (currentDomain) {
            domain = domain || (1,require)("domain");
            domain.active = process.domain = null;
        }

        // Avoid tick recursion - use setImmediate if it exists.
        if (flushing && hasSetImmediate) {
            setImmediate(flush);
        } else {
            process.nextTick(flush);
        }

        if (currentDomain) {
            domain.active = process.domain = currentDomain;
        }
    };

} else if (hasSetImmediate) {
    // In IE10, or https://github.com/NobleJS/setImmediate
    requestFlush = function () {
        setImmediate(flush);
    };

} else if (typeof MessageChannel !== "undefined") {
    // modern browsers
    // http://www.nonblocking.io/2011/06/windownexttick.html
    var channel = new MessageChannel();
    channel.port1.onmessage = flush;
    requestFlush = function () {
        channel.port2.postMessage(0);
    };

} else {
    // old browsers
    requestFlush = function () {
        setTimeout(flush, 0);
    };
}

function asap(task) {
    if (isNodeJS && process.domain) {
        task = process.domain.bind(task);
    }

    tail = tail.next = {task: task, next: null};

    if (!flushing) {
        requestFlush();
        flushing = true;
    }
};

module.exports = asap;
<commit_msg>Fix intermittent Safari bug<commit_after>"use strict";

// Use the fastest possible means to execute a task in a future turn
// of the event loop.

// linked list of tasks (single, with head node)
var head = {task: void 0, next: null};
var tail = head;
var flushing = false;
var requestFlush = void 0;
var hasSetImmediate = typeof setImmediate === "function";
var domain;

// Avoid shims from browserify.
// The existence of `global` in browsers is guaranteed by browserify.
var process = global.process;

// Note that some fake-Node environments,
// like the Mocha test runner, introduce a `process` global.
var isNodeJS = !!process && ({}).toString.call(process) === "[object process]";

function flush() {
    /* jshint loopfunc: true */

    while (head.next) {
        head = head.next;
        var task = head.task;
        head.task = void 0;

        try {
            task();

        } catch (e) {
            if (isNodeJS) {
                // In node, uncaught exceptions are considered fatal errors.
                // Re-throw them to interrupt flushing!

                // Ensure continuation if an uncaught exception is suppressed
                // listening process.on("uncaughtException") or domain("error").
                requestFlush();

                throw e;

            } else {
                // In browsers, uncaught exceptions are not fatal.
                // Re-throw them asynchronously to avoid slow-downs.
                setTimeout(function () {
                    throw e;
                }, 0);
            }
        }
    }

    flushing = false;
}

if (isNodeJS) {
    // Node.js
    requestFlush = function () {
        // Ensure flushing is not bound to any domain.
        var currentDomain = process.domain;
        if (currentDomain) {
            domain = domain || (1,require)("domain");
            domain.active = process.domain = null;
        }

        // Avoid tick recursion - use setImmediate if it exists.
        if (flushing && hasSetImmediate) {
            setImmediate(flush);
        } else {
            process.nextTick(flush);
        }

        if (currentDomain) {
            domain.active = process.domain = currentDomain;
        }
    };

} else if (hasSetImmediate) {
    // In IE10, or https://github.com/NobleJS/setImmediate
    requestFlush = function () {
        setImmediate(flush);
    };

} else if (typeof MessageChannel !== "undefined") {
    // modern browsers
    // http://www.nonblocking.io/2011/06/windownexttick.html
    var channel = new MessageChannel();
    // At least Safari Version 6.0.5 (8536.30.1) intermittently cannot create
    // working message ports the first time a page loads.
    channel.port1.onmessage = function () {
        requestFlush = requestPortFlush;
        channel.port1.onmessage = flush;
        flush();
    };
    var requestPortFlush = function () {
        // Opera requires us to provide a message payload, regardless of
        // whether we use it.
        channel.port2.postMessage(0);
    };
    requestFlush = function () {
        setTimeout(flush, 0);
        requestPortFlush();
    };

} else {
    // old browsers
    requestFlush = function () {
        setTimeout(flush, 0);
    };
}

function asap(task) {
    if (isNodeJS && process.domain) {
        task = process.domain.bind(task);
    }

    tail = tail.next = {task: task, next: null};

    if (!flushing) {
        requestFlush();
        flushing = true;
    }
};

module.exports = asap;
<|endoftext|>


<commit_before>describe("cdb.geo.ui.layer_selector", function() {

  describe("cdb.geo.ui.layer_selector", function() {

    var view;

    beforeEach(function() {
      view  = new cdb.geo.ui.LayerSelector({
      template: _.template('Visible layers
<%= count %>
')
      });
    });

    it("should have a dropdown", function() {
      view.render();
      //expect(view.dropdown).toBeDefined();
    });

  });

  describe("cdb.geo.ui.layer", function() {
    describe("model", function() {

      var model;

      beforeEach(function() {
        model = new cdb.geo.ui.Layer();
      });

      it("should be disabled by default", function() {
        expect(model.get("disabled")).toBeTruthy();
      });

      it("shouldn't be selected by default", function() {
        expect(model.get("selected")).toBeFalsy();
      });

    });

    describe("view", function() {

      var spyEvent, view, spy;

      beforeEach(function() {

        spy = {
          switchChanged: function() {}
        };

        spyEvent = spyOn(spy, "switchChanged");

        view  = new cdb.geo.ui.LayerView({
          name: "Layer name",
          template: '<%= name %> '
        }).bind("switchChanged", spy.switchChanged, spy);

      });

      it("should change the select status when the switch button is clicked", function() {
        view.render();
        view.$el.find(".switch").click();
        expect(view.model.get("selected")).toBeTruthy();
        expect(view.model.get("selected")).toBeTruthy();
      });

      it("should trigger a switchChanged event when the switch button is clicked", function() {
        view.render();
        view.$el.find(".switch").click();

        expect(spyEvent).toHaveBeenCalledWith(true);
      });

      it("should toggle the enabled/disabled classes when the switch button is clicked", function() {
        view.render();
        view.$el.find(".switch").click();

        expect(view.$el.find(".switch").hasClass("enabled")).toBeTruthy();
        expect(view.$el.find(".switch").hasClass("disabled")).toBeFalsy();

        view.$el.find(".switch").click();

        expect(view.$el.find(".switch").hasClass("enabled")).toBeFalsy();
        expect(view.$el.find(".switch").hasClass("disabled")).toBeTruthy();

      });

    });

  });

});
<commit_msg>Removes test<commit_after>describe("cdb.geo.ui.layer_selector", function() {

  describe("cdb.geo.ui.layer_selector", function() {

    var view;

    beforeEach(function() {
      view  = new cdb.geo.ui.LayerSelector({
      template: _.template('Visible layers
<%= count %>
')
      });
    });

    //it("should have a dropdown", function() {
      //view.render();
      //expect(view.dropdown).toBeDefined();
    //});

  });

  describe("cdb.geo.ui.layer", function() {
    describe("model", function() {

      var model;

      beforeEach(function() {
        model = new cdb.geo.ui.Layer();
      });

      it("should be disabled by default", function() {
        expect(model.get("disabled")).toBeTruthy();
      });

      it("shouldn't be selected by default", function() {
        expect(model.get("selected")).toBeFalsy();
      });

    });

    describe("view", function() {

      var spyEvent, view, spy;

      beforeEach(function() {

        spy = {
          switchChanged: function() {}
        };

        spyEvent = spyOn(spy, "switchChanged");

        view  = new cdb.geo.ui.LayerView({
          name: "Layer name",
          template: '<%= name %> '
        }).bind("switchChanged", spy.switchChanged, spy);

      });

      it("should change the select status when the switch button is clicked", function() {
        view.render();
        view.$el.find(".switch").click();
        expect(view.model.get("selected")).toBeTruthy();
        expect(view.model.get("selected")).toBeTruthy();
      });

      it("should trigger a switchChanged event when the switch button is clicked", function() {
        view.render();
        view.$el.find(".switch").click();

        expect(spyEvent).toHaveBeenCalledWith(true);
      });

      it("should toggle the enabled/disabled classes when the switch button is clicked", function() {
        view.render();
        view.$el.find(".switch").click();

        expect(view.$el.find(".switch").hasClass("enabled")).toBeTruthy();
        expect(view.$el.find(".switch").hasClass("disabled")).toBeFalsy();

        view.$el.find(".switch").click();

        expect(view.$el.find(".switch").hasClass("enabled")).toBeFalsy();
        expect(view.$el.find(".switch").hasClass("disabled")).toBeTruthy();

      });

    });

  });

});
<|endoftext|>


<commit_before>const jsonfile = require('jsonfile')
const minimist = require('minimist')

const dbConn = require('./../lib/dbConn')
const dbUtil = require('./../lib/dbUtil')
const db = dbConn.create(console)

const OrganizationOps = require('./../lib/organizationOps')
const organizationOps = OrganizationOps(db.pool, console)

const PolicyOps = require('./../lib/policyOps')
const policyOps = PolicyOps(db.pool, console)

const exit = (message, db) => {
  console.log(message)
  if (db) {
    db.shutdown({}, () => {
      process.exit()
    })
  }

  process.exit()
}

const argv = minimist(process.argv.slice(2))

const organizationId = argv.org
if (!organizationId) {
  exit('Please provide the organization id')
}

const source = argv.src || argv._[0]
if (!source) {
  exit('Please provide a file')
}

const input = jsonfile.readFileSync(source, { throws: false })
if (!input || !input.policies) {
  exit('Invalid json')
}

organizationOps.readById(organizationId, (error, organization) => {
  if (error || !organization) {
    exit('Please provide a valid organization', db)
  }

  const tasks = input.policies.map((policy) => {
    const policyData = {
      version: policy.version,
      name: policy.name,
      organizationId: organizationId,
      statements: JSON.stringify({ Statement: policy.statements })
    }
    return (job, next) => policyOps.createPolicy(policyData, next)
  })

  dbUtil.withTransaction(db.pool, tasks, (err, x) => {
    if (err) {
      exit(err, db)
    }

    db.shutdown({}, () => {
      console.log('Done!')
    })
  })
})
<commit_msg>added file format in the script<commit_after>/*
 *  {
 *    "policies": [
 *      {
 *        "version": "",
 *        "name": "policy name",
 *        "statements": [
 *          {
 *            "Effect": "Allow/Deny",
 *            "Action": "act",
 *            "Resource": "res"
 *          },
 *          { ... }
 *        ]
 *      },
 *      { ... }
 *    ]
 *  }
 */

const jsonfile = require('jsonfile')
const minimist = require('minimist')

const dbConn = require('./../lib/dbConn')
const dbUtil = require('./../lib/dbUtil')
const db = dbConn.create(console)

const OrganizationOps = require('./../lib/organizationOps')
const organizationOps = OrganizationOps(db.pool, console)

const PolicyOps = require('./../lib/policyOps')
const policyOps = PolicyOps(db.pool, console)

const exit = (message, db) => {
  console.log(message)
  if (db) {
    db.shutdown({}, () => {
      process.exit()
    })
  }

  process.exit()
}

const argv = minimist(process.argv.slice(2))

const organizationId = argv.org
if (!organizationId) {
  exit('Please provide the organization id')
}

const source = argv.src || argv._[0]
if (!source) {
  exit('Please provide a file')
}

const input = jsonfile.readFileSync(source, { throws: false })
if (!input || !input.policies) {
  exit('Invalid json')
}

organizationOps.readById(organizationId, (error, organization) => {
  if (error || !organization) {
    exit('Please provide a valid organization', db)
  }

  const tasks = input.policies.map((policy) => {
    const policyData = {
      version: policy.version,
      name: policy.name,
      organizationId: organizationId,
      statements: JSON.stringify({ Statement: policy.statements })
    }
    return (job, next) => policyOps.createPolicy(policyData, next)
  })

  dbUtil.withTransaction(db.pool, tasks, (err, x) => {
    if (err) {
      exit(err, db)
    }

    db.shutdown({}, () => {
      console.log('Done!')
    })
  })
})
<|endoftext|>


<commit_before>// @flow

// Vendor
import React from 'react';
import { Link } from 'react-router-dom';

// Material-UI components
import AppBar from 'material-ui/AppBar';
import Drawer from 'material-ui/Drawer';
import MenuItem from 'material-ui/MenuItem';

/* ------------------------------------------------------------------
   --------------------------- COMPONENT ----------------------------
	 ------------------------------------------------------------------ */

type Props = {
	handleClose: () => void,
	handleSetVisible: boolean => void,
	menuVisible: boolean
};

/**
 * SideMenu drawer component.
 * @param {function()} handleClose from {@link App#handleClose}
 * @param {function(boolean)} handleSetVisible from {@link App#handleSetVisible}
 * @param {boolean} menuVisible 			whether the menu is visible
 */
const SideBar = (props: Props) => {
	const { menuVisible, handleClose, handleSetVisible } = props;

	return (
		<Drawer
			className="side-bar"
			docked={false}
			width={200}
			open={menuVisible}
			onRequestChange={menuVisible => handleSetVisible(menuVisible)}
		>
			<AppBar
				className="side-bar-head"
				title="Flybrary"
				showMenuIconButton={false}
			/>

			<MenuItem
				className="side-bar-link"
				onTouchTap={handleClose}
				containerElement={<Link to="/" />}
			>
				Home
			</MenuItem>

			<MenuItem
				className="side-bar-link"
				onTouchTap={handleClose}
				containerElement={<Link to="/shelves" />}
			>
				Shelves
			</MenuItem>

			<MenuItem
				className="side-bar-link"
				onTouchTap={handleClose}
				containerElement={<Link to="/search" />}
			>
				Search
			</MenuItem>

			<MenuItem
				className="side-bar-link"
				onTouchTap={handleClose}
				containerElement={<Link to="/move" />}
			>
				Move
			</MenuItem>
		</Drawer>
	);
};

export default SideBar;
<commit_msg>remove unnecessary lambda from SideBar<commit_after>// @flow

// Vendor
import React from 'react';
import { Link } from 'react-router-dom';

// Material-UI components
import AppBar from 'material-ui/AppBar';
import Drawer from 'material-ui/Drawer';
import MenuItem from 'material-ui/MenuItem';

/* ------------------------------------------------------------------
   --------------------------- COMPONENT ----------------------------
	 ------------------------------------------------------------------ */

type Props = {
	handleClose: () => void,
	handleSetVisible: boolean => void,
	menuVisible: boolean
};

/**
 * SideMenu drawer component.
 * @param {function()} handleClose from {@link App#handleClose}
 * @param {function(boolean)} handleSetVisible from {@link App#handleSetVisible}
 * @param {boolean} menuVisible 			whether the menu is visible
 */
const SideBar = (props: Props) => {
	const { menuVisible, handleClose, handleSetVisible } = props;

	return (
		<Drawer
			className="side-bar"
			docked={false}
			width={200}
			open={menuVisible}
			onRequestChange={handleSetVisible}
		>
			<AppBar
				className="side-bar-head"
				title="Flybrary"
				showMenuIconButton={false}
			/>

			<MenuItem
				className="side-bar-link"
				onTouchTap={handleClose}
				containerElement={<Link to="/" />}
			>
				Home
			</MenuItem>

			<MenuItem
				className="side-bar-link"
				onTouchTap={handleClose}
				containerElement={<Link to="/shelves" />}
			>
				Shelves
			</MenuItem>

			<MenuItem
				className="side-bar-link"
				onTouchTap={handleClose}
				containerElement={<Link to="/search" />}
			>
				Search
			</MenuItem>

			<MenuItem
				className="side-bar-link"
				onTouchTap={handleClose}
				containerElement={<Link to="/move" />}
			>
				Move
			</MenuItem>
		</Drawer>
	);
};

export default SideBar;
<|endoftext|>