<commit_before>"use strict";

function $(id){ return document.getElementById(id); }

function showElement( e ) { e.style.visibility = "visible"; }
function hideElement( e ) { e.style.visibility = "hidden"; }

function PPUtils() {}

PPUtils.log = function ( output ) {
    if (window.console ) {
      console.log(output);
    }
}

PPUtils.objectImplementsMethod = function ( obj, method ) {

  if (obj == null || !obj[method] || typeof obj[method] !== 'function') {
    return false;
  }

  return true;
}

PPUtils.objectImplementsMethods = function ( obj, methodArray ) {
  for (var i = 0; i < methodArray.length; i++) {
    if ( PPUtils.objectImplementsMethod(obj, methodArray[i]) == false) {
      return false;
    }
  }
  return true;
}

PPUtils.setElementAttributes = function ( element, attributeArray, valuesArray) {
   for( var i = 0; i < attributeArray.length; i ++ ) {
     element.setAttribute( attributeArray[i], valuesArray[i]);
   }
}

// References:
//   http://krasimirtsonev.com/blog/article/object-oriented-programming-oop-in-javascript-extending-Inheritance-classes
//   http://peter.michaux.ca/articles/class-based-inheritance-in-javascript
PPUtils.extend = function (ChildClass, ParentClass) {
    var parent = new ParentClass();
    ChildClass.prototype = parent;
    ChildClass.prototype.superclass = parent.constructor;
    ChildClass.prototype.constructor = ChildClass;
    ChildClass.superclass =  ParentClass;
    ChildClass.superproto = ParentClass.prototype;
}

// Returns the callback so that it can be removed later
PPUtils.bindTextField = function(event, element, boundObj, objCallback) {

  var callback = function receive(evt) {
    boundObj[objCallback](element, evt);
  }

  if ( typeof element.addEventListener != "undefined" ) {
    element.addEventListener(event, callback, false);
  } else if ( typeof element.attachEvent != "undefined" ) { // Supports IE < 9
    element.attachEvent(event, callback);
  }

  return callback;
}
PPUtils.bind = function(event, element, callback) {
  if ( typeof element.addEventListener != "undefined" ) {
    element.addEventListener(event, callback, false);
  } else if ( typeof element.attachEvent != "undefined" ) { // Supports IE < 9
    element.attachEvent(event, callback);
  }
}

PPUtils.notifyListeners = function (listenersArray, listenerMethod,value ) {
  for (var i = 0 ; i < listenersArray.length; i++) {
    var obj = listenersArrays[i];
    obj[listenerMethod](value);
  }
}
<commit_msg>add isPowerOf2<commit_after>"use strict";

function $(id){ return document.getElementById(id); }

function showElement( e ) { e.style.visibility = "visible"; }
function hideElement( e ) { e.style.visibility = "hidden"; }

function PPUtils() {}

PPUtils.log = function ( output ) {
    if (window.console ) {
      console.log(output);
    }
}

PPUtils.objectImplementsMethod = function ( obj, method ) {

  if (obj == null || !obj[method] || typeof obj[method] !== 'function') {
    return false;
  }

  return true;
}

PPUtils.objectImplementsMethods = function ( obj, methodArray ) {
  for (var i = 0; i < methodArray.length; i++) {
    if ( PPUtils.objectImplementsMethod(obj, methodArray[i]) == false) {
      return false;
    }
  }
  return true;
}

PPUtils.setElementAttributes = function ( element, attributeArray, valuesArray) {
   for( var i = 0; i < attributeArray.length; i ++ ) {
     element.setAttribute( attributeArray[i], valuesArray[i]);
   }
}

// References:
//   http://krasimirtsonev.com/blog/article/object-oriented-programming-oop-in-javascript-extending-Inheritance-classes
//   http://peter.michaux.ca/articles/class-based-inheritance-in-javascript
PPUtils.extend = function (ChildClass, ParentClass) {
    var parent = new ParentClass();
    ChildClass.prototype = parent;
    ChildClass.prototype.superclass = parent.constructor;
    ChildClass.prototype.constructor = ChildClass;
    ChildClass.superclass =  ParentClass;
    ChildClass.superproto = ParentClass.prototype;
}

// Returns the callback so that it can be removed later
PPUtils.bindTextField = function(event, element, boundObj, objCallback) {

  var callback = function receive(evt) {
    boundObj[objCallback](element, evt);
  }

  if ( typeof element.addEventListener != "undefined" ) {
    element.addEventListener(event, callback, false);
  } else if ( typeof element.attachEvent != "undefined" ) { // Supports IE < 9
    element.attachEvent(event, callback);
  }

  return callback;
}
PPUtils.bind = function(event, element, callback) {
  if ( typeof element.addEventListener != "undefined" ) {
    element.addEventListener(event, callback, false);
  } else if ( typeof element.attachEvent != "undefined" ) { // Supports IE < 9
    element.attachEvent(event, callback);
  }
}

PPUtils.isPowerOf2 = function(x) {
  return x == 1 || x == 2 || x == 4 || x == 8 || x == 16 || x == 32 ||
     x == 64 || x == 128 || x == 256 || x == 512 || x == 1024 ||
                x == 2048 || x == 4096 || x == 8192 || x == 16384 ||
                x == 32768 || x == 65536 || x == 131072 || x == 262144 ||
                x == 524288 || x == 1048576 || x == 2097152 ||
                x == 4194304 || x == 8388608 || x == 16777216 ||
                x == 33554432 || x == 67108864 || x == 134217728 ||
                x == 268435456 || x == 536870912 || x == 1073741824 ||
                x == 2147483648;
}

PPUtils.notifyListeners = function (listenersArray, listenerMethod,value ) {
  for (var i = 0 ; i < listenersArray.length; i++) {
    var obj = listenersArrays[i];
    obj[listenerMethod](value);
  }
}
<|endoftext|>


<commit_before>var spaceship;
var blockSize;
var bullets;
var allowedBullets = 1;
var invasionWave;
var world;
var invaderSpeed = 2;

function setup() {
  createCanvas(400, 400);
  blockSize = 5;

  spaceship = new Spaceship();
  bullets = [];
  invasionWave = new InvasionWave(5,6);
  world = new World(4);
  // frameRate(10);
}

function draw() {
  background(0);
  spaceship.draw();

  let bulletHit;
  for (var i = 0; i < bullets.length; i++) {
    bullets[i].draw();
    bullets[i].tick();

    if (bullets[i].y < 0){
      bullets.splice(i, 1);
      continue;
    }

    bulletHit = world.collisionTest(bullets[i]);
    if (bulletHit) {
      bullets.splice(i, 1);
      continue;
    }

    bulletHit = invasionWave.collisionTest(bullets[i]);
    if (bulletHit) {
      bullets.splice(i, 1);
    }
  }

  world.draw();

  invasionWave.draw();
  invasionWave.tick();
}

function keyPressed() {
  if (keyCode === RIGHT_ARROW) {
    spaceship.move(RIGHT_ARROW);
  } else if (keyCode === LEFT_ARROW) {
    spaceship.move(LEFT_ARROW);
  } else if (keyCode === UP_ARROW) {
    spaceship.fireBullet();
  }
}

function xyInRect(x, y, rectX, rectY, rectWidth, rectHeight){
  return (rectX <= x && x <= (rectX + rectWidth)) &&
         (rectY <= y && y <= (rectY + rectHeight));
}

class Spaceship {
  constructor(){
    this.x = width/2;
    this.y = height - 40;
  }

  draw(){
    rectMode(CENTER);
    fill(30,200,230);
    rect(this.x, this.y, 30, 10);
  }

  move(direction){
    if (keyCode === RIGHT_ARROW) {
      this.x += 10;
    } else if (keyCode === LEFT_ARROW) {
      this.x -= 10;
    }
  }

  fireBullet(){
    if (bullets.length >= allowedBullets){
      return;
    }
    bullets.push(new Bullet(this.x, this.y - 10));
  }
}

class Bullet {
  constructor(x, y){
    this.x = x;
    this.y = y;
  }

  draw(){
    rectMode(CENTER);
    fill(200,200,30);
    rect(this.x, this.y, 5, 10);
  }

  tick(){
    this.y -= 10;
  }
}

class World {
  constructor(numBases){
    this.bases = [];
    this.numBases = numBases;
    this.initBases();
  }

  initBases(){
    const y = spaceship.y - 50 - LandBase.height / 2;
    let margins = 40;
    let dynamicSpacing = (width - 2 * margins - 4 * LandBase.width) / (this.numBases - 1);
    let tmpX;

    for (var i = 0; i < this.numBases; i++) {
      tmpX = margins + i * (LandBase.width + dynamicSpacing);
      this.bases.push(new LandBase(tmpX, y));
    }
  }

  draw(){
    for (var i = 0; i < this.numBases; i++) {
      this.bases[i].draw();
    }
  }

  collisionTest(bullet){
    let tmpBase;
    for (var i = 0; i < this.numBases; i++) {
      tmpBase = this.bases[i];

      if (xyInRect(bullet.x, bullet.y,
            tmpBase.x, tmpBase.y, LandBase.width, LandBase.height))
      {
        return true;
      }
    }
  }
}

class LandBase {
  constructor(x, y){
    this.x = x;
    this.y = y;
  }

  static get width()      { return 40; }
  static get height()     { return 25; }

  draw(){
    rectMode(CORNER);
    fill(200,30,30);
    rect(this.x, this.y, LandBase.width, LandBase.height);
  }
}

class InvasionWave {
  constructor(rows, cols){
    this.rows = rows;
    this.cols = cols;

    this.direction = 1;
    this.framesOfMovementPerRow = 10;
    this.calcBounds();
    this.initInvaders();
  }

  calcBounds(){
    const range = width - InvasionWave.colSpacing;
    const numPotentialCols = floor(range / this.totalColumnWidth());
    this.minAllowedX = InvasionWave.colSpacing + this.framesOfMovementPerRow * invaderSpeed;
    this.maxAllowedX = this.minAllowedX + numPotentialCols * this.totalColumnWidth() - this.framesOfMovementPerRow * invaderSpeed;
  }

  totalColumnWidth(){
    return Invader.width + InvasionWave.colSpacing;
  }

  static get colSpacing()   { return 5; }
  static get rowSpacing()   { return 10; }

  initInvaders(){
    let baseX = this.minAllowedX + 3 * this.framesOfMovementPerRow;
    // let baseX = this.maxAllowedX - this.cols * this.totalColumnWidth() - 0.5 * Invader.width - 3 * this.framesOfMovementPerRow;
    // let baseX =  width - InvasionWave.colSpacing - 5 * (InvasionWave.colSpacing + Invader.width);
    let baseY = 40;
    let numPerRow = 6;

    let tmpX;
    let tmpY;
    this.invaders = []

    for (var i = 0; i < this.rows; i++) {
      this.invaders[i] = [];
      tmpY = baseY + i * (Invader.height + InvasionWave.rowSpacing);

      for (var j = 0; j < this.cols; j++) {
        tmpX = baseX + j * (Invader.width + InvasionWave.colSpacing);
        this.invaders[i][j] = new Invader(tmpX, tmpY);
      }
    }
  }

  draw(){
    this.debugMaxMinX();

    for (var i = 0; i < this.rows; i++) {
      for (var j = 0; j < this.cols; j++) {
        this.invaders[i][j].draw();
      }
    }
  }

  debugMaxMinX(){
    stroke(255, 255, 0);
    line(this.minAllowedX, 0, this.minAllowedX, height);
    line(this.maxAllowedX, 0, this.maxAllowedX, height);
    noStroke();
  }

