<commit_before>var assert = require('assert');
var reaccess = require('../src');
var request = require('supertest');
var express = require('express');

describe('reacesss should throw err', function() {

  it('when there is no rights', function(done) {
    testReq()
      .expect(500, 'Unauthorized access!')
      .end(function(err, res){
        if(err) throw err;
        done();
      });
  });
    it('when there is no rights matching the path', function(done) {
      testReq({
        rightsObj: {
          path: '/bar',
          methods: reaccess.METHODS
        }
      })
      .expect(500, /The rights property must be an array/)
      .end(function(err, res){
        if(err) throw err;
        done();
      });
    });

    it('when there is no rights matching the path', function(done) {
      testReq({
        rightsObj: [{
          path: '/bar',
          methods: reaccess.METHODS
        },{
          path: '/plop',
          methods: reaccess.METHODS
        }]
      })
      .expect(500, /Unauthorized access!/)
      .end(function(err, res){
        if(err) throw err;
        done();
      });
    });

    it('when there is no rights matching the templated path', function(done) {
      testReq({
        rightsObj: [{
          path: '/bar',
          methods: reaccess.METHODS
        },{
          path: '/plop',
          methods: reaccess.METHODS
        }]
      })
      .expect(500, /Unauthorized access!/)
      .end(function(err, res){
        if(err) throw err;
        done();
      });
    });

    it('when there is no rights matching the method', function(done) {
      testReq({
        rightsObj: [{
          path: '/foo/:bar.ba.pa.pa/plop',
          methods: reaccess.METHODS ^ reaccess.GET
        },{
          path: '/plop',
          methods: reaccess.METHODS
        }]
      })
      .expect(500, /Unauthorized access!/)
      .end(function(err, res){
        if(err) throw err;
        done();
      });
    });

});

describe('reacesss should work', function() {

    it('when there is one right that match', function(done) {
      testReq({
        rightsObj: [{
          path: '/foo',
          methods: reaccess.ALL_MASK
        },{
          path: '/plop',
          methods: reaccess.ALL_MASK
        }]
      })
      .expect(200, 'plop')
      .end(function(err, res){
        if(err) throw err;
        done();
      });
    });

    it('when there is one templated right that match', function(done) {
      testReq({
        rightsObj: [{
          path: '/foo/:bar.ba.pa.pa/plop',
          methods: reaccess.ALL_MASK
        },{
          path: '/plop/:foo/bar',
          methods: reaccess.ALL_MASK
        }],
        userProp: 'user.content',
        userObj: {
          bar: {
            ba: {
              pa: {
                pa: 1
              }
            }
          },
          lol: 2
        }
      }, {
        userProp: 'user.content'
      }, '/foo/1/plop')
      .expect(200, 'plop')
      .end(function(err, res){
        if(err) throw err;
        done();
      });
    });

    it('when a templated right contains special regexp chars', function(done) {
      testReq({
        rightsObj: [{
          path: '/foo/:bar/plop',
          methods: reaccess.ALL_MASK
        },{
          path: '/plop/:foo/bar',
          methods: reaccess.ALL_MASK
        }],
        userProp: 'user.content',
        userObj: {
          bar: 'a',
          plop: '|)}'
        }
      }, {
        userProp: 'user.content'
      }, '/foo/a/plop')
      .expect(200, 'plop')
      .end(function(err, res){
        if(err) throw err;
        done();
      });
    });

    it('when there is one templated right with a wildcard that match', function(done) {
      testReq({
        rightsObj: [{
          path: '/foo/:bar.ba.*.pa.*.pa/plop',
          methods: reaccess.ALL_MASK
        },{
          path: '/plop/:foo/bar',
          methods: reaccess.ALL_MASK
        }],
        userProp: 'user.content',
        userObj: {
          bar: {
            ba: [{
              pa: {
                pip: {
                  pa: 1
                }
              }
            }]
          },
          lol: 2
        }
      }, {
        userProp: 'user.content'
      }, '/foo/1/plop')
      .expect(200, 'plop')
      .end(function(err, res){
        if(err) throw err;
        done();
      });
    });

    it('when there is one templated right with a #/@ special cards that match', function(done) {
      testReq({
        rightsObj: [{
          path: '/foo/:bar.ba.#.pa.@.pa/plop',
          methods: reaccess.ALL_MASK
        },{
          path: '/plop/:foo/bar',
          methods: reaccess.ALL_MASK
        }],
        userProp: 'user.content',
        userObj: {
          bar: {
            ba: [{
              pa: {
                plop: {
                  pa: 1
                }
              }
            }]
          },
          lol: 2
        }
      }, {
        userProp: 'user.content'
      }, '/foo/1/plop')
      .expect(200, 'plop')
      .end(function(err, res){
        if(err) throw err;
        done();
      });
    });

    it('when there is one templated right with a wildcard that match but is not the first', function(done) {
      testReq({
        rightsObj: [{
          path: '/foo/:bar.ba.*.pa.*.pa/plop',
          methods: reaccess.ALL_MASK
        },{
          path: '/plop/:foo/bar',
          methods: reaccess.ALL_MASK
        }],
        userProp: 'user.content',
        userObj: {
          bar: {
            ba: [{
              pa: {
                pa: {
                  pa: 2
                }
              }
            }, {
              pa: {
                pip: {
                  pa: 1
                }
              }
            }]
          }
        }
      }, {
        userProp: 'user.content'
      }, '/foo/1/plop')
      .expect(200, 'plop')
      .end(function(err, res){
        if(err) throw err;
        done();
      });
    });

});

// Helper middleware
function testReq(props, opts, path) {
  var app = express();
  app.use(setProps(props));
  app.use(reaccess(opts));
  app.use(path || '/foo', function(req, res, next) {
    res.send(200, 'plop');
  });
  app.use(function(err, req, res, next) {
    res.send(500, err.message);
  });

  return request(app).get(path || '/foo');
}

function setProps(options) {
  options = options || {};
  options.rightsProp = options.rightsProp || 'user.rights';
  options.rightsObj = options.rightsObj || [];
  options.userProp = options.userProp || '';
  options.userObj = options.userObj || {};
  return function (req, res, next) {
    setProp(req, options.rightsProp,  options.rightsObj);
    if(options.userProp) {
      setProp(req, options.userProp,  options.userObj);
    }
    next();
  };
}

function setProp(obj, prop, value) {
  var nodes = prop.split('.');
  var node;
  do {
    node = nodes.shift();
    if(nodes.length) {

      obj = obj[node] || (obj[node] = {});
    }
  } while(nodes.length);
  obj[node] = value;
}

<commit_msg>Fixing tests<commit_after>var assert = require('assert');
var reaccess = require('../src');
var request = require('supertest');
var express = require('express');

describe('reacesss should throw err', function() {

  it('when there is no rights', function(done) {
    testReq()
      .expect(500, 'Unauthorized access!')
      .end(function(err, res){
        if(err) throw err;
        done();
      });
  });
    it('when there is no rights matching the path', function(done) {
      testReq({
        rightsObj: {
          path: '/bar',
          methods: reaccess.ALL_MASK
        }
      })
      .expect(500, /The rights property must be an array/)
      .end(function(err, res){
        if(err) throw err;
        done();
      });
    });

    it('when there is no rights matching the path', function(done) {
      testReq({
        rightsObj: [{
          path: '/bar',
          methods: reaccess.ALL_MASK
        },{
          path: '/plop',
          methods: reaccess.ALL_MASK
        }]
      })
      .expect(500, /Unauthorized access!/)
      .end(function(err, res){
        if(err) throw err;
        done();
      });
    });

    it('when there is no rights matching the templated path', function(done) {
      testReq({
        rightsObj: [{
          path: '/bar',
          methods: reaccess.ALL_MASK
        },{
          path: '/plop',
          methods: reaccess.ALL_MASK
        }]
      })
      .expect(500, /Unauthorized access!/)
      .end(function(err, res){
        if(err) throw err;
        done();
      });
    });

    it('when there is no rights matching the method', function(done) {
      testReq({
        rightsObj: [{
          path: '/foo/:bar.ba.pa.pa/plop',
          methods: reaccess.ALL_MASK ^ reaccess.GET
        },{
          path: '/plop',
          methods: reaccess.ALL_MASK
        }]
      })
      .expect(500, /Unauthorized access!/)
      .end(function(err, res){
        if(err) throw err;
        done();
      });
    });

});

