<commit_before>const SVGTextWrapper = require('./svg-text-wrapper');
const SvgRenderer = require('scratch-svg-renderer').SVGRenderer;
const xmlescape = require('xml-escape');

const MAX_LINE_LENGTH = 170;
const MIN_WIDTH = 50;

class SVGTextBubble {
    constructor () {
        this.svgRenderer = new SvgRenderer();
        this.svgTextWrapper = new SVGTextWrapper();
        this._textSizeCache = {};
    }

    _speechBubble (w, h, radius, pointsLeft) {
        let pathString = `
            M 0 ${radius}
            A ${radius} ${radius} 0 0 1 ${radius} 0
            L ${w - radius} 0
            A ${radius} ${radius} 0 0 1 ${w} ${radius}
            L ${w} ${h - radius}
            A ${radius} ${radius} 0 0 1 ${w - radius} ${h}`;

        if (pointsLeft) {
            pathString += `
                L 32 ${h}
                c -5 8 -15 12 -18 12
                a 2 2 0 0 1 -2 -2
                c 0 -2 4 -6 4 -10`;
        } else {
            pathString += `
                L ${w - 16} ${h}
                c 0 4 4 8 4 10
                a 2 2 0 0 1 -2 2
                c -3 0 -13 -4 -18 -12`;
        }

        pathString += `
            L ${radius} ${h}
            A ${radius} ${radius} 0 0 1 0 ${h - radius}
            Z`;

        return `
            <g>
                <path
                  d="${pathString}"
                  stroke="rgba(0, 0, 0, 0.15)"
                  stroke-width="4"
                  fill="rgba(0, 0, 0, 0.15)"
                  stroke-line-join="round"
              />
              <path
                d="${pathString}"
                stroke="none"
                fill="white" />
            </g>`;
    }

    _thinkBubble (w, h, radius, pointsLeft) {
        const e1rx = 2.25;
        const e1ry = 2.25;
        const e2rx = 1.5;
        const e2ry = 1.5;
        const e1x = 16 + 7 + e1rx;
        const e1y = 5 + h + e1ry;
        const e2x = 16 + e2rx;
        const e2y = 8 + h + e2ry;
        const insetR = 4;
        const pInset1 = 12 + radius;
        const pInset2 = pInset1 + (2 * insetR);

        let pathString = `
            M 0 ${radius}
            A ${radius} ${radius} 0 0 1 ${radius} 0
            L ${w - radius} 0
            A ${radius} ${radius} 0 0 1 ${w} ${radius}
            L ${w} ${h - radius}
            A ${radius} ${radius} 0 0 1 ${w - radius} ${h}`;

        if (pointsLeft) {
            pathString += `
                L ${pInset2} ${h}
                A ${insetR} ${insetR} 0 0 1 ${pInset2 - insetR} ${h + insetR}
                A ${insetR} ${insetR} 0 0 1 ${pInset1} ${h}`;
        } else {
            pathString += `
                L ${w - pInset1} ${h}
                A ${insetR} ${insetR} 0 0 1 ${w - pInset1 - insetR} ${h + insetR}
                A ${insetR} ${insetR} 0 0 1 ${w - pInset2} ${h}`;
        }

        pathString += `
            L ${radius} ${h}
            A ${radius} ${radius} 0 0 1 0 ${h - radius}
            Z`;

        const ellipseSvg = (cx, cy, rx, ry) => `
            <g>
                <ellipse
                    cx="${cx}" cy="${cy}"
                    rx="${rx}" ry="${ry}"
                    fill="rgba(0, 0, 0, 0.15)"
                    stroke="rgba(0, 0, 0, 0.15)"
                    stroke-width="4"
                />
                <ellipse
                    cx="${cx}" cy="${cy}"
                    rx="${rx}" ry="${ry}"
                    fill="white"
                    stroke="none"
                />
            </g>`;
        let ellipses = [];
        if (pointsLeft) {
            ellipses = [
                ellipseSvg(e1x, e1y, e1rx, e1ry),
                ellipseSvg(e2x, e2y, e2rx, e2ry)
            ];
        } else {
            ellipses = [
                ellipseSvg(w - e1x, e1y, e1rx, e1ry),
                ellipseSvg(w - e2x, e2y, e2rx, e2ry)
            ];
        }

        return `
             <g>
                <path d="${pathString}" stroke="rgba(0, 0, 0, 0.15)" stroke-width="4" fill="rgba(0, 0, 0, 0.15)" />
                <path d="${pathString}" stroke="none" fill="white" />
                ${ellipses.join('\n')}
            </g>`;
    }

    _getTextSize () {
        const svgString = this._wrapSvgFragment(this._textFragment());
        if (!this._textSizeCache[svgString]) {
            this._textSizeCache[svgString] = this.svgRenderer.measure(svgString);
        }
        return this._textSizeCache[svgString];
    }

    _wrapSvgFragment (fragment) {
        return `
          <svg xmlns="http://www.w3.org/2000/svg" version="1.1">
              ${fragment}
          </svg>
        `;
    }

    _textFragment () {
        return `<text fill="#575E75">${xmlescape(this.lines.join('\n'))}</text>`;
    }

    buildString (type, text, pointsLeft) {
        this.type = type;
        this.pointsLeft = pointsLeft;
        this.lines = this.svgTextWrapper.wrapText(MAX_LINE_LENGTH, text);

        let fragment = '';

        const radius = 16;
        const {x, y, width, height} = this._getTextSize();
        const padding = 10;
        const fullWidth = Math.max(MIN_WIDTH, width) + (2 * padding);
        const fullHeight = height + (2 * padding);
        if (this.type === 'say') {
            fragment += this._speechBubble(fullWidth, fullHeight, radius, this.pointsLeft);
        } else {
            fragment += this._thinkBubble(fullWidth, fullHeight, radius, this.pointsLeft);
        }
        fragment += `<g transform="translate(${padding - x}, ${padding - y})">${this._textFragment()}</g>`;
        return this._wrapSvgFragment(fragment);
    }
}

module.exports = SVGTextBubble;
<commit_msg>Actually fix the font in the say bubbles<commit_after>const SVGTextWrapper = require('./svg-text-wrapper');
const SvgRenderer = require('scratch-svg-renderer').SVGRenderer;
const xmlescape = require('xml-escape');

const MAX_LINE_LENGTH = 170;
const MIN_WIDTH = 50;

class SVGTextBubble {
    constructor () {
        this.svgRenderer = new SvgRenderer();
        this.svgTextWrapper = new SVGTextWrapper();
        this._textSizeCache = {};
    }

    _speechBubble (w, h, radius, pointsLeft) {
        let pathString = `
            M 0 ${radius}
            A ${radius} ${radius} 0 0 1 ${radius} 0
            L ${w - radius} 0
            A ${radius} ${radius} 0 0 1 ${w} ${radius}
            L ${w} ${h - radius}
            A ${radius} ${radius} 0 0 1 ${w - radius} ${h}`;

        if (pointsLeft) {
            pathString += `
                L 32 ${h}
                c -5 8 -15 12 -18 12
                a 2 2 0 0 1 -2 -2
                c 0 -2 4 -6 4 -10`;
        } else {
            pathString += `
                L ${w - 16} ${h}
                c 0 4 4 8 4 10
                a 2 2 0 0 1 -2 2
                c -3 0 -13 -4 -18 -12`;
        }

        pathString += `
            L ${radius} ${h}
            A ${radius} ${radius} 0 0 1 0 ${h - radius}
            Z`;

        return `
            <g>
                <path
                  d="${pathString}"
                  stroke="rgba(0, 0, 0, 0.15)"
                  stroke-width="4"
                  fill="rgba(0, 0, 0, 0.15)"
                  stroke-line-join="round"
              />
              <path
                d="${pathString}"
                stroke="none"
                fill="white" />
            </g>`;
    }

    _thinkBubble (w, h, radius, pointsLeft) {
        const e1rx = 2.25;
        const e1ry = 2.25;
        const e2rx = 1.5;
        const e2ry = 1.5;
        const e1x = 16 + 7 + e1rx;
        const e1y = 5 + h + e1ry;
        const e2x = 16 + e2rx;
        const e2y = 8 + h + e2ry;
        const insetR = 4;
        const pInset1 = 12 + radius;
        const pInset2 = pInset1 + (2 * insetR);

        let pathString = `
            M 0 ${radius}
            A ${radius} ${radius} 0 0 1 ${radius} 0
            L ${w - radius} 0
            A ${radius} ${radius} 0 0 1 ${w} ${radius}
            L ${w} ${h - radius}
            A ${radius} ${radius} 0 0 1 ${w - radius} ${h}`;

        if (pointsLeft) {
            pathString += `
                L ${pInset2} ${h}
                A ${insetR} ${insetR} 0 0 1 ${pInset2 - insetR} ${h + insetR}
                A ${insetR} ${insetR} 0 0 1 ${pInset1} ${h}`;
        } else {
            pathString += `
                L ${w - pInset1} ${h}
                A ${insetR} ${insetR} 0 0 1 ${w - pInset1 - insetR} ${h + insetR}
                A ${insetR} ${insetR} 0 0 1 ${w - pInset2} ${h}`;
        }

        pathString += `
            L ${radius} ${h}
            A ${radius} ${radius} 0 0 1 0 ${h - radius}
            Z`;

        const ellipseSvg = (cx, cy, rx, ry) => `
            <g>
                <ellipse
                    cx="${cx}" cy="${cy}"
                    rx="${rx}" ry="${ry}"
                    fill="rgba(0, 0, 0, 0.15)"
                    stroke="rgba(0, 0, 0, 0.15)"
                    stroke-width="4"
                />
                <ellipse
                    cx="${cx}" cy="${cy}"
                    rx="${rx}" ry="${ry}"
                    fill="white"
                    stroke="none"
                />
            </g>`;
        let ellipses = [];
        if (pointsLeft) {
            ellipses = [
                ellipseSvg(e1x, e1y, e1rx, e1ry),
                ellipseSvg(e2x, e2y, e2rx, e2ry)
            ];
        } else {
            ellipses = [
                ellipseSvg(w - e1x, e1y, e1rx, e1ry),
                ellipseSvg(w - e2x, e2y, e2rx, e2ry)
            ];
        }

        return `
             <g>
                <path d="${pathString}" stroke="rgba(0, 0, 0, 0.15)" stroke-width="4" fill="rgba(0, 0, 0, 0.15)" />
                <path d="${pathString}" stroke="none" fill="white" />
                ${ellipses.join('\n')}
            </g>`;
    }

    _getTextSize () {
        const svgString = this._wrapSvgFragment(this._textFragment());
        if (!this._textSizeCache[svgString]) {
            this._textSizeCache[svgString] = this.svgRenderer.measure(svgString);
        }
        return this._textSizeCache[svgString];
    }

    _wrapSvgFragment (fragment) {
        return `
          <svg xmlns="http://www.w3.org/2000/svg" version="1.1">
              ${fragment}
          </svg>
        `;
    }

    _textFragment () {
        const attrs = `font-family="Helvetica, Arial, sans-serif" font-size="14px" fill="#575E75"`;
        return `<text ${attrs}>${xmlescape(this.lines.join('\n'))}</text>`;
    }

    buildString (type, text, pointsLeft) {
        this.type = type;
        this.pointsLeft = pointsLeft;
        this.lines = this.svgTextWrapper.wrapText(MAX_LINE_LENGTH, text);

        let fragment = '';

        const radius = 16;
        const {x, y, width, height} = this._getTextSize();
        const padding = 10;
        const fullWidth = Math.max(MIN_WIDTH, width) + (2 * padding);
        const fullHeight = height + (2 * padding);
        if (this.type === 'say') {
            fragment += this._speechBubble(fullWidth, fullHeight, radius, this.pointsLeft);
        } else {
            fragment += this._thinkBubble(fullWidth, fullHeight, radius, this.pointsLeft);
        }
        fragment += `<g transform="translate(${padding - x}, ${padding - y})">${this._textFragment()}</g>`;
        return this._wrapSvgFragment(fragment);
    }
}