  tick(){
    let bottomRow = this.bottomRowStillInvading();

    if (bottomRow == -1) {
      console.log("You won!!");
    }

    const rowMoving = this.rows - 1 - (floor((frameCount -1) / this.framesOfMovementPerRow) % this.rows);
    const maxMinX = this.getMaxMinX(rowMoving);
    if (this.direction == 1 && maxMinX[1] >= this.maxAllowedX){
      this.moveAllDown();
      this.direction = -1;
    } else if (this.direction == -1 && maxMinX[0] <= this.minAllowedX){
      this.moveAllDown();
      this.direction = 1;
    }

    for (var j = 0; j < this.cols; j++) {
      this.invaders[rowMoving][j].move(this.direction);
    }
  }

  moveAllDown(){
    for (var i = 0; i < this.rows; i++) {
      for (var j = 0; j < this.cols; j++) {
        this.invaders[i][j].moveDown(Invader.height + InvasionWave.rowSpacing);
      }
    }
  }

  collisionTest(bullet){
    let tmpInvader;
    for (var i = 0; i < this.rows; i++) {
      for (var j = 0; j < this.cols; j++) {
        tmpInvader = this.invaders[i][j];
        if (tmpInvader.state == Invader.STATE_BLOWN_UP) {
          continue;
        }
        if (xyInRect(bullet.x, bullet.y,
              tmpInvader.x, tmpInvader.y, Invader.width, Invader.height))
        {
          tmpInvader.state = Invader.STATE_BLOWN_UP;
          return true;
        }
      }
    }
  }

  bottomRowStillInvading(){
    let tmpBottomRow = -1;
    let tmpInvader;
    for (var i = 0; i < this.rows; i++) {
      for (var j = 0; j < this.cols; j++) {
        tmpInvader = this.invaders[i][j];
        if (this.invaders[i][j].state == Invader.STATE_INVADING) {
          tmpBottomRow = i;
          break;
        }
      }
    }
    return tmpBottomRow;
  }

  getMaxMinX(aboveRow){
    let constraints = [width, 0]; // (min, max)
    let tmpInvader;
    for (var i = 0; i < this.rows; i++) {
      if (i >= aboveRow){
        break;
      }
      for (var j = 0; j < this.cols; j++) {
        tmpInvader = this.invaders[i][j];
        if (tmpInvader.state == Invader.STATE_BLOWN_UP) {
          continue;
        }
        constraints[0] = min(constraints[0], tmpInvader.x);
        constraints[1] = max(constraints[1], tmpInvader.x + Invader.width);
      }
    }
    return constraints;
  }
}

class Invader {
  constructor(x, y){
    this.x = x;
    this.y = y;
    this.updateColor();
    this.state = Invader.STATE_INVADING;
  }

  static get width()    { return 30; }
  static get height()   { return 30; }

  static get STATE_INVADING()   { return 0; }
  static get STATE_BLOWN_UP()   { return 1; }

  static get colors() {
    return [
      color(200,30,200),
      color(200, 200, 30)
    ];
  }

  draw(){
    if (this.state == Invader.STATE_BLOWN_UP){
      return;
    }
    rectMode(CORNER);
    noStroke();
    fill(this.color);
    rect(this.x, this.y, Invader.width, Invader.height);
  }

  move(direction){
    this.x += 1 * direction * invaderSpeed;
  }

  updateColor(){
    this.color = lerpColor(Invader.colors[0], Invader.colors[1], this.y / (height - 120));
  }

  moveDown(deltaY){
    this.y += deltaY;
    this.updateColor();
  }
}
<commit_msg>p5js/space-invaders - Add difficult setting for bullet speed<commit_after>var spaceship;
var blockSize;
var bullets;
var invasionWave;
var world;

// Difficulty Settings
var allowedBullets = 1;
var invaderSpeed = 2;
var bulletSpeed = 5;

function setup() {
  createCanvas(400, 400);
  blockSize = 5;

  spaceship = new Spaceship();
  bullets = [];
  invasionWave = new InvasionWave(5,6);
  world = new World(4);
  // frameRate(10);
}

function draw() {
  background(0);
  spaceship.draw();

  let bulletHit;
  for (var i = 0; i < bullets.length; i++) {
    bullets[i].draw();
    bullets[i].tick();

    if (bullets[i].y < 0){
      bullets.splice(i, 1);
      continue;
    }

    bulletHit = world.collisionTest(bullets[i]);
    if (bulletHit) {
      bullets.splice(i, 1);
      continue;
    }

    bulletHit = invasionWave.collisionTest(bullets[i]);
    if (bulletHit) {
      bullets.splice(i, 1);
    }
  }

  world.draw();

  invasionWave.draw();
  invasionWave.tick();
}

function keyPressed() {
  if (keyCode === RIGHT_ARROW) {
    spaceship.move(RIGHT_ARROW);
  } else if (keyCode === LEFT_ARROW) {
    spaceship.move(LEFT_ARROW);
  } else if (keyCode === UP_ARROW) {
    spaceship.fireBullet();
  }
}

function xyInRect(x, y, rectX, rectY, rectWidth, rectHeight){
  return (rectX <= x && x <= (rectX + rectWidth)) &&
         (rectY <= y && y <= (rectY + rectHeight));
}

class Spaceship {
  constructor(){
    this.x = width/2;
    this.y = height - 40;
  }

  draw(){
    rectMode(CENTER);
    fill(30,200,230);
    rect(this.x, this.y, 30, 10);
  }

  move(direction){
    if (keyCode === RIGHT_ARROW) {
      this.x += 10;
    } else if (keyCode === LEFT_ARROW) {
      this.x -= 10;
    }
  }

  fireBullet(){
    if (bullets.length >= allowedBullets){
      return;
    }
    bullets.push(new Bullet(this.x, this.y - 10));
  }
}

class Bullet {
  constructor(x, y){
    this.x = x;
    this.y = y;
  }

  draw(){
    rectMode(CENTER);
    fill(200,200,30);
    rect(this.x, this.y, 5, 10);
  }

  tick(){
    this.y -= bulletSpeed;
  }
}

class World {
  constructor(numBases){
    this.bases = [];
    this.numBases = numBases;
    this.initBases();
  }

  initBases(){
    const y = spaceship.y - 50 - LandBase.height / 2;
    let margins = 40;
    let dynamicSpacing = (width - 2 * margins - 4 * LandBase.width) / (this.numBases - 1);
    let tmpX;

    for (var i = 0; i < this.numBases; i++) {
      tmpX = margins + i * (LandBase.width + dynamicSpacing);
      this.bases.push(new LandBase(tmpX, y));
    }
  }

  draw(){
    for (var i = 0; i < this.numBases; i++) {
      this.bases[i].draw();
    }
  }

  collisionTest(bullet){
    let tmpBase;
    for (var i = 0; i < this.numBases; i++) {
      tmpBase = this.bases[i];

      if (xyInRect(bullet.x, bullet.y,
            tmpBase.x, tmpBase.y, LandBase.width, LandBase.height))
      {
        return true;
      }
    }
  }
}

class LandBase {
  constructor(x, y){
    this.x = x;
    this.y = y;
  }

  static get width()      { return 40; }
  static get height()     { return 25; }

  draw(){
    rectMode(CORNER);
    fill(200,30,30);
    rect(this.x, this.y, LandBase.width, LandBase.height);
  }
}

class InvasionWave {
  constructor(rows, cols){
    this.rows = rows;
    this.cols = cols;

    this.direction = 1;
    this.framesOfMovementPerRow = 10;
    this.calcBounds();
    this.initInvaders();
  }

  calcBounds(){
    const range = width - InvasionWave.colSpacing;
    const numPotentialCols = floor(range / this.totalColumnWidth());
    this.minAllowedX = InvasionWave.colSpacing + this.framesOfMovementPerRow * invaderSpeed;
    this.maxAllowedX = this.minAllowedX + numPotentialCols * this.totalColumnWidth() - this.framesOfMovementPerRow * invaderSpeed;
  }

  totalColumnWidth(){
    return Invader.width + InvasionWave.colSpacing;
  }

  static get colSpacing()   { return 5; }
  static get rowSpacing()   { return 10; }

  initInvaders(){
    let baseX = this.minAllowedX + 3 * this.framesOfMovementPerRow;
    // let baseX = this.maxAllowedX - this.cols * this.totalColumnWidth() - 0.5 * Invader.width - 3 * this.framesOfMovementPerRow;
    // let baseX =  width - InvasionWave.colSpacing - 5 * (InvasionWave.colSpacing + Invader.width);
    let baseY = 40;
    let numPerRow = 6;

    let tmpX;
    let tmpY;
    this.invaders = []

    for (var i = 0; i < this.rows; i++) {
      this.invaders[i] = [];
      tmpY = baseY + i * (Invader.height + InvasionWave.rowSpacing);

      for (var j = 0; j < this.cols; j++) {
        tmpX = baseX + j * (Invader.width + InvasionWave.colSpacing);
        this.invaders[i][j] = new Invader(tmpX, tmpY);
      }
    }
  }

  draw(){
    this.debugMaxMinX();

    for (var i = 0; i < this.rows; i++) {
      for (var j = 0; j < this.cols; j++) {
        this.invaders[i][j].draw();
      }
    }
  }

  debugMaxMinX(){
    stroke(255, 255, 0);
    line(this.minAllowedX, 0, this.minAllowedX, height);
    line(this.maxAllowedX, 0, this.maxAllowedX, height);
    noStroke();
  }

  tick(){
    let bottomRow = this.bottomRowStillInvading();

    if (bottomRow == -1) {
      console.log("You won!!");
    }

    const rowMoving = this.rows - 1 - (floor((frameCount -1) / this.framesOfMovementPerRow) % this.rows);
    const maxMinX = this.getMaxMinX(rowMoving);
    if (this.direction == 1 && maxMinX[1] >= this.maxAllowedX){
      this.moveAllDown();
      this.direction = -1;
    } else if (this.direction == -1 && maxMinX[0] <= this.minAllowedX){
      this.moveAllDown();
      this.direction = 1;
    }

    for (var j = 0; j < this.cols; j++) {
      this.invaders[rowMoving][j].move(this.direction);
    }
  }

  moveAllDown(){
    for (var i = 0; i < this.rows; i++) {
      for (var j = 0; j < this.cols; j++) {
        this.invaders[i][j].moveDown(Invader.height + InvasionWave.rowSpacing);
      }
    }
  }

  collisionTest(bullet){
    let tmpInvader;
    for (var i = 0; i < this.rows; i++) {
      for (var j = 0; j < this.cols; j++) {
        tmpInvader = this.invaders[i][j];
        if (tmpInvader.state == Invader.STATE_BLOWN_UP) {
          continue;
        }
        if (xyInRect(bullet.x, bullet.y,
              tmpInvader.x, tmpInvader.y, Invader.width, Invader.height))
        {
          tmpInvader.state = Invader.STATE_BLOWN_UP;
          return true;
        }
      }
    }
  }

  bottomRowStillInvading(){
    let tmpBottomRow = -1;
    let tmpInvader;
    for (var i = 0; i < this.rows; i++) {
      for (var j = 0; j < this.cols; j++) {
        tmpInvader = this.invaders[i][j];
        if (this.invaders[i][j].state == Invader.STATE_INVADING) {
          tmpBottomRow = i;
          break;
        }
      }
    }
    return tmpBottomRow;
  }