describe('reacesss should work', function() {

    it('when there is one right that match', function(done) {
      testReq({
        rightsObj: [{
          path: '/foo',
          methods: reaccess.ALL_MASK
        },{
          path: '/plop',
          methods: reaccess.ALL_MASK
        }]
      })
      .expect(200, 'plop')
      .end(function(err, res){
        if(err) throw err;
        done();
      });
    });

    it('when there is one templated right that match', function(done) {
      testReq({
        rightsObj: [{
          path: '/foo/:bar.ba.pa.pa/plop',
          methods: reaccess.ALL_MASK
        },{
          path: '/plop/:foo/bar',
          methods: reaccess.ALL_MASK
        }],
        userProp: 'user.content',
        userObj: {
          bar: {
            ba: {
              pa: {
                pa: 1
              }
            }
          },
          lol: 2
        }
      }, {
        userProp: 'user.content'
      }, '/foo/1/plop')
      .expect(200, 'plop')
      .end(function(err, res){
        if(err) throw err;
        done();
      });
    });

    it('when a templated right contains special regexp chars', function(done) {
      testReq({
        rightsObj: [{
          path: '/foo/:bar/plop',
          methods: reaccess.ALL_MASK
        },{
          path: '/plop/:foo/bar',
          methods: reaccess.ALL_MASK
        }],
        userProp: 'user.content',
        userObj: {
          bar: 'a',
          plop: '|)}'
        }
      }, {
        userProp: 'user.content'
      }, '/foo/a/plop')
      .expect(200, 'plop')
      .end(function(err, res){
        if(err) throw err;
        done();
      });
    });

    it('when there is one templated right with a wildcard that match', function(done) {
      testReq({
        rightsObj: [{
          path: '/foo/:bar.ba.*.pa.*.pa/plop',
          methods: reaccess.ALL_MASK
        },{
          path: '/plop/:foo/bar',
          methods: reaccess.ALL_MASK
        }],
        userProp: 'user.content',
        userObj: {
          bar: {
            ba: [{
              pa: {
                pip: {
                  pa: 1
                }
              }
            }]
          },
          lol: 2
        }
      }, {
        userProp: 'user.content'
      }, '/foo/1/plop')
      .expect(200, 'plop')
      .end(function(err, res){
        if(err) throw err;
        done();
      });
    });

    it('when there is one templated right with a #/@ special cards that match', function(done) {
      testReq({
        rightsObj: [{
          path: '/foo/:bar.ba.#.pa.@.pa/plop',
          methods: reaccess.ALL_MASK
        },{
          path: '/plop/:foo/bar',
          methods: reaccess.ALL_MASK
        }],
        userProp: 'user.content',
        userObj: {
          bar: {
            ba: [{
              pa: {
                plop: {
                  pa: 1
                }
              }
            }]
          },
          lol: 2
        }
      }, {
        userProp: 'user.content'
      }, '/foo/1/plop')
      .expect(200, 'plop')
      .end(function(err, res){
        if(err) throw err;
        done();
      });
    });

    it('when there is one templated right with a wildcard that match but is not the first', function(done) {
      testReq({
        rightsObj: [{
          path: '/foo/:bar.ba.*.pa.*.pa/plop',
          methods: reaccess.ALL_MASK
        },{
          path: '/plop/:foo/bar',
          methods: reaccess.ALL_MASK
        }],
        userProp: 'user.content',
        userObj: {
          bar: {
            ba: [{
              pa: {
                pa: {
                  pa: 2
                }
              }
            }, {
              pa: {
                pip: {
                  pa: 1
                }
              }
            }]
          }
        }
      }, {
        userProp: 'user.content'
      }, '/foo/1/plop')
      .expect(200, 'plop')
      .end(function(err, res){
        if(err) throw err;
        done();
      });
    });

});

// Helper middleware
function testReq(props, opts, path) {
  var app = express();
  app.use(setProps(props));
  app.use(reaccess(opts));
  app.use(path || '/foo', function(req, res, next) {
    res.send(200, 'plop');
  });
  app.use(function(err, req, res, next) {
    res.send(500, err.message);
  });

  return request(app).get(path || '/foo');
}

function setProps(options) {
  options = options || {};
  options.rightsProp = options.rightsProp || 'user.rights';
  options.rightsObj = options.rightsObj || [];
  options.userProp = options.userProp || '';
  options.userObj = options.userObj || {};
  return function (req, res, next) {
    setProp(req, options.rightsProp,  options.rightsObj);
    if(options.userProp) {
      setProp(req, options.userProp,  options.userObj);
    }
    next();
  };
}

function setProp(obj, prop, value) {
  var nodes = prop.split('.');
  var node;
  do {
    node = nodes.shift();
    if(nodes.length) {

      obj = obj[node] || (obj[node] = {});
    }
  } while(nodes.length);
  obj[node] = value;
}

<|endoftext|>


<commit_before>const { Gpio } = require( 'onoff' );
var socket = require('socket.io-client')('http://localhost:3000');

// set BCM 4 pin as 'output'
const in1 = new Gpio('4', 'out')
const in2  = new Gpio( '17', 'out' );
const in3 = new Gpio('27', 'out');
const in4 = new Gpio('22', 'out')

// current LED state
let isLedOn = false;

function driveReset () {
    in1.writeSync(0);
    in2.writeSync(0);
    in3.writeSync(0);
    in4.writeSync(0);
}

function driveLeft () {
    in1.writeSync(1);
    in2.writeSync(0);
    in3.writeSync(1);
    in4.writeSync(0);
}

function driveRight () {
    in1.writeSync(0);
    in2.writeSync(0);
    in3.writeSync(0);
    in4.writeSync(0);
}

function driveForward () {
    in1.writeSync(0);
    in2.writeSync(0);
    in3.writeSync(0);
    in4.writeSync(0);
}

function driveBackward () {
    in1.writeSync(0);
    in2.writeSync(0);
    in3.writeSync(0);
    in4.writeSync(0);
}

driveReset();

socket.on('connect', function(){
    console.log("Connected to weebo server");
});

socket.on('weebo-control', function(data){
    console.log("Received instruction:", data);
    driveReset();
    switch (data) {
        case "l":
            console.log("going left")
            driveLeft();
            break;
        case "r":
            console.log("going right")
            driveRight();
            break;
        case "f":
            console.log("going forward");
            driveForward();
            break;
        case "b":
            console.log("going backward")
            driveBackward();
            break;
        default:
            console.log("stopping")
            driveReset();
            break;
    }
});

socket.on('disconnect', function(){
    console.log("Disconnected from weebo server");
});

/*
// run a infinite interval
setInterval( () => {
  in1.writeSync( isLedOn ? 0 : 1 ); // provide 1 or 0
  isLedOn = !isLedOn; // toggle state
  console.log("LED: ", isLedOn)
}, 3000 ); // 3s
*/<commit_msg>Drive instructions<commit_after>const { Gpio } = require( 'onoff' );
var socket = require('socket.io-client')('http://localhost:3000');

// set BCM 4 pin as 'output'
const in1 = new Gpio('4', 'out')
const in2  = new Gpio( '17', 'out' );
const in3 = new Gpio('27', 'out');
const in4 = new Gpio('22', 'out')

// current LED state
let isLedOn = false;

function driveReset () {
    in1.writeSync(0);
    in2.writeSync(0);
    in3.writeSync(0);
    in4.writeSync(0);
}

function driveLeft () {
    in1.writeSync(1);
    in2.writeSync(0);
    in3.writeSync(0);
    in4.writeSync(1);
}

function driveRight () {
    in1.writeSync(0);
    in2.writeSync(1);
    in3.writeSync(1);
    in4.writeSync(0);
}

function driveForward () {
    in1.writeSync(1);
    in2.writeSync(0);
    in3.writeSync(1);
    in4.writeSync(0);
}

function driveBackward () {
    in1.writeSync(0);
    in2.writeSync(1);
    in3.writeSync(0);
    in4.writeSync(1);
}

driveReset();

socket.on('connect', function(){
    console.log("Connected to weebo server");
});

socket.on('weebo-control', function(data){
    console.log("Received instruction:", data);
    driveReset();
    switch (data) {
        case "l":
            console.log("going left")
            driveLeft();
            break;
        case "r":
            console.log("going right")
            driveRight();
            break;
        case "f":
            console.log("going forward");
            driveForward();
            break;
        case "b":
            console.log("going backward")
            driveBackward();
            break;
        default:
            console.log("stopping")
            driveReset();
            break;
    }
});

socket.on('disconnect', function(){
    console.log("Disconnected from weebo server");
});