module.exports = SVGTextBubble;
<|endoftext|>


<commit_before>const { Forbidden, BadRequest } = require('../errors');
const { userRepo } = require('../components/user/repo/index');

const restrictToRole = async (id, roleName, app) => {
	if (!id) {
		throw new BadRequest('The request query should include a valid userId');
	}
	if (!roleName) {
		throw new BadRequest('The request query should include a valid roleName');
	}

	const roles = await userRepo.getUserRoles(id, app);

	if (roles.some((role) => role.name === roleName)) {
		return true;
	}
	throw new Forbidden('You have no access.');
};

module.exports = restrictToRole;
<commit_msg>code style<commit_after>const { Forbidden, BadRequest } = require('../errors');
const { userRepo } = require('../components/user/repo');

const restrictToRole = async (id, roleName, app) => {
	if (!id) {
		throw new BadRequest('The request query should include a valid userId');
	}
	if (!roleName) {
		throw new BadRequest('The request query should include a valid roleName');
	}

	const roles = await userRepo.getUserRoles(id, app);

	if (roles.some((role) => role.name === roleName)) {
		return true;
	}
	throw new Forbidden('You have no access.');
};

module.exports = restrictToRole;
<|endoftext|>


<commit_before>navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;

var peer = new Adawarp();
var myID = null;
var call;

var localStream;
var connectedCall;

var myID;
var partnerID;

var yaw = 90;

window.onload = function(){
    displayMyCamera();
    peer.on('open', function(){
        document.getElementById("my-id").innerHTML = peer.id;
    });
    peer.login();
}

peer.on('connection', function(conn) {
    document.getElementById("partnerID").innerHTML = conn.peer;
    conn.on('data', function(data){
        console.log(data);
        document.getElementById("receive_message").innerHTML = data;
        /*console.log(typeof(data));
        console.log(data[0]);
        convertData(data);*/

    });
});

peer.on('call', function(call){
    connectedCall = call;
    call.answer(localStream);

    call.on('stream', function(stream){
        document.getElementById("partnerVideo").src = URL.createObjectURL(stream);
    });
});

function displayMyCamera(){
    navigator.getUserMedia({audio: true, video: true}, function(stream){
        localStream = stream;
        document.getElementById("myVideo").src = URL.createObjectURL(stream);
    }, function() { alert("Error!"); });
}<commit_msg>commentout converting data<commit_after>navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;

var peer = new Adawarp();
var myID = null;
var call;

var localStream;
var connectedCall;

var myID;
var partnerID;

var yaw = 90;

window.onload = function(){
    displayMyCamera();
    peer.on('open', function(){
        document.getElementById("my-id").innerHTML = peer.id;
    });
    peer.login();
}

peer.on('connection', function(conn) {
    document.getElementById("partnerID").innerHTML = conn.peer;
    conn.on('data', function(data){
        console.log(data[1]);
        document.getElementById("receive_message").innerHTML = data;
        /*console.log(typeof(data));
        console.log(data[0]);
        convertData(data);*/

    });
});

peer.on('call', function(call){
    connectedCall = call;
    call.answer(localStream);

    call.on('stream', function(stream){
        document.getElementById("partnerVideo").src = URL.createObjectURL(stream);
    });
});

function displayMyCamera(){
    navigator.getUserMedia({audio: true, video: true}, function(stream){
        localStream = stream;
        document.getElementById("myVideo").src = URL.createObjectURL(stream);
    }, function() { alert("Error!"); });
}<|endoftext|>


<commit_before>const User = require('./user')
const Event = require('./event')
const Result = require('./result')

module.exports = class Generator {
  randomize (min, max) {
    let res = Math.floor(Math.random() * (max - min + 1)) + min
    return res
  }
  generateResult (eventId, connectionPool) {
    let EventQuery = new Event(connectionPool)
    let ResultQuery = new Result(connectionPool)

    EventQuery.getById(eventId).done((res) => {
      if (res) {
        let users = res[0].userIds.split(',')
        let sender
        let receiver

        let i = 0
        let orders = []
        while (i < users.length) {
          let index = this.randomize(0, users.length - 1)
          if (orders.indexOf(users[index].trim() / 1) === -1) {
            orders.push(users[index].trim() / 1)
            i++
          }
        }

        ResultQuery.deleteByEventId(res[0].id)

        orders.forEach((order, index) => {
          let object = {
            sender: order,
            receiver: (index === orders.length - 1) ? orders[0] : orders[index + 1],
            eventId: res[0].id,
            emailSent: false,
            timestamp: 'now()'
          }

          ResultQuery.insert(object).done((res2) => {
            console.log('done', object, res2)
          })
        })
        return 200
      }
      return 500
    })
  }
}
<commit_msg>Fixing the generator<commit_after>const User = require('./user')
const Event = require('./event')
const Result = require('./result')

module.exports = class Generator {
  randomize (min, max) {
    let res = Math.floor(Math.random() * (max - min + 1)) + min
    return res
  }
  generateResult (eventId, connectionPool) {
    let EventQuery = new Event(connectionPool)
    let ResultQuery = new Result(connectionPool)

    EventQuery.getById(eventId).done((res) => {
      if (res) {
        let users = res[0].userIds.split(',')
        let sender
        let receiver

        let i = 0
        let orders = []
        while (i < users.length) {
          let index = this.randomize(0, users.length - 1)
          if (orders.indexOf(users[index].trim() / 1) === -1) {
            orders.push(users[index].trim() / 1)
            i++
          }
        }

        ResultQuery.deleteByEventId(res[0].id).done((response) => {
            orders.forEach((order, index) => {
                let object = {
                    sender: order,
                    receiver: (index === orders.length - 1) ? orders[0] : orders[index + 1],
                    eventId: res[0].id,
                    emailSent: false,
                    timestamp: 'now()'
                }

                ResultQuery.insert(object).done((res2) => {
                    console.log('done', object, res2)
                })
            })
            return 200
        })
      }
    })
  }
}
<|endoftext|>


<commit_before>openerp.poi_pos_auth_approval = function(instance){

    var module = instance.point_of_sale;
    var QWeb = instance.web.qweb;

	_t = instance.web._t;

    module.PaymentScreenWidget = module.PaymentScreenWidget.extend({

        validate_order: function(options) {
            var self = this;
            var realvalidate = this._super;

            var connection = new openerp.Session(self, null, {session_id: openerp.session.session_id});
            var currentOrder = self.pos.get('selectedOrder');

            currentOrder.save_lines_on_db().then(function(){
                // This is in case S&P was rejected before
                // we're removing S&P authorization fields to avoid false response
                (new instance.web.Model('pos.order')).get_func('sp_execute')(currentOrder.get_order_id(), 'remove')
            }).then(function(){
                return connection.rpc('/poi_pos_auth_approval/check_validate_order',
                    {'config_id': self.pos.config.id,
                     'order_id': currentOrder.get_order_id(),
                     'current_order': [currentOrder.export_as_JSON()]
                })
            }).then(function(authorization){
                currentOrder.authorization = authorization;
            }).then(function(){
                if(currentOrder.authorization.approved){
                    realvalidate.call(self);
                }else{
                    self.pos_widget.screen_selector.show_popup('ApprovalPopup');
                }
            });
        }
    });

    module.ApprovalPopup = module.PopUpWidget.extend({
        template: 'ApprovalPopup',
        init: function (parent, options) {
            this._super(parent, options);
            this.messages = [];
            this.state = '';
        },
        show: function () {
            var self = this;
            var currentOrder = self.pos.get('selectedOrder');

            if (currentOrder.authorization.auth_state == undefined)
                currentOrder.authorization.auth_state = 'rejected';

            self.messages = currentOrder.authorization.messages;
            self.state = currentOrder.authorization.auth_state;

            self._super();
            self.renderElement();

            this.$el.find('#app_send').off('click').click(function () {
                self.pos_widget.screen_selector.close_popup();
                return (new instance.web.Model('pos.order')).get_func('send_approval_message')(
                    currentOrder.get_order_id(),
                    currentOrder.authorization.users_notified,
                    currentOrder.authorization.messages,
                    self.$el.find('#request_text').val()
                );
            });

            this.$el.find('#app_cancel').off('click').click(function () {

                self.pos_widget.screen_selector.close_popup();

                if (self.state !== 'submit') {
                    if (self.state == 'rejected')
                        (new instance.web.Model('pos.order')).get_func('sp_execute')(currentOrder.get_order_id(), 'reject_notified');

                    if (self.state == 'none')
                        (new instance.web.Model('pos.order')).get_func('sp_execute')(currentOrder.get_order_id(), 'remove');

                    currentOrder.sp_reason = false;
                    currentOrder.authorization.messages = [];
                    currentOrder.authorization.auth_state = 'none';
                }
            });
        }
    });

    module.PosWidget = module.PosWidget.extend({
        init: function(parent, options) {
            this._super(parent, options);
            var  self = this;
        },
        build_widgets: function() {
            this._super();

            //Creating Pop-up "ApprovalPopup"
            this.approval_popup = new module.ApprovalPopup(this, {});
            this.approval_popup.appendTo(this.$el);
            this.screen_selector.add_popup('ApprovalPopup',this.approval_popup);
        }
    });
};<commit_msg>Authorizations: Fixed vulnerability when using other device<commit_after>openerp.poi_pos_auth_approval = function(instance){

    var module = instance.point_of_sale;
    var QWeb = instance.web.qweb;

	_t = instance.web._t;

    module.PaymentScreenWidget = module.PaymentScreenWidget.extend({

        show: function(){
            var self = this;
            var currentOrder = self.pos.get('selectedOrder');

            self.get_auth().then(function(){
                console.log("MRC currentOrder.authorization", currentOrder.authorization);
                if (currentOrder.authorization.state == 'approved') {
                    (new instance.web.Model('pos.order')).get_func('sp_execute')(currentOrder.get_order_id(), 'back');
                }
            });
            self._super();
        },

        get_auth: function(){
            var self = this;
            var currentOrder = self.pos.get('selectedOrder');

            var connection = new openerp.Session(self, null, {session_id: openerp.session.session_id});

            return connection.rpc('/poi_pos_auth_approval/check_validate_order', {
                'config_id': self.pos.config.id,
                'order_id': currentOrder.get_order_id(),
                'current_order': [currentOrder.export_as_JSON()]
            }).then(function(authorization){
                currentOrder.authorization = authorization;
            });
        },

        back: function() {
            var self = this;
            var currentOrder = self.pos.get('selectedOrder');
            console.log("MRC currentOrder.authorization.state", currentOrder.authorization.state);

            self.get_auth().then(function(){
                switch (currentOrder.authorization.state){
                    case 'submit':
                        alert("Cannot go back before manager sends a response.");
                    break;
                    case 'approved':
                        if(confirm("Manager approved previous requirement. This authorization will be lost if you go back.")) {
                            return (new instance.web.Model('pos.order')).get_func('sp_execute')(currentOrder.get_order_id(), 'back')
                            .then(function(){
                                self.remove_empty_lines();
                                self.pos_widget.screen_selector.set_current_screen(self.back_screen);
                            });
                        }
                    break;
                    case 'rejected':
                        alert("Manager rejected previous request.");
                        return (new instance.web.Model('pos.order')).get_func('sp_execute')(currentOrder.get_order_id(), 'back')
                        .then(function(){
                            self.remove_empty_lines();
                            self.pos_widget.screen_selector.set_current_screen(self.back_screen);
                        });
                    break;
                    default:
                        self.remove_empty_lines();
                        self.pos_widget.screen_selector.set_current_screen(self.back_screen);
                    break;
                }
            });
        },
        validate_order: function(options) {
            var self = this;
            var realvalidate = this._super;

            var connection = new openerp.Session(self, null, {session_id: openerp.session.session_id});
            var currentOrder = self.pos.get('selectedOrder');

            currentOrder.save_lines_on_db().then(function(){
                //      This is in case S&P was rejected before
                //      we're removing S&P authorization fields to avoid false response
                (new instance.web.Model('pos.order')).get_func('sp_execute')(currentOrder.get_order_id(), 'remove')
            }).then(function(){
                return connection.rpc('/poi_pos_auth_approval/check_validate_order',
                    {'config_id': self.pos.config.id,
                     'order_id': currentOrder.get_order_id(),
                     'current_order': [currentOrder.export_as_JSON()]
                })
            }).then(function(authorization){
                currentOrder.authorization = authorization;
            }).then(function(){
                if(currentOrder.authorization.approved){
                    realvalidate.call(self);
                }else{
                    self.pos_widget.screen_selector.show_popup('ApprovalPopup');
                }
            });
        }
    });

    module.ApprovalPopup = module.PopUpWidget.extend({
        template: 'ApprovalPopup',
        init: function (parent, options) {
            this._super(parent, options);
            this.messages = [];
            this.state = '';
        },
        show: function () {
            var self = this;
            var currentOrder = self.pos.get('selectedOrder');

            if (currentOrder.authorization.auth_state == undefined)
                currentOrder.authorization.auth_state = 'rejected';

            self.messages = currentOrder.authorization.messages;
            self.state = currentOrder.authorization.auth_state;

            self._super();
            self.renderElement();

            this.$el.find('#app_send').off('click').click(function () {
                self.pos_widget.screen_selector.close_popup();
                return (new instance.web.Model('pos.order')).get_func('send_approval_message')(
                    currentOrder.get_order_id(),
                    currentOrder.authorization.users_notified,
                    currentOrder.authorization.messages,
                    self.$el.find('#request_text').val()
                );
            });

            this.$el.find('#app_cancel').off('click').click(function () {

                self.pos_widget.screen_selector.close_popup();

                if (self.state !== 'submit') {
                    if (self.state == 'rejected')
                        (new instance.web.Model('pos.order')).get_func('sp_execute')(currentOrder.get_order_id(), 'reject_notified');

                    if (self.state == 'none')
                        (new instance.web.Model('pos.order')).get_func('sp_execute')(currentOrder.get_order_id(), 'remove');

                    currentOrder.sp_reason = false;
                    currentOrder.authorization.messages = [];
                    currentOrder.authorization.auth_state = 'none';
                }
            });
        }
    });

    module.PosWidget = module.PosWidget.extend({
        init: function(parent, options) {
            this._super(parent, options);
            var  self = this;
        },

        build_widgets: function() {
            this._super();

            //Creating Pop-up "ApprovalPopup"
            this.approval_popup = new module.ApprovalPopup(this, {});
            this.approval_popup.appendTo(this.$el);
            this.screen_selector.add_popup('ApprovalPopup',this.approval_popup);
        }
    });

    module.ProductScreenWidget = module.ProductScreenWidget.extend({
        show: function () {
            var self = this;
            var connection = new openerp.Session(self, null, {session_id: openerp.session.session_id});
            var currentOrder = self.pos.get('selectedOrder');

            if (currentOrder.get_order_id()){
                connection.rpc('/poi_pos_auth_approval/check_validate_order',{
                    'config_id': self.pos.config.id,
                    'order_id': currentOrder.get_order_id(),
                    'current_order': [currentOrder.export_as_JSON()]
                }).then(function(authorization){
                    currentOrder.authorization = authorization;
                }).then(function(){
                    console.log("MRC currentOrder.authorization", currentOrder.authorization);

                    if(currentOrder.authorization.state == 'submit' || currentOrder.authorization.state == 'approved'){
                        self.pos_widget.screen_selector.set_current_screen('payment');
                    }
                });
            }
            self._super();
        }
    });
};<|endoftext|>