  getMaxMinX(aboveRow){
    let constraints = [width, 0]; // (min, max)
    let tmpInvader;
    for (var i = 0; i < this.rows; i++) {
      if (i >= aboveRow){
        break;
      }
      for (var j = 0; j < this.cols; j++) {
        tmpInvader = this.invaders[i][j];
        if (tmpInvader.state == Invader.STATE_BLOWN_UP) {
          continue;
        }
        constraints[0] = min(constraints[0], tmpInvader.x);
        constraints[1] = max(constraints[1], tmpInvader.x + Invader.width);
      }
    }
    return constraints;
  }
}

class Invader {
  constructor(x, y){
    this.x = x;
    this.y = y;
    this.updateColor();
    this.state = Invader.STATE_INVADING;
  }

  static get width()    { return 30; }
  static get height()   { return 30; }

  static get STATE_INVADING()   { return 0; }
  static get STATE_BLOWN_UP()   { return 1; }

  static get colors() {
    return [
      color(200,30,200),
      color(200, 200, 30)
    ];
  }

  draw(){
    if (this.state == Invader.STATE_BLOWN_UP){
      return;
    }
    rectMode(CORNER);
    noStroke();
    fill(this.color);
    rect(this.x, this.y, Invader.width, Invader.height);
  }

  move(direction){
    this.x += 1 * direction * invaderSpeed;
  }

  updateColor(){
    this.color = lerpColor(Invader.colors[0], Invader.colors[1], this.y / (height - 120));
  }

  moveDown(deltaY){
    this.y += deltaY;
    this.updateColor();
  }
}
<|endoftext|>


<commit_before>/**
 * Created by USER: tarso.
 * On         DATE: 04/05/17.
 * By         NAME: app.js.
 */

'use strict';

const consign = require('consign');
var   cfg1a   = {};
var   cfg1b   = {};
var   cfg2    = {};

consign()
  .include('config/users')
  .into(cfg1a)
;
consign()
  .include('config/dbs')
  .into(cfg1b)
;
consign()
  .include('config')
  .into(cfg2)
;

console.log('==== Users ====');
console.log('cfg1a                     :', cfg1a);
console.log('cfg1a.config.users.admin  :', cfg1a.config.users.admin);

console.log('==== DBs ====');
console.log('cfg1b                                     :', cfg1b);
console.log('cfg1b.config.dbs.dbMongo                  :', cfg1b.config.dbs.dbMongo);
console.log('cfg1b.config.dbs.dbMongo.credentials.user :', cfg1b.config.dbs.dbMongo.credentials.user);

console.log('==== cfg2 ====');
console.log('cfg2                     :', cfg2);

console.log('==== cfg2 Users ====');
console.log('cfg2.config.users.admin  :', cfg2.config.users.admin);

console.log('==== cfg2 DBs ====');
console.log('cfg2.config.dbs.dbMongo                  :', cfg2.config.dbs.dbMongo);
console.log('cfg2.config.dbs.dbMongo.credentials.user :', cfg2.config.dbs.dbMongo.credentials.user);
<commit_msg>Config file with Consig module<commit_after>/**
 * Created by USER: tarso.
 * On         DATE: 04/05/17.
 * By         NAME: app.js.
 */

'use strict';

const consign = require('consign');
var   cfg1a   = {};
var   cfg1a2  = {};
var   cfg1b   = {};
var   cfg2    = {};

consign()
  .include('config/users')
  .into(cfg1a)
;
consign()
  .include('config/users/admin.json')
  .then   ('config/users/guest.json')
  .then   ('config/users/user.json')
  .into(cfg1a2)
;
consign()
  .include('config/dbs')
  .into(cfg1b)
;
consign()
  .include('config')
  .into(cfg2)
;

console.log('==== Users ====');
console.log('cfg1a                     :', cfg1a);
console.log('cfg1a.config.users.admin  :', cfg1a.config.users.admin);
console.log('cfg1a2                    :', cfg1a2);

console.log('==== DBs ====');
console.log('cfg1b                                     :', cfg1b);
console.log('cfg1b.config.dbs.dbMongo                  :', cfg1b.config.dbs.dbMongo);
console.log('cfg1b.config.dbs.dbMongo.credentials.user :', cfg1b.config.dbs.dbMongo.credentials.user);

console.log('==== cfg2 ====');
console.log('cfg2                     :', cfg2);

console.log('==== cfg2 Users ====');
console.log('cfg2.config.users.admin  :', cfg2.config.users.admin);

console.log('==== cfg2 DBs ====');
console.log('cfg2.config.dbs.dbMongo                  :', cfg2.config.dbs.dbMongo);
console.log('cfg2.config.dbs.dbMongo.credentials.user :', cfg2.config.dbs.dbMongo.credentials.user);
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import { graphql, commitMutation } from 'react-relay/compat';
import { Store } from 'react-relay/classic';
import Tab from '@material-ui/core/Tab';
import Tabs from '@material-ui/core/Tabs';
import Box from '@material-ui/core/Box';
import { browserHistory } from 'react-router';
import Button from '@material-ui/core/Button';
import HelpIcon from '@material-ui/icons/HelpOutline';
import IconButton from '@material-ui/core/IconButton';
import KeyboardArrowLeftIcon from '@material-ui/icons/KeyboardArrowLeft';
import KeyboardArrowRightIcon from '@material-ui/icons/KeyboardArrowRight';
import CheckCircleOutlineIcon from '@material-ui/icons/CheckCircleOutline';
import HighlightOffIcon from '@material-ui/icons/HighlightOff';
import Typography from '@material-ui/core/Typography';
import IconArrowBack from '@material-ui/icons/ArrowBack';
import { makeStyles } from '@material-ui/core/styles';
import MediaExpanded from '../MediaExpanded';
import MediaRequests from '../MediaRequests';
import MediaComments from '../MediaComments';
import {
  Column,
  inProgressYellow,
  checkBlue,
  completedGreen,
  alertRed,
  brandSecondary,
} from '../../../styles/js/shared';
import { isBotInstalled } from '../../../helpers';

const useStyles = makeStyles(theme => ({
  title: {
    color: inProgressYellow,
  },
  helpIcon: {
    color: checkBlue,
  },
  disabled: {
    opacity: 0.5,
  },
  media: {
    background: 'white',
    border: `1px solid ${brandSecondary}`,
    borderRadius: 8,
    color: 'black',
  },
  noMedia: {
    color: 'black',
    paddingTop: theme.spacing(5),
    textAlign: 'center',
  },
  spaced: {
    padding: theme.spacing(1),
  },
}));

const MediaSuggestionsComponent = ({
  relationships,
  team,
}) => {
  const classes = useStyles();
  const itemUrl = window.location.pathname.replace(/\/suggested-matches$/, '');
  const [index, setIndex] = React.useState(0);
  const [saving, setSaving] = React.useState(false);

  const relationship = relationships[index];
  const projectMedia = relationship ? { dbid: relationship.target_id } : null;
  const total = relationships.length;
  const hasNext = (index + 1 < total);
  const hasPrevious = (index > 0);

  const handleGoBack = () => {
    browserHistory.push(itemUrl);
  };

  const handleNext = () => {
    if (hasNext) {
      setIndex(index + 1);
    }
  };

  const handlePrevious = () => {
    if (hasPrevious) {
      setIndex(index - 1);
    }
  };

  const handleCompleted = () => {
    setSaving(false);
  };

  const handleConfirm = () => {
    setSaving(true);

    const relationship_type = 'confirmed_sibling';

    const mutation = graphql`
      mutation MediaSuggestionsComponentUpdateRelationshipMutation($input: UpdateRelationshipInput!) {
        updateRelationship(input: $input) {
          relationship {
            relationship_type
          }
          source_project_media {
            demand
            requests_count
            hasMain: is_confirmed_similar_to_another_item
            suggestionsCount: suggested_similar_items_count
            confirmedSimilarCount: confirmed_similar_items_count
            suggested_similar_relationships(first: 10000) {
              edges {
                node {
                  id
                  target_id
                }
              }
            }
            confirmed_similar_relationships(first: 10000) {
              edges {
                node {
                  id
                  dbid
                  source_id
                  target_id
                  target {
                    requests_count
                    ...MediaItem_projectMedia
                  }
                }
              }
            }
          }
          target_project_media {
            demand
            requests_count
            hasMain: is_confirmed_similar_to_another_item
            suggestionsCount: suggested_similar_items_count
            confirmedSimilarCount: confirmed_similar_items_count
            suggested_similar_relationships(first: 10000) {
              edges {
                node {
                  id
                  target_id
                }
              }
            }
          }
        }
      }
    `;

    commitMutation(Store, {
      mutation,
      variables: {
        input: {
          id: relationship.id,
          relationship_source_type: relationship_type,
          relationship_target_type: relationship_type,
        },
      },
      onCompleted: () => {
        handleCompleted();
      },
      onError: () => {
        handleCompleted();
      },
    });
  };

  const handleReject = () => {
    setSaving(true);

    const mutation = graphql`
      mutation MediaSuggestionsComponentDestroyRelationshipMutation($input: DestroyRelationshipInput!) {
        destroyRelationship(input: $input) {
          source_project_media {
            hasMain: is_confirmed_similar_to_another_item
            suggestionsCount: suggested_similar_items_count
            confirmedSimilarCount: confirmed_similar_items_count
            suggested_similar_relationships(first: 10000) {
              edges {
                node {
                  id
                  target_id
                }
              }
            }
          }
          target_project_media {
            hasMain: is_confirmed_similar_to_another_item
            suggestionsCount: suggested_similar_items_count
            confirmedSimilarCount: confirmed_similar_items_count
            suggested_similar_relationships(first: 10000) {
              edges {
                node {
                  id
                  target_id
                }
              }
            }
          }
        }
      }
    `;

    commitMutation(Store, {
      mutation,
      variables: {
        input: {
          id: relationship.id,
        },
      },
      onCompleted: () => {
        handleCompleted();
      },
      onError: () => {
        handleCompleted();
      },
    });
  };

  const handleHelp = () => {
    window.open('http://help.checkmedia.org/en/articles/4705965-similarity-matching-and-suggestions');
  };

  return (
    <React.Fragment>
      <Column className="media__column">
        <Box display="flex" width="1" justifyContent="space-between" alignItems="center">
          <Box>
            <Button startIcon={<IconArrowBack />} onClick={handleGoBack} size="small" disabled={saving}>
              <FormattedMessage
                id="mediaSuggestionsComponent.back"
                defaultMessage="Back"
              />
            </Button>
            <Typography variant="button" display="block" className={classes.title}>
              <FormattedMessage
                id="mediaSuggestionsComponent.title"
                defaultMessage="Suggested matches ({current} of {total})"
                values={{
                  current: total === 0 ? 0 : index + 1,
                  total,
                }}
              />
            </Typography>
            <Box display="flex" alignItems="center">
              <Typography variant="body2">
                <FormattedMessage
                  id="mediaSuggestionsComponent.question"
                  defaultMessage="Is the suggested media similar to the main?"
                />
              </Typography>
              <IconButton onClick={handleHelp}>
                <HelpIcon className={classes.helpIcon} />
              </IconButton>
            </Box>
          </Box>
          <Box display="flex" alignItems="center">
            <IconButton onClick={handlePrevious} disabled={!hasPrevious || saving}>
              <KeyboardArrowLeftIcon fontSize="large" />
            </IconButton>
            <IconButton
              onClick={handleConfirm}
              style={{ color: completedGreen }}
              disabled={total === 0 || saving}
              className={total === 0 || saving ? classes.disabled : ''}
            >
              <CheckCircleOutlineIcon fontSize="large" />
            </IconButton>
            <IconButton
              onClick={handleReject}
              style={{ color: alertRed }}
              disabled={total === 0 || saving}
              className={total === 0 || saving ? classes.disabled : ''}
            >
              <HighlightOffIcon fontSize="large" />
            </IconButton>
            <IconButton onClick={handleNext} disabled={!hasNext || saving}>
              <KeyboardArrowRightIcon fontSize="large" />
            </IconButton>
          </Box>
        </Box>
        <Box className={projectMedia ? classes.media : classes.noMedia}>
          { projectMedia ?
            <MediaExpanded
              media={projectMedia}
              mediaUrl={itemUrl}
            /> :
            <Box justifyContent="center">
              <Box mb={2}>
                <Typography>
                  <FormattedMessage
                    id="mediaSuggestionsComponent.noSuggestions"
                    defaultMessage="There are no suggested matches."
                  />
                </Typography>
              </Box>
              <Button onClick={handleGoBack} color="primary" variant="contained">
                <FormattedMessage
                  id="mediaSuggestionsComponent.goBack"
                  defaultMessage="Back to main view"
                />
              </Button>
            </Box>
          }
        </Box>
      </Column>
      <Column className="media__annotations-column">
        { isBotInstalled(team, 'smooch') ?
          <React.Fragment>
            <Tabs indicatorColor="primary" textColor="primary" className="media__annotations-tabs" value="requests">
              <Tab
                label={
                  <FormattedMessage
                    id="mediaSuggestionsComponent.requests"
                    defaultMessage="Requests"
                  />
                }
                value="requests"
                className="media-tab__requests"
              />
            </Tabs>
            { projectMedia ?
              <MediaRequests media={{ dbid: projectMedia.dbid }} all={false} /> :
              <Typography variant="subtitle2" className={classes.spaced}>
                <FormattedMessage
                  id="mediaSuggestionsComponent.noRequests"
                  defaultMessage="No requests"
                />
              </Typography>
            }
          </React.Fragment> :
          <React.Fragment>
            <Tabs indicatorColor="primary" textColor="primary" className="media__annotations-tabs" value="notes">
              <Tab
                label={
                  <FormattedMessage
                    id="mediaSuggestionsComponent.notes"
                    defaultMessage="Notes"
                  />
                }
                value="notes"
                className="media-tab__notes"
              />
            </Tabs>
            { projectMedia ?
              <MediaComments media={{ dbid: projectMedia.dbid }} /> :
              <Typography variant="subtitle2" className={classes.spaced}>
                <FormattedMessage
                  id="mediaSuggestionsComponent.noNotes"
                  defaultMessage="No notes"
                />
              </Typography>
            }
          </React.Fragment>
        }
      </Column>
    </React.Fragment>
  );
};

