<commit_before>define([
    "chai",
    "underscore",
    "fossil/application",
    "fossil/module",
    "fossil/factory",
], function (chai, _, Application, Module, Factory) {

    var assert = chai.assert;

    describe('Fossil.Application configuration', function () {
        it('should be possible to give modules as options', function() {
            var Module1 = Module.extend({});
            var Module2 = Module.extend({});
            var application = new Application({
                modules: {
                    '': Module1,
                    'foo': Module2
                }
            });

            assert.equal(_.size(application.getModule()), 2, 'It is possible to access all applicaitons at once');
            assert.instanceOf(application.getModule(""), Module1, 'Applicaiton key can be empty');
            assert.instanceOf(application.getModule("foo"), Module2, 'Applicaiton key can contain letters');
        });

        it('should be possible to register events as options', function(done) {
            this.timeout(10);
            done = _.after(2, done);
            var Application1 = Application.extend({
                bar: function () {
                    assert.ok('It is possible to define callbacks directly in event hash');
                    done();
                }
            });
            var application = new Application1({
                events: {
                    'foo': function () {
                        assert.ok('It is possible to define callbacks directly in event hash');
                        done();
                    },
                    'bar': 'bar'
                }
            });

            application.trigger('foo');
            application.trigger('bar');
        });
    });

    describe('Fossil.Application can connect module', function () {

        it('should be possible to connect an Module and retrieve it.', function () {
            var application = new Application();
            application.connect('', Module);

            assert.equal(_.size(application.getModule()), 1, 'It is possible to access all applicaitons at once');
            assert.instanceOf(application.getModule(""), Module, 'Registered module is accessible via path key');
        });

        it('should be possible to connect multiple Module-s.', function () {
            var Module1 = Module.extend({});
            var Module2 = Module.extend({});
            var Module3 = Module.extend({});
            var application = new Application();
            application.connect('', Module1);
            application.connect('foo', Module2);
            application.connect('bar/baz', Module3);

            assert.equal(_.size(application.getModule()), 3, 'It is possible to access all applicaitons at once');
            assert.instanceOf(application.getModule(""), Module1, 'Applicaiton key can be empty');
            assert.instanceOf(application.getModule("foo"), Module2, 'Applicaiton key can contain letters');
            assert.instanceOf(application.getModule("bar/baz"), Module3, 'Module key can be a path');
        });

        it('should be possible to connect Module instance', function() {
            var application = new Application();
            application.connect('', new Module(application));

            assert.equal(_.size(application.getModule()), 1, 'It is possible to access all applicaitons at once');
            assert.instanceOf(application.getModule(""), Module, 'Registered module is accessible via path key');
        });

        it('connects module key as path', function () {
            var application = new Application();
            application.connect('foo', Module);

            assert.equal(application.getModule('foo').path, 'foo');
        });
    });

    describe('Fossil.Application can use Factory-s', function () {
        it('should be possible to use a factory and retreive it', function () {
            var application = new Application();
            application.use('foo', new Factory());

            assert.instanceOf(application.factories.foo, Factory);
        });

        it('should be possible to use multiple factories and retreive it', function () {
            var application = new Application();
            var Factory1 = Factory.extend({});
            var Factory2 = Factory.extend({});

            application.use('foo', new Factory1());
            application.use('bar', new Factory2());

            assert.instanceOf(application.factories.foo, Factory1);
            assert.instanceOf(application.factories.bar, Factory2);
        });

        it('should be possible to use an uninstanciated factory', function () {
            var application = new Application();
            application.use('foo', Factory);

            assert.instanceOf(application.factories.foo, Factory);
        });

        it('should be possible to define factories in options', function () {
            var application = new Application({
                factories: {
                    'foo': Factory
                }
            });

            assert.instanceOf(application.factories.foo, Factory);
        });

        it('should activate factory for application when in use', function (done) {
            this.timeout(10);
            var application = new Application();
            var Factory1 = Factory.extend({
                _doActivateApplication: function (_application) {
                    assert.strictEqual(application, _application);
                    done();
                }
            });

            application.use('factory1', Factory1);
        });

        it('should suspend previous factory for application when in use', function (done) {
            this.timeout(10);
            done = _.after(3, done);
            var application = new Application();
            var Factory1 = Factory.extend({
                _doSuspendApplication: function (_application) {
                    assert.strictEqual(application, _application);
                    done();
                }
            });
            var Factory2 = Factory.extend({
                _doActivateApplication: function (_application) {
                    assert.strictEqual(application, _application);
                    done();
                }
            });

            application.use('factory1', Factory1);
            application.use('factory1', Factory2);
            assert.instanceOf(application.factories.factory1, Factory2);
            done();
        });

        it('should trigger a factory:use event when new factory is used', function (done) {
            this.timeout(10);
            var application = new Application();
            var factory = new Factory();
            application.on('factory:use', function (_factory, id, application) {
                assert.strictEqual(_factory, factory);
                assert.equal(id, 'factory1');
                done();
            });
            application.use('factory1', factory);
        });
    });

    describe('Fossil.Application provides a PubSub', function (done) {
        it('should be possible to communicate using events', function() {
            this.timeout(10);
            var application = new Application();
            application.on('foo', done);
            application.trigger('foo');
        });

        it('should accept events definition in the prototype', function(done) {
            this.timeout(10);
            var Application1 = Application.extend({
                events: {
                    'bar': 'foo'
                },
                foo: function () {
                    done();
                }
            });

            var application = new Application1();
            application.trigger('bar');
        });
    });

    describe('Fossil.Application Publish Subscribe generation', function () {
        it('should be able to register listeners on application', function(done) {
            this.timeout(10);
            var application = new Application();
            var pubsub = application.createPubSub();

            pubsub.on('foo', done);
            application.trigger('foo');
        });

        it('should be able to trigger events on application', function(done) {
            this.timeout(10);
            var application = new Application();
            var pubsub = application.createPubSub();

            application.on('foo', function (a, b) {
                assert.equal(arguments.length, 2);
                assert.deepEqual(a, "a");
                assert.deepEqual(b, "b");
                done();
            });
            pubsub.trigger('foo', "a", "b");
        });

        it('should be able to unregister a listener', function() {
            var application = new Application();
            var pubsub = application.createPubSub();

            function callback() {
                throw new Error('this should have been removed');
            }

            application.on('foo', callback);
            pubsub.off('foo', callback);
            application.trigger('foo', "a", "b");
        });
    });
});
<commit_msg>Wrap all application tests into one describe.<commit_after>define([
    "chai",
    "underscore",
    "fossil/application",
    "fossil/module",
    "fossil/factory",
], function (chai, _, Application, Module, Factory) {

    var assert = chai.assert;

    describe('Fossil.Application', function () {
        describe('Fossil.Application configuration', function () {
            it('should be possible to give modules as options', function() {
                var Module1 = Module.extend({});
                var Module2 = Module.extend({});
                var application = new Application({
                    modules: {
                        '': Module1,
                        'foo': Module2
                    }
                });

                assert.equal(_.size(application.getModule()), 2, 'It is possible to access all applicaitons at once');
                assert.instanceOf(application.getModule(""), Module1, 'Applicaiton key can be empty');
                assert.instanceOf(application.getModule("foo"), Module2, 'Applicaiton key can contain letters');
            });

            it('should be possible to register events as options', function(done) {
                this.timeout(10);
                done = _.after(2, done);
                var Application1 = Application.extend({
                    bar: function () {
                        assert.ok('It is possible to define callbacks directly in event hash');
                        done();
                    }
                });
                var application = new Application1({
                    events: {
                        'foo': function () {
                            assert.ok('It is possible to define callbacks directly in event hash');
                            done();
                        },
                        'bar': 'bar'
                    }
                });

                application.trigger('foo');
                application.trigger('bar');
            });
        });

        describe('Fossil.Application can connect module', function () {

            it('should be possible to connect an Module and retrieve it.', function () {
                var application = new Application();
                application.connect('', Module);

                assert.equal(_.size(application.getModule()), 1, 'It is possible to access all applicaitons at once');
                assert.instanceOf(application.getModule(""), Module, 'Registered module is accessible via path key');
            });

            it('should be possible to connect multiple Module-s.', function () {
                var Module1 = Module.extend({});
                var Module2 = Module.extend({});
                var Module3 = Module.extend({});
                var application = new Application();
                application.connect('', Module1);
                application.connect('foo', Module2);
                application.connect('bar/baz', Module3);

                assert.equal(_.size(application.getModule()), 3, 'It is possible to access all applicaitons at once');
                assert.instanceOf(application.getModule(""), Module1, 'Applicaiton key can be empty');
                assert.instanceOf(application.getModule("foo"), Module2, 'Applicaiton key can contain letters');
                assert.instanceOf(application.getModule("bar/baz"), Module3, 'Module key can be a path');
            });

            it('should be possible to connect Module instance', function() {
                var application = new Application();
                application.connect('', new Module(application));

                assert.equal(_.size(application.getModule()), 1, 'It is possible to access all applicaitons at once');
                assert.instanceOf(application.getModule(""), Module, 'Registered module is accessible via path key');
            });

            it('connects module key as path', function () {
                var application = new Application();
                application.connect('foo', Module);

                assert.equal(application.getModule('foo').path, 'foo');
            });
        });

        describe('Fossil.Application can use Factory-s', function () {
            it('should be possible to use a factory and retreive it', function () {
                var application = new Application();
                application.use('foo', new Factory());

                assert.instanceOf(application.factories.foo, Factory);
            });

            it('should be possible to use multiple factories and retreive it', function () {
                var application = new Application();
                var Factory1 = Factory.extend({});
                var Factory2 = Factory.extend({});

                application.use('foo', new Factory1());
                application.use('bar', new Factory2());

                assert.instanceOf(application.factories.foo, Factory1);
                assert.instanceOf(application.factories.bar, Factory2);
            });

            it('should be possible to use an uninstanciated factory', function () {
                var application = new Application();
                application.use('foo', Factory);

                assert.instanceOf(application.factories.foo, Factory);
            });

            it('should be possible to define factories in options', function () {
                var application = new Application({
                    factories: {
                        'foo': Factory
                    }
                });

                assert.instanceOf(application.factories.foo, Factory);
            });

            it('should activate factory for application when in use', function (done) {
                this.timeout(10);
                var application = new Application();
                var Factory1 = Factory.extend({
                    _doActivateApplication: function (_application) {
                        assert.strictEqual(application, _application);
                        done();
                    }
                });

                application.use('factory1', Factory1);
            });

            it('should suspend previous factory for application when in use', function (done) {
                this.timeout(10);
                done = _.after(3, done);
                var application = new Application();
                var Factory1 = Factory.extend({
                    _doSuspendApplication: function (_application) {
                        assert.strictEqual(application, _application);
                        done();
                    }
                });
                var Factory2 = Factory.extend({
                    _doActivateApplication: function (_application) {
                        assert.strictEqual(application, _application);
                        done();
                    }
                });

                application.use('factory1', Factory1);
                application.use('factory1', Factory2);
                assert.instanceOf(application.factories.factory1, Factory2);
                done();
            });

            it('should trigger a factory:use event when new factory is used', function (done) {
                this.timeout(10);
                var application = new Application();
                var factory = new Factory();
                application.on('factory:use', function (_factory, id, application) {
                    assert.strictEqual(_factory, factory);
                    assert.equal(id, 'factory1');
                    done();
                });
                application.use('factory1', factory);
            });
        });

        describe('Fossil.Application provides a PubSub', function (done) {
            it('should be possible to communicate using events', function() {
                this.timeout(10);
                var application = new Application();
                application.on('foo', done);
                application.trigger('foo');
            });

            it('should accept events definition in the prototype', function(done) {
                this.timeout(10);
                var Application1 = Application.extend({
                    events: {
                        'bar': 'foo'
                    },
                    foo: function () {
                        done();
                    }
                });

                var application = new Application1();
                application.trigger('bar');
            });
        });

        describe('Fossil.Application Publish Subscribe generation', function () {
            it('should be able to register listeners on application', function(done) {
                this.timeout(10);
                var application = new Application();
                var pubsub = application.createPubSub();

                pubsub.on('foo', done);
                application.trigger('foo');
            });

            it('should be able to trigger events on application', function(done) {
                this.timeout(10);
                var application = new Application();
                var pubsub = application.createPubSub();

                application.on('foo', function (a, b) {
                    assert.equal(arguments.length, 2);
                    assert.deepEqual(a, "a");
                    assert.deepEqual(b, "b");
                    done();
                });
                pubsub.trigger('foo', "a", "b");
            });

            it('should be able to unregister a listener', function() {
                var application = new Application();
                var pubsub = application.createPubSub();

                function callback() {
                    throw new Error('this should have been removed');
                }

                application.on('foo', callback);
                pubsub.off('foo', callback);
                application.trigger('foo', "a", "b");
            });
        });
    });
});
<|endoftext|>