<commit_before>var app = angular.module('CAHOnline',['ngRoute','ngCookies','ngOrderObjectBy', 'ngAnimate', 'ngSanitize'])
app.factory('socket', function ($rootScope) {
  var socket = io('/').connect("http://localhost:5000")
  return {
    on: function (eventName, callback) {
      socket.on(eventName, function () {
        var args = arguments
        $rootScope.$apply(function () {
          callback.apply(socket, args)
        })
      })
    },
    emit: function (eventName, data, callback) {
      socket.emit(eventName, data, function () {
        var args = arguments
        $rootScope.$apply(function () {
          if (callback) {
            callback.apply(socket, args)
          }
        })
      })
    },
    id: function(){
      return socket.io.engine.id
    },
    removeAllListeners: function() {
      socket.removeAllListeners()
    }
  }
})

app.config(function($routeProvider, $locationProvider) {
  $routeProvider
  .when("/", {
    templateUrl: "./templates/home.html",
    controller: "mainCtrl"
  })
  .when("/:room", {
    templateUrl: "./templates/game.html",
    controller: "joinGame"
  })

  $locationProvider.html5Mode(true)
})

app.controller("joinGame", function ($scope, $routeParams, $cookies, socket){
  $scope.room=$routeParams.room
  $scope.playerid=socket.id()
  socket.on('first_load', function(data){
    //RECONNECTION LOGIC
    $scope.playerid=socket.id()
    var lastId = $cookies.get("lastId")
    if(data.players[lastId]){
      var playerObject = data.players[lastId]
      delete data.players[lastId]
      playerObject.id = $scope.playerid
      data.players[playerObject.id]=playerObject
      socket.emit('reconnect_player', {newPlayer: playerObject, oldPlayer: lastId})
      $scope.whiteCards = $cookies.getObject("whiteCards")
    }
    else{
      socket.emit('give_whitecards',{room: $scope.room, amount: 10})
    }
    $cookies.put("lastId",$scope.playerid)
    $scope.players=data.players
    $scope.iAmGameMaster=data.players[$scope.playerid].isGameMaster
    $scope.gameState=data.gameState
    $scope.myPlayedCards=[]
    $scope.playedCards=[]
    $scope.time=20
  })

  socket.emit('get_first_load',{room: $scope.room})

  socket.on('display_players', function(data){
    $scope.players=data.players
    $scope.iAmGameMaster=data.players[$scope.playerid].isGameMaster
  })

  socket.on('display_whitecards', function(data){
    $scope.whiteCards=data.whiteCards
    $cookies.putObject("whiteCards",data.whiteCards)
  })

  socket.on('display_blackcard', function(data){
    $scope.blackCard = data.blackCard
  })

  socket.on('sync_gamestate', function(data){
    $scope.gameState=data.gameState

    switch(data.gameState){
      case 1:
        $scope.time=20
        setTimeout(function(){
          $scope.time--
          $scope.$apply()
          var timer = setInterval(function(){
            if($scope.time>0) {
              $scope.time--
              $scope.$apply()
            }
            else  {
              //TIME IS OVER
              clearInterval(timer)
              $scope.gameState=2
              if($scope.iAmGameMaster) socket.emit("sync_room_gamestate",{room: $scope.room, gameState: 2})
            }
          },1000)
        },1)
        break
      case 2:
        //TODO: l'opposto di quanto sopra; + rendere clickabili al gamemaster le carte sul tavolo
        break
    }
  })

  socket.on('display_played_card', function(data){
    //$scope.playedCards.push(card)
    $scope.playedCards=data.cards
    console.log(JSON.stringify(data.cards))
  })

  $scope.startGame = function(){
    socket.emit('start_game',{room: $scope.room})
    socket.emit('give_blackcard',{room: $scope.room})
  }

  $scope.playCard = function(index){
    $scope.myPlayedCards.push($scope.whiteCards[index])
    socket.emit("play_card",{text: $scope.whiteCards[index], player: $scope.playerid, room: $scope.room})
    $scope.whiteCards.splice(index,1)
    $cookies.putObject("whiteCards",$scope.whiteCards)
  }

  $scope.$on('$destroy', function (event) {
    socket.removeAllListeners()
  })
})

app.controller('mainCtrl', function($scope, $location, $cookies, socket) {
  //if user clicked to go back to home we should remove him from the players, until he joins another room
  socket.emit("delete_player")
  $cookies.remove("lastId")

  $scope.createRoom = function() {
    if ($scope.playerName && $scope.playerName.length > 2) {
      socket.emit("create_room", {name: $scope.playerName})
    } else {
      alert("Name is too short or void")
    }
  }

  $scope.joinRoom = function() {
    if ($scope.roomId && ($scope.playerName ? $scope.playerName.length > 2 : false)) {
      socket.emit("join_room", {
        name: $scope.playerName,
        roomId: $scope.roomId })
    } else {
      alert("Inserisci un id della stanza")
    }
  }

  socket.on('load_game_page', function(data){
    $location.path("/"+data.room)
    //$scope.$apply()
  })

  $scope.$on('$destroy', function (event) {
      socket.removeAllListeners()
      // or something like
      // socket.removeListener(this);
  })
})<commit_msg>Mockup for winner selection<commit_after>var app = angular.module('CAHOnline',['ngRoute','ngCookies','ngOrderObjectBy', 'ngAnimate', 'ngSanitize'])
app.factory('socket', function ($rootScope) {
  var socket = io('/').connect("http://localhost:5000")
  return {
    on: function (eventName, callback) {
      socket.on(eventName, function () {
        var args = arguments
        $rootScope.$apply(function () {
          callback.apply(socket, args)
        })
      })
    },
    emit: function (eventName, data, callback) {
      socket.emit(eventName, data, function () {
        var args = arguments
        $rootScope.$apply(function () {
          if (callback) {
            callback.apply(socket, args)
          }
        })
      })
    },
    id: function(){
      return socket.io.engine.id
    },
    removeAllListeners: function() {
      socket.removeAllListeners()
    }
  }
})

app.config(function($routeProvider, $locationProvider) {
  $routeProvider
  .when("/", {
    templateUrl: "./templates/home.html",
    controller: "mainCtrl"
  })
  .when("/:room", {
    templateUrl: "./templates/game.html",
    controller: "joinGame"
  })

  $locationProvider.html5Mode(true)
})

app.controller("joinGame", function ($scope, $routeParams, $cookies, socket){
  $scope.room=$routeParams.room
  $scope.playerid=socket.id()
  socket.on('first_load', function(data){
    //RECONNECTION LOGIC
    $scope.playerid=socket.id()
    var lastId = $cookies.get("lastId")
    if(data.players[lastId]){
      var playerObject = data.players[lastId]
      delete data.players[lastId]
      playerObject.id = $scope.playerid
      data.players[playerObject.id]=playerObject
      socket.emit('reconnect_player', {newPlayer: playerObject, oldPlayer: lastId})
      $scope.whiteCards = $cookies.getObject("whiteCards")
    }
    else{
      socket.emit('give_whitecards',{room: $scope.room, amount: 10})
    }
    $cookies.put("lastId",$scope.playerid)
    $scope.players=data.players
    $scope.iAmGameMaster=data.players[$scope.playerid].isGameMaster
    $scope.gameState=data.gameState
    $scope.myPlayedCards=[]
    $scope.playedCards=[]
    $scope.time=20
  })

  socket.emit('get_first_load',{room: $scope.room})

  socket.on('display_players', function(data){
    $scope.players=data.players
    $scope.iAmGameMaster=data.players[$scope.playerid].isGameMaster
  })

  socket.on('display_whitecards', function(data){
    $scope.whiteCards=data.whiteCards
    $cookies.putObject("whiteCards",data.whiteCards)
  })

  socket.on('display_blackcard', function(data){
    $scope.blackCard = data.blackCard
  })

  socket.on('sync_gamestate', function(data){
    $scope.gameState=data.gameState

    switch(data.gameState){
      case 1:
        $scope.time=20
        setTimeout(function(){
          $scope.time--
          $scope.$apply()
          var timer = setInterval(function(){
            if($scope.time>0) {
              $scope.time--
              $scope.$apply()
            }
            else  {
              //TIME IS OVER
              clearInterval(timer)
              $scope.gameState=2
              if($scope.iAmGameMaster) socket.emit("sync_room_gamestate",{room: $scope.room, gameState: 2})
            }
          },1000)
        },1)
        break
      case 2:
        //TODO: l'opposto di quanto sopra; + rendere clickabili al gamemaster le carte sul tavolo
        break
    }
  })

  socket.on('display_played_card', function(data){
    //$scope.playedCards.push(card)
    $scope.playedCards=data.cards
    console.log(JSON.stringify(data.cards))
  })

  $scope.startGame = function(){
    socket.emit('start_game',{room: $scope.room})
    socket.emit('give_blackcard',{room: $scope.room})
  }

  $scope.playCard = function(index){
    $scope.myPlayedCards.push($scope.whiteCards[index])
    socket.emit("play_card",{text: $scope.whiteCards[index], player: $scope.playerid, room: $scope.room})
    $scope.whiteCards.splice(index,1)
    $cookies.putObject("whiteCards",$scope.whiteCards)
  }

  $scope.pickWinner = function(playerid){
    console.log("Il giocatore " + playerid + " ha giocato la carta più divertente!")
  }

  $scope.$on('$destroy', function (event) {
    socket.removeAllListeners()
  })
})