MediaSuggestionsComponent.propTypes = {
  relationships: PropTypes.arrayOf(PropTypes.shape({
    id: PropTypes.string.isRequired,
    target_id: PropTypes.number.isRequired,
  })).isRequired,
  team: PropTypes.shape({
    team_bot_installations: PropTypes.shape({
      edges: PropTypes.arrayOf(PropTypes.shape({
        node: PropTypes.shape({
          team_bot: PropTypes.shape({
            identifier: PropTypes.string,
          }),
        }),
      })).isRequired,
    }).isRequired,
  }).isRequired,
};

export default MediaSuggestionsComponent;
<commit_msg>Ticket #8901: Trying to fix QA/Live problem where similarities list is not updated automatically after accepting a suggestion<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import { graphql, commitMutation } from 'react-relay/compat';
import { Store } from 'react-relay/classic';
import Tab from '@material-ui/core/Tab';
import Tabs from '@material-ui/core/Tabs';
import Box from '@material-ui/core/Box';
import { browserHistory } from 'react-router';
import Button from '@material-ui/core/Button';
import HelpIcon from '@material-ui/icons/HelpOutline';
import IconButton from '@material-ui/core/IconButton';
import KeyboardArrowLeftIcon from '@material-ui/icons/KeyboardArrowLeft';
import KeyboardArrowRightIcon from '@material-ui/icons/KeyboardArrowRight';
import CheckCircleOutlineIcon from '@material-ui/icons/CheckCircleOutline';
import HighlightOffIcon from '@material-ui/icons/HighlightOff';
import Typography from '@material-ui/core/Typography';
import IconArrowBack from '@material-ui/icons/ArrowBack';
import { makeStyles } from '@material-ui/core/styles';
import MediaExpanded from '../MediaExpanded';
import MediaRequests from '../MediaRequests';
import MediaComments from '../MediaComments';
import {
  Column,
  inProgressYellow,
  checkBlue,
  completedGreen,
  alertRed,
  brandSecondary,
} from '../../../styles/js/shared';
import { isBotInstalled } from '../../../helpers';

const useStyles = makeStyles(theme => ({
  title: {
    color: inProgressYellow,
  },
  helpIcon: {
    color: checkBlue,
  },
  disabled: {
    opacity: 0.5,
  },
  media: {
    background: 'white',
    border: `1px solid ${brandSecondary}`,
    borderRadius: 8,
    color: 'black',
  },
  noMedia: {
    color: 'black',
    paddingTop: theme.spacing(5),
    textAlign: 'center',
  },
  spaced: {
    padding: theme.spacing(1),
  },
}));

const MediaSuggestionsComponent = ({
  relationships,
  team,
}) => {
  const classes = useStyles();
  const itemUrl = window.location.pathname.replace(/\/suggested-matches$/, '');
  const [index, setIndex] = React.useState(0);
  const [saving, setSaving] = React.useState(false);

  const relationship = relationships[index];
  const projectMedia = relationship ? { dbid: relationship.target_id } : null;
  const total = relationships.length;
  const hasNext = (index + 1 < total);
  const hasPrevious = (index > 0);

  const handleGoBack = () => {
    browserHistory.push(itemUrl);
  };

  const handleNext = () => {
    if (hasNext) {
      setIndex(index + 1);
    }
  };

  const handlePrevious = () => {
    if (hasPrevious) {
      setIndex(index - 1);
    }
  };

  const handleCompleted = () => {
    setSaving(false);
  };

  const handleConfirm = () => {
    setSaving(true);

    const relationship_type = 'confirmed_sibling';

    const mutation = graphql`
      mutation MediaSuggestionsComponentUpdateRelationshipMutation($input: UpdateRelationshipInput!) {
        updateRelationship(input: $input) {
          relationship {
            relationship_type
          }
          source_project_media {
            demand
            requests_count
            hasMain: is_confirmed_similar_to_another_item
            suggestionsCount: suggested_similar_items_count
            confirmedSimilarCount: confirmed_similar_items_count
            suggested_similar_relationships(first: 10000) {
              edges {
                node {
                  id
                  target_id
                }
              }
            }
            confirmed_similar_relationships(first: 10000) {
              edges {
                node {
                  id
                  dbid
                  source_id
                  target_id
                  target {
                    id
                    dbid
                    title
                    picture
                    created_at
                    type
                    requests_count
                  }
                }
              }
            }
          }
          target_project_media {
            demand
            requests_count
            hasMain: is_confirmed_similar_to_another_item
            suggestionsCount: suggested_similar_items_count
            confirmedSimilarCount: confirmed_similar_items_count
            suggested_similar_relationships(first: 10000) {
              edges {
                node {
                  id
                  target_id
                }
              }
            }
          }
        }
      }
    `;

    commitMutation(Store, {
      mutation,
      variables: {
        input: {
          id: relationship.id,
          relationship_source_type: relationship_type,
          relationship_target_type: relationship_type,
        },
      },
      onCompleted: () => {
        handleCompleted();
      },
      onError: () => {
        handleCompleted();
      },
    });
  };

  const handleReject = () => {
    setSaving(true);

    const mutation = graphql`
      mutation MediaSuggestionsComponentDestroyRelationshipMutation($input: DestroyRelationshipInput!) {
        destroyRelationship(input: $input) {
          source_project_media {
            hasMain: is_confirmed_similar_to_another_item
            suggestionsCount: suggested_similar_items_count
            confirmedSimilarCount: confirmed_similar_items_count
            suggested_similar_relationships(first: 10000) {
              edges {
                node {
                  id
                  target_id
                }
              }
            }
          }
          target_project_media {
            hasMain: is_confirmed_similar_to_another_item
            suggestionsCount: suggested_similar_items_count
            confirmedSimilarCount: confirmed_similar_items_count
            suggested_similar_relationships(first: 10000) {
              edges {
                node {
                  id
                  target_id
                }
              }
            }
          }
        }
      }
    `;

    commitMutation(Store, {
      mutation,
      variables: {
        input: {
          id: relationship.id,
        },
      },
      onCompleted: () => {
        handleCompleted();
      },
      onError: () => {
        handleCompleted();
      },
    });
  };

  const handleHelp = () => {
    window.open('http://help.checkmedia.org/en/articles/4705965-similarity-matching-and-suggestions');
  };

  return (
    <React.Fragment>
      <Column className="media__column">
        <Box display="flex" width="1" justifyContent="space-between" alignItems="center">
          <Box>
            <Button startIcon={<IconArrowBack />} onClick={handleGoBack} size="small" disabled={saving}>
              <FormattedMessage
                id="mediaSuggestionsComponent.back"
                defaultMessage="Back"
              />
            </Button>
            <Typography variant="button" display="block" className={classes.title}>
              <FormattedMessage
                id="mediaSuggestionsComponent.title"
                defaultMessage="Suggested matches ({current} of {total})"
                values={{
                  current: total === 0 ? 0 : index + 1,
                  total,
                }}
              />
            </Typography>
            <Box display="flex" alignItems="center">
              <Typography variant="body2">
                <FormattedMessage
                  id="mediaSuggestionsComponent.question"
                  defaultMessage="Is the suggested media similar to the main?"
                />
              </Typography>
              <IconButton onClick={handleHelp}>
                <HelpIcon className={classes.helpIcon} />
              </IconButton>
            </Box>
          </Box>
          <Box display="flex" alignItems="center">
            <IconButton onClick={handlePrevious} disabled={!hasPrevious || saving}>
              <KeyboardArrowLeftIcon fontSize="large" />
            </IconButton>
            <IconButton
              onClick={handleConfirm}
              style={{ color: completedGreen }}
              disabled={total === 0 || saving}
              className={total === 0 || saving ? classes.disabled : ''}
            >
              <CheckCircleOutlineIcon fontSize="large" />
            </IconButton>
            <IconButton
              onClick={handleReject}
              style={{ color: alertRed }}
              disabled={total === 0 || saving}
              className={total === 0 || saving ? classes.disabled : ''}
            >
              <HighlightOffIcon fontSize="large" />
            </IconButton>
            <IconButton onClick={handleNext} disabled={!hasNext || saving}>
              <KeyboardArrowRightIcon fontSize="large" />
            </IconButton>
          </Box>
        </Box>
        <Box className={projectMedia ? classes.media : classes.noMedia}>
          { projectMedia ?
            <MediaExpanded
              media={projectMedia}
              mediaUrl={itemUrl}
            /> :
            <Box justifyContent="center">
              <Box mb={2}>
                <Typography>
                  <FormattedMessage
                    id="mediaSuggestionsComponent.noSuggestions"
                    defaultMessage="There are no suggested matches."
                  />
                </Typography>
              </Box>
              <Button onClick={handleGoBack} color="primary" variant="contained">
                <FormattedMessage
                  id="mediaSuggestionsComponent.goBack"
                  defaultMessage="Back to main view"
                />
              </Button>
            </Box>
          }
        </Box>
      </Column>
      <Column className="media__annotations-column">
        { isBotInstalled(team, 'smooch') ?
          <React.Fragment>
            <Tabs indicatorColor="primary" textColor="primary" className="media__annotations-tabs" value="requests">
              <Tab
                label={
                  <FormattedMessage
                    id="mediaSuggestionsComponent.requests"
                    defaultMessage="Requests"
                  />
                }
                value="requests"
                className="media-tab__requests"
              />
            </Tabs>
            { projectMedia ?
              <MediaRequests media={{ dbid: projectMedia.dbid }} all={false} /> :
              <Typography variant="subtitle2" className={classes.spaced}>
                <FormattedMessage
                  id="mediaSuggestionsComponent.noRequests"
                  defaultMessage="No requests"
                />
              </Typography>
            }
          </React.Fragment> :
          <React.Fragment>
            <Tabs indicatorColor="primary" textColor="primary" className="media__annotations-tabs" value="notes">
              <Tab
                label={
                  <FormattedMessage
                    id="mediaSuggestionsComponent.notes"
                    defaultMessage="Notes"
                  />
                }
                value="notes"
                className="media-tab__notes"
              />
            </Tabs>
            { projectMedia ?
              <MediaComments media={{ dbid: projectMedia.dbid }} /> :
              <Typography variant="subtitle2" className={classes.spaced}>
                <FormattedMessage
                  id="mediaSuggestionsComponent.noNotes"
                  defaultMessage="No notes"
                />
              </Typography>
            }
          </React.Fragment>
        }
      </Column>
    </React.Fragment>
  );
};