<commit_before>odoo.define('point_of_sale.BaseWidget', function (require) {
"use strict";

var formats = require('web.formats');
var utils = require('web.utils');
var Widget = require('web.Widget');

var round_di = utils.round_decimals;

// This is a base class for all Widgets in the POS. It exposes relevant data to the
// templates :
// - widget.currency : { symbol: '$' | '€' | ..., position: 'before' | 'after }
// - widget.format_currency(amount) : this method returns a formatted string based on the
//   symbol, the position, and the amount of money.
// if the PoS is not fully loaded when you instanciate the widget, the currency might not
// yet have been initialized. Use __build_currency_template() to recompute with correct values
// before rendering.
var PosBaseWidget = Widget.extend({
    init:function(parent,options){
        this._super(parent);
        options = options || {};
        this.pos    = options.pos    || (parent ? parent.pos : undefined);
        this.chrome = options.chrome || (parent ? parent.chrome : undefined);
        this.gui    = options.gui    || (parent ? parent.gui : undefined);
    },
    format_currency: function(amount,precision){
        var currency = (this.pos && this.pos.currency) ? this.pos.currency : {symbol:'$', position: 'after', rounding: 0.01, decimals: 2};

        amount = this.format_currency_no_symbol(amount,precision);

        if (currency.position === 'after') {
            return amount + ' ' + (currency.symbol || '');
        } else {
            return (currency.symbol || '') + ' ' + amount;
        }
    },
    format_currency_no_symbol: function(amount, precision) {
        var currency = (this.pos && this.pos.currency) ? this.pos.currency : {symbol:'$', position: 'after', rounding: 0.01, decimals: 2};
        var decimals = currency.decimals;

        if (precision && (typeof this.pos.dp[precision]) !== undefined) {
            decimals = this.pos.dp[precision];
        }

        if (typeof amount === 'number') {
            amount = round_di(amount,decimals).toFixed(decimals);
            amount = formats.format_value(round_di(amount, decimals), { type: 'float', digits: [69, decimals]});
        }

        return amount;
    },
    show: function(){
        this.$el.removeClass('oe_hidden');
    },
    hide: function(){
        this.$el.addClass('oe_hidden');
    },
    format_pr: function(value,precision){
        var decimals = precision > 0 ? Math.max(0,Math.ceil(Math.log(1.0/precision) / Math.log(10))) : 0;
        return value.toFixed(decimals);
    },
    format_fixed: function(value,integer_width,decimal_width){
        value = value.toFixed(decimal_width || 0);
        var width = value.indexOf('.');
        if (width < 0 ) {
            width = value.length;
        }
        var missing = integer_width - width;
        while (missing > 0) {
            value = '0' + value;
            missing--;
        }
        return value;
    },
});

return PosBaseWidget;

});
<commit_msg>[FIX] point_of_sale: bug in decimal.precision lookup<commit_after>odoo.define('point_of_sale.BaseWidget', function (require) {
"use strict";

var formats = require('web.formats');
var utils = require('web.utils');
var Widget = require('web.Widget');

var round_di = utils.round_decimals;

// This is a base class for all Widgets in the POS. It exposes relevant data to the
// templates :
// - widget.currency : { symbol: '$' | '€' | ..., position: 'before' | 'after }
// - widget.format_currency(amount) : this method returns a formatted string based on the
//   symbol, the position, and the amount of money.
// if the PoS is not fully loaded when you instanciate the widget, the currency might not
// yet have been initialized. Use __build_currency_template() to recompute with correct values
// before rendering.
var PosBaseWidget = Widget.extend({
    init:function(parent,options){
        this._super(parent);
        options = options || {};
        this.pos    = options.pos    || (parent ? parent.pos : undefined);
        this.chrome = options.chrome || (parent ? parent.chrome : undefined);
        this.gui    = options.gui    || (parent ? parent.gui : undefined);
    },
    format_currency: function(amount,precision){
        var currency = (this.pos && this.pos.currency) ? this.pos.currency : {symbol:'$', position: 'after', rounding: 0.01, decimals: 2};

        amount = this.format_currency_no_symbol(amount,precision);

        if (currency.position === 'after') {
            return amount + ' ' + (currency.symbol || '');
        } else {
            return (currency.symbol || '') + ' ' + amount;
        }
    },
    format_currency_no_symbol: function(amount, precision) {
        var currency = (this.pos && this.pos.currency) ? this.pos.currency : {symbol:'$', position: 'after', rounding: 0.01, decimals: 2};
        var decimals = currency.decimals;

        if (precision && this.pos.dp[precision] !== undefined) {
            decimals = this.pos.dp[precision];
        }

        if (typeof amount === 'number') {
            amount = round_di(amount,decimals).toFixed(decimals);
            amount = formats.format_value(round_di(amount, decimals), { type: 'float', digits: [69, decimals]});
        }

        return amount;
    },
    show: function(){
        this.$el.removeClass('oe_hidden');
    },
    hide: function(){
        this.$el.addClass('oe_hidden');
    },
    format_pr: function(value,precision){
        var decimals = precision > 0 ? Math.max(0,Math.ceil(Math.log(1.0/precision) / Math.log(10))) : 0;
        return value.toFixed(decimals);
    },
    format_fixed: function(value,integer_width,decimal_width){
        value = value.toFixed(decimal_width || 0);
        var width = value.indexOf('.');
        if (width < 0 ) {
            width = value.length;
        }
        var missing = integer_width - width;
        while (missing > 0) {
            value = '0' + value;
            missing--;
        }
        return value;
    },
});

return PosBaseWidget;

});
<|endoftext|>