/*
// run a infinite interval
setInterval( () => {
  in1.writeSync( isLedOn ? 0 : 1 ); // provide 1 or 0
  isLedOn = !isLedOn; // toggle state
  console.log("LED: ", isLedOn)
}, 3000 ); // 3s
*/<|endoftext|>


<commit_before>//simple code that allows you to browser hair/horns or fanart.
window.onload = function() {
	loadNavbar();
	if (getParameterByName("hair")  == "true") renderAllHair();
	if (getParameterByName("horns")  == "true") renderAllHorns();
	if (getParameterByName("grimAB")  == "true") renderFanArtGrimAB();
}

//don't hard code fan art, instead, scrape all files of .png or .jpg or .gif or .jpeg out of a given folder and render.
function renderFanArtGrimAB(){
	//var folder = "images/misc/fanArt/ABFanArt/"
	var folder = "http://farragofiction.com/SBURBSimE/images/misc/fanArt/ABFanArt/";
	renderAllImagesInFolder(folder); //if can't scrape from local computer, make this an absolute reference to server.  haha, no i can't cross session scripting is a bitch. HAVE to test on server l8r.
}

//use ajax to get index file, then do yo thang.
//https://stackoverflow.com/questions/22061073/how-do-i-get-images-file-name-from-a-given-folder
function renderAllImagesInFolder(folder){
	var fileExt = {};
    fileExt[0]=".png";
    fileExt[1]=".jpg";
    fileExt[2]=".gif";
	fileExt[2]=".jpeg";
		$.ajax({
			//This will retrieve the contents of the folder if the folder is configured as 'browsable'
			url: folder,
			success: function (data) {
			   //List all png or jpg or gif file names in the page
			   $(data).find("a:contains(" + fileExt[0] + "),a:contains(" + fileExt[1] + "),a:contains(" + fileExt[2] + ")").each(function () {
				  // var filename = this.href.replace(window.location.host, "").replace("http:///", "");
					console.log(this.href);
					var filename = folder + this.href;
				   renderRegularSprite(new SpritePart(filename, filename));
			   });
			 }

		  });
}