MediaSuggestionsComponent.propTypes = {
  relationships: PropTypes.arrayOf(PropTypes.shape({
    id: PropTypes.string.isRequired,
    target_id: PropTypes.number.isRequired,
  })).isRequired,
  team: PropTypes.shape({
    team_bot_installations: PropTypes.shape({
      edges: PropTypes.arrayOf(PropTypes.shape({
        node: PropTypes.shape({
          team_bot: PropTypes.shape({
            identifier: PropTypes.string,
          }),
        }),
      })).isRequired,
    }).isRequired,
  }).isRequired,
};

export default MediaSuggestionsComponent;
<|endoftext|>


<commit_before>var svg = require('simplesvg');
var hammer = require('hammerjs');

module.exports = scene;

var MOVE_EVENTS = 'panstart panmove panend';

function scene(container, layout) {
  var svgRoot = createSvgRoot(container);
  var sceneRoot = createSceneRoot(svgRoot);
  var sceneTransform = createSceneTransform(sceneRoot.element);
  var panSession = {};
  var panNode = 0;

  var linkLayer = addLayer('links', sceneRoot);
  var nodeLayer = addLayer('nodes', sceneRoot);

  var nodes = Object.create(null);
  var links = Object.create(null);

  var fromX = 0, fromY = 0;
  var screenPinchX, screenPinchY, lastScale;
  var cachedPos = { x: 0, y: 0 },
      cachedFromPos = { x: 0, y: 0 },
      cachedToPos = { x: 0, y: 0 };

  var defaultUI = require('./defaultUI.js');
  var nodeBuilder = defaultUI.nodeBuilder,
    nodePositionCallback = defaultUI.nodePositionCallback,
    linkBuilder = defaultUI.linkBuilder,
    linkPositionCallback = defaultUI.linkPositionCallback;

  var currentTransform = {
    tx : 0,
    ty : 0,
    scale: 1
  };

  var api = {
    renderFrame: renderFrame,

    addNode: addNode,
    removeNode: removeNode,
    addLink: addLink,
    removeLink: removeLink,

    moveTo: moveTo,
    zoomTo: zoomTo,

    setNodeBuilder: setNodeBuilder,
    setLinkBuilder: setLinkBuilder,
    placeNode: function(newPlaceCallback) { nodePositionCallback = newPlaceCallback; },
    placeLink: function(newPlaceLinkCallback) { linkPositionCallback = newPlaceLinkCallback; },

    dispose: dispose
  };

  return api;

  function renderFrame() {
    for (var nodeId in nodes) {
      var nodeInfo = nodes[nodeId];
      cachedPos.x = nodeInfo.pos.x;
      cachedPos.y = nodeInfo.pos.y;
      nodePositionCallback(nodeInfo.ui, cachedPos, nodeInfo.model);
    }

    for (var linkId in links) {
      var linkInfo = links[linkId];
      cachedFromPos.x = linkInfo.pos.from.x;
      cachedFromPos.y = linkInfo.pos.from.y;
      cachedToPos.x = linkInfo.pos.to.x;
      cachedToPos.y = linkInfo.pos.to.y;
      linkPositionCallback(linkInfo.ui, cachedToPos, cachedFromPos, linkInfo.model);
    }
  }

  function moveTo(x, y) {
    currentTransform.tx = x;
    currentTransform.ty = y;
    updateTransformMatrix();
  }

  function createSceneTransform(scene) {
    var transform = svgRoot.element.createSVGTransform();
    scene.transform.baseVal.appendItem(transform);

    return transform;
  }

  function updateTransformMatrix() {
    sceneTransform.matrix.e = currentTransform.tx;
    sceneTransform.matrix.f = currentTransform.ty;
    sceneTransform.matrix.a = sceneTransform.matrix.d = currentTransform.scale;
  }

  function setNodeBuilder(builderCallback) {
    if (typeof builderCallback !== "function") throw new Error('node builder callback is supposed to be a function');

    nodeBuilder = builderCallback; // todo: rebuild all nodes?
  }

  function setLinkBuilder(builderCallback) {
    if (typeof builderCallback !== "function") throw new Error('link builder callback is supposed to be a function');

    linkBuilder = builderCallback; // todo: rebuild all nodes?
  }

  function addNode(node) {
    var ui = nodeBuilder(node);
    if (!ui) throw new Error('Node builder is supposed to return SVG object');

    nodeLayer.append(ui);

    var nodeDescriptor = {
      pos: layout.getNodePosition(node.id),
      model: node,
      ui: ui
    };

    ui.element.node = nodeDescriptor;

    var recognizers = { recognizers:[ [hammer.Pan, { threshold: 1 }]] };
    nodeDescriptor.events = hammer(ui.element, recognizers).on(MOVE_EVENTS, onNodePan);
    nodes[node.id] = nodeDescriptor;
  }

  function removeNode(node) {
    var descriptor = nodes[node.id];
    if (!descriptor) return;

    descriptor.events.off(MOVE_EVENTS);

    var parent = descriptor.ui.element.parentNode;
    if (parent) parent.removeChild(descriptor.ui.element);

    delete nodes[node.id];
  }

  function addLink(link) {
    var linkUI = linkBuilder(link);
    if (!linkUI) throw new Error('Link builder is supposed to return SVG object');

    links[link.id] = {
      pos: layout.getLinkPosition(link.id),
      model: link,
      ui: linkUI
    };

    linkLayer.append(linkUI);
  }

  function removeLink(link) {
    var descriptor = links[link.id];
    if (!descriptor) return;

    var parent = descriptor.ui.element.parentNode;
    if (parent) parent.removeChild(descriptor.ui.element);

    delete links[link.id];
  }

  function createSvgRoot(element) {
    if (element instanceof SVGSVGElement) return element;
    var svgRoot = svg("svg");
    element.appendChild(svgRoot.element);

    return svgRoot;
  }

  function createSceneRoot(svgRoot) {
    var scene = svg('g').attr("buffered-rendering", "dynamic");
    svgRoot.append(scene);
    var sceneElement = svgRoot.element;

    var sceneMoveRecognizer = { recognizers: [
      [hammer.Pan, { threshold: 1 }],
      [hammer.Pinch, { enable: true }]
    ] };

    // somehow ios does not fire events on svg. Use body instead:
    hammer(document.body, sceneMoveRecognizer)
      .on(MOVE_EVENTS, onScenePan)
      .on('pinchstart pinchin pinchout', onScreenPinch);

    var addWheelListener = require('wheel');
    addWheelListener(sceneElement, onWheel);
    return scene;
  }

  function onScreenPinch(e) {
    if (e.target !== svgRoot.element) return;

    if (e.type === 'pinchstart') {
      screenPinchX = e.center.x;
      screenPinchY = e.center.y;
      lastScale = e.scale;
    } else {
      var direction = lastScale > e.scale ? -1 : 1;
      lastScale = e.scale;
      var factor = (1 + direction * 0.04);
      zoomTo(screenPinchX, screenPinchY, factor);
    }
  }

  function onWheel(e) {
    var isZoomIn = e.deltaY < 0;
    var direction = isZoomIn ? 1 : -1;
    var factor = (1 + direction * 0.1);
    zoomTo(e.clientX, e.clientY, factor);
  }

  function zoomTo(x, y, factor) {
    currentTransform.tx = x - factor * (x - currentTransform.tx);
    currentTransform.ty = y - factor * (y - currentTransform.ty);
    currentTransform.scale *= factor;
    updateTransformMatrix();
  }

  function onScenePan(e) {
    if (e.target !== svgRoot.element || panNode > 0) return;
    if (e.type === 'panmove') {
      currentTransform.tx = fromX + e.deltaX;
      currentTransform.ty = fromY + e.deltaY;
      updateTransformMatrix();
    } else if (e.type === 'panstart') {
      fromX = currentTransform.tx;
      fromY = currentTransform.ty;
    }
  }

  function addLayer(name, parent) {
    var layer = svg('g').attr('id', name);
    parent.append(layer);
    return layer;
  }

  function onNodePan(e) {
    var node = e.target.node;
    var model = node.model;

    var clickPosition = getModelPosition(e.center);

    if (e.type === 'panmove') {
      var status = panSession[model.id];
      layout.setNodePosition(model.id, clickPosition.x - status.dx , clickPosition.y - status.dy);
    } else if (e.type === 'panstart') {
      panSession[model.id] = {
        isPinned: layout.isNodePinned(model),
        dx: clickPosition.x - node.pos.x,
        dy: clickPosition.y - node.pos.y
      };
      layout.pinNode(model, true);
      panNode += 1;
    } else if (e.type === 'panend') {
      layout.pinNode(model, panSession[model.id].isPinned);
      panNode -= 1;
    }
  }

  function getModelPosition(pos) {
    return {
      x: (pos.x - currentTransform.tx)/currentTransform.scale,
      y: (pos.y - currentTransform.ty)/currentTransform.scale,
    };
  }

  function dispose() {
    // todo: implement me:
    // 1. scene hammer
    // 2. scene mouse wheel
  }
}
<commit_msg>Moved node/pos into closure<commit_after>var svg = require('simplesvg');
var hammer = require('hammerjs');

module.exports = scene;

var MOVE_EVENTS = 'panstart panmove panend';