<commit_before>define(function(require, exports, module) {
"use strict";

var oop = require("ace/lib/oop");
var event = require("ace/lib/event");
var Range = require("ace/range").Range;
var EventEmitter = require("ace/lib/event_emitter").EventEmitter;

var HoverLink = function(editor) {
    if (editor.hoverLink)
        return;
    editor.hoverLink = this;
    this.editor = editor;

    this.update = this.update.bind(this);
    this.onMouseMove = this.onMouseMove.bind(this);
    this.onMouseOut = this.onMouseOut.bind(this);
    this.onClick = this.onClick.bind(this);
    this.onContextMenu = this.onContextMenu.bind(this);
    event.addListener(editor.renderer.scroller, "mousemove", this.onMouseMove);
    event.addListener(editor.renderer.content, "mouseout", this.onMouseOut);
    event.addListener(editor.renderer.content, "click", this.onClick);
    event.addListener(editor.renderer.container, "contextmenu", this.onContextMenu);
};

(function(){
    oop.implement(this, EventEmitter);

    this.token = {};
    this.range = new Range();

    this.update = function() {
        this.$timer = null;
        var editor = this.editor;
        var renderer = editor.renderer;

        var canvasPos = renderer.scroller.getBoundingClientRect();
        var offset = (this.x + renderer.scrollLeft - canvasPos.left - renderer.$padding) / renderer.characterWidth;
        var row = Math.floor((this.y + renderer.scrollTop - canvasPos.top) / renderer.lineHeight);
        var col = Math.round(offset);

        var screenPos = {row: row, column: col, side: offset - col > 0 ? 1 : -1};
        var session = editor.session;
        var docPos = session.screenToDocumentPosition(screenPos.row, screenPos.column);

        var selectionRange = editor.selection.getRange();
        if (!selectionRange.isEmpty()) {
            if (selectionRange.start.row <= row && selectionRange.end.row >= row)
                return this.clear();
        }

        var line = editor.session.getLine(docPos.row);
        if (docPos.column == line.length) {
            var clippedPos = editor.session.documentToScreenPosition(docPos.row, docPos.column);
            if (clippedPos.column != screenPos.column) {
                return this.clear();
            }
        }

        var token = this.findLink(docPos.row, docPos.column);
        // var isFocused = editor.isFocused();
        this.link = token;
        if (!token) {
            return this.clear();
        }
        if (!this.isOpen) {
            this.isOpen = true;
        }
        // token.isFocused = isFocused;
        editor.renderer.setCursorStyle("pointer");

        session.removeMarker(this.marker);

        this.range = this.getRange(token);
        this.marker = session.addMarker(this.range, "ace_link_marker", "text", true);
    };

    this.clear = function() {
        if (this.isOpen) {
            this.editor.session.removeMarker(this.marker);
            this.editor.renderer.setCursorStyle("");
            this.isOpen = false;
        }
    };

    this.getMatchAround = function(regExp, string, col) {
        var match;
        regExp.lastIndex = 0;
        string.replace(regExp, function(str) {
            var offset = arguments[arguments.length-2];
            var length = str.length;
            if (offset <= col && offset + length >= col)
                match = {
                    start: offset,
                    value: str
                };
        });

        return match;
    };

    this.onClick = function(e) {
        if (this.link && this.isOpen) { // && this.link.isFocused
            if (this.editor.selection.isEmpty()) {
                this.editor.selection.setSelectionRange(this.range);
                this.lastRange = this.range;
            }

            this.link.editor = this.editor;
            this.link.x = e.clientX;
            this.link.y = e.clientY;
            this.link.metaKey = e.metaKey;
            this.link.ctrlKey = e.ctrlKey;
            this._signal("open", this.link);
        }
    };

    this.onContextMenu = function(e) {
        var range = this.editor.selection.getRange();
        if (!range.isEmpty()) {
            if (this.lastRange && range.isEqual(this.lastRange)) {
                this.editor.selection.clearSelection();
                this.update();
            }
        }
        if (this.link && this.isOpen) {
            if (this.editor.selection.isEmpty()) {
                this.editor.selection.setSelectionRange(this.range);
                this.lastRange = this.range;
            }
        }
    };

    this.getRange = function(token) {
        var session = this.editor.session;
        var startCol = token.start;
        var row = token.row;
        var line = session.getLine(row);
        while (line && line.length < startCol) {
            startCol -= line.length;
            row++;
            line = session.getLine(row);
        }
        var startRow = row;
        var endCol = startCol + token.value.length;
        while (line && line.length < endCol) {
            endCol -= line.length;
            row++;
            line = session.getLine(row);
        }
        var endRow = row;
        return new Range(startRow, startCol, endRow, endCol);
    };

    this.findLink = function(row, column) {
        var editor = this.editor;
        var session = editor.session;
        var lineData = session.getLineData(row);
        var prevLineData = session.getLineData(row - 1);
        var line = session.getLine(row);
        for (var i = 1; lineData && lineData.wrapped; i++) {
            line += session.getLine(row + i);
            lineData = session.getLineData(row + i);
        }
        while (prevLineData && prevLineData.wrapped) {
            row --;
            var prevLine = session.getLine(row);
            column += prevLine.length;
            line = prevLine + line;
            prevLineData = session.getLineData(row - 1);
        }
        lineData = session.getLineData(row);

        var match = this.getMatchAround(/https?:\/\/[^\s"']+|[~\/\w.]([:.~/\w-_]|\\.)+/g, line, column);
        if (!match)
            return;

        match.row = row;
        var value = match.value;
        if (/^https?:|\bc9.io\b|(\d{1,3}\b.?){4}|localhost/.test(value)) {
            match.type = "link";
            var m =  /((https?:\/\/)?(\d{1,3}\b.?){4}(:\d+[^\d\/]|[^:\d\/]))/.exec(value);
            if (m)
                value = m[0].slice(0, -1);
            value = value.replace(/[>)}\].,;:]+$/, "");
            match.value = value;
            return match;
        }
        var prompt = this.findPrompt(row);
        if (!prompt) {
            if (/^(\/|~|\/?\w:[\\/])/.test(value)) { // windows or unix absolute path
                match.type = "path";
                match.value = value.replace(/["'>)}\].,;:]+$/, "");
                return match;
            }
            return;
        }

        if (lineData.prompt && match.start <= prompt.index) {
            match.value = value = value.substr(prompt.index - match.start);
            match.start = prompt.index;
            if (match.start > column || !value)
                return;
            return;
        }

        match.command = prompt.command;
        match.args = prompt.args;
        match.basePath = prompt.path;

        if (prompt.command === "ls") {
            match.type = "path";
            if (lineData.prompt)
                return;
            // update basepath for ls /dir/name
            if (prompt.args)
                match.basePath = this.findBasePath(prompt.args, prompt.path);
            if (prompt.args && /( |^)(--help|-h)\b/.test(prompt.args))
                return;
            var longStyle = /(^|\s)[ld\-][\-rwx]+\s/.test(line);
            if (longStyle) {
                if (/[*@|=>]$/.test(line))
                    line = line.slice(0, -1);
                if (match.start + value.length < line.length) {
                    var isLink = line[0] == "l" && line.substr(match.start + value.length, 4) == " -> ";
                    if (!isLink)
                        return;
                }
            } else {
                var before = line.substring(0, match.start).match(/[^\s\\\/@"']+ $/);
                var after = line.substr(match.start + value.length).match(/^ [^\s\\\/@"']+/);
                if (before && !/\d+/.test(before[0])) {
                    value = before[0] + value;
                    match.start -= before[0].length;
                }
                if (after) {
                    value += after[0];
                }
                match.value = value;
                return match;
            }
        }
        else if (prompt.command === "find") {
            if (match.start !== 0 || match.length < line.length)
                return;
            if (prompt.args)
                match.basePath = this.findBasePath(prompt.args, prompt.path);
            match.type = "path";
        }
        else if (prompt.command === "grep") {
            if (match.start !== 0)
                return;
            match.type = "path";
            match.value = value.replace(/:[^\d][^:]*$/, "");
            // match.basePath = "";
        }
        else if (prompt.command === "ack" || prompt.command === "ag") {
            match.type = "path";
            var fontColor = lineData[column] && lineData[column][0];
            if (match.start !== 0) {
                if (fontColor == 131840)
                    return;

                var col = column;
                while (lineData[col] && lineData[col][0] == fontColor)
                    col--;
                match.start = col + 1;
                col = column;
                while (lineData[col] && lineData[col][0] == fontColor)
                    col++;
                match.value = line.substring(match.start, col);
            }

            var jumpLine = line.match(/^(\d*:)?/)[0];
            var jumpColumn = Math.max(match.start - jumpLine.length, 0);

            var pathLine = line;
            while (/^\d+/.test(pathLine) && row > prompt.row) {
                lineData = session.getLineData(row);
                if (!lineData.wrapped) {
                    pathLine = session.getLine(row);
                }
                row--;
            }

            match.path = pathLine;
            if (jumpLine)
                match.path += ":" + jumpLine + jumpColumn;

            if (match.start == 0 && jumpLine)
                match.action = "open";
        }
        else if (/^(~|\.\.?)?[\/\\]/.test(value) || /\w:[\\]/.test(value)) {
            match.type = "path";
            match.value = value.replace(/['">)}\].,;:]+$/, "");
        }
        else if (/^[ab]?\//.test(value) && /^([+\-]{3}|diff)/.test(line)) { // diff
                match.type = "path";
                match.basePath = "";
                match.start++;
                match.value = value.substr(2);
        }
        else if (prompt.command === "git") { // git status
            var prefix = line.substr(0, match.start);
            if (match.start + value.length == line.length
                && /^(#|[ MDR?A]{2})\s+([\w\s]+:\s+)?$/.test(prefix)
            ) {
                match.type = "path";
            } else {
                value = value.replace(/[.:]$/, "");
                if (value.match(/[/][^/]*\.\w+[.:]$/) || prefix.match(/( in |merging )$/)) {
                    match.type = "path";
                    match.value = value;
                } else {
                    return;
                }
            }
        } else {
            return;
        }

        return match;
    };

    this.findBasePath = function(args, basePath) {
        var argList = args.split(" ").filter(function(x) {
            return x[0] != "-";
        });
        var pathArg = argList[argList.length - 1];
        if (pathArg) {
            if (pathArg[0] === "~" || pathArg[0] === "/")
                return pathArg;
            return basePath + "/" + pathArg;
        }
        return basePath;
    };

    this.findPrompt = function(row) {
        var promptRe = /([~\/](?:[^\\\s'"\(<]|\\.)*)[^$]*?\$/;
        var editor = this.editor;
        var session = editor.session;
        var prompt, args, command, promptRow;
        do {
            var lineData = session.getLineData(row);

            if (lineData.prompt)
                return lineData.prompt;

            var line = session.getLine(row);
            var m = promptRe.exec(line);
            if (m) {
                line = line.substr(m.index + m[0].length);
                var m2 = /^\s*([\w\-]+)/.exec(line);
                if (m2) {
                    command = m2[1];
                    args = line.substr(m2[0].length);
                }
                if (!prompt || lineData.isUserInput) {
                    prompt = {
                        path: m[1],
                        command: command,
                        index: m.index,
                        args: args,
                        lineData: lineData,
                        row: row
                    };
                }
                if (lineData.isUserInput)
                    break;
            }
        } while (row-- > 0);
        if (prompt && promptRow < session.term.ybase)
            prompt.lineData.prompt = prompt;
        return prompt;
    };

    this.onMouseMove = function(e) {
        if (this.editor.$mouseHandler.isMousePressed) {
            if (!this.editor.selection.isEmpty())
                this.clear();
            return;
        }
        if (this.x == e.clientX && this.y == e.clientY)
            return;
        this.x = e.clientX;
        this.y = e.clientY;
        if (this.isOpen) {
            this.lastT = e.timeStamp;
        }
        this.update();
    };

    this.onMouseOut = function(e) {
        this.clear();
        this.$timer = clearTimeout(this.$timer);
    };

    this.destroy = function() {
        this.onMouseOut();
        event.removeListener(this.editor.renderer.scroller, "mousemove", this.onMouseMove);
        event.removeListener(this.editor.renderer.content, "mouseout", this.onMouseOut);
        delete this.editor.hoverLink;
    };

}).call(HoverLink.prototype);

exports.HoverLink = HoverLink;

});<commit_msg>tweak ack link_handler<commit_after>define(function(require, exports, module) {
"use strict";

var oop = require("ace/lib/oop");
var event = require("ace/lib/event");
var Range = require("ace/range").Range;
var EventEmitter = require("ace/lib/event_emitter").EventEmitter;

var HoverLink = function(editor) {
    if (editor.hoverLink)
        return;
    editor.hoverLink = this;
    this.editor = editor;

    this.update = this.update.bind(this);
    this.onMouseMove = this.onMouseMove.bind(this);
    this.onMouseOut = this.onMouseOut.bind(this);
    this.onClick = this.onClick.bind(this);
    this.onContextMenu = this.onContextMenu.bind(this);
    event.addListener(editor.renderer.scroller, "mousemove", this.onMouseMove);
    event.addListener(editor.renderer.content, "mouseout", this.onMouseOut);
    event.addListener(editor.renderer.content, "click", this.onClick);
    event.addListener(editor.renderer.container, "contextmenu", this.onContextMenu);
};

(function(){
    oop.implement(this, EventEmitter);

    this.token = {};
    this.range = new Range();

    this.update = function() {
        this.$timer = null;
        var editor = this.editor;
        var renderer = editor.renderer;

        var canvasPos = renderer.scroller.getBoundingClientRect();
        var offset = (this.x + renderer.scrollLeft - canvasPos.left - renderer.$padding) / renderer.characterWidth;
        var row = Math.floor((this.y + renderer.scrollTop - canvasPos.top) / renderer.lineHeight);
        var col = Math.round(offset);

        var screenPos = {row: row, column: col, side: offset - col > 0 ? 1 : -1};
        var session = editor.session;
        var docPos = session.screenToDocumentPosition(screenPos.row, screenPos.column);

        var selectionRange = editor.selection.getRange();
        if (!selectionRange.isEmpty()) {
            if (selectionRange.start.row <= row && selectionRange.end.row >= row)
                return this.clear();
        }

        var line = editor.session.getLine(docPos.row);
        if (docPos.column == line.length) {
            var clippedPos = editor.session.documentToScreenPosition(docPos.row, docPos.column);
            if (clippedPos.column != screenPos.column) {
                return this.clear();
            }
        }

        var token = this.findLink(docPos.row, docPos.column);
        // var isFocused = editor.isFocused();
        this.link = token;
        if (!token) {
            return this.clear();
        }
        if (!this.isOpen) {
            this.isOpen = true;
        }
        // token.isFocused = isFocused;
        editor.renderer.setCursorStyle("pointer");

        session.removeMarker(this.marker);

        this.range = this.getRange(token);
        this.marker = session.addMarker(this.range, "ace_link_marker", "text", true);
    };

    this.clear = function() {
        if (this.isOpen) {
            this.editor.session.removeMarker(this.marker);
            this.editor.renderer.setCursorStyle("");
            this.isOpen = false;
        }
    };

    this.getMatchAround = function(regExp, string, col) {
        var match;
        regExp.lastIndex = 0;
        string.replace(regExp, function(str) {
            var offset = arguments[arguments.length-2];
            var length = str.length;
            if (offset <= col && offset + length >= col)
                match = {
                    start: offset,
                    value: str
                };
        });

        return match;
    };

    this.onClick = function(e) {
        if (this.link && this.isOpen) { // && this.link.isFocused
            if (this.editor.selection.isEmpty()) {
                this.editor.selection.setSelectionRange(this.range);
                this.lastRange = this.range;
            }

            this.link.editor = this.editor;
            this.link.x = e.clientX;
            this.link.y = e.clientY;
            this.link.metaKey = e.metaKey;
            this.link.ctrlKey = e.ctrlKey;
            this._signal("open", this.link);
        }
    };

    this.onContextMenu = function(e) {
        var range = this.editor.selection.getRange();
        if (!range.isEmpty()) {
            if (this.lastRange && range.isEqual(this.lastRange)) {
                this.editor.selection.clearSelection();
                this.update();
            }
        }
        if (this.link && this.isOpen) {
            if (this.editor.selection.isEmpty()) {
                this.editor.selection.setSelectionRange(this.range);
                this.lastRange = this.range;
            }
        }
    };

    this.getRange = function(token) {
        var session = this.editor.session;
        var startCol = token.start;
        var row = token.row;
        var line = session.getLine(row);
        while (line && line.length < startCol) {
            startCol -= line.length;
            row++;
            line = session.getLine(row);
        }
        var startRow = row;
        var endCol = startCol + token.value.length;
        while (line && line.length < endCol) {
            endCol -= line.length;
            row++;
            line = session.getLine(row);
        }
        var endRow = row;
        return new Range(startRow, startCol, endRow, endCol);
    };

    this.findLink = function(row, column) {
        var editor = this.editor;
        var session = editor.session;
        var lineData = session.getLineData(row);
        var prevLineData = session.getLineData(row - 1);
        var line = session.getLine(row);
        for (var i = 1; lineData && lineData.wrapped; i++) {
            line += session.getLine(row + i);
            lineData = session.getLineData(row + i);
        }
        while (prevLineData && prevLineData.wrapped) {
            row --;
            var prevLine = session.getLine(row);
            column += prevLine.length;
            line = prevLine + line;
            prevLineData = session.getLineData(row - 1);
        }
        lineData = session.getLineData(row);

        var match = this.getMatchAround(/https?:\/\/[^\s"']+|[~\/\w.]([:.~/\w-_]|\\.)+/g, line, column);
        if (!match)
            return;

        match.row = row;
        var value = match.value;
        if (/^https?:|\bc9.io\b|(\d{1,3}\b.?){4}|localhost/.test(value)) {
            match.type = "link";
            var m =  /((https?:\/\/)?(\d{1,3}\b.?){4}(:\d+[^\d\/]|[^:\d\/]))/.exec(value);
            if (m)
                value = m[0].slice(0, -1);
            value = value.replace(/[>)}\].,;:]+$/, "");
            match.value = value;
            return match;
        }
        var prompt = this.findPrompt(row);
        if (!prompt) {
            if (/^(\/|~|\/?\w:[\\/])/.test(value)) { // windows or unix absolute path
                match.type = "path";
                match.value = value.replace(/["'>)}\].,;:]+$/, "");
                return match;
            }
            return;
        }

        if (lineData.prompt && match.start <= prompt.index) {
            match.value = value = value.substr(prompt.index - match.start);
            match.start = prompt.index;
            if (match.start > column || !value)
                return;
            return;
        }

        match.command = prompt.command;
        match.args = prompt.args;
        match.basePath = prompt.path;

        if (prompt.command === "ls") {
            match.type = "path";
            if (lineData.prompt)
                return;
            // update basepath for ls /dir/name
            if (prompt.args)
                match.basePath = this.findBasePath(prompt.args, prompt.path);
            if (prompt.args && /( |^)(--help|-h)\b/.test(prompt.args))
                return;
            var longStyle = /(^|\s)[ld\-][\-rwx]+\s/.test(line);
            if (longStyle) {
                if (/[*@|=>]$/.test(line))
                    line = line.slice(0, -1);
                if (match.start + value.length < line.length) {
                    var isLink = line[0] == "l" && line.substr(match.start + value.length, 4) == " -> ";
                    if (!isLink)
                        return;
                }
            } else {
                var before = line.substring(0, match.start).match(/[^\s\\\/@"']+ $/);
                var after = line.substr(match.start + value.length).match(/^ [^\s\\\/@"']+/);
                if (before && !/\d+/.test(before[0])) {
                    value = before[0] + value;
                    match.start -= before[0].length;
                }
                if (after) {
                    value += after[0];
                }
                match.value = value;
                return match;
            }
        }
        else if (prompt.command === "find") {
            if (match.start !== 0 || match.length < line.length)
                return;
            if (prompt.args)
                match.basePath = this.findBasePath(prompt.args, prompt.path);
            match.type = "path";
        }
        else if (prompt.command === "grep") {
            if (match.start !== 0)
                return;
            match.type = "path";
            match.value = value.replace(/:[^\d][^:]*$/, "");
            // match.basePath = "";
        }
        else if (prompt.command === "ack" || prompt.command === "ag" || prompt.command === "ack-grep") {
            match.type = "path";
            var fontColor = lineData[column] && lineData[column][0];
            if (match.start !== 0) {
                if (fontColor == session.term.defAttr)
                    return;

                var col = column;
                while (lineData[col] && lineData[col][0] == fontColor)
                    col--;
                match.start = col + 1;
                col = column;
                while (lineData[col] && lineData[col][0] == fontColor)
                    col++;
                match.value = line.substring(match.start, col);
            }

            var jumpLine = line.match(/^(\d*:)?/)[0];
            var jumpColumn = Math.max(match.start - jumpLine.length, 0);

            if (match.start == 0 && jumpLine)
                match.value = jumpLine;

            var pathLine = line;
            while (/^\d+/.test(pathLine) && row > prompt.row) {
                lineData = session.getLineData(row);
                if (!lineData.wrapped) {
                    pathLine = session.getLine(row);
                }
                row--;
            }

            match.path = pathLine;
            if (jumpLine)
                match.path += ":" + jumpLine + jumpColumn;

            if (match.start == 0 && jumpLine)
                match.action = "open";
        }
        else if (/^(~|\.\.?)?[\/\\]/.test(value) || /\w:[\\]/.test(value)) {
            match.type = "path";
            match.value = value.replace(/['">)}\].,;:]+$/, "");
        }
        else if (/^[ab]?\//.test(value) && /^([+\-]{3}|diff)/.test(line)) { // diff
                match.type = "path";
                match.basePath = "";
                match.start++;
                match.value = value.substr(2);
        }
        else if (prompt.command === "git") { // git status
            var prefix = line.substr(0, match.start);
            if (match.start + value.length == line.length
                && /^(#|[ MDR?A]{2})\s+([\w\s]+:\s+)?$/.test(prefix)
            ) {
                match.type = "path";
            } else {
                value = value.replace(/[.:]$/, "");
                if (value.match(/[/][^/]*\.\w+[.:]$/) || prefix.match(/( in |merging )$/)) {
                    match.type = "path";
                    match.value = value;
                } else {
                    return;
                }
            }
        } else {
            return;
        }

        return match;
    };

    this.findBasePath = function(args, basePath) {
        var argList = args.split(" ").filter(function(x) {
            return x[0] != "-";
        });
        var pathArg = argList[argList.length - 1];
        if (pathArg) {
            if (pathArg[0] === "~" || pathArg[0] === "/")
                return pathArg;
            return basePath + "/" + pathArg;
        }
        return basePath;
    };

    this.findPrompt = function(row) {
        var promptRe = /([~\/](?:[^\\\s'"\(<]|\\.)*)[^$]*?\$/;
        var editor = this.editor;
        var session = editor.session;
        var prompt, args, command, promptRow;
        do {
            var lineData = session.getLineData(row);

            if (lineData.prompt)
                return lineData.prompt;

            var line = session.getLine(row);
            var m = promptRe.exec(line);
            if (m) {
                line = line.substr(m.index + m[0].length);
                var m2 = /^\s*([\w\-]+)/.exec(line);
                if (m2) {
                    command = m2[1];
                    args = line.substr(m2[0].length);
                }
                if (!prompt || lineData.isUserInput) {
                    prompt = {
                        path: m[1],
                        command: command,
                        index: m.index,
                        args: args,
                        lineData: lineData,
                        row: row
                    };
                }
                if (lineData.isUserInput)
                    break;
            }
        } while (row-- > 0);
        if (prompt && promptRow < session.term.ybase)
            prompt.lineData.prompt = prompt;
        return prompt;
    };

    this.onMouseMove = function(e) {
        if (this.editor.$mouseHandler.isMousePressed) {
            if (!this.editor.selection.isEmpty())
                this.clear();
            return;
        }
        if (this.x == e.clientX && this.y == e.clientY)
            return;
        this.x = e.clientX;
        this.y = e.clientY;
        if (this.isOpen) {
            this.lastT = e.timeStamp;
        }
        this.update();
    };

    this.onMouseOut = function(e) {
        this.clear();
        this.$timer = clearTimeout(this.$timer);
    };

    this.destroy = function() {
        this.onMouseOut();
        event.removeListener(this.editor.renderer.scroller, "mousemove", this.onMouseMove);
        event.removeListener(this.editor.renderer.content, "mouseout", this.onMouseOut);
        delete this.editor.hoverLink;
    };

}).call(HoverLink.prototype);

exports.HoverLink = HoverLink;

});<|endoftext|>


<commit_before>'use strict';

var util = require('util');
var common = require('../../modules/common-functions');
var OUTGOINGS_QUESTIONS = require('../../modules/constants').OUTGOINGS_QUESTIONS;

module.exports = {
  'Start page': common.startPage,

  'Categories of law (Your problem)': function(client) {
    client
      .assert.urlContains('/problem')
      .assert.containsText('h1', 'What do you need help with?')
      .click('input[name="categories"][value="clinneg"]')
      .assert.attributeEquals('input[name="categories"][value="clinneg"]', 'checked', 'true')
      .submitForm('form')
    ;
  },

  'Face-to-face page': function(client) {
    client
      .waitForElementVisible('.legal-adviser-search', 5000)
      .assert.urlContains('/face-to-face')
      .assert.containsText('h1', 'You may be able to get free advice from a legal adviser')
    ;

    client.end();
  }

};
<commit_msg>TEST: Remove unused variable<commit_after>'use strict';

var util = require('util');
var common = require('../../modules/common-functions');

module.exports = {
  'Start page': common.startPage,

  'Categories of law (Your problem)': function(client) {
    client
      .assert.urlContains('/problem')
      .assert.containsText('h1', 'What do you need help with?')
      .click('input[name="categories"][value="clinneg"]')
      .assert.attributeEquals('input[name="categories"][value="clinneg"]', 'checked', 'true')
      .submitForm('form')
    ;
  },

  'Face-to-face page': function(client) {
    client
      .waitForElementVisible('.legal-adviser-search', 5000)
      .assert.urlContains('/face-to-face')
      .assert.containsText('h1', 'You may be able to get free advice from a legal adviser')
    ;

    client.end();
  }

};
<|endoftext|>


<commit_before>var L = require('leaflet'),
	Util = require('../util');

module.exports = {
	class: L.Class.extend({
		options: {
			serviceUrl: '//nominatim.openstreetmap.org/',
			geocodingQueryParams: {},
			reverseQueryParams: {},
			htmlTemplate: function(r) {
				var a = r.address,
					parts = [];
				if (a.road || a.building) {
					parts.push('{building} {road} {house_number}');
				}

				if (a.city || a.town || a.village) {
					parts.push(' 0 ? 'leaflet-control-geocoder-address-detail' : '') +
						'">{postcode} {city} {town} {village}');
				}

				if (a.state || a.country) {
					parts.push(' 0 ? 'leaflet-control-geocoder-address-context' : '') +
						'">{state} {country}');
				}

				return Util.template(parts.join('
'), a, true);
			}
		},

		initialize: function(options) {
			L.Util.setOptions(this, options);
		},

		geocode: function(query, cb, context) {
			Util.jsonp(this.options.serviceUrl + 'search', L.extend({
				q: query,
				limit: 5,
				format: 'json',
				addressdetails: 1
			}, this.options.geocodingQueryParams),
			function(data) {
				var results = [];
				for (var i = data.length - 1; i >= 0; i--) {
					var bbox = data[i].boundingbox;
					for (var j = 0; j < 4; j++) bbox[j] = parseFloat(bbox[j]);
					results[i] = {
						icon: data[i].icon,
						name: data[i].display_name,
						html: this.options.htmlTemplate ?
							this.options.htmlTemplate(data[i])
							: undefined,
						bbox: L.latLngBounds([bbox[0], bbox[2]], [bbox[1], bbox[3]]),
						center: L.latLng(data[i].lat, data[i].lon),
						properties: data[i]
					};
				}
				cb.call(context, results);
			}, this, 'json_callback');
		},

		reverse: function(location, scale, cb, context) {
			Util.jsonp(this.options.serviceUrl + 'reverse', L.extend({
				lat: location.lat,
				lon: location.lng,
				zoom: Math.round(Math.log(scale / 256) / Math.log(2)),
				addressdetails: 1,
				format: 'json'
			}, this.options.reverseQueryParams), function(data) {
				var result = [],
				    loc;

				if (data && data.lat && data.lon) {
					loc = L.latLng(data.lat, data.lon);
					result.push({
						name: data.display_name,
						html: this.options.htmlTemplate ?
							this.options.htmlTemplate(data)
							: undefined,
						center: loc,
						bounds: L.latLngBounds(loc, loc),
						properties: data
					});
				}

				cb.call(context, result);
			}, this, 'json_callback');
		}
	}),

	factory: function(options) {
		return new L.Control.Geocoder.Nominatim(options);
	}
};
<commit_msg>Add hamlet's name in results<commit_after>var L = require('leaflet'),
	Util = require('../util');

module.exports = {
	class: L.Class.extend({
		options: {
			serviceUrl: '//nominatim.openstreetmap.org/',
			geocodingQueryParams: {},
			reverseQueryParams: {},
			htmlTemplate: function(r) {
				var a = r.address,
					parts = [];
				if (a.road || a.building) {
					parts.push('{building} {road} {house_number}');
				}

				if (a.city || a.town || a.village || a.hamlet) {
					parts.push(' 0 ? 'leaflet-control-geocoder-address-detail' : '') +
						'">{postcode} {city} {town} {village} {hamlet}');
				}

				if (a.state || a.country) {
					parts.push(' 0 ? 'leaflet-control-geocoder-address-context' : '') +
						'">{state} {country}');
				}

				return Util.template(parts.join('
'), a, true);
			}
		},

		initialize: function(options) {
			L.Util.setOptions(this, options);
		},

		geocode: function(query, cb, context) {
			Util.jsonp(this.options.serviceUrl + 'search', L.extend({
				q: query,
				limit: 5,
				format: 'json',
				addressdetails: 1
			}, this.options.geocodingQueryParams),
			function(data) {
				var results = [];
				for (var i = data.length - 1; i >= 0; i--) {
					var bbox = data[i].boundingbox;
					for (var j = 0; j < 4; j++) bbox[j] = parseFloat(bbox[j]);
					results[i] = {
						icon: data[i].icon,
						name: data[i].display_name,
						html: this.options.htmlTemplate ?
							this.options.htmlTemplate(data[i])
							: undefined,
						bbox: L.latLngBounds([bbox[0], bbox[2]], [bbox[1], bbox[3]]),
						center: L.latLng(data[i].lat, data[i].lon),
						properties: data[i]
					};
				}
				cb.call(context, results);
			}, this, 'json_callback');
		},

		reverse: function(location, scale, cb, context) {
			Util.jsonp(this.options.serviceUrl + 'reverse', L.extend({
				lat: location.lat,
				lon: location.lng,
				zoom: Math.round(Math.log(scale / 256) / Math.log(2)),
				addressdetails: 1,
				format: 'json'
			}, this.options.reverseQueryParams), function(data) {
				var result = [],
				    loc;

				if (data && data.lat && data.lon) {
					loc = L.latLng(data.lat, data.lon);
					result.push({
						name: data.display_name,
						html: this.options.htmlTemplate ?
							this.options.htmlTemplate(data)
							: undefined,
						center: loc,
						bounds: L.latLngBounds(loc, loc),
						properties: data
					});
				}

				cb.call(context, result);
			}, this, 'json_callback');
		}
	}),

	factory: function(options) {
		return new L.Control.Geocoder.Nominatim(options);
	}
};
<|endoftext|>


<commit_before>import axios from 'axios'
import {forEach, pipe, uniqBy} from 'ramda'
import {appState} from '../store/lukkariStore'

const urlParamLength = 9

export const addUrlParameter = (courseCode, groupName) => {
  const params = window.location.search
  const urlParam = courseCode.substring(0, 2) === 'FV' ? `${courseCode}-${groupName}` : courseCode
  if (params.length > urlParamLength) {
    if (params.indexOf(courseCode) < 0) {
      history.pushState({}, '', `?courses=${params.substring(urlParamLength, params.length)}+${urlParam}`)
    }
  } else if (params.indexOf('?courses=') < 0) {
    history.pushState({}, '', `?courses=${params}${urlParam}`)
  } else {
    history.pushState({}, '', `${params}${urlParam}`)
  }
}

export const updateUrlParams = (selectedCourses) => {
  pipe(
    uniqBy((c) => c.course_code),
    forEach((c) => addUrlParameter(c.course_code, c.group_name))
  )(selectedCourses)
}

export const removeUrlParameter = (courseCode) => {
  const params = window.location.search
  const updatedParams = params.substring(urlParamLength, params.length).split('+').filter((p) => {
    if (p.indexOf('-') > -1) {
      const groupLetterStripped = p.substring(0, p.indexOf('-'))
      return groupLetterStripped !== courseCode
    } else {
      return p !== courseCode
    }
  })
  if (updatedParams.length > 0) {
    history.pushState({}, '', `?courses=${updatedParams.join('+')}`)
  } else {
    history.pushState({}, '', '?courses=')
  }
}

export const sendEmail = (email) => {
  axios.post('api/save', {email, link: window.location.href.toString()})
    .then(() => {
      appState.dispatch({type: 'EMAIL_SEND_DONE', waitingAjax: false})
    })
    .catch(() => {
      appState.dispatch({type: 'EMAIL_SEND_FAILED', waitingAjax: false})
    })
}
<commit_msg>Sanitaze url params when before add/remove course<commit_after>import axios from 'axios'
import {forEach, pipe, uniqBy} from 'ramda'
import {appState} from '../store/lukkariStore'

const urlParamLength = 9

const sanitizeUrlParam = () => window.location.search.indexOf('courses=') < 0 ? '' : window.location.search

export const addUrlParameter = (courseCode, groupName) => {
  const params = sanitizeUrlParam()
  const urlParam = courseCode.substring(0, 2) === 'FV' ? `${courseCode}-${groupName}` : courseCode
  if (params.length > urlParamLength) {
    if (params.indexOf(courseCode) < 0) {
      history.pushState({}, '', `?courses=${params.substring(urlParamLength, params.length)}+${urlParam}`)
    }
  } else if (params.indexOf('?courses=') < 0) {
    history.pushState({}, '', `?courses=${params}${urlParam}`)
  } else {
    history.pushState({}, '', `${params}${urlParam}`)
  }
}

export const updateUrlParams = (selectedCourses) => {
  pipe(
    uniqBy((c) => c.course_code),
    forEach((c) => addUrlParameter(c.course_code, c.group_name))
  )(selectedCourses)
}

export const removeUrlParameter = (courseCode) => {
  const params = sanitizeUrlParam()
  const updatedParams = params.substring(urlParamLength, params.length).split('+').filter((p) => {
    if (p.indexOf('-') > -1) {
      const groupLetterStripped = p.substring(0, p.indexOf('-'))
      return groupLetterStripped !== courseCode
    } else {
      return p !== courseCode
    }
  })
  if (updatedParams.length > 0) {
    history.pushState({}, '', `?courses=${updatedParams.join('+')}`)
  } else {
    history.pushState({}, '', '?courses=')
  }
}

export const sendEmail = (email) => {
  axios.post('api/save', {email, link: window.location.href.toString()})
    .then(() => {
      appState.dispatch({type: 'EMAIL_SEND_DONE', waitingAjax: false})
    })
    .catch(() => {
      appState.dispatch({type: 'EMAIL_SEND_FAILED', waitingAjax: false})
    })
}
<|endoftext|>


<commit_before>var paraview;
var midas = midas || {};
midas.visualize = midas.visualize || {};

midas.visualize.renderers = {};

midas.visualize.start = function () {
    // Create a paraview proxy
    var file = json.visualize.url;
    var container = $('#renderercontainer');

    if(typeof Paraview != 'function') {
        alert('Paraview javascript was not fetched correctly from server.');
        return;
    }

    paraview = new Paraview("/PWService");
    paraview.errorListener = {
        manageError: function(error) {
            midas.createNotice('A ParaViewWeb error occurred; check the console for information', 4000, 'error');
            console.log(error);
            return true;
        }
    };
    paraview.createSession("midas", "slice viz", "default");

    midas.visualize.input = paraview.OpenDataFile({filename: file});
    paraview.Show();
    paraview.Hide();

    var imageData = paraview.GetDataInformation();
    midas.visualize.bounds = imageData.Bounds;
    midas.visualize.minVal = imageData.PointData.Arrays[0].Ranges[0][0];
    midas.visualize.maxVal = imageData.PointData.Arrays[0].Ranges[0][1];
    midas.visualize.imageWindow = [midas.visualize.minVal, midas.visualize.maxVal];

    if(midas.visualize.bounds.length != 6) {
        console.log('Invalid image bounds:');
        console.log(midas.visualize.bounds);
        return;
    }

    midas.visualize.midI = (midas.visualize.bounds[0] + midas.visualize.bounds[1]) / 2.0;
    midas.visualize.midJ = (midas.visualize.bounds[2] + midas.visualize.bounds[3]) / 2.0;
    midas.visualize.midK = Math.ceil((midas.visualize.bounds[4] + midas.visualize.bounds[5]) / 2.0) - 1;

    var sliceFilter = paraview.ExtractSubset({
      Input: midas.visualize.input,
      SampleRateI: 1,
      SampleRateJ: 1,
      SampleRateK: 1,
      VOI: [midas.visualize.bounds[0],
            midas.visualize.bounds[1],
            midas.visualize.bounds[2],
            midas.visualize.bounds[3],
            midas.visualize.midK,
            midas.visualize.midK + 1]
    });
    paraview.Show({proxy: sliceFilter});

    midas.visualize.activeView = paraview.CreateIfNeededRenderView();
    midas.visualize.activeView.setViewSize(container.width(), container.height());
    midas.visualize.activeView.setCenterAxesVisibility(false);
    midas.visualize.activeView.setOrientationAxesVisibility(false);
    midas.visualize.activeView.setCameraParallelProjection(true);
    midas.visualize.activeView.setCameraPosition([midas.visualize.midI,
                                                  midas.visualize.midJ,
                                                  midas.visualize.bounds[5] + 1]);
    midas.visualize.activeView.setCameraFocalPoint([midas.visualize.midI,
                                                    midas.visualize.midJ,
                                                    midas.visualize.midK]);
    midas.visualize.activeView.setCenterOfRotation(midas.visualize.activeView.getCameraFocalPoint());

    var lookupTable = paraview.GetLookupTableForArray('MetaImage', 1);
    lookupTable.setRGBPoints([midas.visualize.minVal,
                              0.0, 0.0, 0.0,
                              midas.visualize.maxVal,
                              1.0, 1.0, 1.0]); //initial transfer function def
    lookupTable.setColorSpace(0); // 0 corresponds to RGB

    paraview.SetDisplayProperties({
        proxy: sliceFilter,
        view: midas.visualize.activeView,
        Representation: 'Volume',
        ColorArrayName: 'MetaImage',
        LookupTable: lookupTable
    });
    paraview.Render();
    midas.visualize.activeView.setCameraParallelScale(
      Math.max(midas.visualize.midI, midas.visualize.midJ));

    midas.visualize.switchRenderer(true); // render in the div
    $('img.visuLoading').hide();
    container.show();
    midas.visualize.setupSliders();

    midas.visualize.updateSliceInfo(midas.visualize.midK);
    midas.visualize.updateWindowInfo([midas.visualize.minVal, midas.visualize.maxVal]);
    midas.visualize.disableMouseInteraction();
};

/**
 * Helper function to setup the slice and window/level sliders
 */
midas.visualize.setupSliders = function () {
    $('#sliceSlider').slider({
        min: midas.visualize.bounds[4],
        max: midas.visualize.bounds[5] - 1,
        value: midas.visualize.midK,
        change: function(event, ui) {
            midas.visualize.changeSlice(ui.value);
        },
        slide: function(event, ui) {
            midas.visualize.updateSliceInfo(ui.value);
        }
    });
    $('#windowLevelSlider').slider({
        range: true,
        min: midas.visualize.minVal,
        max: midas.visualize.maxVal,
        values: [midas.visualize.minVal, midas.visualize.maxVal],
        change: function(event, ui) {
            midas.visualize.changeWindow(ui.values);
        },
        slide: function(event, ui) {
            midas.visualize.updateWindowInfo(ui.values);
        }
    });
};

/**
 * Unregisters all mouse event handlers on the renderer
 */
midas.visualize.disableMouseInteraction = function () {
    var el = midas.visualize.renderers.current.view;
    el.onclick = null;
    el.onmousemove = null;
    el.onmousedown = null;
    el.onmouseup = null;
    el.oncontextmenu = null;
    el.ontouchstart = null;
    el.ontouchmove = null;
};

/**
 * Update the client GUI values for window and level, without
 * actually changing them in PVWeb
 */
midas.visualize.updateWindowInfo = function (values) {
    $('#windowLevelInfo').html('Window: '+values[0]+' - '+values[1]);
};

/** Make the actual request to PVWeb to set the window */
midas.visualize.changeWindow = function (values) {
    var lookupTable = paraview.GetLookupTableForArray('MetaImage', 1);
    midas.visualize.imageWindow = values;
    lookupTable.setRGBPoints([values[0], 0.0, 0.0, 0.0, values[1], 1.0, 1.0, 1.0]);

    paraview.Render();
};

midas.visualize.changeSlice = function (slice) {
    if(slice < midas.visualize.bounds[4] || slice > midas.visualize.bounds[5] - 1) {
        console.log('Invalid slice number: '+slice);
        return;
    }

    var prevSlice = paraview.GetActiveSource();
    midas.visualize.activeView.setCameraFocalPoint([midas.visualize.midI,
                                                    midas.visualize.midJ,
                                                    slice]);
    var sliceFilter = paraview.ExtractSubset({
      Input: midas.visualize.input,
      SampleRateI: 1,
      SampleRateJ: 1,
      SampleRateK: 1,
      VOI: [midas.visualize.bounds[0],
            midas.visualize.bounds[1],
            midas.visualize.bounds[2],
            midas.visualize.bounds[3],
            slice,
            slice + 1]
    });
    var lookupTable = paraview.GetLookupTableForArray('MetaImage', 1);
    // set current window state on this slice
    lookupTable.setRGBPoints([midas.visualize.imageWindow[0],
                              0.0, 0.0, 0.0,
                              midas.visualize.imageWindow[1],
                              1.0, 1.0, 1.0]);
    lookupTable.setColorSpace(0); // 0 corresponds to RGB

    paraview.SetDisplayProperties({
        proxy: sliceFilter,
        view: midas.visualize.activeView,
        Representation: 'Volume',
        ColorArrayName: 'MetaImage',
        LookupTable: lookupTable
    });
    paraview.Show({proxy: sliceFilter}); //show the next slice
    paraview.Hide({proxy: prevSlice}); //hide the previous slice
};

/**
 * Update the value of the current slice, without rendering the slice.
 */
midas.visualize.updateSliceInfo = function (slice) {
    $('#sliceInfo').html('Slice: ' + (slice+1) + ' of '+ midas.visualize.bounds[5]);
};

/**
 * Initialize or re-initialize the renderer within the DOM
 */
midas.visualize.switchRenderer = function (first) {
    if(midas.visualize.renderers.js == undefined) {
        midas.visualize.renderers.js = new JavaScriptRenderer("jsRenderer", "/PWService");
        midas.visualize.renderers.js.init(paraview.sessionId, midas.visualize.activeView.__selfid__);
        $('img.toolButton').show();
    }

    if(!first) {
        midas.visualize.renderers.current.unbindToElementId('renderercontainer');
    }
    midas.visualize.renderers.current = midas.visualize.renderers.js;
    midas.visualize.renderers.current.bindToElementId('renderercontainer');
    midas.visualize.renderers.current.start();
};

$(window).load(function () {
    json = jQuery.parseJSON($('div.jsonContent').html());
    midas.visualize.start();
});

$(window).unload(function () {
    paraview.disconnect();
});

<commit_msg>ENH: refs #787. Black background in render view<commit_after>var paraview;
var midas = midas || {};
midas.visualize = midas.visualize || {};

midas.visualize.renderers = {};

midas.visualize.start = function () {
    // Create a paraview proxy
    var file = json.visualize.url;
    var container = $('#renderercontainer');

    if(typeof Paraview != 'function') {
        alert('Paraview javascript was not fetched correctly from server.');
        return;
    }

    paraview = new Paraview("/PWService");
    paraview.errorListener = {
        manageError: function(error) {
            midas.createNotice('A ParaViewWeb error occurred; check the console for information', 4000, 'error');
            console.log(error);
            return true;
        }
    };
    paraview.createSession("midas", "slice viz", "default");

    midas.visualize.input = paraview.OpenDataFile({filename: file});
    paraview.Show();
    paraview.Hide();

    var imageData = paraview.GetDataInformation();
    midas.visualize.bounds = imageData.Bounds;
    midas.visualize.minVal = imageData.PointData.Arrays[0].Ranges[0][0];
    midas.visualize.maxVal = imageData.PointData.Arrays[0].Ranges[0][1];
    midas.visualize.imageWindow = [midas.visualize.minVal, midas.visualize.maxVal];

    if(midas.visualize.bounds.length != 6) {
        console.log('Invalid image bounds:');
        console.log(midas.visualize.bounds);
        return;
    }

    midas.visualize.midI = (midas.visualize.bounds[0] + midas.visualize.bounds[1]) / 2.0;
    midas.visualize.midJ = (midas.visualize.bounds[2] + midas.visualize.bounds[3]) / 2.0;
    midas.visualize.midK = Math.ceil((midas.visualize.bounds[4] + midas.visualize.bounds[5]) / 2.0) - 1;

    var sliceFilter = paraview.ExtractSubset({
      Input: midas.visualize.input,
      SampleRateI: 1,
      SampleRateJ: 1,
      SampleRateK: 1,
      VOI: [midas.visualize.bounds[0],
            midas.visualize.bounds[1],
            midas.visualize.bounds[2],
            midas.visualize.bounds[3],
            midas.visualize.midK,
            midas.visualize.midK + 1]
    });
    paraview.Show({proxy: sliceFilter});

    midas.visualize.activeView = paraview.CreateIfNeededRenderView();
    midas.visualize.activeView.setViewSize(container.width(), container.height());
    midas.visualize.activeView.setCenterAxesVisibility(false);
    midas.visualize.activeView.setOrientationAxesVisibility(false);
    midas.visualize.activeView.setCameraParallelProjection(true);
    midas.visualize.activeView.setCameraPosition([midas.visualize.midI,
                                                  midas.visualize.midJ,
                                                  midas.visualize.bounds[5] + 1]);
    midas.visualize.activeView.setCameraFocalPoint([midas.visualize.midI,
                                                    midas.visualize.midJ,
                                                    midas.visualize.midK]);
    midas.visualize.activeView.setCenterOfRotation(midas.visualize.activeView.getCameraFocalPoint());
    midas.visualize.activeView.setBackground([0.0, 0.0, 0.0]);
    midas.visualize.activeView.setBackground2([0.0, 0.0, 0.0]); //solid black background

    var lookupTable = paraview.GetLookupTableForArray('MetaImage', 1);
    lookupTable.setRGBPoints([midas.visualize.minVal,
                              0.0, 0.0, 0.0,
                              midas.visualize.maxVal,
                              1.0, 1.0, 1.0]); //initial transfer function def
    lookupTable.setColorSpace(0); // 0 corresponds to RGB

    paraview.SetDisplayProperties({
        proxy: sliceFilter,
        view: midas.visualize.activeView,
        Representation: 'Volume',
        ColorArrayName: 'MetaImage',
        LookupTable: lookupTable
    });
    paraview.Render();
    midas.visualize.activeView.setCameraParallelScale(
      Math.max(midas.visualize.midI, midas.visualize.midJ));

    midas.visualize.switchRenderer(true); // render in the div
    $('img.visuLoading').hide();
    container.show();
    midas.visualize.setupSliders();

    midas.visualize.updateSliceInfo(midas.visualize.midK);
    midas.visualize.updateWindowInfo([midas.visualize.minVal, midas.visualize.maxVal]);
    midas.visualize.disableMouseInteraction();
};

/**
 * Helper function to setup the slice and window/level sliders
 */
midas.visualize.setupSliders = function () {
    $('#sliceSlider').slider({
        min: midas.visualize.bounds[4],
        max: midas.visualize.bounds[5] - 1,
        value: midas.visualize.midK,
        change: function(event, ui) {
            midas.visualize.changeSlice(ui.value);
        },
        slide: function(event, ui) {
            midas.visualize.updateSliceInfo(ui.value);
        }
    });
    $('#windowLevelSlider').slider({
        range: true,
        min: midas.visualize.minVal,
        max: midas.visualize.maxVal,
        values: [midas.visualize.minVal, midas.visualize.maxVal],
        change: function(event, ui) {
            midas.visualize.changeWindow(ui.values);
        },
        slide: function(event, ui) {
            midas.visualize.updateWindowInfo(ui.values);
        }
    });
};

/**
 * Unregisters all mouse event handlers on the renderer
 */
midas.visualize.disableMouseInteraction = function () {
    var el = midas.visualize.renderers.current.view;
    el.onclick = null;
    el.onmousemove = null;
    el.onmousedown = null;
    el.onmouseup = null;
    el.oncontextmenu = null;
    el.ontouchstart = null;
    el.ontouchmove = null;
};

/**
 * Update the client GUI values for window and level, without
 * actually changing them in PVWeb
 */
midas.visualize.updateWindowInfo = function (values) {
    $('#windowLevelInfo').html('Window: '+values[0]+' - '+values[1]);
};

/** Make the actual request to PVWeb to set the window */
midas.visualize.changeWindow = function (values) {
    var lookupTable = paraview.GetLookupTableForArray('MetaImage', 1);
    midas.visualize.imageWindow = values;
    lookupTable.setRGBPoints([values[0], 0.0, 0.0, 0.0, values[1], 1.0, 1.0, 1.0]);

    paraview.Render();
};

midas.visualize.changeSlice = function (slice) {
    if(slice < midas.visualize.bounds[4] || slice > midas.visualize.bounds[5] - 1) {
        console.log('Invalid slice number: '+slice);
        return;
    }

    var prevSlice = paraview.GetActiveSource();
    midas.visualize.activeView.setCameraFocalPoint([midas.visualize.midI,
                                                    midas.visualize.midJ,
                                                    slice]);
    var sliceFilter = paraview.ExtractSubset({
      Input: midas.visualize.input,
      SampleRateI: 1,
      SampleRateJ: 1,
      SampleRateK: 1,
      VOI: [midas.visualize.bounds[0],
            midas.visualize.bounds[1],
            midas.visualize.bounds[2],
            midas.visualize.bounds[3],
            slice,
            slice + 1]
    });
    var lookupTable = paraview.GetLookupTableForArray('MetaImage', 1);
    // set current window state on this slice
    lookupTable.setRGBPoints([midas.visualize.imageWindow[0],
                              0.0, 0.0, 0.0,
                              midas.visualize.imageWindow[1],
                              1.0, 1.0, 1.0]);
    lookupTable.setColorSpace(0); // 0 corresponds to RGB

    paraview.SetDisplayProperties({
        proxy: sliceFilter,
        view: midas.visualize.activeView,
        Representation: 'Volume',
        ColorArrayName: 'MetaImage',
        LookupTable: lookupTable
    });
    paraview.Show({proxy: sliceFilter}); //show the next slice
    paraview.Hide({proxy: prevSlice}); //hide the previous slice
};

/**
 * Update the value of the current slice, without rendering the slice.
 */
midas.visualize.updateSliceInfo = function (slice) {
    $('#sliceInfo').html('Slice: ' + (slice+1) + ' of '+ midas.visualize.bounds[5]);
};

/**
 * Initialize or re-initialize the renderer within the DOM
 */
midas.visualize.switchRenderer = function (first) {
    if(midas.visualize.renderers.js == undefined) {
        midas.visualize.renderers.js = new JavaScriptRenderer("jsRenderer", "/PWService");
        midas.visualize.renderers.js.init(paraview.sessionId, midas.visualize.activeView.__selfid__);
        $('img.toolButton').show();
    }

    if(!first) {
        midas.visualize.renderers.current.unbindToElementId('renderercontainer');
    }
    midas.visualize.renderers.current = midas.visualize.renderers.js;
    midas.visualize.renderers.current.bindToElementId('renderercontainer');
    midas.visualize.renderers.current.start();
};

$(window).load(function () {
    json = jQuery.parseJSON($('div.jsonContent').html());
    midas.visualize.start();
});

$(window).unload(function () {
    paraview.disconnect();
});

<|endoftext|>


<commit_before>odoo.define('pos_mobile_restaurant.chrome', function (require) {
    "use strict";
    if (!odoo.is_mobile) {
        return;
    }

    var screens = require('pos_mobile.screens');
    var chrome = require('pos_mobile.chrome');

    chrome.Chrome.include({
        // This method instantiates all the screens, widgets, etc.
        build_widgets: function() {
            var self = this;
            // floors swiper (you can to use the 'resistanceRatio': 1 parameter)
            // read more about it http://idangero.us/swiper/api/#parameters
            this.swiper_floors = new window.Swiper('.swiper-container-map', {
                'resistanceRatio': 0
            });

            // Event will be fired after transition to another slide
            this.swiper_floors.on('transitionEnd', function() {
                self.change_current_floor();
            });

            this._super();

            // floor screen swiper
            this.swiper_floor_screen = new window.Swiper('.swiper-container-floor-screen', {
                slidesPerView: 'auto',
                initialSlide: 1,
                resistanceRatio: 0,
                slideToClickedSlide: true,
            });

            // remove all events for floor swiper
            this.swiper_floor_screen.destroy(false , false);

            var floor_selector = $('.floor-screen .floor-selector');
            if (floor_selector.length) {
                floor_selector.detach();
                $(".mobile-floor-selector").append(floor_selector);
            }

            // floors
            if (this.pos.floors) {
                _.each(this.pos.floors, function(floor, index){
                    self.render_all_floors(floor.id, index);
                });
            }

            if (this.pos.floors.length < 2) {
                // remove all events for floors
                this.swiper_floors.destroy(false , false);
            }

            var order_button = $('.control-button.order-submit');
            order_button.detach();
            $(".mobile-order-container .mobile-search-bar .searchbox").prepend(order_button);

            // // show first floor
            if (this.pos.floors && this.pos.floors.length) {
                this.change_current_floor(this.pos.floors[0].id);
            }

            // for compatibility with pos_multi_session_restaurant
            this.pos.bind('change:orders-count-on-floor-screen', function () {
                self.change_current_floor();
            });

            // add a div for specific control buttons
            $('.slide-numpad .pads').prepend("

");

            var guests = $('.control-button.order-guests');
            var discount = $('.control-button.js_discount');
            var note = $('.control-button.order-note');

            guests.detach();
            discount.detach();
            note.detach();

            $('.top-control-buttons').append(guests);
            $('.top-control-buttons').append(discount);
            $('.top-control-buttons').append(note);

            /* The new Printbill Button in ActionpadWidget, delete the old Printbill button */
            var printbill = $('.slide-buttons .control-button.order-printbill');
            printbill.remove();
        },
        menu_button_click: function() {
            var slider = this.swiper_floor_screen;
            if (this.menu_is_opened) {
                slider.slideNext();
                this.menuButton.removeClass('cross');
                this.menu_is_opened = false;
            } else {
                slider.slidePrev();
                this.menuButton.addClass('cross');
                this.menu_is_opened = true;
            }
        },
        render_all_floors: function(id, index) {
            var floor_widget = this.gui.screen_instances.floors;
            floor_widget.floor = this.pos.floors_by_id[id];
            floor_widget.renderElement();
        },
        // set or change current order
        change_current_floor: function(id) {
            if (!this.pos.floors || !this.pos.floors.length) {
                return false;
            }
            var self = this;
            var active_floor = $('.slide-floor.swiper-slide-active');

            var floor_id = id || active_floor.data('id');

            this.gui.screen_instances.floors.floor = this.pos.floors_by_id[floor_id];
            this.gui.screen_instances.floors.renderElement();

            // replace floor selector
            var floor_selector = $('.floor-screen .floor-selector');
            if (floor_selector.length) {
                floor_selector.detach();
                $(".mobile-floor-selector .floor-selector").replaceWith(floor_selector);
            }

            // event for menu button
            this.menuButton = $('.menu-button');
            this.menu_is_opened = false;

            // Each time a function is called, the click event is recorded without removing the previous event.
            // When you click the menu button, the event was generated many times, which led to a hang.
            // Therefore, before each function call, you must remove the event.
            this.menuButton.off("click");
            this.menuButton.click(function() {
                self.menu_button_click();
            });

            // close left menu
            this.swiper_floor_screen.slideTo(1);
            this.menuButton.removeClass('cross');

            // set active selector
            $('.mobile-floor-selector').find('.button-floor.active').removeClass('active');
            $('.mobile-floor-selector').find('.button-floor[data-id=' + floor_id +']').addClass('active');
            active_floor.find('.tables').getNiceScroll().doScrollPos(0, 0);

            if (!this.pos.iOS) {
                active_floor.find('.tables').niceScroll({
                    horizrailenabled: false,
                    scrollCLass: 'floor-scroll',
                });
            }
        }
    });

    return chrome;
});
<commit_msg>:ambulance: correctly selector name<commit_after>odoo.define('pos_mobile_restaurant.chrome', function (require) {
    "use strict";
    if (!odoo.is_mobile) {
        return;
    }

    var screens = require('pos_mobile.screens');
    var chrome = require('pos_mobile.chrome');

    chrome.Chrome.include({
        // This method instantiates all the screens, widgets, etc.
        build_widgets: function() {
            var self = this;
            // floors swiper (you can to use the 'resistanceRatio': 1 parameter)
            // read more about it http://idangero.us/swiper/api/#parameters
            this.swiper_floors = new window.Swiper('.swiper-container-map', {
                'resistanceRatio': 0
            });

            // Event will be fired after transition to another slide
            this.swiper_floors.on('transitionEnd', function() {
                self.change_current_floor();
            });

            this._super();

            // floor screen swiper
            this.swiper_floor_screen = new window.Swiper('.swiper-container-floor-screen', {
                slidesPerView: 'auto',
                initialSlide: 1,
                resistanceRatio: 0,
                slideToClickedSlide: true,
            });

            // remove all events for floor swiper
            this.swiper_floor_screen.destroy(false , false);

            var floor_selector = $('.floor-screen .floor-selector');
            if (floor_selector.length) {
                floor_selector.detach();
                $(".mobile-floor-selector").append(floor_selector);
            }

            // floors
            if (this.pos.floors) {
                _.each(this.pos.floors, function(floor, index){
                    self.render_all_floors(floor.id, index);
                });
            }

            if (this.pos.floors.length < 2) {
                // remove all events for floors
                this.swiper_floors.destroy(false , false);
            }

            var order_button = $('.control-button.order-submit');
            order_button.detach();
            $(".mobile-order-container .mobile-search-bar .searchbox").prepend(order_button);

            // // show first floor
            if (this.pos.floors && this.pos.floors.length) {
                this.change_current_floor(this.pos.floors[0].id);
            }

            // for compatibility with pos_multi_session_restaurant
            this.pos.bind('change:orders-count-on-floor-screen', function () {
                self.change_current_floor();
            });

            // add a div for specific control buttons
            $('.slide-numpad .pads').prepend("

");

            var guests = $('.control-button.order-guests');
            var discount = $('.control-button.js_discount');
            var note = $('.control-button.order-note');

            guests.detach();
            discount.detach();
            note.detach();

            $('.top-control-buttons').append(guests);
            $('.top-control-buttons').append(discount);
            $('.top-control-buttons').append(note);

            /* The new Printbill Button in ActionpadWidget, delete the old Printbill button */
            var printbill = $('.slide-buttons .control-button.order-printbill');
            printbill.remove();
        },
        menu_button_click: function() {
            var slider = this.swiper_floor_screen;
            if (this.menu_is_opened) {
                slider.slideNext();
                this.menuButton.removeClass('cross');
                this.menu_is_opened = false;
            } else {
                slider.slidePrev();
                this.menuButton.addClass('cross');
                this.menu_is_opened = true;
            }
        },
        render_all_floors: function(id, index) {
            var floor_widget = this.gui.screen_instances.floors;
            floor_widget.floor = this.pos.floors_by_id[id];
            floor_widget.renderElement();
        },
        // set or change current order
        change_current_floor: function(id) {
            if (!this.pos.floors || !this.pos.floors.length) {
                return false;
            }
            var self = this;
            var active_floor = $('.slide-floor.swiper-slide-active');

            var floor_id = id || active_floor.data('id');

            this.gui.screen_instances.floors.floor = this.pos.floors_by_id[floor_id];
            this.gui.screen_instances.floors.renderElement();

            // replace floor selector
            var floor_selector = $('.floor-screen .floor-selector');
            if (floor_selector.length) {
                floor_selector.detach();
                $(".mobile-floor-selector .floor-selector").replaceWith(floor_selector);
            }

            // event for menu button
            this.menuButton = $('.mobile-floor-selector .menu-button');
            this.menu_is_opened = false;

            this.menuButton.click(function() {
                self.menu_button_click();
            });

            // close left menu
            this.swiper_floor_screen.slideTo(1);
            this.menuButton.removeClass('cross');

            // set active selector
            $('.mobile-floor-selector').find('.button-floor.active').removeClass('active');
            $('.mobile-floor-selector').find('.button-floor[data-id=' + floor_id +']').addClass('active');
            active_floor.find('.tables').getNiceScroll().doScrollPos(0, 0);

            if (!this.pos.iOS) {
                active_floor.find('.tables').niceScroll({
                    horizrailenabled: false,
                    scrollCLass: 'floor-scroll',
                });
            }
        }
    });

    return chrome;
});
<|endoftext|>


<commit_before>import React from 'react';
import './DetailVizitka.css';

const DetailVizitka = ({politician}) => (

{politician.firstname} {politician.surname}, {politician.title}

Funkcia: {politician.office_name_male}, {politician.term_start} - {politician.term_finish}

Strana: {politician.party_nom}

);
export default DetailVizitka;

<commit_msg>mena vo vizitke mensie<commit_after>import React from 'react';
import './DetailVizitka.css';

const DetailVizitka = ({politician}) => (

{politician.firstname} {politician.surname}, {politician.title}

Funkcia: {politician.office_name_male}, {politician.term_start} - {politician.term_finish}

Strana: {politician.party_nom}

);
export default DetailVizitka;

<|endoftext|>


<commit_before>/* eslint-disable react/no-danger */
import React from 'react';
import App from 'next/app';
import Head from 'next/head';
import { AnimatePresence } from 'framer-motion';
import ColourBar from '../components/ColourBar';
import ColourContext from '../context/colour';
import Navigation from '../components/Navigation';
import Favico from '../components/Favico';
import colourClock from '../scripts/colour-clock';
import '../styles/main.css';

class MyApp extends App {
  constructor(props) {
    super(props);
    this.state = {
      colour: '#fff',
      time: '',
    };
  }

  componentDidMount() {
    this.startColourClock();
  }

  componentWillUnmount() {
    const { interval } = this.state;
    clearInterval(interval);
  }

  startColourClock() {
    this.setState({ ...colourClock() });
    const interval = setInterval(() => {
      this.setState({ ...colourClock() });
    }, 1000);
    this.setState({ interval });
  }

  render() {
    const { colour, time } = this.state;
    const { Component, pageProps, router } = this.props;

    return (
      <ColourContext.Provider value={{ colour, time }}>
        <Head>
          <link key="favico" rel="icon" sizes="any" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Crect width='16' height='16' fill='%23aab4cc'/%3E%3C/svg%3E"/>
          <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png" />
          <meta name="msapplication-TileColor" content="#da532c" />
          <meta name="theme-color" content="#ffffff" />
          <link rel="manifest" href="/site.webmanifest" />
          <script async src="https://www.googletagmanager.com/gtag/js?id=UA-44359005-1" />
          <script dangerouslySetInnerHTML={{
            __html: `
              window.dataLayer = window.dataLayer || [];
              function gtag(){dataLayer.push(arguments);}
              gtag('js', new Date());
              gtag('config', 'UA-44359005-1');
            `,
          }}
          />
        </Head>
        <Favico />
        <ColourBar />
        <Navigation />
        <AnimatePresence exitBeforeEnter>
          <Component {...pageProps} key={router.route} />
        </AnimatePresence>
      </ColourContext.Provider>
    );
  }
}

export default MyApp;
<commit_msg>Add GA only in production<commit_after>/* eslint-disable react/no-danger */
import React from 'react';
import App from 'next/app';
import Head from 'next/head';
import { AnimatePresence } from 'framer-motion';
import ColourBar from '../components/ColourBar';
import ColourContext from '../context/colour';
import Navigation from '../components/Navigation';
import Favico from '../components/Favico';
import colourClock from '../scripts/colour-clock';
import '../styles/main.css';

class MyApp extends App {
  constructor(props) {
    super(props);
    this.state = {
      colour: '#fff',
      time: '',
    };
  }

  componentDidMount() {
    this.startColourClock();
  }

  componentWillUnmount() {
    const { interval } = this.state;
    clearInterval(interval);
  }

  startColourClock() {
    this.setState({ ...colourClock() });
    const interval = setInterval(() => {
      this.setState({ ...colourClock() });
    }, 1000);
    this.setState({ interval });
  }

  render() {
    const { colour, time } = this.state;
    const { Component, pageProps, router } = this.props;

    return (
      <ColourContext.Provider value={{ colour, time }}>
        <Head>
          <link key="favico" rel="icon" sizes="any" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Crect width='16' height='16' fill='%23aab4cc'/%3E%3C/svg%3E"/>
          <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png" />
          <meta name="msapplication-TileColor" content="#da532c" />
          <meta name="theme-color" content="#ffffff" />
          <link rel="manifest" href="/site.webmanifest" />
          {process.env.NODE_ENV === 'production' &&
            <>
              <script async src="https://www.googletagmanager.com/gtag/js?id=UA-44359005-1" />
              <script dangerouslySetInnerHTML={{
                __html: `
                  window.dataLayer = window.dataLayer || [];
                  function gtag(){dataLayer.push(arguments);}
                  gtag('js', new Date());
                  gtag('config', 'UA-44359005-1');
                `,
              }}
              />
            </>
          }
        </Head>
        <Favico />
        <ColourBar />
        <Navigation />
        <AnimatePresence exitBeforeEnter>
          <Component {...pageProps} key={router.route} />
        </AnimatePresence>
      </ColourContext.Provider>
    );
  }
}

export default MyApp;
<|endoftext|>