function renderRegularSprite(spritePart){
	$("#images").append("
"+spritePart.name);
}

function renderAllHair(){
	var minHair = 1;
	var blankPlayer = new Player();
	var maxHair = blankPlayer.maxHairNumber
	//don't use canvas, but still layer?  bg, like for KR.
	for(var i = minHair; i<= maxHair; i++){
			renderLayeredSprites([new SpritePart("images/Hair/hair_back"+i+".png", "Hair " +i),new SpritePart("images/Hair/head.png", ""), new SpritePart("images/Hair/hair"+i+".png", "")]);
	}
}

function renderAllHorns(){
	var minHorn = 1
	var blankPlayer = new Player();
	var maxHorn = blankPlayer.maxHornNumber
	for(var i = minHorn; i<= maxHorn; i++){
			renderLayeredSprites([new SpritePart("images/Horns/left"+i+".png","leftHorn "+i),new SpritePart("images/Horns/right"+i+".png", "rightHorn" +i)]);
	}
}

//first thing on bottom, last thing on top
function renderLayeredSprites(spriteArray){
	var html = "
"; //all images should be rendered at same position in sprite parent
	for(var i = 0; i<spriteArray.length; i++){
		html += "
"+spriteArray[i].name;
	}
	html += "
"
	$("#images").append(html);
}

function SpritePart(location, name){
	this.location = location;
	this.name = name;
}
<commit_msg>testing<commit_after>//simple code that allows you to browser hair/horns or fanart.
window.onload = function() {
	loadNavbar();
	if (getParameterByName("hair")  == "true") renderAllHair();
	if (getParameterByName("horns")  == "true") renderAllHorns();
	if (getParameterByName("grimAB")  == "true") renderFanArtGrimAB();
}

//don't hard code fan art, instead, scrape all files of .png or .jpg or .gif or .jpeg out of a given folder and render.
function renderFanArtGrimAB(){
	//var folder = "images/misc/fanArt/ABFanArt/"
	var folder = "http://farragofiction.com/SBURBSimE/images/misc/fanArt/ABFanArt/";
	renderAllImagesInFolder(folder); //if can't scrape from local computer, make this an absolute reference to server.  haha, no i can't cross session scripting is a bitch. HAVE to test on server l8r.
}

//use ajax to get index file, then do yo thang.
//https://stackoverflow.com/questions/22061073/how-do-i-get-images-file-name-from-a-given-folder
function renderAllImagesInFolder(folder){
	var fileExt = {};
    fileExt[0]=".png";
    fileExt[1]=".jpg";
    fileExt[2]=".gif";
	fileExt[2]=".jpeg";
		$.ajax({
			//This will retrieve the contents of the folder if the folder is configured as 'browsable'
			url: folder,
			success: function (data) {
			   //List all png or jpg or gif file names in the page
			   $(data).find("a:contains(" + fileExt[0] + "),a:contains(" + fileExt[1] + "),a:contains(" + fileExt[2] + ")").each(function () {
				  var filename = this.href.replace(window.location.host, "").replace("http:///", "");
					console.log(this.href);
					//var filename = this.href;
				   renderRegularSprite(new SpritePart(filename, filename));
			   });
			 }

		  });
}

function renderRegularSprite(spritePart){
	$("#images").append("
"+spritePart.name);
}

function renderAllHair(){
	var minHair = 1;
	var blankPlayer = new Player();
	var maxHair = blankPlayer.maxHairNumber
	//don't use canvas, but still layer?  bg, like for KR.
	for(var i = minHair; i<= maxHair; i++){
			renderLayeredSprites([new SpritePart("images/Hair/hair_back"+i+".png", "Hair " +i),new SpritePart("images/Hair/head.png", ""), new SpritePart("images/Hair/hair"+i+".png", "")]);
	}
}

function renderAllHorns(){
	var minHorn = 1
	var blankPlayer = new Player();
	var maxHorn = blankPlayer.maxHornNumber
	for(var i = minHorn; i<= maxHorn; i++){
			renderLayeredSprites([new SpritePart("images/Horns/left"+i+".png","leftHorn "+i),new SpritePart("images/Horns/right"+i+".png", "rightHorn" +i)]);
	}
}

//first thing on bottom, last thing on top
function renderLayeredSprites(spriteArray){
	var html = "
"; //all images should be rendered at same position in sprite parent
	for(var i = 0; i<spriteArray.length; i++){
		html += "
"+spriteArray[i].name;
	}
	html += "
"
	$("#images").append(html);
}

function SpritePart(location, name){
	this.location = location;
	this.name = name;
}
<|endoftext|>


<commit_before>// Simulate config options from your production environment by
// customising the .env file in your project's root folder.
require('dotenv').config();

// Require keystone
var keystone = require('keystone');

// Initialise Keystone with your project's configuration.
// See http://keystonejs.com/guide/config for available options
// and documentation.

keystone.init({
	'name': 'Little Benchmark BOM',
	'brand': 'Little Benchmark BOM',

	'less': 'public',
	'static': 'public',
	'favicon': 'public/favicon.ico',
	'views': 'templates/views',
	'view engine': 'jade',

	'emails': 'templates/emails',

	'auto update': true,
	'session': true,
	'auth': true,
	'user model': 'User',
});

// Load your project's Models
keystone.import('models');

// Setup common locals for your templates. The following are required for the
// bundled templates and layouts. Any runtime locals (that should be set uniquely
// for each request) should be added to ./routes/middleware.js
keystone.set('locals', {
	_: require('lodash'),
	env: keystone.get('env'),
	utils: keystone.utils,
	editable: keystone.content.editable,
});

// Load your project's Routes
keystone.set('routes', require('./routes'));

// Setup common locals for your emails. The following are required by Keystone's
// default email templates, you may remove them if you're using your own.
keystone.set('email locals', {
	logo_src: '/images/logo-email.gif',
	logo_width: 194,
	logo_height: 76,
	theme: {
		email_bg: '#f9f9f9',
		link_color: '#2697de',
		buttons: {
			color: '#fff',
			background_color: '#2697de',
			border_color: '#1a7cb7',
		},
	},
});

// Load your project's email test routes
keystone.set('email tests', require('./routes/emails'));

// Configure the navigation bar in Keystone's Admin UI
keystone.set('nav', {
	posts: ['posts', 'post-categories'],
	enquiries: 'enquiries',
	users: 'users',
});

keystone.set('s3 config', { bucket: process.env.AMAZON_BUCKET, key: process.env.AMAZON_KEY, secret: process.env.AMAZON_SECRET });

// Start Keystone to connect to your database and initialise the web server

keystone.start();
<commit_msg>Minor updates<commit_after>// Simulate config options from your production environment by
// customising the .env file in your project's root folder.
if(process.env.LOCAL_DEV){
	require('dotenv').config();
}

// Require keystone
var keystone = require('keystone');

// Initialise Keystone with your project's configuration.
// See http://keystonejs.com/guide/config for available options
// and documentation.

keystone.init({
	'name': 'Little Benchmark BOM',
	'brand': 'Little Benchmark BOM',

	'less': 'public',
	'static': 'public',
	'favicon': 'public/favicon.ico',
	'views': 'templates/views',
	'view engine': 'jade',

	'emails': 'templates/emails',

	'auto update': true,
	'session': true,
	'auth': true,
	'user model': 'User',
});

// Load your project's Models
keystone.import('models');

// Setup common locals for your templates. The following are required for the
// bundled templates and layouts. Any runtime locals (that should be set uniquely
// for each request) should be added to ./routes/middleware.js
keystone.set('locals', {
	_: require('lodash'),
	env: keystone.get('env'),
	utils: keystone.utils,
	editable: keystone.content.editable,
});

// Load your project's Routes
keystone.set('routes', require('./routes'));

// Setup common locals for your emails. The following are required by Keystone's
// default email templates, you may remove them if you're using your own.
keystone.set('email locals', {
	logo_src: '/images/logo-email.gif',
	logo_width: 194,
	logo_height: 76,
	theme: {
		email_bg: '#f9f9f9',
		link_color: '#2697de',
		buttons: {
			color: '#fff',
			background_color: '#2697de',
			border_color: '#1a7cb7',
		},
	},
});

// Load your project's email test routes
keystone.set('email tests', require('./routes/emails'));

// Configure the navigation bar in Keystone's Admin UI
keystone.set('nav', {
	posts: ['posts', 'post-categories'],
	enquiries: 'enquiries',
	users: 'users',
});

keystone.set('s3 config', { bucket: process.env.AMAZON_BUCKET, key: process.env.AMAZON_KEY, secret: process.env.AMAZON_SECRET });

keystone.set('embedly api key', process.env.EMBEDLY_API_KEY);

keystone.set('mandrill api key', process.env.MANDRILL_API_KEY);
keystone.set('mandrill username', process.env.MANDRILL_USERNAME);

// Start Keystone to connect to your database and initialise the web server

keystone.start();
<|endoftext|>


<commit_before>/* eslint max-nested-callbacks:0 func-names:0 */

'use strict';

var gulp = require('gulp');
var gutil = require('gulp-util');
var Stream = require('stream');
var fs = require('fs');
var path = require('path');

var assert = require('assert');
var StreamTest = require('streamtest');

var ttf2eot = require('../src/index.js');

// Erasing date to get an invariant created and modified font date
// See: https://github.com/fontello/ttf2eot/blob/c6de4bd45d50afc6217e150dbc69f1cd3280f8fe/lib/sfnt.js#L19
Date = (function(d) {
  function Date() {
    d.call(this, 3600);
  }
  Date.now = d.now;
  return Date;
})(Date);

describe('gulp-ttf2eot conversion', function() {
  var filename = path.joinf(__dirname, 'fixtures', 'iconsfont');
  var eot = fs.readFileSync(filename + '.eot');

  // Iterating through versions
  StreamTest.versions.forEach(function(version) {

    describe('for ' + version + ' streams', function() {

      describe('with null contents', function() {

        it('should let null files pass through', function(done) {

          StreamTest[version].fromObjects([new gutil.File({
            path: 'bibabelula.foo',
            contents: null,
          })])
          .pipe(ttf2eot())
          .pipe(StreamTest[version].toObjects(function(err, objs) {
            if(err) {
              return done(err);
            }
            assert.equal(objs.length, 1);
            assert.equal(objs[0].path, 'bibabelula.foo');
            assert.equal(objs[0].contents, null);
            done();
          }));

        });

      });

      describe('in buffer mode', function() {

        it('should work', function(done) {

          gulp.src(filename + '.ttf', { buffer: true })
            .pipe(ttf2eot())
            // Uncomment to regenerate the test files if changes in the ttf2eot lib
            // .pipe(gulp.dest(__dirname + '/fixtures/'))
            .pipe(StreamTest[version].toObjects(function(err, objs) {
              if(err) {
                return done(err);
              }
              assert.equal(objs.length, 1);
              assert.equal(objs[0].path, filename + '.eot');
              assert.equal(objs[0].contents.toString('utf-8'), eot.toString('utf-8'));
              done();
            }));

        });

        it('should work with the clone option', function(done) {

          gulp.src(filename + '.ttf', { buffer: true })
            .pipe(ttf2eot({ clone: true }))
            .pipe(StreamTest[version].toObjects(function(err, objs) {
              if(err) {
                return done(err);
              }
              assert.equal(objs.length, 2);
              assert.equal(objs[0].path, filename + '.ttf');
              assert.equal(
                objs[0].contents.toString('utf-8'),
                fs.readFileSync(filename + '.ttf', 'utf-8')
              );
              assert.equal(objs[1].path, filename + '.eot');
              assert.equal(objs[1].contents.toString('utf-8'), eot.toString('utf-8'));
              done();
            }));

        });

        it('should let non-ttf files pass through', function(done) {

          StreamTest[version].fromObjects([new gutil.File({
            path: 'bibabelula.foo',
            contents: new Buffer('ohyeah'),
          })])
          .pipe(ttf2eot())
          .pipe(StreamTest[version].toObjects(function(err, objs) {
            if(err) {
              return done(err);
            }
            assert.equal(objs.length, 1);
            assert.equal(objs[0].path, 'bibabelula.foo');
            assert.equal(objs[0].contents.toString('utf-8'), 'ohyeah');
            done();
          }));

        });
      });

      describe('in stream mode', function() {
        it('should work', function(done) {

          gulp.src(filename + '.ttf', { buffer: false })
            .pipe(ttf2eot())
            .pipe(StreamTest[version].toObjects(function(err, objs) {
              if(err) {
                return done(err);
              }
              assert.equal(objs.length, 1);
              assert.equal(objs[0].path, filename + '.eot');
              objs[0].contents.pipe(StreamTest[version].toText(function(err, text) {
                if(err) {
                  return done(err);
                }
                assert.equal(text, eot.toString('utf-8'));
                done();
              }));
            }));

        });

        it('should work with the clone option', function(done) {

          gulp.src(filename + '.ttf', { buffer: false })
            .pipe(ttf2eot({ clone: true }))
            .pipe(StreamTest[version].toObjects(function(err, objs) {
              if(err) {
                return done(err);
              }
              assert.equal(objs.length, 2);
              assert.equal(objs[0].path, filename + '.ttf');
              assert.equal(objs[1].path, filename + '.eot');
              objs[0].contents.pipe(StreamTest[version].toText(function(err, text) {
                if(err) {
                  return done(err);
                }
                assert.equal(text, fs.readFileSync(filename + '.ttf', 'utf-8'));
                objs[1].contents.pipe(StreamTest[version].toText(function(err, text) {
                  if(err) {
                    return done(err);
                  }
                  assert.equal(text, eot.toString('utf-8'));
                  done();
                }));
              }));
            }));

        });

        it('should let non-ttf files pass through', function(done) {

          StreamTest[version].fromObjects([new gutil.File({
            path: 'bibabelula.foo',
            contents: new Stream.PassThrough(),
          })])
          .pipe(ttf2eot())
          .pipe(StreamTest[version].toObjects(function(err, objs) {
            if(err) {
              return done(err);
            }
            assert.equal(objs.length, 1);
            assert.equal(objs[0].path, 'bibabelula.foo');
            assert(objs[0].contents instanceof Stream.PassThrough);
            done();
          }));

        });
      });

    });

  });

});
<commit_msg>Remove old ttf2eot bug fix<commit_after>/* eslint max-nested-callbacks:0 func-names:0 */

'use strict';

var gulp = require('gulp');
var gutil = require('gulp-util');
var Stream = require('stream');
var fs = require('fs');
var path = require('path');

var assert = require('assert');
var StreamTest = require('streamtest');

var ttf2eot = require('../src/index.js');

describe('gulp-ttf2eot conversion', function() {
  var filename = path.join(__dirname, 'fixtures', 'iconsfont');
  var eot = fs.readFileSync(filename + '.eot');

  // Iterating through versions
  StreamTest.versions.forEach(function(version) {

    describe('for ' + version + ' streams', function() {

      describe('with null contents', function() {

        it('should let null files pass through', function(done) {

          StreamTest[version].fromObjects([new gutil.File({
            path: 'bibabelula.foo',
            contents: null,
          })])
          .pipe(ttf2eot())
          .pipe(StreamTest[version].toObjects(function(err, objs) {
            if(err) {
              return done(err);
            }
            assert.equal(objs.length, 1);
            assert.equal(objs[0].path, 'bibabelula.foo');
            assert.equal(objs[0].contents, null);
            done();
          }));

        });

      });

      describe('in buffer mode', function() {

        it('should work', function(done) {

          gulp.src(filename + '.ttf', { buffer: true })
            .pipe(ttf2eot())
            // Uncomment to regenerate the test files if changes in the ttf2eot lib
            // .pipe(gulp.dest(__dirname + '/fixtures/'))
            .pipe(StreamTest[version].toObjects(function(err, objs) {
              if(err) {
                return done(err);
              }
              assert.equal(objs.length, 1);
              assert.equal(objs[0].path, filename + '.eot');
              assert.equal(objs[0].contents.toString('utf-8'), eot.toString('utf-8'));
              done();
            }));

        });

        it('should work with the clone option', function(done) {

          gulp.src(filename + '.ttf', { buffer: true })
            .pipe(ttf2eot({ clone: true }))
            .pipe(StreamTest[version].toObjects(function(err, objs) {
              if(err) {
                return done(err);
              }
              assert.equal(objs.length, 2);
              assert.equal(objs[0].path, filename + '.ttf');
              assert.equal(
                objs[0].contents.toString('utf-8'),
                fs.readFileSync(filename + '.ttf', 'utf-8')
              );
              assert.equal(objs[1].path, filename + '.eot');
              assert.equal(objs[1].contents.toString('utf-8'), eot.toString('utf-8'));
              done();
            }));

        });

        it('should let non-ttf files pass through', function(done) {

          StreamTest[version].fromObjects([new gutil.File({
            path: 'bibabelula.foo',
            contents: new Buffer('ohyeah'),
          })])
          .pipe(ttf2eot())
          .pipe(StreamTest[version].toObjects(function(err, objs) {
            if(err) {
              return done(err);
            }
            assert.equal(objs.length, 1);
            assert.equal(objs[0].path, 'bibabelula.foo');
            assert.equal(objs[0].contents.toString('utf-8'), 'ohyeah');
            done();
          }));

        });
      });

      describe('in stream mode', function() {
        it('should work', function(done) {

          gulp.src(filename + '.ttf', { buffer: false })
            .pipe(ttf2eot())
            .pipe(StreamTest[version].toObjects(function(err, objs) {
              if(err) {
                return done(err);
              }
              assert.equal(objs.length, 1);
              assert.equal(objs[0].path, filename + '.eot');
              objs[0].contents.pipe(StreamTest[version].toText(function(err, text) {
                if(err) {
                  return done(err);
                }
                assert.equal(text, eot.toString('utf-8'));
                done();
              }));
            }));

        });

        it('should work with the clone option', function(done) {

          gulp.src(filename + '.ttf', { buffer: false })
            .pipe(ttf2eot({ clone: true }))
            .pipe(StreamTest[version].toObjects(function(err, objs) {
              if(err) {
                return done(err);
              }
              assert.equal(objs.length, 2);
              assert.equal(objs[0].path, filename + '.ttf');
              assert.equal(objs[1].path, filename + '.eot');
              objs[0].contents.pipe(StreamTest[version].toText(function(err, text) {
                if(err) {
                  return done(err);
                }
                assert.equal(text, fs.readFileSync(filename + '.ttf', 'utf-8'));
                objs[1].contents.pipe(StreamTest[version].toText(function(err, text) {
                  if(err) {
                    return done(err);
                  }
                  assert.equal(text, eot.toString('utf-8'));
                  done();
                }));
              }));
            }));

        });

        it('should let non-ttf files pass through', function(done) {

          StreamTest[version].fromObjects([new gutil.File({
            path: 'bibabelula.foo',
            contents: new Stream.PassThrough(),
          })])
          .pipe(ttf2eot())
          .pipe(StreamTest[version].toObjects(function(err, objs) {
            if(err) {
              return done(err);
            }
            assert.equal(objs.length, 1);
            assert.equal(objs[0].path, 'bibabelula.foo');
            assert(objs[0].contents instanceof Stream.PassThrough);
            done();
          }));

        });
      });

    });

  });

});
<|endoftext|>


<commit_before>/*
 * Wegas
 * http://wegas.albasim.ch
 *
 * Copyright (c) 2018 School of Business and Engineering Vaud, Comem
 * Licensed under the MIT License
 *
 * NB: as of August 2018, Instascan needs this patch for iOS:
 * https://github.com/centogram/instascan
 *
 * When a camera access rights issue is detected, the client game can display help instructions inside a text box
 * following this widget. That box will then appear as this widget receives the additional class "error". Sample CSS:
 *     .wegas-qrcode-scanner.error ~ .qrcode-help-box {
 *         display: block;
 *     }
 *
 */

/* global Instascan */

YUI.add('wegas-qrcode-scanner', function(Y) {
    "use strict";

    var QrCodeScanner,
        CONTENTBOX = "contentBox";

    /**
     *  The QR-code scanner class.
     */
    QrCodeScanner = Y.Base.create("wegas-qrcode-scanner", Y.Widget, [Y.Wegas.Widget, Y.WidgetChild, Y.Wegas.Editable], {
        // *** Lifecycle Methods *** //
        initializer: function() {
            this.handlers = {};
            this.cameras = {};
            this.mirror = this.get("mirror");
            this.autostart = this.get("autostart");
        },
        renderUI: function() { // Create all DOM elements
            var iOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream,
                // Instascan bugfix from https://github.com/schmich/instascan/pull/112 :
                videoAttrs = iOS ? "muted autoplay playsinline" : "muted playsinline";
            this.get(CONTENTBOX).setContent("<button class='fa fa-qrcode initiator'>" +
                I18n.t("qrcode.startScan")+ "</button>");
            this.get(CONTENTBOX).append("
"
                + "  <button class='mirror fa fa-arrows-h'>" +
                    I18n.t("qrcode.mirror") + "</button>"
                + "

"
                + "
"
                + "    <video class='scanner' " + videoAttrs + "></video>"
                + "
"
                + "
");
        },
        syncUI: function() {
            if (this.autostart) {
                this.toggleScanner();
            }
        },
        bindUI: function() {
            this.get(CONTENTBOX).delegate("click", this.toggleScanner, ".initiator", this);
            this.get(CONTENTBOX).delegate("click", this.flip, ".mirror", this);
            this.get(CONTENTBOX).delegate("click", this.changeCamera, ".cameras .camera", this);
        },
        changeCamera: function(e) {
            this.startScanner(e.target.getData("cameraId"));
        },
        startScanner: function(cameraId) {
            if (this.scanner && this.currentCameraId !== cameraId) {
                this.scanner.start(this.cameras[cameraId]);
                this.currentCameraId = cameraId;
                var cb = this.get(CONTENTBOX);
                cb.one(".initiator .fa-button-label").setContent(I18n.t("qrcode.cancelScan"));
                cb.all(".camera").addClass("inactive");
                var me = cb.one('.camera[data-cameraId = "' + cameraId + '"]');
                me && me.removeClass("inactive");
            }
        },
        stopScanner: function() {
            if (this.scanner) {
                this.scanner.stop();
            }
            this.currentCameraId = null;
            var cb = this.get(CONTENTBOX);
            cb.one(".initiator .fa-button-label").setContent(I18n.t("qrcode.startScan"));
        },
        flip: function() {
            this.mirror = !this.mirror;
            if (this.scanner) {
                this.scanner.stop();

                var scanner = new Instascan.Scanner({
                    video: this.get(CONTENTBOX).one(".scanner").getDOMNode(),
                    mirror: this.mirror,
                    scanPeriod: 5
                });

                scanner.addListener('scan', Y.bind(this.process, this));

                scanner.start(this.cameras[this.currentCameraId]);
                this.scanner = scanner;
            }
        },
        toggleScanner: function() {
            Y.log("ToggleScanner");
            var cb = this.get(CONTENTBOX),
                // Enable game-specific help box for solving access rights issues:
                pt = cb.get("parentNode");
            if (!this.scanner) {
                var scanner = new Instascan.Scanner({
                    video: cb.one(".scanner").getDOMNode(),
                    mirror: this.mirror,
                    scanPeriod: 5
                });

                scanner.addListener('scan', Y.bind(this.process, this));

                Instascan.Camera.getCameras().then(Y.bind(function(cameras) {
                    if (cameras.length > 0) {
                        var list = cb.one(".cameras");
                        list.setContent();
                        for (var i in cameras) {
                            this.cameras[cameras[i].id] = cameras[i];
                            list.append("<button class='camera fa fa-camera' data-cameraId=" + cameras[i].id +
                                ">" +
                                cameras[i].name + "</button>");
                        }

                        pt.removeClass("error");
                        cb.addClass("scanning");
                        this.scanner = scanner;
                        this.startScanner(cameras[0].id);
                    } else {
                        this.showMessage("error", I18n.t("qrcode.noCamera"));
                        cb.removeClass("scanning");
                        pt.addClass("error");
                    }
                }, this)).catch(Y.bind(function(e) {
                    this.showMessage("error", I18n.t("qrcode.accessRights") + "
(" + e + ")
");
                    cb.removeClass("scanning");
                    pt.addClass("error");
                }, this));

            } else {
                //cb.one(".the_scanner") && cb.one(".the_scanner").remove();
                this.stopScanner();
                this.scanner = null;
                cb.removeClass("error");
                cb.removeClass("scanning");
            }
        },

        toggleScanner_qrScanner: function() {
            var cb = this.get(CONTENTBOX);
            if (!this.scanner) {
                var scanner = new QrScanner(cb.one(".scanner").getDOMNode(), Y.bind(this.process, this));
                this.scanner = scanner;
                this.scanner.start();
                cb.toggleClass("scanning", true);
            } else {
                cb.one("video").remove();
                this.scanner.stop();
                this.scanner = null;
                cb.toggleClass("scanning", false);
            }
        },

        process: function(qrCodeValue) {
            var o = JSON.parse(qrCodeValue);
            if (o && o.type) {
                var type = o.type;
                var payload = o.payload;
                switch (type) {
                    case "runJs":
                        this.showOverlay();
                        Y.Wegas.Facade.Variable.script.remoteEval(
                            {
                                "@class": "Script",
                                content: payload
                            },
                            {
                                on: {
                                    success: Y.bind(this.hideOverlay, this),
                                    failure:
                                        // The QR-code seems to be encoded properly for Wegas, but did generate an error:
                                        Y.bind(function(e) {
                                            this.hideOverlay();
                                            // Hide any low-level error panel:
                                            var panel = Y.one(".wegas-panel"),
                                                ok = panel && panel.one(".yui3-button");
                                            if (ok) {
                                                YUI().use('node-event-simulate', function(Y) {
                                                    ok.simulate("click");
                                                });
                                            }
                                            this.showMessage("error", I18n.t("qrcode.notUnderstood"));
                                            Y.log("*** " + I18n.t("qrcode.notUnderstood"));
                                            Y.log(" Decoded QR-code: " + qrCodeValue);
                                        }, this)
                                }
                            }
                        );
                        break;
                    case "selectChoice":
                        /* payload={
                         choiceName : "choiceName"
                         }
                         */
                        var choice = Y.Wegas.Facade.Variable.cache.find("name", payload.choiceName);
                        Y.Wegas.Facade.Variable.sendRequest({
                            request: "/QuestionDescriptor/SelectChoice/" + choice.get('id')
                                + "/Player/" + Y.Wegas.Facade.Game.get('currentPlayerId')
                                + "/StartTime/0",
                            cfg: {
                                method: "GET" // initially: POST
                            }
                        });
                        break;
                    case "cancelChoice":
                        var replies = Y.Wegas.Facade.Variable.cache.find("name", payload.choiceName).getInstance().get("replies");
                        if (replies && replies.length) {
                            // TODO reply = first
                            Y.Wegas.Facade.Variable.sendRequest({
                                request: "/QuestionDescriptor/CancelReply/" + replies[0].get('id')
                                    + "/Player/" + Wegas.Facade.Game.get('currentPlayerId'),
                                cfg: {
                                    method: "GET"
                                }
                            });
                        }
                        break;
                    case "selectValidateChoice":
                        var choice = Y.Wegas.Facade.Variable.cache.find("name", payload.choiceName);
                        Y.Wegas.Facade.Variable.sendRequest({
                            request: "/QuestionDescriptor/SelectAndValidateChoice/"
                                + choice.get('id') + "/Player/"
                                + Y.Wegas.Facade.Game.get('currentPlayerId'),
                            cfg: {
                                method: "POST"
                            }
                        });
                        break;
                    case "validateQuestion":
                        break;
                    case "openPage":
                        /*
                         payload = {
                         pageId: 123,
                         pageDisplayId :  || 'maindisplayarea'
                         }
                         */
                        break;
                }

                this.toggleScanner();
            } else {
                // The QR-code was apparently not encoded for Wegas :
                this.showMessage("error", I18n.t("qrcode.notUnderstood"));
                Y.log("*** " + I18n.t("qrcode.notUnderstood"));
                Y.log(" Decoded QR-code: " + qrCodeValue);
            }
        },
        destructor: function() {
            for (var k in this.handlers) {
                this.handlers[k].detach();
            }
        }
    }, {
        generateRunScript: function(node, content) {
            return new QRCode(node, {
                text: JSON.stringify({
                    type: "runJs",
                    payload: content.get ? content.get("content") : content.content
                })
            });
        },
        updateRunScript: function(qrCode, content) {
            qrCode.clear();
            qrCode.makeCode(JSON.stringify({
                type: "runJs",
                payload: content.get ? content.get("content") : content.content
            }));
        },
        generateSelectAndValidateChoice: function(node, choice) {
            return new QRCode(node, {
                text: JSON.stringify({
                    type: "selectValidateChoice",
                    payload: choice.get("name")
                })
            });
        },
        updateSelectAndValidateChoice: function(qrCode, choice) {
            qrCode.clear();
            qrCode.makeCode(JSON.stringify({
                type: "selectValidateChoice",
                payload: choice.get("name")
            }));
        },
        ATTRS: {
            mirror: {
                type: "boolean",
                value: false,
                view: {
                    label: "Mirror"
                }
            },
            autostart: {
                type: "boolean",
                value: false,
                view: {
                    label: "Autostart"
                }
            }
        }
    });

    Y.Wegas.QrCodeScanner = QrCodeScanner;

});
<commit_msg>qrcode scanner<commit_after>/*
 * Wegas
 * http://wegas.albasim.ch
 *
 * Copyright (c) 2018 School of Business and Engineering Vaud, Comem
 * Licensed under the MIT License
 *
 * NB: as of August 2018, Instascan needs this patch for iOS:
 * https://github.com/centogram/instascan
 *
 * When a camera access rights issue is detected, the client game can display help instructions inside a text box
 * following this widget. That box will then appear as this widget receives the additional class "error". Sample CSS:
 *     .wegas-qrcode-scanner.error ~ .qrcode-help-box {
 *         display: block;
 *     }
 *
 */

/* global Instascan */

YUI.add('wegas-qrcode-scanner', function(Y) {
    "use strict";

    var QrCodeScanner,
        CONTENTBOX = "contentBox";

    /**
     *  The QR-code scanner class.
     */
    QrCodeScanner = Y.Base.create("wegas-qrcode-scanner", Y.Widget, [Y.Wegas.Widget, Y.WidgetChild, Y.Wegas.Editable], {
        // *** Lifecycle Methods *** //
        initializer: function() {
            this.handlers = {};
            this.cameras = {};
            this.mirror = this.get("mirror");
            this.autostart = this.get("autostart");
        },
        renderUI: function() { // Create all DOM elements
            var iOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream,
                // Instascan bugfix from https://github.com/schmich/instascan/pull/112 :
                videoAttrs = iOS ? "muted autoplay playsinline" : "muted playsinline";
            this.get(CONTENTBOX).setContent("<button class='fa fa-qrcode initiator'>" +
                I18n.t("qrcode.startScan") + "</button>");
            this.get(CONTENTBOX).append("
"
                + "  <button class='mirror fa fa-arrows-h'>" +
                I18n.t("qrcode.mirror") + "</button>"
                + "

"
                + "
"
                + "    <video class='scanner' " + videoAttrs + "></video>"
                + "
"
                + "
");
        },
        syncUI: function() {
            if (this.autostart) {
                this.toggleScanner();
            }
        },
        bindUI: function() {
            this.get(CONTENTBOX).delegate("click", this.toggleScanner, ".initiator", this);
            this.get(CONTENTBOX).delegate("click", this.flip, ".mirror", this);
            this.get(CONTENTBOX).delegate("click", this.changeCamera, ".cameras .camera", this);
        },
        changeCamera: function(e) {
            this.startScanner(e.target.getData("cameraId"));
        },
        startScanner: function(cameraId) {
            if (this.scanner && this.currentCameraId !== cameraId) {
                this.scanner.start(this.cameras[cameraId]);
                this.currentCameraId = cameraId;
                var cb = this.get(CONTENTBOX);
                cb.one(".initiator .fa-button-label").setContent(I18n.t("qrcode.cancelScan"));
                cb.all(".camera").addClass("inactive");
                var me = cb.one('.camera[data-cameraId = "' + cameraId + '"]');
                me && me.removeClass("inactive");
            }
        },
        stopScanner: function() {
            if (this.scanner) {
                this.scanner.stop();
            }
            this.currentCameraId = null;
            var cb = this.get(CONTENTBOX);
            cb.one(".initiator .fa-button-label").setContent(I18n.t("qrcode.startScan"));
        },
        flip: function() {
            this.mirror = !this.mirror;
            if (this.scanner) {
                this.scanner.stop();

                var scanner = new Instascan.Scanner({
                    video: this.get(CONTENTBOX).one(".scanner").getDOMNode(),
                    mirror: this.mirror,
                    scanPeriod: 5
                });

                scanner.addListener('scan', Y.bind(this.process, this));

                scanner.start(this.cameras[this.currentCameraId]);
                this.scanner = scanner;
            }
        },
        toggleScanner: function() {
            Y.log("ToggleScanner");
            var cb = this.get(CONTENTBOX),
                bb = this.get("boundingBox"),
                // Enable game-specific help box for solving access rights issues:
                pt = cb.get("parentNode");
            if (!this.scanner) {
                var scanner = new Instascan.Scanner({
                    video: cb.one(".scanner").getDOMNode(),
                    mirror: this.mirror,
                    scanPeriod: 5
                });

                scanner.addListener('scan', Y.bind(this.process, this));

                Instascan.Camera.getCameras().then(Y.bind(function(cameras) {
                    if (cameras.length > 0) {
                        var list = cb.one(".cameras");
                        list.setContent();
                        for (var i in cameras) {
                            this.cameras[cameras[i].id] = cameras[i];
                            list.append("<button class='camera fa fa-camera' data-cameraId=" + cameras[i].id +
                                ">" +
                                cameras[i].name + "</button>");
                        }

                        pt.removeClass("error");
                        cb.addClass("scanning");
                        bb.addClass("bb-scanning");
                        this.scanner = scanner;
                        this.startScanner(cameras[0].id);
                    } else {
                        this.showMessage("error", I18n.t("qrcode.noCamera"));
                        cb.removeClass("scanning");
                        bb.removeClass("bb-scanning");
                        pt.addClass("error");
                    }
                }, this)).catch(Y.bind(function(e) {
                    this.showMessage("error", I18n.t("qrcode.accessRights") + "
(" + e + ")
");
                    bb.removeClass("bb-scanning");
                    cb.removeClass("scanning");
                    pt.addClass("error");
                }, this));

            } else {
                //cb.one(".the_scanner") && cb.one(".the_scanner").remove();
                this.stopScanner();
                this.scanner = null;
                cb.removeClass("error");
                bb.removeClass("bb-scanning");
                cb.removeClass("scanning");
            }
        },

        toggleScanner_qrScanner: function() {
            var cb = this.get(CONTENTBOX);
            if (!this.scanner) {
                var scanner = new QrScanner(cb.one(".scanner").getDOMNode(), Y.bind(this.process, this));
                this.scanner = scanner;
                this.scanner.start();
                cb.toggleClass("scanning", true);
            } else {
                cb.one("video").remove();
                this.scanner.stop();
                this.scanner = null;
                cb.toggleClass("scanning", false);
            }
        },

        process: function(qrCodeValue) {
            var o = JSON.parse(qrCodeValue);
            if (o && o.type) {
                var type = o.type;
                var payload = o.payload;
                switch (type) {
                    case "runJs":
                        this.showOverlay();
                        Y.Wegas.Facade.Variable.script.remoteEval(
                            {
                                "@class": "Script",
                                content: payload
                            },
                            {
                                on: {
                                    success: Y.bind(this.hideOverlay, this),
                                    failure:
                                        // The QR-code seems to be encoded properly for Wegas, but did generate an error:
                                        Y.bind(function(e) {
                                            this.hideOverlay();
                                            // Hide any low-level error panel:
                                            var panel = Y.one(".wegas-panel"),
                                                ok = panel && panel.one(".yui3-button");
                                            if (ok) {
                                                YUI().use('node-event-simulate', function(Y) {
                                                    ok.simulate("click");
                                                });
                                            }
                                            this.showMessage("error", I18n.t("qrcode.notUnderstood"));
                                            Y.log("*** " + I18n.t("qrcode.notUnderstood"));
                                            Y.log(" Decoded QR-code: " + qrCodeValue);
                                        }, this)
                                }
                            }
                        );
                        break;
                    case "selectChoice":
                        /* payload={
                         choiceName : "choiceName"
                         }
                         */
                        var choice = Y.Wegas.Facade.Variable.cache.find("name", payload.choiceName);
                        Y.Wegas.Facade.Variable.sendRequest({
                            request: "/QuestionDescriptor/SelectChoice/" + choice.get('id')
                                + "/Player/" + Y.Wegas.Facade.Game.get('currentPlayerId')
                                + "/StartTime/0",
                            cfg: {
                                method: "GET" // initially: POST
                            }
                        });
                        break;
                    case "cancelChoice":
                        var replies = Y.Wegas.Facade.Variable.cache.find("name", payload.choiceName).getInstance().get("replies");
                        if (replies && replies.length) {
                            // TODO reply = first
                            Y.Wegas.Facade.Variable.sendRequest({
                                request: "/QuestionDescriptor/CancelReply/" + replies[0].get('id')
                                    + "/Player/" + Wegas.Facade.Game.get('currentPlayerId'),
                                cfg: {
                                    method: "GET"
                                }
                            });
                        }
                        break;
                    case "selectValidateChoice":
                        var choice = Y.Wegas.Facade.Variable.cache.find("name", payload.choiceName);
                        Y.Wegas.Facade.Variable.sendRequest({
                            request: "/QuestionDescriptor/SelectAndValidateChoice/"
                                + choice.get('id') + "/Player/"
                                + Y.Wegas.Facade.Game.get('currentPlayerId'),
                            cfg: {
                                method: "POST"
                            }
                        });
                        break;
                    case "validateQuestion":
                        break;
                    case "openPage":
                        /*
                         payload = {
                         pageId: 123,
                         pageDisplayId :  || 'maindisplayarea'
                         }
                         */
                        break;
                }

                this.toggleScanner();
            } else {
                // The QR-code was apparently not encoded for Wegas :
                this.showMessage("error", I18n.t("qrcode.notUnderstood"));
                Y.log("*** " + I18n.t("qrcode.notUnderstood"));
                Y.log(" Decoded QR-code: " + qrCodeValue);
            }
        },
        destructor: function() {
            for (var k in this.handlers) {
                this.handlers[k].detach();
            }
        }
    }, {
        generateRunScript: function(node, content) {
            return new QRCode(node, {
                text: JSON.stringify({
                    type: "runJs",
                    payload: content.get ? content.get("content") : content.content
                })
            });
        },
        updateRunScript: function(qrCode, content) {
            qrCode.clear();
            qrCode.makeCode(JSON.stringify({
                type: "runJs",
                payload: content.get ? content.get("content") : content.content
            }));
        },
        generateSelectAndValidateChoice: function(node, choice) {
            return new QRCode(node, {
                text: JSON.stringify({
                    type: "selectValidateChoice",
                    payload: choice.get("name")
                })
            });
        },
        updateSelectAndValidateChoice: function(qrCode, choice) {
            qrCode.clear();
            qrCode.makeCode(JSON.stringify({
                type: "selectValidateChoice",
                payload: choice.get("name")
            }));
        },
        ATTRS: {
            mirror: {
                type: "boolean",
                value: false,
                view: {
                    label: "Mirror"
                }
            },
            autostart: {
                type: "boolean",
                value: false,
                view: {
                    label: "Autostart"
                }
            }
        }
    });

    Y.Wegas.QrCodeScanner = QrCodeScanner;

});
<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');
var assert = require('assert-plus');
var fs = require('fs');
var Gremlin = require('gremlin-v3');
var mkdirp = require('mkdirp');
var Work = require('./lib/work.js');

var gremlin = new Gremlin();
var java = gremlin.java;
var Class = java.import('java.lang.Class');

function loadClass(className) {
  return java.getClassLoader().loadClassSync(className);
}

function shortClassName(className) {
  var m = className.match(/\.([\$\w]+)$/);
  assert.ok(m);
  return m[1];
}

//   'com.tinkerpop.gremlin.process.graph.GraphTraversal',
//   'com.tinkerpop.gremlin.process.graph.ElementTraversal',
//   'com.tinkerpop.gremlin.structure.Vertex',
//   'com.tinkerpop.gremlin.structure.Edge',
//   'com.tinkerpop.gremlin.process.Traversal$SideEffects'

// The set of packages and classes we are interested in. We ignore others.
var whiteList = [
  /^com\.tinkerpop\.gremlin/,
  /^java\.util\.Iterator/
];

function inWhiteList(className) {
  return _.find(whiteList, function (ns) { return className.match(ns); });
}

function mapMethod(method, work) {
  var methodMap = {
    name: method.getNameSync(),
    declared: method.getDeclaringClassSync().getNameSync(),
    returns: method.getReturnTypeSync().getNameSync(),
    params: _.map(method.getParameterTypesSync(), function (p) { return p.getNameSync(); }),
    isVarArgs: method.isVarArgsSync(),
    generic: method.toGenericStringSync(),
    string: method.toStringSync(),
  };

  methodMap.signature = methodMap.name + ':[' + methodMap.params.join() + ']';

  function addIfNotQueued(className) {
    if (inWhiteList(className)) {
      work.addTodo(className);
    }
  }

  addIfNotQueued(methodMap.declared);
  addIfNotQueued(methodMap.returns);

  return methodMap;
}

function mapClass(className, work) {
  var clazz = loadClass(className);
  assert.strictEqual(clazz.getNameSync(), className);

  var shortName = shortClassName(className);
  var methods = _.map(clazz.getMethodsSync(), function (m) { return mapMethod(m, work); });

  var interfaces = _.map(clazz.getInterfacesSync(), function (intf) { return intf.getNameSync(); });

  var classMap = {
    fullName: className,
    shortName: shortName,
    interfaces: interfaces,
    methods: methods
  };

  return classMap;
}

function processClass(className, work) {
  var classMap = mapClass(className, work);
  fs.writeFileSync('out/txt/' + classMap.shortName + '.txt', JSON.stringify(classMap, null, '  '));
  return classMap;
}

function locateMethodDefinitions(className, classes, work) {
  assert.ok(className in classes);
  var classMap = classes[className];
  assert.strictEqual(className, classMap.fullName);

  _.forEach(classMap.interfaces, function (intf) {
    if (!work.alreadyDone(intf) && intf in classes) {
      locateMethodDefinitions(intf, classes, work);
    }
  });

  console.log(className);
  work.setDone(className);
}

function main() {

  mkdirp.sync('out/txt');
  mkdirp.sync('out/lib');
  mkdirp.sync('out/test');

  var classes = {};

  var work = new Work();
  work.addTodo('com.tinkerpop.gremlin.structure.Graph');

  while (!work.isDone()) {
    var className = work.next();
    work.setDone(className);
    classes[className] = processClass(className, work);
  }

  // HACK: in TP3, some *Traversal classes are not declared to implement Traversal,
  // e.g. ElementTraversal. I believe we will want to treat these classes as if they
  // actually do implement that interface.
  var baseTraversal = 'com.tinkerpop.gremlin.process.Traversal';
  _.forOwn(classes, function (classMap, className) {
    if (className.match(/(\w+)Traversal$/)) {
      if (_.indexOf(classMap.interfaces, baseTraversal) === -1) {
        classMap.interfaces.push(baseTraversal);
        console.log('Added %s to interfaces of %s', baseTraversal, className);
      }
    }
  });

  var newWork = new Work(work.getDone());

  locateMethodDefinitions('com.tinkerpop.gremlin.process.Traversal', classes, newWork);
  while (!newWork.isDone()) {
    var className = newWork.next();
    locateMethodDefinitions(className, classes, newWork);
  }

}

main();
<commit_msg>Extract functions for phases of work from main().<commit_after>'use strict';

var _ = require('lodash');
var assert = require('assert-plus');
var fs = require('fs');
var Gremlin = require('gremlin-v3');
var mkdirp = require('mkdirp');
var Work = require('./lib/work.js');

var gremlin = new Gremlin();
var java = gremlin.java;
var Class = java.import('java.lang.Class');

function loadClass(className) {
  return java.getClassLoader().loadClassSync(className);
}

function shortClassName(className) {
  var m = className.match(/\.([\$\w]+)$/);
  assert.ok(m);
  return m[1];
}

//   'com.tinkerpop.gremlin.process.graph.GraphTraversal',
//   'com.tinkerpop.gremlin.process.graph.ElementTraversal',
//   'com.tinkerpop.gremlin.structure.Vertex',
//   'com.tinkerpop.gremlin.structure.Edge',
//   'com.tinkerpop.gremlin.process.Traversal$SideEffects'

// The set of packages and classes we are interested in. We ignore others.
var whiteList = [
  /^com\.tinkerpop\.gremlin/,
  /^java\.util\.Iterator/
];

function inWhiteList(className) {
  return _.find(whiteList, function (ns) { return className.match(ns); });
}

function mapMethod(method, work) {
  var methodMap = {
    name: method.getNameSync(),
    declared: method.getDeclaringClassSync().getNameSync(),
    returns: method.getReturnTypeSync().getNameSync(),
    params: _.map(method.getParameterTypesSync(), function (p) { return p.getNameSync(); }),
    isVarArgs: method.isVarArgsSync(),
    generic: method.toGenericStringSync(),
    string: method.toStringSync(),
  };

  methodMap.signature = methodMap.name + ':[' + methodMap.params.join() + ']';

  function addIfNotQueued(className) {
    if (inWhiteList(className)) {
      work.addTodo(className);
    }
  }

  addIfNotQueued(methodMap.declared);
  addIfNotQueued(methodMap.returns);

  return methodMap;
}

function mapClass(className, work) {
  var clazz = loadClass(className);
  assert.strictEqual(clazz.getNameSync(), className);

  var shortName = shortClassName(className);
  var methods = _.map(clazz.getMethodsSync(), function (m) { return mapMethod(m, work); });

  var interfaces = _.map(clazz.getInterfacesSync(), function (intf) { return intf.getNameSync(); });

  var classMap = {
    fullName: className,
    shortName: shortName,
    interfaces: interfaces,
    methods: methods
  };

  return classMap;
}

function processClass(className, work) {
  var classMap = mapClass(className, work);
  fs.writeFileSync('out/txt/' + classMap.shortName + '.txt', JSON.stringify(classMap, null, '  '));
  return classMap;
}

function locateMethodDefinitions(className, classes, work) {
  assert.ok(className in classes);
  var classMap = classes[className];
  assert.strictEqual(className, classMap.fullName);

  _.forEach(classMap.interfaces, function (intf) {
    if (!work.alreadyDone(intf) && intf in classes) {
      locateMethodDefinitions(intf, classes, work);
    }
  });

  console.log(className);
  work.setDone(className);
}

function loadAllClasses() {
  var classes = {};
  var work = new Work();
  work.addTodo('com.tinkerpop.gremlin.structure.Graph');

  while (!work.isDone()) {
    var className = work.next();
    work.setDone(className);
    classes[className] = processClass(className, work);
  }
  return classes;
}

function hackTraversalInterfaces(classes) {
  // HACK: in TP3, some *Traversal classes are not declared to implement Traversal,
  // e.g. ElementTraversal. I believe we will want to treat these classes as if they
  // actually do implement that interface.
  var baseTraversal = 'com.tinkerpop.gremlin.process.Traversal';
  _.forOwn(classes, function (classMap, className) {
    if (className.match(/(\w+)Traversal$/)) {
      if (_.indexOf(classMap.interfaces, baseTraversal) === -1) {
        classMap.interfaces.push(baseTraversal);
      }
    }
  });
}

function mapMethodDefinitions(classes) {
  var work = new Work(_.keys(classes));
  while (!work.isDone()) {
    var className = work.next();
    locateMethodDefinitions(className, classes, work);
  }
}

function main() {

  mkdirp.sync('out/txt');
  mkdirp.sync('out/lib');
  mkdirp.sync('out/test');

  var classes = loadAllClasses();
  hackTraversalInterfaces(classes);
  mapMethodDefinitions(classes);
}

main();
<|endoftext|>