function scene(container, layout) {
  var svgRoot = createSvgRoot(container);
  var sceneRoot = createSceneRoot(svgRoot);
  var sceneTransform = createSceneTransform(sceneRoot);
  var panSession = {};
  var panNode = 0;

  var linkLayer = addLayer('links', sceneRoot);
  var nodeLayer = addLayer('nodes', sceneRoot);

  var nodes = Object.create(null);
  var links = Object.create(null);

  var fromX = 0, fromY = 0;
  var screenPinchX, screenPinchY, lastScale;
  var cachedPos = { x: 0, y: 0 },
      cachedFromPos = { x: 0, y: 0 },
      cachedToPos = { x: 0, y: 0 };

  var defaultUI = require('./defaultUI.js');
  var nodeBuilder = defaultUI.nodeBuilder,
    nodePositionCallback = defaultUI.nodePositionCallback,
    linkBuilder = defaultUI.linkBuilder,
    linkPositionCallback = defaultUI.linkPositionCallback;

  var currentTransform = {
    tx : 0,
    ty : 0,
    scale: 1
  };

  var api = {
    renderFrame: renderFrame,

    addNode: addNode,
    removeNode: removeNode,
    addLink: addLink,
    removeLink: removeLink,

    moveTo: moveTo,
    zoomTo: zoomTo,

    setNodeBuilder: setNodeBuilder,
    setLinkBuilder: setLinkBuilder,
    placeNode: function(newPlaceCallback) { nodePositionCallback = newPlaceCallback; },
    placeLink: function(newPlaceLinkCallback) { linkPositionCallback = newPlaceLinkCallback; },

    dispose: dispose
  };

  return api;

  function renderFrame() {
    for (var nodeId in nodes) {
      var nodeInfo = nodes[nodeId];
      cachedPos.x = nodeInfo.pos.x;
      cachedPos.y = nodeInfo.pos.y;
      nodePositionCallback(nodeInfo.ui, cachedPos, nodeInfo.model);
    }

    for (var linkId in links) {
      var linkInfo = links[linkId];
      cachedFromPos.x = linkInfo.pos.from.x;
      cachedFromPos.y = linkInfo.pos.from.y;
      cachedToPos.x = linkInfo.pos.to.x;
      cachedToPos.y = linkInfo.pos.to.y;
      linkPositionCallback(linkInfo.ui, cachedToPos, cachedFromPos, linkInfo.model);
    }
  }

  function moveTo(x, y) {
    currentTransform.tx = x;
    currentTransform.ty = y;
    updateTransformMatrix();
  }

  function createSceneTransform(scene) {
    var transform = svgRoot.createSVGTransform();
    scene.transform.baseVal.appendItem(transform);

    return transform;
  }

  function updateTransformMatrix() {
    sceneTransform.matrix.e = currentTransform.tx;
    sceneTransform.matrix.f = currentTransform.ty;
    sceneTransform.matrix.a = sceneTransform.matrix.d = currentTransform.scale;
  }

  function setNodeBuilder(builderCallback) {
    if (typeof builderCallback !== "function") throw new Error('node builder callback is supposed to be a function');

    nodeBuilder = builderCallback; // todo: rebuild all nodes?
  }

  function setLinkBuilder(builderCallback) {
    if (typeof builderCallback !== "function") throw new Error('link builder callback is supposed to be a function');

    linkBuilder = builderCallback; // todo: rebuild all nodes?
  }

  function addNode(node) {
    var ui = nodeBuilder(node);
    if (!ui) throw new Error('Node builder is supposed to return SVG object');

    nodeLayer.append(ui);

    var pos = layout.getNodePosition(node.id);
    var nodeDescriptor = {
      pos: pos,
      model: node,
      ui: ui
    };

    var recognizers = { recognizers:[ [hammer.Pan, { threshold: 1 }]] };
    nodeDescriptor.events = hammer(ui, recognizers).on(MOVE_EVENTS, onNodePan(pos, node));
    nodes[node.id] = nodeDescriptor;

  }

  function onNodePan(pos, model) {
    return function onNodePan(e) {
      var clickPosition = getModelPosition(e.center);

      if (e.type === 'panmove') {
        var status = panSession[model.id];
        layout.setNodePosition(model.id, clickPosition.x - status.dx , clickPosition.y - status.dy);
      } else if (e.type === 'panstart') {
        panSession[model.id] = {
          isPinned: layout.isNodePinned(model),
          dx: clickPosition.x - pos.x,
          dy: clickPosition.y - pos.y
        };
        layout.pinNode(model, true);
        panNode += 1;
      } else if (e.type === 'panend') {
        layout.pinNode(model, panSession[model.id].isPinned);
        panNode -= 1;
      }
    };
  }

  function removeNode(node) {
    var descriptor = nodes[node.id];
    if (!descriptor) return;

    descriptor.events.off(MOVE_EVENTS);

    var parent = descriptor.ui.parentNode;
    if (parent) parent.removeChild(descriptor.ui);

    delete nodes[node.id];
  }

  function addLink(link) {
    var linkUI = linkBuilder(link);
    if (!linkUI) throw new Error('Link builder is supposed to return SVG object');

    links[link.id] = {
      pos: layout.getLinkPosition(link.id),
      model: link,
      ui: linkUI
    };

    linkLayer.append(linkUI);
  }

  function removeLink(link) {
    var descriptor = links[link.id];
    if (!descriptor) return;

    var parent = descriptor.ui.parentNode;
    if (parent) parent.removeChild(descriptor.ui);

    delete links[link.id];
  }

  function createSvgRoot(element) {
    if (element instanceof SVGSVGElement) return element;
    var svgRoot = svg("svg");
    element.appendChild(svgRoot);

    return svgRoot;
  }

  function createSceneRoot(svgRoot) {
    var scene = svg('g').attr("buffered-rendering", "dynamic");
    svgRoot.append(scene);

    var sceneMoveRecognizer = { recognizers: [
      [hammer.Pan, { threshold: 1 }],
      [hammer.Pinch, { enable: true }]
    ] };

    // somehow ios does not fire events on svg. Use body instead:
    hammer(document.body, sceneMoveRecognizer)
      .on(MOVE_EVENTS, onScenePan)
      .on('pinchstart pinchin pinchout', onScreenPinch);

    var addWheelListener = require('wheel');
    addWheelListener(svgRoot, onWheel);
    return scene;
  }

  function onScreenPinch(e) {
    if (e.target !== svgRoot) return;

    if (e.type === 'pinchstart') {
      screenPinchX = e.center.x;
      screenPinchY = e.center.y;
      lastScale = e.scale;
    } else {
      var direction = lastScale > e.scale ? -1 : 1;
      lastScale = e.scale;
      var factor = (1 + direction * 0.04);
      zoomTo(screenPinchX, screenPinchY, factor);
    }
  }

  function onWheel(e) {
    var isZoomIn = e.deltaY < 0;
    var direction = isZoomIn ? 1 : -1;
    var factor = (1 + direction * 0.1);
    zoomTo(e.clientX, e.clientY, factor);
  }

  function zoomTo(x, y, factor) {
    currentTransform.tx = x - factor * (x - currentTransform.tx);
    currentTransform.ty = y - factor * (y - currentTransform.ty);
    currentTransform.scale *= factor;
    updateTransformMatrix();
  }

  function onScenePan(e) {
    if (e.target !== svgRoot || panNode > 0) return;
    if (e.type === 'panmove') {
      currentTransform.tx = fromX + e.deltaX;
      currentTransform.ty = fromY + e.deltaY;
      updateTransformMatrix();
    } else if (e.type === 'panstart') {
      fromX = currentTransform.tx;
      fromY = currentTransform.ty;
    }
  }

  function addLayer(name, parent) {
    var layer = svg('g').attr('id', name);
    parent.append(layer);
    return layer;
  }

  function getModelPosition(pos) {
    return {
      x: (pos.x - currentTransform.tx)/currentTransform.scale,
      y: (pos.y - currentTransform.ty)/currentTransform.scale,
    };
  }

  function dispose() {
    // todo: implement me:
    // 1. scene hammer
    // 2. scene mouse wheel
  }
}
<|endoftext|>


<commit_before>var request = require('supertest');
var app = require('../app');

describe('auth', function() {
  var agent = request.agent(app);

  before('Make sure all tables exist', function(done) {
    app.db.sequelize.sync({force: true})
    .then(function() {
      done();
    });
  });

  it('should start logged out', function(done) {
    agent.get('/')
    .expect(200)
    .expect(/please login/)
    .end(done);
  });

  it('should refuse get on auth', function(done) {
    agent.get('/auth/login')
    .expect(401)
    .end(done);
  });

  it('should refuse access if require_login', function(done) {
    agent.get('/authg/register')
    .expect(401)
    .expect(/Required: Login/)
    .end(done);
  });

  it('should refuse access if require_user', function(done) {
    agent.get('/registration/receipt')
    .expect(401)
    .expect(/Required: Login/)
    .end(done);
  });

  it('should welcome the user', function(done) {
    agent.post('/auth/login')
    .send({'email': 'usera@regcfp'})
    .expect(200)
    .expect('Welcome usera@regcfp')
    .end(done);
  });

  it('should tell the user is logged in', function(done) {
    agent.get('/')
    .expect(200)
    .expect(/Welcome, usera@regcfp/)
    .end(done);
  });

  it('should redirect user to register', function(done) {
    agent.get('/papers/submit')
    .expect(302)
    .expect('Location', '/authg/register?origin=/papers/submit')
    .end(done);
  });

  it('should show register form', function(done) {
    agent.get('/authg/register?origin=/papers/submit')
    .expect(200)
    .expect(/some additional information/)
    .end(done);
  });

  it('should refuse empty name', function(done) {
    agent.post('/authg/register')
    .send({'origin': '/papers/submit'})
    .send({'fullname': ''})
    .expect(302)
    .expect('Location', '/authg/register?origin=/papers/submit')
    .end(done);
  });

  it('should register correctly', function(done) {
    agent.post('/authg/register')
    .send({'origin': '/papers/submit'})
    .send({'fullname': 'TestUser A'})
    .expect(302)
    .expect('Location', '/papers/submit')
    .end(done);
  });

  it('should show the user name', function(done) {
    agent.get('/')
    .expect(200)
    .expect(/Welcome, TestUser A/)
    .end(done);
  });

  it('should not allow desk access', function(done) {
    agent.get('/desk')
    .expect(401)
    .expect(/No permissions/)
    .end(done);
  });

  it('should allow logout', function(done) {
    agent.post('/auth/logout')
    .expect(200)
    .expect('Logged out')
    .end(done);
  });

  it('should tell the user is logged out', function(done) {
    agent.get('/')
    .expect(200)
    .expect(/please login/)
    .end(done);
  });
});
<commit_msg>Add some security tests<commit_after>var request = require('supertest');
var app = require('../app');

describe('auth', function() {
  var agent = request.agent(app);

  before('Make sure all tables exist', function(done) {
    app.db.sequelize.sync({force: true})
    .then(function() {
      done();
    });
  });

  it('should start logged out', function(done) {
    agent.get('/')
    .expect(200)
    .expect(/please login/)
    .end(done);
  });

  it('should refuse get on auth', function(done) {
    agent.get('/auth/login')
    .expect(401)
    .end(done);
  });

  it('should refuse access if require_login', function(done) {
    agent.get('/authg/register')
    .expect(401)
    .expect(/Required: Login/)
    .end(done);
  });

  it('should refuse access if require_user', function(done) {
    agent.get('/registration/receipt')
    .expect(401)
    .expect(/Required: Login/)
    .end(done);
  });

  it('should welcome the user', function(done) {
    agent.post('/auth/login')
    .send({'email': 'usera@regcfp'})
    .expect(200)
    .expect('Welcome usera@regcfp')
    .end(done);
  });

  it('should tell the user is logged in', function(done) {
    agent.get('/')
    .expect(200)
    .expect(/Welcome, usera@regcfp/)
    .end(done);
  });

  it('should redirect user to register', function(done) {
    agent.get('/papers/submit')
    .expect(302)
    .expect('Location', '/authg/register?origin=/papers/submit')
    .end(done);
  });

  it('should show register form', function(done) {
    agent.get('/authg/register?origin=/papers/submit')
    .expect(200)
    .expect(/some additional information/)
    .end(done);
  });

  it('should refuse empty name', function(done) {
    agent.post('/authg/register')
    .send({'origin': '/papers/submit'})
    .send({'fullname': ''})
    .expect(302)
    .expect('Location', '/authg/register?origin=/papers/submit')
    .end(done);
  });

  it('should handle empty origin', function(done) {
    agent.post('/authg/register')
    .send({'fullname': ''})
    .expect(302)
    .expect('Location', '/authg/register?origin=/')
    .end(done);
  });

  it('should register correctly', function(done) {
    agent.post('/authg/register')
    .send({'origin': '/papers/submit'})
    .send({'fullname': 'TestUser A'})
    .expect(302)
    .expect('Location', '/papers/submit')
    .end(done);
  });

  it('should not do covert redirects', function(done) {
    agent.post('/authg/register')
    .send({'origin': 'https://fedoraproject.org/'})
    .send({'fullname': 'Some User'})
    .expect(302)
    .expect('Location', '/')
    .end(done);
  });

  it('should show the user name', function(done) {
    agent.get('/')
    .expect(200)
    .expect(/Welcome, TestUser A/)
    .end(done);
  });

  it('should not allow desk access', function(done) {
    agent.get('/desk')
    .expect(401)
    .expect(/No permissions/)
    .end(done);
  });

  it('should allow logout', function(done) {
    agent.post('/auth/logout')
    .expect(200)
    .expect('Logged out')
    .end(done);
  });

  it('should tell the user is logged out', function(done) {
    agent.get('/')
    .expect(200)
    .expect(/please login/)
    .end(done);
  });
});
<|endoftext|>