app.controller('mainCtrl', function($scope, $location, $cookies, socket) {
  //if user clicked to go back to home we should remove him from the players, until he joins another room
  socket.emit("delete_player")
  $cookies.remove("lastId")

  $scope.createRoom = function() {
    if ($scope.playerName && $scope.playerName.length > 2) {
      socket.emit("create_room", {name: $scope.playerName})
    } else {
      alert("Name is too short or void")
    }
  }

  $scope.joinRoom = function() {
    if ($scope.roomId && ($scope.playerName ? $scope.playerName.length > 2 : false)) {
      socket.emit("join_room", {
        name: $scope.playerName,
        roomId: $scope.roomId })
    } else {
      alert("Inserisci un id della stanza")
    }
  }

  socket.on('load_game_page', function(data){
    $location.path("/"+data.room)
    //$scope.$apply()
  })

  $scope.$on('$destroy', function (event) {
      socket.removeAllListeners()
      // or something like
      // socket.removeListener(this);
  })
})<|endoftext|>


<commit_before>import { resolve, join, sep } from 'path'
import webpack from 'webpack'
import glob from 'glob-promise'
import WriteFilePlugin from 'write-file-webpack-plugin'
import FriendlyErrorsWebpackPlugin from 'friendly-errors-webpack-plugin'
import CaseSensitivePathPlugin from 'case-sensitive-paths-webpack-plugin'
import UnlinkFilePlugin from './plugins/unlink-file-plugin'
import PagesPlugin from './plugins/pages-plugin'
import CombineAssetsPlugin from './plugins/combine-assets-plugin'
import getConfig from '../config'

const nextNodeModulesDir = join(__dirname, '../../../node_modules')

export default async function createCompiler (dir, { buildId = '-', dev = false, quiet = false, conf = null } = {}) {
  dir = resolve(dir)
  const config = getConfig(dir, conf)
  const defaultEntries = dev ? [
    require.resolve('../../../browser/client/webpack-hot-middleware-client')
  ] : []
  const mainJS = dev
    ? require.resolve('../../../browser/client/next-dev') : require.resolve('../../../browser/client/next')

  let totalPages

  const entry = async () => {
    const entries = {
      'main.js': [
        ...defaultEntries,
        ...config.clientBootstrap || [],
        mainJS
      ]
    }

    const pages = await glob('pages/**/*.js', { cwd: dir })
    const devPages = pages.filter((p) => p === 'pages/_error.js')

    // In the dev environment, on-demand-entry-handler will take care of
    // managing pages.
    const entryPages = dev ? devPages : pages.filter((p) => p !== 'pages/_document.js' && !/\.test\.js/.test(p))
    for (const p of entryPages) {
      entries[p.replace(/^(pages\/.*)\/index.js$/, '$1.js')] = [`./${p}?entry`]
    }

    totalPages = pages.length

    return entries
  }

  const plugins = [
    new webpack.IgnorePlugin(/(precomputed)/, /node_modules.+(elliptic)/),
    new WriteFilePlugin({
      exitOnErrors: false,
      log: false,
      // required not to cache removed files
      useHashIndex: false
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'commons',
      filename: 'commons.js',
      minChunks (module, count) {
        // We need to move react-dom explicitly into common chunks.
        // Otherwise, if some other page or module uses it, it might
        // included in that bundle too.
        if (module.context && module.context.indexOf(`${sep}react-dom${sep}`) >= 0) {
          return true
        }

        // In the dev we use on-demand-entries.
        // So, it makes no sense to use commonChunks based on the minChunks count.
        // Instead, we move all the code in node_modules into each of the pages.
        if (dev) {
          return false
        }

        // If there are one or two pages, only move modules to common if they are
        // used in all of the pages. Otherwise, move modules used in at-least
        // 1/2 of the total pages into commons.
        if (totalPages <= 2) {
          return count >= totalPages
        }
        return count >= totalPages * 0.5
      }
    }),
    // This chunk contains all the webpack related code. So, all the changes
    // related to that happens to this chunk.
    // It won't touch commons.js and that gives us much better re-build perf.
    new webpack.optimize.CommonsChunkPlugin({
      name: 'manifest',
      filename: 'manifest.js'
    }),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(dev ? 'development' : 'production')
    }),
    new PagesPlugin(),
    new CaseSensitivePathPlugin()
  ]

  if (dev) {
    plugins.push(
      new webpack.HotModuleReplacementPlugin(),
      new webpack.NoEmitOnErrorsPlugin(),
      new UnlinkFilePlugin()
    )
    if (!quiet) {
      plugins.push(new FriendlyErrorsWebpackPlugin())
    }
  } else {
    plugins.push(new webpack.NormalModuleReplacementPlugin(
      /react-hot-loader/,
      require.resolve('../../../browser/client/hot-module-loader.stub')
    ))
    plugins.push(
      new CombineAssetsPlugin({
        input: ['manifest.js', 'pages/_error.js', 'commons.js', 'main.js'],
        output: 'app.js'
      }),
      new webpack.optimize.UglifyJsPlugin({
        exclude: ['manifest.js', 'commons.js', 'main.js', 'pages/_error.js'],
        compress: { warnings: false },
        sourceMap: false,
        extractComments: true
      })
    )
    plugins.push(new webpack.optimize.ModuleConcatenationPlugin())
  }

  const nodePathList = (process.env.NODE_PATH || '')
    .split(process.platform === 'win32' ? ';' : ':')
    .filter((p) => !!p)

  const mainBabelOptions = {
    cacheDirectory: true,
    presets: []
  }

  const rules = (dev ? [{
    test: /\.js(\?[^?]*)?$/,
    loader: 'hot-self-accept-loader',
    include: [
      join(dir, 'pages')
    ]
  }] : [])
    .concat([{
      test: /\.json$/,
      loader: 'json-loader'
    }, {
      test: /\.js(\?[^?]*)?$/,
      loader: 'babel-loader',
      include: [dir],
      exclude (str) {
        return /node_modules/.test(str)
      },
      options: mainBabelOptions
    }])

  let webpackConfig = {
    context: dir,
    entry,
    output: {
      pathinfo: !!dev,
      path: join(dir, '.next', 'bundles'),
      filename: '[name]',
      libraryTarget: 'commonjs2',
      publicPath: `/_next/${buildId}/`,
      strictModuleExceptionHandling: true,
      // This saves chunks with the name given via require.ensure()
      chunkFilename: '[name]'
    },
    resolve: {
      modules: [
        nextNodeModulesDir,
        'node_modules',
        ...nodePathList
      ],
      alias: {
        'object-assign': 'core-js/fn/object/assign',
        'strip-ansi': require.resolve('../../../browser/client/strip-ansi.stub')
      }
    },
    resolveLoader: {
      modules: [
        nextNodeModulesDir,
        'node_modules',
        join(__dirname, 'loaders'),
        ...nodePathList
      ]
    },
    plugins,
    module: {
      rules
    },
    devtool: dev ? 'cheap-module-inline-source-map' : false,
    performance: { hints: false }
  }

  if (config.webpack) {
    console.log(`> Using "webpack" config function defined in ${config.configOrigin}.`)
    webpackConfig = await config.webpack(webpackConfig, { buildId, dev })
  }
  return webpack(webpackConfig)
}
<commit_msg>Filter out tests dir from page builds<commit_after>import { resolve, join, sep } from 'path'
import webpack from 'webpack'
import glob from 'glob-promise'
import WriteFilePlugin from 'write-file-webpack-plugin'
import FriendlyErrorsWebpackPlugin from 'friendly-errors-webpack-plugin'
import CaseSensitivePathPlugin from 'case-sensitive-paths-webpack-plugin'
import UnlinkFilePlugin from './plugins/unlink-file-plugin'
import PagesPlugin from './plugins/pages-plugin'
import CombineAssetsPlugin from './plugins/combine-assets-plugin'
import getConfig from '../config'

const nextNodeModulesDir = join(__dirname, '../../../node_modules')

export default async function createCompiler (dir, { buildId = '-', dev = false, quiet = false, conf = null } = {}) {
  dir = resolve(dir)
  const config = getConfig(dir, conf)
  const defaultEntries = dev ? [
    require.resolve('../../../browser/client/webpack-hot-middleware-client')
  ] : []
  const mainJS = dev
    ? require.resolve('../../../browser/client/next-dev') : require.resolve('../../../browser/client/next')

  let totalPages

  const entry = async () => {
    const entries = {
      'main.js': [
        ...defaultEntries,
        ...config.clientBootstrap || [],
        mainJS
      ]
    }

    const pages = await glob('pages/**/*.js', { cwd: dir })
    const devPages = pages.filter((p) => p === 'pages/_error.js')

    // In the dev environment, on-demand-entry-handler will take care of
    // managing pages.
    const entryPages = dev ? devPages : pages.filter((p) => p !== 'pages/_document.js' && !/\.test\.js/.test(p) && !/__tests__/.test(p))
    for (const p of entryPages) {
      entries[p.replace(/^(pages\/.*)\/index.js$/, '$1.js')] = [`./${p}?entry`]
    }

    totalPages = pages.length

    return entries
  }

  const plugins = [
    new webpack.IgnorePlugin(/(precomputed)/, /node_modules.+(elliptic)/),
    new WriteFilePlugin({
      exitOnErrors: false,
      log: false,
      // required not to cache removed files
      useHashIndex: false
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'commons',
      filename: 'commons.js',
      minChunks (module, count) {
        // We need to move react-dom explicitly into common chunks.
        // Otherwise, if some other page or module uses it, it might
        // included in that bundle too.
        if (module.context && module.context.indexOf(`${sep}react-dom${sep}`) >= 0) {
          return true
        }

        // In the dev we use on-demand-entries.
        // So, it makes no sense to use commonChunks based on the minChunks count.
        // Instead, we move all the code in node_modules into each of the pages.
        if (dev) {
          return false
        }

        // If there are one or two pages, only move modules to common if they are
        // used in all of the pages. Otherwise, move modules used in at-least
        // 1/2 of the total pages into commons.
        if (totalPages <= 2) {
          return count >= totalPages
        }
        return count >= totalPages * 0.5
      }
    }),
    // This chunk contains all the webpack related code. So, all the changes
    // related to that happens to this chunk.
    // It won't touch commons.js and that gives us much better re-build perf.
    new webpack.optimize.CommonsChunkPlugin({
      name: 'manifest',
      filename: 'manifest.js'
    }),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify(dev ? 'development' : 'production')
    }),
    new PagesPlugin(),
    new CaseSensitivePathPlugin()
  ]

  if (dev) {
    plugins.push(
      new webpack.HotModuleReplacementPlugin(),
      new webpack.NoEmitOnErrorsPlugin(),
      new UnlinkFilePlugin()
    )
    if (!quiet) {
      plugins.push(new FriendlyErrorsWebpackPlugin())
    }
  } else {
    plugins.push(new webpack.NormalModuleReplacementPlugin(
      /react-hot-loader/,
      require.resolve('../../../browser/client/hot-module-loader.stub')
    ))
    plugins.push(
      new CombineAssetsPlugin({
        input: ['manifest.js', 'pages/_error.js', 'commons.js', 'main.js'],
        output: 'app.js'
      }),
      new webpack.optimize.UglifyJsPlugin({
        exclude: ['manifest.js', 'commons.js', 'main.js', 'pages/_error.js'],
        compress: { warnings: false },
        sourceMap: false,
        extractComments: true
      })
    )
    plugins.push(new webpack.optimize.ModuleConcatenationPlugin())
  }

  const nodePathList = (process.env.NODE_PATH || '')
    .split(process.platform === 'win32' ? ';' : ':')
    .filter((p) => !!p)

  const mainBabelOptions = {
    cacheDirectory: true,
    presets: []
  }

  const rules = (dev ? [{
    test: /\.js(\?[^?]*)?$/,
    loader: 'hot-self-accept-loader',
    include: [
      join(dir, 'pages')
    ]
  }] : [])
    .concat([{
      test: /\.json$/,
      loader: 'json-loader'
    }, {
      test: /\.js(\?[^?]*)?$/,
      loader: 'babel-loader',
      include: [dir],
      exclude (str) {
        return /node_modules/.test(str)
      },
      options: mainBabelOptions
    }])

  let webpackConfig = {
    context: dir,
    entry,
    output: {
      pathinfo: !!dev,
      path: join(dir, '.next', 'bundles'),
      filename: '[name]',
      libraryTarget: 'commonjs2',
      publicPath: `/_next/${buildId}/`,
      strictModuleExceptionHandling: true,
      // This saves chunks with the name given via require.ensure()
      chunkFilename: '[name]'
    },
    resolve: {
      modules: [
        nextNodeModulesDir,
        'node_modules',
        ...nodePathList
      ],
      alias: {
        'object-assign': 'core-js/fn/object/assign',
        'strip-ansi': require.resolve('../../../browser/client/strip-ansi.stub')
      }
    },
    resolveLoader: {
      modules: [
        nextNodeModulesDir,
        'node_modules',
        join(__dirname, 'loaders'),
        ...nodePathList
      ]
    },
    plugins,
    module: {
      rules
    },
    devtool: dev ? 'cheap-module-inline-source-map' : false,
    performance: { hints: false }
  }

  if (config.webpack) {
    console.log(`> Using "webpack" config function defined in ${config.configOrigin}.`)
    webpackConfig = await config.webpack(webpackConfig, { buildId, dev })
  }
  return webpack(webpackConfig)
}
<|endoftext|>