<commit_before>(function () {
  'use strict';

  var sha1 = require('./sha1');
  var summarizer = require('./summarizer');

  function fromItems(array, serialize) {
    return summarizer.fromItems(array, serialize, sha1, 3);
  }

  function fromJSON(producer) {
    return summarizer.fromJSON(producer, sha1, 3);
  }

  module.exports = {
    summarizer: {
      fromItems : fromItems,
      fromJSON : fromJSON,
      fromLarge : summarizer.fromLarge
    },
    resolver: require('./resolver')
  };
})();
<commit_msg>Javascript default summarizer uses bucket selector<commit_after>(function () {
  'use strict';

  var sha1 = require('./sha1');
  var summarizer = require('./summarizer');
  var selector = require('./bucketSelector').padAndHash(sha1, 3);

  function fromItems(array, serialize) {
    return summarizer.fromItems(array, serialize, sha1, selector);
  }

  function fromJSON(producer) {
    return summarizer.fromJSON(producer, sha1, selector);
  }

  module.exports = {
    summarizer: {
      fromItems : fromItems,
      fromJSON : fromJSON,
      fromLarge : summarizer.fromLarge
    },
    resolver: require('./resolver')
  };
})();
<|endoftext|>


<commit_before>module.exports = {
    master: {
        product: require('./data-util/master/product-data-util'),
        uom: require('./data-util/master/uom-data-util'),
        vat: require('./data-util/master/vat-data-util'),
        currency: require('./data-util/master/currency-data-util'),
        buyer: require('./data-util/master/buyer-data-util'),
        budget: require('./data-util/master/budget-data-util'),
        supplier: require('./data-util/master/supplier-data-util'),
        unit: require('./data-util/master/unit-data-util'),
        category: require('./data-util/master/category-data-util')
    },
    transaction: {
        purchaseRequest: require('./data-util/transaction/purchase-request-data-util'),
        purchaseOrder: require('./data-util/transaction/purchase-order-data-util'),
        purchaseOrderExternal: require('./data-util/transaction/purchase-order-external-data-util'),
        deliveryOrder: require('./data-util/transaction/delivery-order-data-util'),
        unitReceiptNote: require('./data-util/transaction/unit-receipt-note-data-util'),
        unitPaymentOrder: require('./data-util/transaction/unit-payment-order-data-util'),
        unitPaymentPriceCorrectionNote: require('./data-util/transaction/unit-payment-price-correction-note-data-util')
    }
};
<commit_msg>add unitPaymentQuantityCorrectionNote<commit_after>module.exports = {
    master: {
        product: require('./data-util/master/product-data-util'),
        uom: require('./data-util/master/uom-data-util'),
        vat: require('./data-util/master/vat-data-util'),
        currency: require('./data-util/master/currency-data-util'),
        buyer: require('./data-util/master/buyer-data-util'),
        budget: require('./data-util/master/budget-data-util'),
        supplier: require('./data-util/master/supplier-data-util'),
        unit: require('./data-util/master/unit-data-util'),
        category: require('./data-util/master/category-data-util')
    },
    transaction: {
        purchaseRequest: require('./data-util/transaction/purchase-request-data-util'),
        purchaseOrder: require('./data-util/transaction/purchase-order-data-util'),
        purchaseOrderExternal: require('./data-util/transaction/purchase-order-external-data-util'),
        deliveryOrder: require('./data-util/transaction/delivery-order-data-util'),
        unitReceiptNote: require('./data-util/transaction/unit-receipt-note-data-util'),
        unitPaymentOrder: require('./data-util/transaction/unit-payment-order-data-util'),
        unitPaymentPriceCorrectionNote: require('./data-util/transaction/unit-payment-price-correction-note-data-util'),
        unitPaymentQuantityCorrectionNote: require('./data-util/transaction/unit-payment-quantity-correction-note-data-util')
    }
};
<|endoftext|>


<commit_before>const path = require('path');

const brunch = require('brunch');
const clipboardy = require('clipboardy');
const logger = require('loggy');

const getBrunchConfigPath = require('./utils.js').getBrunchConfigPath;

const serve = (watchPath, options, onCompile) => {
  watchPath = watchPath || process.cwd();
  options = options || {};
  options.config = options.config || getBrunchConfigPath(watchPath, options);
  options.server = true;
  logger.log(`Watching "${watchPath}" …`);

  // Copy the server URL to the user's clipboard.
  const host = options.network || options.host || 'localhost';
  const port = options.port || 3333;
  const https = options.https || options.ssl || options.secure || false;
  const serverUrl = `http${https ? 's' : ''}://${host}:${port}/`;
  clipboardy.writeSync(serverUrl);

  try {
    return brunch.watch(watchPath, options, onCompile);
  } catch (err) {
    logger.error(`Could not watch "${watchPath}" …`);
    throw err;
  }
};

exports.serve = serve;
exports.printBanner = commandName => {
  // return printBanner(commandName).catch(err => {
    // console.log(err.message);
  // });
};
<commit_msg>fix `aframe serve` to broadcast on network<commit_after>const path = require('path');

const brunch = require('brunch');
const clipboardy = require('clipboardy');
const logger = require('loggy');

const getBrunchConfigPath = require('./utils.js').getBrunchConfigPath;

const serve = (watchPath, options, onCompile) => {
  watchPath = watchPath || process.cwd();
  options = options || {};
  options.config = options.config || getBrunchConfigPath(watchPath, options);
  options.server = true;
  options.network = true;
  logger.log(`Watching "${watchPath}" …`);

  // Copy the server URL to the user's clipboard.
  const host = options.network || options.host || 'localhost';
  const port = options.port || 3333;
  const https = options.https || options.ssl || options.secure || false;
  const serverUrl = `http${https ? 's' : ''}://${host}:${port}/`;
  clipboardy.writeSync(serverUrl);

  try {
    return brunch.watch(watchPath, options, onCompile);
  } catch (err) {
    logger.error(`Could not watch "${watchPath}" …`);
    throw err;
  }
};

exports.serve = serve;
exports.printBanner = commandName => {
  // return printBanner(commandName).catch(err => {
    // console.log(err.message);
  // });
};
<|endoftext|>


<commit_before>'use strict';

/*global describe, beforeEach, it*/

var chai  = require('chai');
var spies = require('chai-spies');
chai.use(spies);
var should = chai.should();
var spy    = chai.spy;

var angular = require('angular');
require('angular-mocks/ngMock');

describe('angular-http-etag', function () {
  beforeEach(angular.mock.module(require('../')));

  var $http, $httpBackend, $cacheFactory, userCache,
      interceptor, ifEtagIs, ifEtagIsNot, onSuccess, onError;

  beforeEach(angular.mock.inject(function ($injector) {
    $http         = $injector.get('$http');
    $httpBackend  = $injector.get('$httpBackend');
    $cacheFactory = $injector.get('$cacheFactory');
    interceptor   = $injector.get('httpEtagInterceptor');

    onSuccess = spy('$http().success', angular.noop);
    onError   = spy('$http().error',   angular.noop);

    ifEtagIs = function (etag) {
      return function (headers) { return headers['If-None-Match'] === etag; };
    };

    ifEtagIsNot = function (etag) {
      return function (headers) { return headers['If-None-Match'] !== etag; };
    };

    userCache = $cacheFactory('test');

    $httpBackend
      .whenGET('/1.json', ifEtagIsNot('1'))
      .respond({ id:1, content:'Test data' }, { 'etag': '1' });
    $httpBackend
      .whenGET('/1.json', ifEtagIs('1'))
      .respond(304);

    $httpBackend
      .whenGET('/1.json?param=test', ifEtagIsNot('1'))
      .respond({ id:1, content:'Test data' }, { 'etag': '1' });
    $httpBackend
      .whenGET('/1.json?param=test', ifEtagIs('1'))
      .respond(304);

  }));

  it('should cache ETags', function () {
    $http.get('/1.json', { etag: true })
      .success(onSuccess);
    $httpBackend.flush();

    $http.get('/1.json', { etag: true })
      .error(onError);
    $httpBackend.flush();

    onSuccess.should.have.been.called();
    onError.should.have.been.called();
  });

  it('should function without ETag config property', function () {
    $http.get('/1.json').success(onSuccess);
    $httpBackend.flush();

    $http.get('/1.json').error(onError);
    $httpBackend.flush();

    onSuccess.should.have.been.called();
    onError.should.not.have.been.called();
  });

  it('should cache ETags for requests with query params', function () {
    $http.get('/1.json', { etag: true, params: { param: 'test' } })
      .success(onSuccess);
    $httpBackend.flush();

    $http.get('/1.json', { etag: true, params: { param: 'test' } })
      .error(onError);
    $httpBackend.flush();

    onSuccess.should.have.been.called();
    onError.should.have.been.called();
  });

  it('should allow for passing of an ETag string', function () {
    $http.get('/1.json', { etag: '1' })
      .error(onError);
    $httpBackend.flush();

    $http.get('/1.json', { etag: '2' })
      .success(onSuccess);
    $httpBackend.flush();

    onSuccess.should.have.been.called();
    onError.should.have.been.called();
  });

  it('should allow for usage of a user\'s own $cacheFactory cache', function () {
    $http.get('/1.json', {
        etag: { cache: { id:'test', key:1 } }
      })
      .success(onSuccess);
    $httpBackend.flush();

    userCache.get(1).$$etag.should.equal('1');

    $http.get('/1.json', {
        etag: { cache: { id:'test', key:1 } }
      })
      .error(onError);
    $httpBackend.flush();

    onSuccess.should.have.been.called();
    onError.should.have.been.called();
  });

  it('should return user\'s $cacheFactory data on 304', function () {
    var cachedData;

    $http.get('/1.json', {
        etag: { cache: { id:'test', key:1 } }
      })
      .success(onSuccess);
    $httpBackend.flush();

    userCache.get(1).$$etag.should.equal('1');

    $http.get('/1.json', {
        etag: { cache: { id:'test', key:1 } }
      })
      .error(function (data) {
        cachedData = data;
      });
    $httpBackend.flush();

    onSuccess.should.have.been.called();
    cachedData.should.deep.equal({
      $$etag: '1',
      id: 1,
      content: 'Test data'
    });
  });

  it('should ignore an invalid $cacheFactory ID', function () {
    $http.get('/1.json', {
        etag: { cache: { id:'invalid', key:1 } }
      })
      .success(onSuccess);
    $httpBackend.flush();

    $http.get('/1.json', {
        etag: { cache: { id:'invalid', key:1 } }
      })
      .success(onSuccess);
    $httpBackend.flush();

    onSuccess.should.have.been.called.twice;
  });

});
<commit_msg>Fix and remove tests<commit_after>'use strict';

/*global describe, beforeEach, it*/

var chai  = require('chai');
var spies = require('chai-spies');
chai.use(spies);
var should = chai.should();
var spy    = chai.spy;

var angular = require('angular');
require('angular-mocks/ngMock');

describe('angular-http-etag', function () {
  beforeEach(angular.mock.module(require('../')));

  var $http, $httpBackend, $cacheFactory, serverData,
      ifEtagIs, ifEtagIsNot, onCache, onSuccess, onError;

  beforeEach(angular.mock.inject(function ($injector) {
    $http         = $injector.get('$http');
    $httpBackend  = $injector.get('$httpBackend');
    $cacheFactory = $injector.get('$cacheFactory');

    onCache   = spy('$http().cache',   angular.noop);
    onSuccess = spy('$http().success', angular.noop);
    onError   = spy('$http().error',   angular.noop);

    ifEtagIs = function (etag) {
      return function (headers) { return headers['If-None-Match'] === etag; };
    };

    ifEtagIsNot = function (etag) {
      return function (headers) { return headers['If-None-Match'] !== etag; };
    };

    serverData = { id:1, content:'Test data' };

    $httpBackend
      .whenGET('/1.json', ifEtagIsNot('1'))
      .respond(serverData, { 'etag': '1' });
    $httpBackend
      .whenGET('/1.json', ifEtagIs('1'))
      .respond(304);

    $httpBackend
      .whenGET('/1.json?param=test', ifEtagIsNot('1'))
      .respond(serverData, { 'etag': '1' });
    $httpBackend
      .whenGET('/1.json?param=test', ifEtagIs('1'))
      .respond(304);

  }));

  it('should cache ETags', function () {
    $http.get('/1.json', { etag: true })
      .success(onSuccess);
    $httpBackend.flush();

    $http.get('/1.json', { etag: true })
      .error(onError);
    $httpBackend.flush();

    onSuccess.should.have.been.called();
    onError.should.have.been.called();
  });

  it('should cache data', function () {
    var userData;

    $http.get('/1.json', { etag: true })
      .success(onSuccess);
    $httpBackend.flush();

    $http.get('/1.json', { etag: true })
      .cache(function (data) {
        userData = data;
      })
      .error(onError);
    $httpBackend.flush();

    userData.should.deep.equal(serverData);
    onError.should.have.been.called();
  });

  it('should function normally without ETag config property', function () {
    $http.get('/1.json').success(onSuccess);
    $httpBackend.flush();

    $http.get('/1.json').error(onError);
    $httpBackend.flush();

    onSuccess.should.have.been.called();
    onError.should.not.have.been.called();
  });

  it('should cache ETags for requests with query params', function () {
    $http.get('/1.json', { etag: true, params: { param: 'test' } })
      .success(onSuccess);
    $httpBackend.flush();

    $http.get('/1.json', { etag: true, params: { param: 'test' } })
      .error(onError);
    $httpBackend.flush();

    onSuccess.should.have.been.called();
    onError.should.have.been.called();
  });

});
<|endoftext|>


<commit_before>import React from 'react';
import { c } from 'ttag';
import PropTypes from 'prop-types';
import { Alert, Label, Table, TableHeader, TableBody, TableRow } from 'react-components';

const VerifySection = ({ domain }) => {
    return (
        <>
            <Alert learnMore="https://protonmail.com/support/knowledge-base/dns-records/">
                {c('Info for domain modal')
                    .t`For security reasons, we need to verify that you are the owner of your domain. Please add the following code into your DNS record.`}
            </Alert>
            <Alert type="warning">
                {c('Warning for domain modal').t`Do not remove it even after successful verification.`}

                {c('Warning for domain modal')
                    .t`This can typically be done in the control panel of your domain name registrar.`}
            </Alert>
            {c('Label for domain modal').t`Please add the following TXT record:`}

                <TableHeader
                    cells={[
                        c('Header for domain modal').t`Type`,
                        c('Header for domain modal').t`Host name`,
                        c('Header for domain modal').t`Value / Data / Points to`
                    ]}
                />
                <TableBody>
                    <TableRow cells={['TXT', '@', domain.VerifyCode]} />
                </TableBody>

            <Alert type="warning">{c('Warning for domain modal')
                .t`It can take up to a day for DNS changes to update.`}</Alert>
        </>
    );
};

VerifySection.propTypes = {
    domain: PropTypes.object.isRequired
};

export default VerifySection;
<commit_msg>Fix MAILWEB-387 - Review Verify table in domain config<commit_after>import React from 'react';
import { c } from 'ttag';
import PropTypes from 'prop-types';
import { Alert, Label, Table, TableHeader, TableBody, TableRow, Copy, useNotifications } from 'react-components';

const VerifySection = ({ domain }) => {
    const { createNotification } = useNotifications();
    const handleCopy = () => createNotification({ text: c('Success').t`Verify code copied to clipboard!` });
    return (
        <>
            <Alert learnMore="https://protonmail.com/support/knowledge-base/dns-records/">
                {c('Info for domain modal')
                    .t`For security reasons, we need to verify that you are the owner of your domain. Please add the following code into your DNS record.`}
            </Alert>
            <Alert type="warning">
                {c('Warning for domain modal').t`Do not remove it even after successful verification.`}

                {c('Warning for domain modal')
                    .t`This can typically be done in the control panel of your domain name registrar.`}
            </Alert>
            {c('Label for domain modal').t`Please add the following TXT record:`}

                <TableHeader
                    cells={[
                        c('Header for domain modal').t`Type`,
                        c('Header for domain modal').t`Host name`,
                        c('Header for domain modal').t`Value / Data / Points to`
                    ]}
                />
                <TableBody>
                    <TableRow
                        cells={[
                            TXT,
                            @,

                                <Copy
                                    onCopy={handleCopy}
                                    className="flex-item-noshrink pm-button--small mr0-5"
                                    value={domain.VerifyCode}
                                />{' '}

                                    {domain.VerifyCode}

                        ]}
                    />
                </TableBody>

            <Alert type="warning">{c('Warning for domain modal')
                .t`It can take up to a day for DNS changes to update.`}</Alert>
        </>
    );
};

VerifySection.propTypes = {
    domain: PropTypes.object.isRequired
};

export default VerifySection;
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
  User = mongoose.model('User'),
  _ = require('lodash'),
  config = require('meanio').loadConfig(),
  templates = require('../template'),
  nodemailer = require('nodemailer'),
  smtpTransport = require('nodemailer-smtp-transport'),
  EmailTemplate = require('../../../mail-templates/node_modules/email-templates').EmailTemplate,
  path = require('path');

function sendMail(mailOptions) {
  var options = config.mailer;

  if (config.mailer.service === 'SMTP') {
    options = smtpTransport(options);
  }

  var transport = nodemailer.createTransport(options);

  transport.sendMail(mailOptions, function (err, response) {
    console.log(err, response);
    if (err) return err;
    return response;
  });
}

//temporary function
//send should be deleted latter and use this function
//as sole interface to main manager
exports.sendEx = function (type, data) {
  if (type === 'comment_email') {
    //template format does not compatible yet
    //use send function
    return;
  }

  data.uriRoot = config.icu.uri;
  data.date = new Date();
  data.attendees = _(data.discussion.watchers).map(function (w) {
    return w.name;
  }).join(', ');

  var templateDir = path.join(__dirname, '..', 'templates', type);
  var template = new EmailTemplate(templateDir);

  template.render(data, function (err, results) {
    if (err) {
      console.log(err.message);
      console.log(err.stack);
    } else {
      console.log(results.html);
    }

    //add discussion owner
    data.discussion.watchers.push(data.assign);
    data.discussion.watchers.forEach(function (watcher) {
      var mailOptions = {
        to: watcher.email,
        from: config.emailFrom,
        subject: data.discussion.title,
        html: results.html,
        text: results.text,
        forceEmbeddedImages: true
      };

      sendMail(mailOptions);
    });
  });
};

exports.send = function (doc, task) {
  var arr = doc.text.match(/@([^ :]*)*/g);
  arr = arr.map(function (item) {
    return item.slice(1)
  });
  User.findOne({
    _id: doc.creator
  }).exec(function (err, from) {
    User.find({
      username: {
        $in: arr
      }
    }).exec(function (err, users) {

      for (var i = 0; i < users.length; i += 1) {
        var user = users[i];
        var mailOptions = {
          to: user.email,
          from: config.emailFrom
        };
        mailOptions = templates.comment_email(user, doc.text, from, task, config.icu.uri, mailOptions);
        sendMail(mailOptions);
      }
    });
  });
};
<commit_msg>fix send mail<commit_after>'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
  User = mongoose.model('User'),
  _ = require('lodash'),
  config = require('meanio').loadConfig(),
  templates = require('../template'),
  nodemailer = require('nodemailer'),
  smtpTransport = require('nodemailer-smtp-transport'),
  EmailTemplate = require('../../../mail-templates/node_modules/email-templates').EmailTemplate,
  path = require('path');

function sendMail(mailOptions) {
  var options = config.mailer;

  if (config.mailer.service === 'SMTP') {
    options = smtpTransport(options);
  }

  var transport = nodemailer.createTransport(options);

  transport.sendMail(mailOptions, function (err, response) {
    console.log(err, response);
    if (err) return err;
    return response;
  });
}

//temporary function
//send should be deleted latter and use this function
//as sole interface to main manager
exports.sendEx = function (type, data) {
  if (type === 'comment_email') {
    //template format does not compatible yet
    //use send function
    return;
  }

  data.uriRoot = config.icu.uri;
  data.date = new Date();
  data.attendees = _(data.discussion.watchers).map(function (w) {
    return w.name;
  }).join(', ');

  var templateDir = path.join(__dirname, '..', 'templates', type);
  var template = new EmailTemplate(templateDir);

  template.render(data, function (err, results) {
    if (err) {
      console.log(err.message);
      console.log(err.stack);
    } else {
      console.log(results.html);
    }

    //add discussion owner
    data.discussion.watchers.push(data.discussion.assign);

    data.discussion.watchers.forEach(function (watcher) {
      var mailOptions = {
        to: watcher.email,
        from: config.emailFrom,
        subject: data.discussion.title,
        html: results.html,
        text: results.text,
        forceEmbeddedImages: true
      };

      sendMail(mailOptions);
    });
  });
};

exports.send = function (doc, task) {
  var arr = doc.text.match(/@([^ :]*)*/g);
  arr = arr.map(function (item) {
    return item.slice(1)
  });
  User.findOne({
    _id: doc.creator
  }).exec(function (err, from) {
    User.find({
      username: {
        $in: arr
      }
    }).exec(function (err, users) {

      for (var i = 0; i < users.length; i += 1) {
        var user = users[i];
        var mailOptions = {
          to: user.email,
          from: config.emailFrom
        };
        mailOptions = templates.comment_email(user, doc.text, from, task, config.icu.uri, mailOptions);
        sendMail(mailOptions);
      }
    });
  });
};
<|endoftext|>