<commit_before>import Reflux from 'reflux'
import Immutable from 'immutable'

import Student from '../models/student'

import studentActions from './studentActions'

let studentStore = Reflux.createStore({
	listenables: studentActions,

	init() {
		this.students = Immutable.Map()
		this.history = Immutable.Stack()
		this.future = Immutable.Stack()

		this._loadData()
	},

	getInitialState() {
		return this.students
	},

	undo() {
		if (this.history.size) {
			console.log('undoing...')
			this.future = this.future.push(this.students)
			this.students = this.history.first()
			this.history = this.history.pop()
			this._postChange()
		}
	},

	redo() {
		if (this.future.size) {
			console.log('redoing...')
			this.history = this.history.push(this.students)
			this.students = this.future.first()
			this.future = this.future.pop()
			this._postChange()
		}
	},

	_loadData(opts={}) {
		console.log('studentStore._loadData, with', opts)
		let rawStudent = null
		let studentId = localStorage.getItem('activeStudentId')
		let demoStudentId = '3AE9E7EE-DA8F-4014-B987-8D88814BB848'

		let localStudent = localStorage.getItem(studentId || demoStudentId) || localStorage.getItem('student-v3.0a6')

		try {
			rawStudent = JSON.parse(localStudent)
		}
		catch (e) {
			console.info('using demo student')
			rawStudent = demoStudent
			rawStudent.active = true
			rawStudent.id = null
		}

		let student = new Student(rawStudent)
		window.studentData = student

		this._preChange()
		this.students = this.students.set(student.id, student)
		this._postChange()
	},

	_preChange() {
		this.history = this.history.unshift(this.students)
	},

	_postChange() {
		console.groupCollapsed('studentStore._postChange')
		console.log('studentStore._postChange', this.students)
		this.students.forEach(student => student.save())
		console.groupEnd('studentStore._postChange')
		this.trigger(this.students)
	},

	_change(studentId, method, ...args) {
		this._preChange()
		this.students = this.students.set(studentId, this.students.get(studentId)[method](...args))
		this._postChange()
	},

	_alter(pathToData, method, ...args) {
		this._preChange()
		this.students = this.students.setIn(pathToData, this.students.getIn(pathToData)[method](...args))
		this._postChange()
	},

	changeName(studentId, ...args)               { this._change(studentId, 'changeName',               ...args) },
	changeActive(studentId, ...args)             { this._change(studentId, 'changeActive',             ...args) },
	changeCreditsNeeded(studentId, ...args)      { this._change(studentId, 'changeCreditsNeeded',      ...args) },
	changeMatriculation(studentId, ...args)      { this._change(studentId, 'changeMatriculation',      ...args) },
	changeGraduation(studentId, ...args)         { this._change(studentId, 'changeGraduation',         ...args) },
	changeSetting(studentId, key, value)         { this._change(studentId, 'changeSetting',            key, value) },
	addArea(studentId, ...args)                  { this._change(studentId, 'addArea',                  ...args) },
	addSchedule(studentId, ...args)              { this._change(studentId, 'addSchedule',              ...args) },
	addFabrication(studentId, ...args)           { this._change(studentId, 'addArea',                  ...args) },
	addOverride(studentId, ...args)              { this._change(studentId, 'addSchedule',              ...args) },
	removeArea(studentId, ...args)               { this._change(studentId, 'removeArea',               ...args) },
	removeMultipleAreas(studentId, ...args)      { this._change(studentId, 'removeMultipleArea',       ...args) },
	destroySchedule(studentId, ...args)          { this._change(studentId, 'destroySchedule',          ...args) },
	destroyMultipleSchedules(studentId, ...args) { this._change(studentId, 'destroyMultipleSchedules', ...args) },

	renameSchedule(studentId, scheduleId, ...args)  { this._alter([studentId, 'schedules', scheduleId], 'rename',        ...args) },
	reorderSchedule(studentId, scheduleId, ...args) { this._alter([studentId, 'schedules', scheduleId], 'reorder',       ...args) },
	moveSchedule(studentId, scheduleId, ...args)    { this._alter([studentId, 'schedules', scheduleId], 'move',          ...args) },
	addCourse(studentId, scheduleId, ...args)       { this._alter([studentId, 'schedules', scheduleId], 'addCourse',     ...args) },
	removeCourse(studentId, scheduleId, ...args)    { this._alter([studentId, 'schedules', scheduleId], 'removeCourse',  ...args) },
	reorderCourse(studentId, scheduleId, ...args)   { this._alter([studentId, 'schedules', scheduleId], 'reorderCourse', ...args) },
	reorderArea(studentId, areaId, ...args)         { this._alter([studentId, 'studies', areaId],       'reorder',       ...args) },
})

window.store = studentStore

export default studentStore
<commit_msg>Stop calling _preChange in _loadData<commit_after>import Reflux from 'reflux'
import Immutable from 'immutable'

import Student from '../models/student'

import studentActions from './studentActions'

let studentStore = Reflux.createStore({
	listenables: studentActions,

	init() {
		this.students = Immutable.Map()
		this.history = Immutable.Stack()
		this.future = Immutable.Stack()

		this._loadData()
	},

	getInitialState() {
		return this.students
	},

	undo() {
		if (this.history.size) {
			console.log('undoing...')
			this.future = this.future.push(this.students)
			this.students = this.history.first()
			this.history = this.history.pop()
			this._postChange()
		}
	},

	redo() {
		if (this.future.size) {
			console.log('redoing...')
			this.history = this.history.push(this.students)
			this.students = this.future.first()
			this.future = this.future.pop()
			this._postChange()
		}
	},

	_loadData(opts={}) {
		console.log('studentStore._loadData, with', opts)
		let rawStudent = null
		let studentId = localStorage.getItem('activeStudentId')
		let demoStudentId = '3AE9E7EE-DA8F-4014-B987-8D88814BB848'

		let localStudent = localStorage.getItem(studentId || demoStudentId) || localStorage.getItem('student-v3.0a6')

		try {
			rawStudent = JSON.parse(localStudent)
		}
		catch (e) {
			console.info('using demo student')
			rawStudent = demoStudent
			rawStudent.active = true
			rawStudent.id = null
		}

		let student = new Student(rawStudent)
		window.studentData = student

		this.students = this.students.set(student.id, student)
		this._postChange()
	},

	_preChange() {
		this.history = this.history.unshift(this.students)
	},

	_postChange() {
		console.groupCollapsed('studentStore._postChange')
		console.log('studentStore._postChange', this.students)
		this.students.forEach(student => student.save())
		console.groupEnd('studentStore._postChange')
		this.trigger(this.students)
	},

	_change(studentId, method, ...args) {
		this._preChange()
		this.students = this.students.set(studentId, this.students.get(studentId)[method](...args))
		this._postChange()
	},

	_alter(pathToData, method, ...args) {
		this._preChange()
		this.students = this.students.setIn(pathToData, this.students.getIn(pathToData)[method](...args))
		this._postChange()
	},

	changeName(studentId, ...args)               { this._change(studentId, 'changeName',               ...args) },
	changeActive(studentId, ...args)             { this._change(studentId, 'changeActive',             ...args) },
	changeCreditsNeeded(studentId, ...args)      { this._change(studentId, 'changeCreditsNeeded',      ...args) },
	changeMatriculation(studentId, ...args)      { this._change(studentId, 'changeMatriculation',      ...args) },
	changeGraduation(studentId, ...args)         { this._change(studentId, 'changeGraduation',         ...args) },
	changeSetting(studentId, key, value)         { this._change(studentId, 'changeSetting',            key, value) },
	addArea(studentId, ...args)                  { this._change(studentId, 'addArea',                  ...args) },
	addSchedule(studentId, ...args)              { this._change(studentId, 'addSchedule',              ...args) },
	addFabrication(studentId, ...args)           { this._change(studentId, 'addArea',                  ...args) },
	addOverride(studentId, ...args)              { this._change(studentId, 'addSchedule',              ...args) },
	removeArea(studentId, ...args)               { this._change(studentId, 'removeArea',               ...args) },
	removeMultipleAreas(studentId, ...args)      { this._change(studentId, 'removeMultipleArea',       ...args) },
	destroySchedule(studentId, ...args)          { this._change(studentId, 'destroySchedule',          ...args) },
	destroyMultipleSchedules(studentId, ...args) { this._change(studentId, 'destroyMultipleSchedules', ...args) },

	renameSchedule(studentId, scheduleId, ...args)  { this._alter([studentId, 'schedules', scheduleId], 'rename',        ...args) },
	reorderSchedule(studentId, scheduleId, ...args) { this._alter([studentId, 'schedules', scheduleId], 'reorder',       ...args) },
	moveSchedule(studentId, scheduleId, ...args)    { this._alter([studentId, 'schedules', scheduleId], 'move',          ...args) },
	addCourse(studentId, scheduleId, ...args)       { this._alter([studentId, 'schedules', scheduleId], 'addCourse',     ...args) },
	removeCourse(studentId, scheduleId, ...args)    { this._alter([studentId, 'schedules', scheduleId], 'removeCourse',  ...args) },
	reorderCourse(studentId, scheduleId, ...args)   { this._alter([studentId, 'schedules', scheduleId], 'reorderCourse', ...args) },
	reorderArea(studentId, areaId, ...args)         { this._alter([studentId, 'studies', areaId],       'reorder',       ...args) },
})

window.store = studentStore

export default studentStore
<|endoftext|>


<commit_before>'use strict';

// Declare app level module which depends on filters, and services
angular.module('myApp.config', [])

   .constant('version', '0.2')

   // where to redirect users if they need to authenticate (see module.routeSecurity)
   .constant('loginRedirectPath', '/login')

   // your Firebase URL goes here
   .constant('FBURL', 'https://current-flow.firebaseio.com')

   //you can use this one to try out a demo of the seed
//   .constant('FBURL', 'https://angularfire-seed.firebaseio.com');

/*********************
 * !!FOR E2E TESTING!!
 *
 * Must enable email/password logins and manually create
 * the test user before the e2e tests will pass
 *
 * user: test@test.com
 * pass: test123
 */
<commit_msg>bumped up version number to 0.3<commit_after>'use strict';

// Declare app level module which depends on filters, and services
angular.module('myApp.config', [])

   .constant('version', '0.3')

   // where to redirect users if they need to authenticate (see module.routeSecurity)
   .constant('loginRedirectPath', '/login')

   // your Firebase URL goes here
   .constant('FBURL', 'https://current-flow.firebaseio.com')

   //you can use this one to try out a demo of the seed
//   .constant('FBURL', 'https://angularfire-seed.firebaseio.com');

/*********************
 * !!FOR E2E TESTING!!
 *
 * Must enable email/password logins and manually create
 * the test user before the e2e tests will pass
 *
 * user: test@test.com
 * pass: test123
 */
<|endoftext|>


<commit_before>walk(document.body);

function walk(node)
{
	// I stole this function from here:
	// http://is.gd/mwZp7E

	var child, next;

	switch ( node.nodeType )
	{
		case 1:  // Element
		case 9:  // Document
		case 11: // Document fragment
			child = node.firstChild;
			while ( child )
			{
				next = child.nextSibling;
				walk(child);
				child = next;
			}
			break;

		case 3: // Text node
			handleText(node);
			break;
	}
}

function handleText(textNode)
{
	var v = textNode.nodeValue;

	// Millennial
	v = v.replace(/\bMillennial\b/g, "Snake Person");
	v = v.replace(/\bmillennial\b/g, "snake person");
	v = v.replace(/\bMillennials\b/g, "Snake People");
	v = v.replace(/\bmillennials\b/g, "snake people");
	v = v.replace(/\bMillennials'\b/g, "Snake People's");
	v = v.replace(/\bmillennials'\b/g, "snake people's");
	v = v.replace(/\bMillienials\b/g, "Snake People"); 		// Common misspelling
	v = v.replace(/\bmillienials\b/g, "snake people"); 	 	// Common misspelling

	// The Great Recession
	v = v.replace(/\bGreat Recession\b/g, "Time of Shedding and Cold Rocks");
	v = v.replace(/\bgreat recession\b/g, "time of shedding and cold rocks");

	// The Great Depression
	v = v.replace(/\bGreat Depression\b/g, "Clutch Plague");
	v = v.replace(/\bgreat depression\b/g, "clutch plague");

	// Occupy Wall Street
	v = v.replace(/\bOccupy Wall Street\b/g, "Great Ape-Snake War");
	v = v.replace(/\boccupy wall street\b/g, "great ape-snake war");
	v = v.replace(/\bOccupy Movement\b/g, "Great Ape-Snake War");
	v = v.replace(/\boccupy movement\b/g, "great ape-snake war");
	v = v.replace(/\bOWS Movement\b/g, "Great Ape-Snake War");
	v = v.replace(/\bOWS movement\b/g, "great ape-snake war");
	v = v.replace(/\bows movement\b/g, "great ape-snake war");
	v = v.replace(/\b ows \b/g, "ga-sw");
	v = v.replace(/\b OWS \b/g, "GA-SW");

	// Helicopter Parents
	v = v.replace(/\bHelicopter Parents\b/g, "Thulsa Doom");
	v = v.replace(/\bhelicopter parents\b/g, "Thoth-Amon");
	v = v.replace(/\bHelicopter Parents'\b/g, "Thulsa Doom's");
	v = v.replace(/\bhelicopter parents'\b/g, "Thoth-Amon's");

	// Trophy Kids
	v = v.replace(/\bTrophy Kids\b/g, "Quetzalcoatl's Chosen");
	v = v.replace(/\btrophy kids\b/g, "Quetzalcoatl's chosen");
	v = v.replace(/\bTrophy Kids'\b/g, "Quetzalcoatl's Chosen's");
	v = v.replace(/\btrophy kids'\b/g, "Quetzalcoatl's chosen's");

	// Digital Natives
	v = v.replace(/\bDigital Native\b/g, "Parseltongue");
	v = v.replace(/\bDigital Natives\b/g, "Parseltongues");
	v = v.replace(/\bdigital native\b/g, "parseltongue");
	v = v.replace(/\bdigital natives\b/g, "parseltongues");

	// Generation Y
	v = v.replace(/\bGeneration Y\b/g, "Serpent Society");
	v = v.replace(/\bgeneration y\b/g, "serpent society");
	v = v.replace(/\bGen Y\b/g, "Society of the Serpent");
	v = v.replace(/\bgen y\b/g, "serpent society");
	v = v.replace(/\bGenY\b/g, "Serpent Society");
	v = v.replace(/\bgeny\b/g, "serpent society");
	v = v.replace(/\bGeneration Why\b/g, "Serpent Society");
	v = v.replace(/\bgeneration why\b/g, "serpent society");

	// Millennial Generation
	v = v.replace(/\bMillennial Generation\b/g, "Plissken Faction");
	v = v.replace(/\bmillennial generation\b/g, "Plissken faction");
	v = v.replace(/\bGeneration Millennial\b/g, "Plissken Faction");
	v = v.replace(/\bgeneration millennial\b/g, "Plissken faction");

	// Generation We
	v = v.replace(/\bGeneration We\b/g, "Caduceus Cult");
	v = v.replace(/\bgeneration we\b/g, "caduceus cult");
	v = v.replace(/\bWe Generation\b/g, "Cult of the Caduceus ");
	v = v.replace(/\bwe generation\b/g, "cult of the caduceus ");

    // Generation Me
    v = v.replace(/\bGeneration Me\b/g, "The Cult of the Serpent");
    v = v.replace(/\bgeneration me\b/g, "the cult of the serpent");

	// Global Generation
	v = v.replace(/\bGlobal Generation\b/g, "Tannin's Horde");
	v = v.replace(/\bglobal generation\b/g, "Tannin's horde");
	v = v.replace(/\bGeneration Global\b/g, "Horde of Tannin");
	v = v.replace(/\bgeneration global\b/g, "horde of Tannin");

	// Generation Next
	v = v.replace(/\bGeneration Next\b/g, "Time of Nidhogg");
	v = v.replace(/\bgeneration next\b/g, "time of Nidhogg");

	// Net Generation
	v = v.replace(/\bNet Generation\b/g, "Damballa's Coils");
	v = v.replace(/\bnet generation\b/g, "Damballa's coils");
	v = v.replace(/\bGeneration Net\b/g, "Coils of Damballa");
	v = v.replace(/\bgeneration net\b/g, "Coils of Damballa");

	// Echo Boomers
	v = v.replace(/\bEcho Boomers\b/g, "Crotalids");
	v = v.replace(/\becho Boomers\b/g, "crotalids");

	// New Boomers
	v = v.replace(/\bNew Boomers\b/g, "Jörmungandr's Circle");
	v = v.replace(/\bnew Boomers\b/g, "Jörmungandr's circle");
	v = v.replace(/\bNew Boomers'\b/g, "Jörmungandr's Circle's");
	v = v.replace(/\bnew Boomers'\b/g, "Jörmungandr's circle's");

	// Generation Flux
	v = v.replace(/\bGeneration Flux\b/g, "Hiss Club");
	v = v.replace(/\bgeneration flux\b/g, "hiss club");
	v = v.replace(/\bFlux Generation\b/g, "Hiss Club");
	v = v.replace(/\bflux generation\b/g, "hiss club");

	// Generation Sell
	v = v.replace(/\bGeneration Sell\b/g, "Kaa Tribe");
	v = v.replace(/\bgeneration sell\b/g, "Kaa tribe");
	v = v.replace(/\bSell Generation\b/g, "Tribe of Kaa");
	v = v.replace(/\bsell generation\b/g, "tribe of Kaa");

	// Boomerang Generation
	v = v.replace(/\bBoomerang Generation\b/g, "Ouroboros Society");
	v = v.replace(/\bboomerang generation\b/g, "ouroboros society");
	v = v.replace(/\bGeneration Boomerang\b/g, "Ouroboros Society");
	v = v.replace(/\bgeneration boomerang\b/g, "ouroboros society");

	// Peter Pan Generation
	v = v.replace(/\bPeter Pan Generation\b/g, "Neheb-Kau Cult");
	v = v.replace(/\bPeter Pan generation\b/g, "Neheb-Kau cult");
	v = v.replace(/\bpeter pan generation\b/g, "Neheb-Kau cult");
	v = v.replace(/\bGeneration Peter Pan\b/g, "Neheb-Kau Cult");
	v = v.replace(/\bgeneration Peter Pan\b/g, "Neheb-Kau cult");
	v = v.replace(/\bgeneration peter pan\b/g, "Neheb-Kau cult");

	// Generation 911
	v = v.replace(/\bGeneration 9\/11\b/g, "Kaa Tribe");
	v = v.replace(/\bGeneration 911\b/g, "Kaa Tribe");
	v = v.replace(/\bgeneration 9\/11\b/g, "Kaa tribe");
	v = v.replace(/\bgeneration 911\b/g, "Kaa tribe");
	v = v.replace(/\b9\/11 Generation\b/g, "Tribe of the Kaa");
	v = v.replace(/\b9\/11 generation\b/g, "tribe of the Kaa");
	v = v.replace(/\bGen 9\/11\b/g, "Kaa Tribe");
	v = v.replace(/\bgen 9\/11\b/g, "Kaa tribe");
	v = v.replace(/\bGen 911\b/g, "Kaa Tribe");
	v = v.replace(/\bgen 911\b/g, "Kaa tribe");

	// The Generation of €700
	v = v.replace(/\bThe Generation of €700\b/g, "Ophion");
	v = v.replace(/\bthe generation of €700\b/g, "ophion");
	v = v.replace(/\b€700 Generation\b/g, "Ophion");
	v = v.replace(/\b€700 generation\b/g, "ophion");

	// Mileurista
	v = v.replace(/\bMileurista\b/g, "Nagual");
	v = v.replace(/\bmileurista\b/g, "Nagual");
	v = v.replace(/\bMilleurista\b/g, "Nagual");
	v = v.replace(/\bmilleurista\b/g, "Nagual");

	// Precarious Generation
	v = v.replace(/\bPrecarious Generation\b/g, "Gargouille");
	v = v.replace(/\bprecarious generation\b/g, "gargouille");
	v = v.replace(/\bGeneration Precarious\b/g, "Gargouille");
	v = v.replace(/\bgeneration precarious\b/g, "gargouille");

	textNode.nodeValue = v;
}

<commit_msg>Add spaces to OWS replacementssssss<commit_after>walk(document.body);

function walk(node)
{
	// I stole this function from here:
	// http://is.gd/mwZp7E

	var child, next;

	switch ( node.nodeType )
	{
		case 1:  // Element
		case 9:  // Document
		case 11: // Document fragment
			child = node.firstChild;
			while ( child )
			{
				next = child.nextSibling;
				walk(child);
				child = next;
			}
			break;

		case 3: // Text node
			handleText(node);
			break;
	}
}

function handleText(textNode)
{
	var v = textNode.nodeValue;

	// Millennial
	v = v.replace(/\bMillennial\b/g, "Snake Person");
	v = v.replace(/\bmillennial\b/g, "snake person");
	v = v.replace(/\bMillennials\b/g, "Snake People");
	v = v.replace(/\bmillennials\b/g, "snake people");
	v = v.replace(/\bMillennials'\b/g, "Snake People's");
	v = v.replace(/\bmillennials'\b/g, "snake people's");
	v = v.replace(/\bMillienials\b/g, "Snake People"); 		// Common misspelling
	v = v.replace(/\bmillienials\b/g, "snake people"); 	 	// Common misspelling

	// The Great Recession
	v = v.replace(/\bGreat Recession\b/g, "Time of Shedding and Cold Rocks");
	v = v.replace(/\bgreat recession\b/g, "time of shedding and cold rocks");

	// The Great Depression
	v = v.replace(/\bGreat Depression\b/g, "Clutch Plague");
	v = v.replace(/\bgreat depression\b/g, "clutch plague");

	// Occupy Wall Street
	v = v.replace(/\bOccupy Wall Street\b/g, "Great Ape-Snake War");
	v = v.replace(/\boccupy wall street\b/g, "great ape-snake war");
	v = v.replace(/\bOccupy Movement\b/g, "Great Ape-Snake War");
	v = v.replace(/\boccupy movement\b/g, "great ape-snake war");
	v = v.replace(/\bOWS Movement\b/g, "Great Ape-Snake War");
	v = v.replace(/\bOWS movement\b/g, "great ape-snake war");
	v = v.replace(/\bows movement\b/g, "great ape-snake war");
	v = v.replace(/\b ows \b/g, " ga-sw ");
	v = v.replace(/\b OWS \b/g, " GA-SW ");

	// Helicopter Parents
	v = v.replace(/\bHelicopter Parents\b/g, "Thulsa Doom");
	v = v.replace(/\bhelicopter parents\b/g, "Thoth-Amon");
	v = v.replace(/\bHelicopter Parents'\b/g, "Thulsa Doom's");
	v = v.replace(/\bhelicopter parents'\b/g, "Thoth-Amon's");

	// Trophy Kids
	v = v.replace(/\bTrophy Kids\b/g, "Quetzalcoatl's Chosen");
	v = v.replace(/\btrophy kids\b/g, "Quetzalcoatl's chosen");
	v = v.replace(/\bTrophy Kids'\b/g, "Quetzalcoatl's Chosen's");
	v = v.replace(/\btrophy kids'\b/g, "Quetzalcoatl's chosen's");

	// Digital Natives
	v = v.replace(/\bDigital Native\b/g, "Parseltongue");
	v = v.replace(/\bDigital Natives\b/g, "Parseltongues");
	v = v.replace(/\bdigital native\b/g, "parseltongue");
	v = v.replace(/\bdigital natives\b/g, "parseltongues");

	// Generation Y
	v = v.replace(/\bGeneration Y\b/g, "Serpent Society");
	v = v.replace(/\bgeneration y\b/g, "serpent society");
	v = v.replace(/\bGen Y\b/g, "Society of the Serpent");
	v = v.replace(/\bgen y\b/g, "serpent society");
	v = v.replace(/\bGenY\b/g, "Serpent Society");
	v = v.replace(/\bgeny\b/g, "serpent society");
	v = v.replace(/\bGeneration Why\b/g, "Serpent Society");
	v = v.replace(/\bgeneration why\b/g, "serpent society");

	// Millennial Generation
	v = v.replace(/\bMillennial Generation\b/g, "Plissken Faction");
	v = v.replace(/\bmillennial generation\b/g, "Plissken faction");
	v = v.replace(/\bGeneration Millennial\b/g, "Plissken Faction");
	v = v.replace(/\bgeneration millennial\b/g, "Plissken faction");

	// Generation We
	v = v.replace(/\bGeneration We\b/g, "Caduceus Cult");
	v = v.replace(/\bgeneration we\b/g, "caduceus cult");
	v = v.replace(/\bWe Generation\b/g, "Cult of the Caduceus ");
	v = v.replace(/\bwe generation\b/g, "cult of the caduceus ");

    // Generation Me
    v = v.replace(/\bGeneration Me\b/g, "The Cult of the Serpent");
    v = v.replace(/\bgeneration me\b/g, "the cult of the serpent");

	// Global Generation
	v = v.replace(/\bGlobal Generation\b/g, "Tannin's Horde");
	v = v.replace(/\bglobal generation\b/g, "Tannin's horde");
	v = v.replace(/\bGeneration Global\b/g, "Horde of Tannin");
	v = v.replace(/\bgeneration global\b/g, "horde of Tannin");

	// Generation Next
	v = v.replace(/\bGeneration Next\b/g, "Time of Nidhogg");
	v = v.replace(/\bgeneration next\b/g, "time of Nidhogg");

	// Net Generation
	v = v.replace(/\bNet Generation\b/g, "Damballa's Coils");
	v = v.replace(/\bnet generation\b/g, "Damballa's coils");
	v = v.replace(/\bGeneration Net\b/g, "Coils of Damballa");
	v = v.replace(/\bgeneration net\b/g, "Coils of Damballa");

	// Echo Boomers
	v = v.replace(/\bEcho Boomers\b/g, "Crotalids");
	v = v.replace(/\becho Boomers\b/g, "crotalids");

	// New Boomers
	v = v.replace(/\bNew Boomers\b/g, "Jörmungandr's Circle");
	v = v.replace(/\bnew Boomers\b/g, "Jörmungandr's circle");
	v = v.replace(/\bNew Boomers'\b/g, "Jörmungandr's Circle's");
	v = v.replace(/\bnew Boomers'\b/g, "Jörmungandr's circle's");

	// Generation Flux
	v = v.replace(/\bGeneration Flux\b/g, "Hiss Club");
	v = v.replace(/\bgeneration flux\b/g, "hiss club");
	v = v.replace(/\bFlux Generation\b/g, "Hiss Club");
	v = v.replace(/\bflux generation\b/g, "hiss club");

	// Generation Sell
	v = v.replace(/\bGeneration Sell\b/g, "Kaa Tribe");
	v = v.replace(/\bgeneration sell\b/g, "Kaa tribe");
	v = v.replace(/\bSell Generation\b/g, "Tribe of Kaa");
	v = v.replace(/\bsell generation\b/g, "tribe of Kaa");

	// Boomerang Generation
	v = v.replace(/\bBoomerang Generation\b/g, "Ouroboros Society");
	v = v.replace(/\bboomerang generation\b/g, "ouroboros society");
	v = v.replace(/\bGeneration Boomerang\b/g, "Ouroboros Society");
	v = v.replace(/\bgeneration boomerang\b/g, "ouroboros society");

	// Peter Pan Generation
	v = v.replace(/\bPeter Pan Generation\b/g, "Neheb-Kau Cult");
	v = v.replace(/\bPeter Pan generation\b/g, "Neheb-Kau cult");
	v = v.replace(/\bpeter pan generation\b/g, "Neheb-Kau cult");
	v = v.replace(/\bGeneration Peter Pan\b/g, "Neheb-Kau Cult");
	v = v.replace(/\bgeneration Peter Pan\b/g, "Neheb-Kau cult");
	v = v.replace(/\bgeneration peter pan\b/g, "Neheb-Kau cult");

	// Generation 911
	v = v.replace(/\bGeneration 9\/11\b/g, "Kaa Tribe");
	v = v.replace(/\bGeneration 911\b/g, "Kaa Tribe");
	v = v.replace(/\bgeneration 9\/11\b/g, "Kaa tribe");
	v = v.replace(/\bgeneration 911\b/g, "Kaa tribe");
	v = v.replace(/\b9\/11 Generation\b/g, "Tribe of the Kaa");
	v = v.replace(/\b9\/11 generation\b/g, "tribe of the Kaa");
	v = v.replace(/\bGen 9\/11\b/g, "Kaa Tribe");
	v = v.replace(/\bgen 9\/11\b/g, "Kaa tribe");
	v = v.replace(/\bGen 911\b/g, "Kaa Tribe");
	v = v.replace(/\bgen 911\b/g, "Kaa tribe");

	// The Generation of €700
	v = v.replace(/\bThe Generation of €700\b/g, "Ophion");
	v = v.replace(/\bthe generation of €700\b/g, "ophion");
	v = v.replace(/\b€700 Generation\b/g, "Ophion");
	v = v.replace(/\b€700 generation\b/g, "ophion");

	// Mileurista
	v = v.replace(/\bMileurista\b/g, "Nagual");
	v = v.replace(/\bmileurista\b/g, "Nagual");
	v = v.replace(/\bMilleurista\b/g, "Nagual");
	v = v.replace(/\bmilleurista\b/g, "Nagual");

	// Precarious Generation
	v = v.replace(/\bPrecarious Generation\b/g, "Gargouille");
	v = v.replace(/\bprecarious generation\b/g, "gargouille");
	v = v.replace(/\bGeneration Precarious\b/g, "Gargouille");
	v = v.replace(/\bgeneration precarious\b/g, "gargouille");

	textNode.nodeValue = v;
}

<|endoftext|>


<commit_before>/*!
 * file upload
 * xiewulong <xiewulong@vip.qq.com>
 * create: 2015/2/27
 * version: 0.0.1
 */

(function($, window, document, undefined){
	var fileupload	= function(input, fn, prop){
			prop = prop || {};
			this.input = input;
			this.name = input.name;
			this.$input = $(input);
			this.$parent = this.$input.parent();
			this.action = prop.action || this.$input.attr('data-action');
			this.min = prop.min || this.$input.attr('data-min');
			this.max = prop.max || this.$input.attr('data-max');
			this.type = prop.type || this.$input.attr('data-type');
			this.sizes = prop.sizes || this.$input.attr('data-sizes');
			this.oss = prop.oss || this.$input.attr('data-oss');
			this.csrf = prop.csrf || this.$input.attr('data-csrf');
			this.pre = prop.pre || 'xFileupload';
			this.before = prop.before || function(){};
			this.fn = fn;

			this.input.value && this.action && this.fn && this.upload();
		};

	fileupload.prototype = {
		upload: function(){
			var _this = this;
			this.before && this.before.call(this.input);
			this.setName();
			this.createElements();
			window[_this.input.name] = function(d){_this.callback(d);};
			this.$form.submit();
		},
		createElements: function(){
			this.$iframe = $('').appendTo('body');
			this.$form = $('<form style="display:none;" action="' + this.action + '" target="' + this.input.name + '" method="post" enctype="multipart/form-data"></form>').appendTo('body');
			this.min && this.$form.append('<input type="hidden" name="min" value="' + this.min + '" />');
			this.max && this.$form.append('<input type="hidden" name="max" value="' + this.max + '" />');
			this.type && this.$form.append('<input type="hidden" name="type" value="' + this.type + '" />');
			this.sizes && this.$form.append('<input type="hidden" name="sizes" value="' + this.sizes + '" />');
			this.oss && this.$form.append('<input type="hidden" name="oss" value="' + this.oss + '" />');
			this.csrf && this.$form.append('<input type="hidden" name="_csrf" value="' + this.csrf + '" />');
			this.$form.append('<input type="hidden" name="name" value="' + this.input.name + '" />');
			this.$form.append(this.input);
		},
		setName: function(){
			var random = (+ new Date()).toString() + Math.floor(Math.random() * 899 + 100).toString();
			this.input.name = this.pre + random;
		},
		callback: function(d){
			this.input.name = this.name;
			this.input.value = '';
			this.$parent.append(this.input);
			this.$form.remove();
			this.$iframe.remove();
			this.fn.call(this.input, d);
		}
	}

	$(document).on('change', '[data-fileupload]', function(){
		new fileupload(this, function(d){
			$(this).trigger('uploaded.x.file', d);
		}, {'before': function(name){
			$(this).trigger('upload.x.file');
		}});
	});

	$.fn.fileupload = function(fn, prop){
		return this.on('change', function(){
			new fileupload(this, fn, prop);
		});
	};
})(jQuery, window, document);<commit_msg>fileupload<commit_after>/*!
 * file upload
 * xiewulong <xiewulong@vip.qq.com>
 * create: 2015/2/27
 * version: 0.0.1
 */

(function($, window, document, undefined){
	var fileupload	= function(input, fn, prop){
			prop = prop || {};
			this.input = input;
			this.name = input.name;
			this.$input = $(input);
			this.$parent = this.$input.parent();
			this.action = prop.action || this.$input.attr('data-action');
			this.min = prop.min || this.$input.attr('data-min');
			this.max = prop.max || this.$input.attr('data-max');
			this.type = prop.type || this.$input.attr('data-type');
			this.sizes = prop.sizes || this.$input.attr('data-sizes');
			this.oss = prop.oss || this.$input.attr('data-oss');
			this.csrf = prop.csrf || this.$input.attr('data-csrf');
			this.pre = prop.pre || 'xFileupload';
			this.before = prop.before || function(){};
			this.fn = fn;

			this.input.value && this.action && this.fn && this.upload();
		};

	fileupload.prototype = {
		upload: function(){
			var _this = this;
			this.before && this.before.call(this.input);
			this.setName();
			this.createElements();
			window[_this.input.name] = function(d){_this.callback(d);};
			this.$form.submit();
		},
		createElements: function(){
			this.$iframe = $('').appendTo('body');
			this.$form = $('<form style="display:none;" action="' + this.action + '" target="' + this.input.name + '" method="post" enctype="multipart/form-data"></form>').appendTo('body');
			this.min && this.$form.append('<input type="hidden" name="min" value="' + this.min + '" />');
			this.max && this.$form.append('<input type="hidden" name="max" value="' + this.max + '" />');
			this.type && this.$form.append('<input type="hidden" name="type" value="' + this.type + '" />');
			this.sizes && this.$form.append('<input type="hidden" name="sizes" value="' + this.sizes + '" />');
			this.oss && this.$form.append('<input type="hidden" name="oss" value="' + this.oss + '" />');
			this.csrf && this.$form.append('<input type="hidden" name="_csrf" value="' + this.csrf + '" />');
			this.$form.append('<input type="hidden" name="name" value="' + this.input.name + '" />');
			this.$form.append(this.input);
		},
		setName: function(){
			var random = (+ new Date()).toString() + Math.floor(Math.random() * 899 + 100).toString();
			this.input.name = this.pre + random;
		},
		callback: function(d){
			this.input.name = this.name;
			this.input.value = '';
			this.$parent.append(this.input);
			this.$form.remove();
			this.$iframe.remove();
			this.fn.call(this.input, d);
		}
	}

	$(document).on('change', '[data-fileupload]', function(){
		new fileupload(this, function(d){
			$(this).trigger('uploaded.x.file', d);
		}, {'before': function(){
			$(this).trigger('upload.x.file');
		}});
	});

	$.fn.fileupload = function(fn, prop){
		return this.on('change', function(){
			new fileupload(this, fn, prop);
		});
	};
})(jQuery, window, document);<|endoftext|>


<commit_before>import Ember from 'ember';
/* global JsDiff */

export function diffText(o, n) {
  var diff = JsDiff.diffWordsWithSpace(o, n);
  var output = "";
  diff.forEach(function(part) {
    var tag = part.added ? 'ins' :
      part.removed ? 'del' : 'span';
    var escaped = Ember.Handlebars.Utils.escapeExpression(part.value);
    output = output + '<' + tag + '>' + escaped + '</' + tag + '>';
  });

  return new Ember.Handlebars.SafeString(output);
}

export default Ember.Handlebars.makeBoundHelper(diffText);
<commit_msg>Update the helper<commit_after>import Ember from 'ember';
/* global JsDiff */

export default Ember.Helper.extend({
  compute(params, hash) {
    var o = params[0];
    var n = params[1];
    var diff = JsDiff.diffWordsWithSpace(o, n);
    var output = "";
    diff.forEach(function(part) {
      var tag = part.added ? 'ins' :
        part.removed ? 'del' : 'span';
      var escaped = Ember.Handlebars.Utils.escapeExpression(part.value);
      output = output + '<' + tag + '>' + escaped + '</' + tag + '>';
    });

    return new Ember.Handlebars.SafeString(output);
  }
});
<|endoftext|>


<commit_before>const debug = require('debug')('app:components:application');
const React = require('react');

const TimelineHeader = require('./TimelineHeader');
const Heatmap = require('./Heatmap');
const ContactView = require('./ContactView');
const TimelineToolbar = require('./TimelineToolbar');
const mui = require('material-ui');
const Paper = mui.Paper;

const TimelineView = React.createClass({
  contextTypes: {
    stores: React.PropTypes.object.isRequired,
  },

  getInitialState() {
    return {
      contacts: null,
      filter: null,
      range: null,
      spinner: true,
    };
  },

  onToolbarStateChange(id, category, selected) {
    if (category === 'groups') {
      this.getContactsFromStore(id);
    } else if (category === 'filters') {
      this.clearData();
      this.setState({filter: selected.value, range: this.state.range, contacts: this.state.contacts, spinner: this.isSpinner()});
    } else if (category === 'ranges') {
      this.setState({filter: this.state.filter, range: selected, contacts: this.state.contacts, spinner: this.isSpinner()});
    }
  },

  getContactsFromStore(groupId) {
    const _this = this;
    if (!this.state.loading) {
      this.state = {filter: _this.state.filter, range: this.state.range, projects: [], loading: true, spinner: true};
      this.clearData();
      return this.context.stores.groups.getGroupContacts(groupId)
        .then((contacts) => {
          _this.setState({filter: _this.state.filter, range: this.state.range, contacts: contacts, loading: false, spinner: _this.isSpinner()});
        })
        .catch((err) => {
          debug('error loading store data', err);
          _this.setState({filter: _this.state.filter, range: this.state.range, loading: false, spinner: _this.isSpinner()});
        });
    }
  },

  getStyles() {
    return {
      padding: '20px',
      margin: '10px',
      boxSizing: 'border-box',
      border: 'none',
    };
  },

  events: [],
  contactsLoaded: 0,

  clearData() {
    this.events = [];
    this.contactsLoaded = 0;
  },

  isHeatMapLoaded() {
    return this.state && this.state.contacts && (this.contactsLoaded >= this.state.contacts.length);
  },

  isSpinner() {
    return !this.isHeatMapLoaded();
  },

  handleLoaded(events) {
    this.contactsLoaded++;
    this.events = this.events.concat(events);
    this.timelineHeaderSpinner(this.isSpinner());
  },

  timelineHeaderSpinner(isSpinner) {
    if (this.state.spinner !== isSpinner) {
      this.setState({contacts: this.state.contacts, range: this.state.range, filter: this.state.filter, spinner: isSpinner});
    }
  },

  // Render header containers wait spinner and time lables
  renderHeader() {
    return (<TimelineHeader spinner={this.state.spinner} range={this.state.range} />);
  },

  // Render a single content along with its timeline
  renderContact(contactIndex) {
    return (
      <ContactView
        key={contactIndex}
        onLoaded={this.handleLoaded}
        filter={this.state.filter}
        range={this.state.range}
        contact={this.state.contacts[contactIndex]} />
    );
  },

  // Render all contacts with timelines
  renderContacts() {
    const contactsView = [];
    for (let index = 0; index < this.state.contacts.length; index++) {
      contactsView.push(this.renderContact(index));
    }
    return contactsView;
  },

  // When all events have came back for all contents, render heatmap
  renderHeatMap() {
    return this.isHeatMapLoaded() ? (<Heatmap events={this.events} range={this.state.range} />) : ();
  },

  // Render toolbar which sets the group and filter for loading content
  renderToolbar() {
    return (
      <TimelineToolbar
        onToolbarChange={this.onToolbarStateChange} />
    );
  },

  // Render contents when contacts and filter have been loaded
  renderBody() {
    return !!(this.state && this.state.contacts && this.state.filter && this.state.range) ? (
      <Paper
        zDepth={1}
        rounded={false}
        style={this.getStyles()}>
        {this.renderHeader()}
        {this.renderHeatMap()}
        {this.renderContacts()}
      </Paper>
    ) : ();
  },

  // Render container
  render() {
    return (

        {this.renderToolbar()}
        {this.renderBody()}

    );
  },
});

module.exports = TimelineView;
<commit_msg>Add fixed header and scrolling, Also brakes some positioning.<commit_after>const debug = require('debug')('app:components:application');
const React = require('react');

const TimelineHeader = require('./TimelineHeader');
const Heatmap = require('./Heatmap');
const ContactView = require('./ContactView');
const TimelineToolbar = require('./TimelineToolbar');
const mui = require('material-ui');
const Paper = mui.Paper;

const TimelineView = React.createClass({
  contextTypes: {
    stores: React.PropTypes.object.isRequired,
  },

  getInitialState() {
    return {
      contacts: null,
      filter: null,
      range: null,
      spinner: true,
    };
  },

  onToolbarStateChange(id, category, selected) {
    if (category === 'groups') {
      this.getContactsFromStore(id);
    } else if (category === 'filters') {
      this.clearData();
      this.setState({filter: selected.value, range: this.state.range, contacts: this.state.contacts, spinner: this.isSpinner()});
    } else if (category === 'ranges') {
      this.setState({filter: this.state.filter, range: selected, contacts: this.state.contacts, spinner: this.isSpinner()});
    }
  },

  getContactsFromStore(groupId) {
    const _this = this;
    if (!this.state.loading) {
      this.state = {filter: _this.state.filter, range: this.state.range, projects: [], loading: true, spinner: true};
      this.clearData();
      return this.context.stores.groups.getGroupContacts(groupId)
        .then((contacts) => {
          _this.setState({filter: _this.state.filter, range: this.state.range, contacts: contacts, loading: false, spinner: _this.isSpinner()});
        })
        .catch((err) => {
          debug('error loading store data', err);
          _this.setState({filter: _this.state.filter, range: this.state.range, loading: false, spinner: _this.isSpinner()});
        });
    }
  },

  getStyles() {
    return {
      padding: '20px',
      margin: '10px',
      boxSizing: 'border-box',
      border: 'none',
      overflow: 'hidden',
    };
  },

  events: [],
  contactsLoaded: 0,

  clearData() {
    this.events = [];
    this.contactsLoaded = 0;
  },

  isHeatMapLoaded() {
    return this.state && this.state.contacts && (this.contactsLoaded >= this.state.contacts.length);
  },

  isSpinner() {
    return !this.isHeatMapLoaded();
  },

  handleLoaded(events) {
    this.contactsLoaded++;
    this.events = this.events.concat(events);
    this.timelineHeaderSpinner(this.isSpinner());
  },

  timelineHeaderSpinner(isSpinner) {
    if (this.state.spinner !== isSpinner) {
      this.setState({contacts: this.state.contacts, range: this.state.range, filter: this.state.filter, spinner: isSpinner});
    }
  },

  // Render header containers wait spinner and time lables
  renderHeader() {
    return (<TimelineHeader spinner={this.state.spinner} range={this.state.range} />);
  },

  // Render a single content along with its timeline
  renderContact(contactIndex) {
    return (
      <ContactView
        key={contactIndex}
        onLoaded={this.handleLoaded}
        filter={this.state.filter}
        range={this.state.range}
        contact={this.state.contacts[contactIndex]} />
    );
  },

  // Render all contacts with timelines
  renderContacts() {
    const contactsView = [];
    for (let index = 0; index < this.state.contacts.length; index++) {
      contactsView.push(this.renderContact(index));
    }
    return contactsView;
  },

  // When all events have came back for all contents, render heatmap
  renderHeatMap() {
    return this.isHeatMapLoaded() ? (<Heatmap events={this.events} range={this.state.range} />) : ();
  },

  // Render toolbar which sets the group and filter for loading content
  renderToolbar() {
    return (
      <TimelineToolbar
        onToolbarChange={this.onToolbarStateChange} />
    );
  },

  // Render contents when contacts and filter have been loaded
  renderBody() {
    return !!(this.state && this.state.contacts && this.state.filter && this.state.range) ? (
      <Paper
        zDepth={1}
        rounded={false}
        style={this.getStyles()}>
        {this.renderHeader()}
        {this.renderHeatMap()}

          {this.renderContacts()}

      </Paper>
    ) : ();
  },

  // Render container
  render() {
    return (

        {this.renderToolbar()}
        {this.renderBody()}

    );
  },
});

module.exports = TimelineView;
<|endoftext|>