<commit_before>(function(window, factory) {
    if (typeof define === 'function' && define.amd) {
        define(['jquery'], function($) {
            return factory(window, $);
        });
    } else if (typeof module === 'object' && typeof module.exports === 'object') {
        module.exports = factory(window, require('jquery'));
    } else {
        window.lity = factory(window, window.jQuery || window.Zepto);
    }
}(window, function(window, $) {
    'use strict';

    var document = window.document;

    var _win = $(window);
    var _html = $('html');
    var _instanceCount = 0;

    var _imageRegexp = /\.(png|jpe?g|gif|svg|webp|bmp|ico|tiff?)(\?\S*)?$/i;
    var _youtubeRegex = /(youtube(-nocookie)?\.com|youtu\.be)\/(watch\?v=|v\/|u\/|embed\/?)?([\w-]{11})(.*)?/i;
    var _vimeoRegex =  /(vimeo(pro)?.com)\/(?:[^\d]+)?(\d+)\??(.*)?$/;
    var _googlemapsRegex = /((maps|www)\.)?google\.([^\/\?]+)\/?((maps\/?)?\?)(.*)/i;

    var _defaultHandlers = {
        image: imageHandler,
        inline: inlineHandler,
        iframe: iframeHandler
    };

    var _defaultOptions = {
        esc: true,
        handler: null,
        template: '

Loading...

<button class="lity-close" type="button" title="Close (Esc)" data-lity-close>×</button>

'
    };

    function globalToggle() {
        _html[_instanceCount > 0 ? 'addClass' : 'removeClass']('lity-active');
    }

    var transitionEndEvent = (function() {
        var el = document.createElement('div');

        var transEndEventNames = {
            WebkitTransition: 'webkitTransitionEnd',
            MozTransition: 'transitionend',
            OTransition: 'oTransitionEnd otransitionend',
            transition: 'transitionend'
        };

        for (var name in transEndEventNames) {
            if (el.style[name] !== undefined) {
                return transEndEventNames[name];
            }
        }

        return false;
    })();

    function transitionEnd(element) {
        var deferred = $.Deferred();

        if (!transitionEndEvent) {
            deferred.resolve();
        } else {
            element.one(transitionEndEvent, deferred.resolve);
            setTimeout(deferred.resolve, 500);
        }

        return deferred.promise();
    }

    function settings(currSettings, key, value) {
        if (arguments.length === 1) {
            return $.extend({}, currSettings);
        }

        if (typeof key === 'string') {
            if (typeof value === 'undefined') {
                return typeof currSettings[key] === 'undefined' ?
                    null :
                    currSettings[key];
            }
            currSettings[key] = value;
        } else {
            $.extend(currSettings, key);
        }

        return this;
    }

    function protocol() {
        return 'file:' === window.location.protocol ? 'http:' : '';
    }

    function parseQueryParams(params){
        var pairs = decodeURI(params).split('&');
        var obj = {}, p;

        for (var i = 0, n = pairs.length; i < n; i++) {
            if (!pairs[i]) {
                continue;
            }

            p = pairs[i].split('=');
            obj[p[0]] = p[1];
        }

        return obj;
    }

    function appendQueryParams(url, params) {
        return url + (url.indexOf('?') > -1 ? '&' : '?') + $.param(params);
    }

    function error(msg) {
        return $('').append(msg);
    }

    function imageHandler(target) {
        if (!_imageRegexp.test(target)) {
            return false;
        }

        var img = $('');
        var deferred = $.Deferred();
        var failed = function() {
            deferred.reject(error('Failed loading image'));
        };

        img
            .on('load', function() {
                if (this.naturalWidth === 0) {
                    return failed();
                }

                deferred.resolve(img);
            })
            .on('error', failed)
        ;

        return deferred.promise();
    }

    function inlineHandler(target) {
        var el;

        try {
            el = $(target);
        } catch (e) {
            return false;
        }

        if (!el.length) {
            return false;
        }

        var placeholder = $('');

        return el
            .after(placeholder)
            .on('lity:ready', function(e, instance) {
                instance.one('lity:remove', function() {
                    placeholder
                        .before(el.addClass('lity-hide'))
                        .remove()
                    ;
                });
            })
        ;
    }

    function iframeHandler(target) {
        var matches, url = target;

        matches = _youtubeRegex.exec(target);

        if (matches) {
            url = appendQueryParams(
                protocol() + '//www.youtube' + (matches[2] || '') + '.com/embed/' + matches[4],
                $.extend(
                    {
                        autoplay: 1
                    },
                    parseQueryParams(matches[5] || '')
                )
            );
        }

        matches = _vimeoRegex.exec(target);

        if (matches) {
            url = appendQueryParams(
                protocol() + '//player.vimeo.com/video/' + matches[3],
                $.extend(
                    {
                        autoplay: 1
                    },
                    parseQueryParams(matches[4] || '')
                )
            );
        }

        matches = _googlemapsRegex.exec(target);

        if (matches) {
            url = appendQueryParams(
                protocol() + '//www.google.' + matches[3] + '/maps?' + matches[6],
                {
                    output: matches[6].indexOf('layer=c') > 0 ? 'svembed' : 'embed'
                }
            );
        }

        return '

';
    }

    function lity(options) {
        var _options = {},
            _handlers = {},
            _instance,
            _content,
            _ready = $.Deferred().resolve();

        function keyup(e) {
            if (e.keyCode === 27) {
                close();
            }
        }

        function resize() {
            var height = document.documentElement.clientHeight ? document.documentElement.clientHeight : Math.round(_win.height());

            _content
                .css('max-height', Math.floor(height) + 'px')
                .trigger('lity:resize', [_instance, popup])
            ;
        }

        function ready(content) {
            if (!_instance) {
                return;
            }

            _content = $(content);

            _win.on('resize', resize);
            resize();

            _instance
                .find('.lity-loader')
                .each(function() {
                    var el = $(this);
                    transitionEnd(el).always(function() {
                        el.remove();
                    });
                })
            ;

            _instance
                .removeClass('lity-loading')
                .find('.lity-content')
                .empty()
                .append(_content)
            ;

            _content
                .removeClass('lity-hide')
                .trigger('lity:ready', [_instance, popup])
            ;

            _ready.resolve();
        }

        function init(handler, content, options) {
            _instanceCount++;
            globalToggle();

            _instance = $(options.template)
                .addClass('lity-loading')
                .appendTo('body');

            if (!!options.esc) {
                _win.one('keyup', keyup);
            }

            setTimeout(function() {
                _instance
                    .addClass('lity-opened lity-' + handler)
                    .on('click', '[data-lity-close]', function(e) {
                        if ($(e.target).is('[data-lity-close]')) {
                            close();
                        }
                    })
                    .trigger('lity:open', [_instance, popup])
                ;

                $.when(content).always(ready);
            }, 0);
        }

        function open(target, options) {
            var handler, content, handlers = $.extend({}, _defaultHandlers, _handlers);

            if (options.handler && handlers[options.handler]) {
                content = handlers[options.handler](target, instance, popup);
                handler = options.handler;
            } else {
                var lateHandlers = {};

                // Run inline and iframe handlers after all other handlers
                $.each(['inline', 'iframe'], function(i, name) {
                    if (handlers[name]) {
                        lateHandlers[name] = handlers[name];
                    }

                    delete handlers[name];
                });

                var call = function(name, callback) {
                    // Handler might be "removed" by setting callback to null
                    if (!callback) {
                        return true;
                    }

                    content = callback(target, popup);

                    if (!!content) {
                        handler = name;
                        return false;
                    }
                };

                $.each(handlers, call);

                if (!handler) {
                    $.each(lateHandlers, call);
                }
            }

            if (content) {
                _ready = $.Deferred();
                $.when(close()).done($.proxy(init, null, handler, content, options));
            }

            return !!content;
        }

        function close() {
            if (!_instance) {
                return;
            }

            var deferred = $.Deferred();

            _ready.done(function() {
                _instanceCount--;
                globalToggle();

                _win
                    .off('resize', resize)
                    .off('keyup', keyup)
                ;

                _content.trigger('lity:close', [_instance, popup]);

                _instance
                    .removeClass('lity-opened')
                    .addClass('lity-closed')
                ;

                var instance = _instance, content = _content;
                _instance = null;
                _content = null;

                transitionEnd(content.add(instance)).always(function() {
                    content.trigger('lity:remove', [instance, popup]);
                    instance.remove();
                    deferred.resolve();
                });
            });

            return deferred.promise();
        }

        function popup(event) {
            // If not an event, act as alias of popup.open
            if (!event.preventDefault) {
                return popup.open(event);
            }

            var el = $(this);
            var target = el.data('lity-target') || el.attr('href') || el.attr('src');

            if (!target) {
                return;
            }

            var options = $.extend(
                {},
                _defaultOptions,
                _options,
                el.data('lity-options') || el.data('lity')
            );

            if (open(target, options)) {
                event.preventDefault();
            }
        }

        popup.handlers = $.proxy(settings, popup, _handlers);
        popup.options = $.proxy(settings, popup, _options);

        popup.open = function(target) {
            open(target, $.extend({}, _defaultOptions, _options));
            return popup;
        };

        popup.close = function() {
            close();
            return popup;
        };

        return popup.options(options);
    }

    lity.version = '@VERSION';
    lity.handlers = $.proxy(settings, lity, _defaultHandlers);
    lity.options = $.proxy(settings, lity, _defaultOptions);

    $(document).on('click', '[data-lity]', lity());

    return lity;
}));
<commit_msg>Add window instance check<commit_after>(function(window, factory) {
    if (typeof define === 'function' && define.amd) {
        define(['jquery'], function($) {
            return factory(window, $);
        });
    } else if (typeof module === 'object' && typeof module.exports === 'object') {
        module.exports = factory(window, require('jquery'));
    } else {
        window.lity = factory(window, window.jQuery || window.Zepto);
    }
}(typeof window !== "undefined" ? window : this, function(window, $) {
    'use strict';

    var document = window.document;

    var _win = $(window);
    var _html = $('html');
    var _instanceCount = 0;

    var _imageRegexp = /\.(png|jpe?g|gif|svg|webp|bmp|ico|tiff?)(\?\S*)?$/i;
    var _youtubeRegex = /(youtube(-nocookie)?\.com|youtu\.be)\/(watch\?v=|v\/|u\/|embed\/?)?([\w-]{11})(.*)?/i;
    var _vimeoRegex =  /(vimeo(pro)?.com)\/(?:[^\d]+)?(\d+)\??(.*)?$/;
    var _googlemapsRegex = /((maps|www)\.)?google\.([^\/\?]+)\/?((maps\/?)?\?)(.*)/i;

    var _defaultHandlers = {
        image: imageHandler,
        inline: inlineHandler,
        iframe: iframeHandler
    };

    var _defaultOptions = {
        esc: true,
        handler: null,
        template: '

Loading...

<button class="lity-close" type="button" title="Close (Esc)" data-lity-close>×</button>

'
    };

    function globalToggle() {
        _html[_instanceCount > 0 ? 'addClass' : 'removeClass']('lity-active');
    }

    var transitionEndEvent = (function() {
        var el = document.createElement('div');

        var transEndEventNames = {
            WebkitTransition: 'webkitTransitionEnd',
            MozTransition: 'transitionend',
            OTransition: 'oTransitionEnd otransitionend',
            transition: 'transitionend'
        };

        for (var name in transEndEventNames) {
            if (el.style[name] !== undefined) {
                return transEndEventNames[name];
            }
        }

        return false;
    })();

    function transitionEnd(element) {
        var deferred = $.Deferred();

        if (!transitionEndEvent) {
            deferred.resolve();
        } else {
            element.one(transitionEndEvent, deferred.resolve);
            setTimeout(deferred.resolve, 500);
        }

        return deferred.promise();
    }

    function settings(currSettings, key, value) {
        if (arguments.length === 1) {
            return $.extend({}, currSettings);
        }

        if (typeof key === 'string') {
            if (typeof value === 'undefined') {
                return typeof currSettings[key] === 'undefined' ?
                    null :
                    currSettings[key];
            }
            currSettings[key] = value;
        } else {
            $.extend(currSettings, key);
        }

        return this;
    }

    function protocol() {
        return 'file:' === window.location.protocol ? 'http:' : '';
    }

    function parseQueryParams(params){
        var pairs = decodeURI(params).split('&');
        var obj = {}, p;

        for (var i = 0, n = pairs.length; i < n; i++) {
            if (!pairs[i]) {
                continue;
            }

            p = pairs[i].split('=');
            obj[p[0]] = p[1];
        }

        return obj;
    }

    function appendQueryParams(url, params) {
        return url + (url.indexOf('?') > -1 ? '&' : '?') + $.param(params);
    }

    function error(msg) {
        return $('').append(msg);
    }

    function imageHandler(target) {
        if (!_imageRegexp.test(target)) {
            return false;
        }

        var img = $('');
        var deferred = $.Deferred();
        var failed = function() {
            deferred.reject(error('Failed loading image'));
        };

        img
            .on('load', function() {
                if (this.naturalWidth === 0) {
                    return failed();
                }

                deferred.resolve(img);
            })
            .on('error', failed)
        ;

        return deferred.promise();
    }

    function inlineHandler(target) {
        var el;

        try {
            el = $(target);
        } catch (e) {
            return false;
        }

        if (!el.length) {
            return false;
        }

        var placeholder = $('');

        return el
            .after(placeholder)
            .on('lity:ready', function(e, instance) {
                instance.one('lity:remove', function() {
                    placeholder
                        .before(el.addClass('lity-hide'))
                        .remove()
                    ;
                });
            })
        ;
    }

    function iframeHandler(target) {
        var matches, url = target;

        matches = _youtubeRegex.exec(target);

        if (matches) {
            url = appendQueryParams(
                protocol() + '//www.youtube' + (matches[2] || '') + '.com/embed/' + matches[4],
                $.extend(
                    {
                        autoplay: 1
                    },
                    parseQueryParams(matches[5] || '')
                )
            );
        }

        matches = _vimeoRegex.exec(target);

        if (matches) {
            url = appendQueryParams(
                protocol() + '//player.vimeo.com/video/' + matches[3],
                $.extend(
                    {
                        autoplay: 1
                    },
                    parseQueryParams(matches[4] || '')
                )
            );
        }

        matches = _googlemapsRegex.exec(target);

        if (matches) {
            url = appendQueryParams(
                protocol() + '//www.google.' + matches[3] + '/maps?' + matches[6],
                {
                    output: matches[6].indexOf('layer=c') > 0 ? 'svembed' : 'embed'
                }
            );
        }

        return '

';
    }

    function lity(options) {
        var _options = {},
            _handlers = {},
            _instance,
            _content,
            _ready = $.Deferred().resolve();

        function keyup(e) {
            if (e.keyCode === 27) {
                close();
            }
        }

        function resize() {
            var height = document.documentElement.clientHeight ? document.documentElement.clientHeight : Math.round(_win.height());

            _content
                .css('max-height', Math.floor(height) + 'px')
                .trigger('lity:resize', [_instance, popup])
            ;
        }

        function ready(content) {
            if (!_instance) {
                return;
            }

            _content = $(content);

            _win.on('resize', resize);
            resize();

            _instance
                .find('.lity-loader')
                .each(function() {
                    var el = $(this);
                    transitionEnd(el).always(function() {
                        el.remove();
                    });
                })
            ;

            _instance
                .removeClass('lity-loading')
                .find('.lity-content')
                .empty()
                .append(_content)
            ;

            _content
                .removeClass('lity-hide')
                .trigger('lity:ready', [_instance, popup])
            ;

            _ready.resolve();
        }

        function init(handler, content, options) {
            _instanceCount++;
            globalToggle();

            _instance = $(options.template)
                .addClass('lity-loading')
                .appendTo('body');

            if (!!options.esc) {
                _win.one('keyup', keyup);
            }

            setTimeout(function() {
                _instance
                    .addClass('lity-opened lity-' + handler)
                    .on('click', '[data-lity-close]', function(e) {
                        if ($(e.target).is('[data-lity-close]')) {
                            close();
                        }
                    })
                    .trigger('lity:open', [_instance, popup])
                ;

                $.when(content).always(ready);
            }, 0);
        }

        function open(target, options) {
            var handler, content, handlers = $.extend({}, _defaultHandlers, _handlers);

            if (options.handler && handlers[options.handler]) {
                content = handlers[options.handler](target, instance, popup);
                handler = options.handler;
            } else {
                var lateHandlers = {};

                // Run inline and iframe handlers after all other handlers
                $.each(['inline', 'iframe'], function(i, name) {
                    if (handlers[name]) {
                        lateHandlers[name] = handlers[name];
                    }

                    delete handlers[name];
                });

                var call = function(name, callback) {
                    // Handler might be "removed" by setting callback to null
                    if (!callback) {
                        return true;
                    }

                    content = callback(target, popup);

                    if (!!content) {
                        handler = name;
                        return false;
                    }
                };

                $.each(handlers, call);

                if (!handler) {
                    $.each(lateHandlers, call);
                }
            }

            if (content) {
                _ready = $.Deferred();
                $.when(close()).done($.proxy(init, null, handler, content, options));
            }

            return !!content;
        }

        function close() {
            if (!_instance) {
                return;
            }

            var deferred = $.Deferred();

            _ready.done(function() {
                _instanceCount--;
                globalToggle();

                _win
                    .off('resize', resize)
                    .off('keyup', keyup)
                ;

                _content.trigger('lity:close', [_instance, popup]);

                _instance
                    .removeClass('lity-opened')
                    .addClass('lity-closed')
                ;

                var instance = _instance, content = _content;
                _instance = null;
                _content = null;

                transitionEnd(content.add(instance)).always(function() {
                    content.trigger('lity:remove', [instance, popup]);
                    instance.remove();
                    deferred.resolve();
                });
            });

            return deferred.promise();
        }

        function popup(event) {
            // If not an event, act as alias of popup.open
            if (!event.preventDefault) {
                return popup.open(event);
            }

            var el = $(this);
            var target = el.data('lity-target') || el.attr('href') || el.attr('src');

            if (!target) {
                return;
            }

            var options = $.extend(
                {},
                _defaultOptions,
                _options,
                el.data('lity-options') || el.data('lity')
            );

            if (open(target, options)) {
                event.preventDefault();
            }
        }

        popup.handlers = $.proxy(settings, popup, _handlers);
        popup.options = $.proxy(settings, popup, _options);

        popup.open = function(target) {
            open(target, $.extend({}, _defaultOptions, _options));
            return popup;
        };

        popup.close = function() {
            close();
            return popup;
        };

        return popup.options(options);
    }

    lity.version = '@VERSION';
    lity.handlers = $.proxy(settings, lity, _defaultHandlers);
    lity.options = $.proxy(settings, lity, _defaultOptions);

    $(document).on('click', '[data-lity]', lity());

    return lity;
}));
<|endoftext|>


<commit_before>/**
 * A simulation of Odometry Reading --
 *
 * @constructor
 * @param {RobotState} lastState - The last estimated state of the robot
 * @param {RobotState} state - The current estimated state of the robot
 */
function Odometry(lastState, state)
{
	this.lastX = lastState.x;
	this.lastY = lastState.y;
	this.lastDir = lastState.dir;

	this.x = state.x;
	this.y = state.y;
	this.dir = state.dir;
}

/**
 * A simulation of Odometry Model --
 * A representation of Motion Model
 * @constructor
 * @param {float} a1 - Noise on rotation 1
 * @param {float} a2 - Noise on translation displacement
 * @param {float} a3 - Nooise on rotation 2
 * @param {float} a4 - Final Rotation
 */
function OdometryModel(a1, a2, a3, a4)
{
	//Noise on rotational 1
	this.a1 = a1;
	//Noise on translational displacement
	this.a2 = a2;
	//Noise on rotational 2
	this.a3 = a3;
	//Final rotation
	this.a4 = a4;
}

//Sample from the distribution p(x_t+1, u, x),
//where u is the control/odometry, x is the state
OdometryModel.prototype.sample = function(u, state)
{
	var dx = u.x-u.lastX;
	var dy = u.y-u.lastY;

	var a1 = this.a1;
	var a2 = this.a2;
	var a3 = this.a3;
	var a4 = this.a4;

	//first rotation
	var rot1 = atan2(dy, dx) - u.lastDir;
	//translational distance traveled
	var trans = sqrt(dx*dx + dy*dy);
	//second rotation
	var rot2 = u.dir - u.lastDir - rot1;

	//Bound radians to interval [-pi, pi]
	rot1 = boundRadian(rot1);
	rot2 = boundRadian(rot2);

	var rot1_squared = rot1*rot1;
	var trans_squared = trans*trans;
	var rot2_squared = rot2*rot2;

	//actual sampling
	rot1 += gaussian() * sqrt(a1*rot1_squared + a2*trans_squared);
	trans += gaussian() * sqrt(a3*trans_squared + a4*rot1_squared + a4*rot2_squared);
	rot2 += gaussian() * sqrt(a1*rot2_squared + a2*trans_squared);

	var x = state.x + trans*cos(state.dir+rot1);
	var y = state.y + trans*sin(state.dir+rot1);

	var dir = state.dir + rot1 + rot2;

	return new RobotState(x, y, dir);
};<commit_msg>finishing odometry comments<commit_after>/**
 * A simulation of Odometry Reading
 * @constructor
 * @param {RobotState} lastState - The last estimated state of the robot
 * @param {RobotState} state - The current estimated state of the robot
 */
function Odometry(lastState, state)
{
	this.lastX = lastState.x;
	this.lastY = lastState.y;
	this.lastDir = lastState.dir;

	this.x = state.x;
	this.y = state.y;
	this.dir = state.dir;
}

/**
 * A simulation of Odometry Model --
 * A representation of Motion Model
 * @constructor
 * @param {float} a1 - Noise on rotation 1
 * @param {float} a2 - Noise on translation displacement
 * @param {float} a3 - Nooise on rotation 2
 * @param {float} a4 - Final Rotation
 */
function OdometryModel(a1, a2, a3, a4)
{
	//Noise on rotational 1
	this.a1 = a1;
	//Noise on translational displacement
	this.a2 = a2;
	//Noise on rotational 2
	this.a3 = a3;
	//Final rotation
	this.a4 = a4;
}

/**
 * Sample from the distribution p(x_t+1, u, x)
 * @function
 * @param {Odometry} u - The Odometry reading
 * @param {RobotState} state - The Current Robot State
 */
OdometryModel.prototype.sample = function(u, state)
{
	var dx = u.x-u.lastX;
	var dy = u.y-u.lastY;

	var a1 = this.a1;
	var a2 = this.a2;
	var a3 = this.a3;
	var a4 = this.a4;

	//first rotation
	var rot1 = atan2(dy, dx) - u.lastDir;
	//translational distance traveled
	var trans = sqrt(dx*dx + dy*dy);
	//second rotation
	var rot2 = u.dir - u.lastDir - rot1;

	//Bound radians to interval [-pi, pi]
	rot1 = boundRadian(rot1);
	rot2 = boundRadian(rot2);

	var rot1_squared = rot1*rot1;
	var trans_squared = trans*trans;
	var rot2_squared = rot2*rot2;

	//actual sampling
	rot1 += gaussian() * sqrt(a1*rot1_squared + a2*trans_squared);
	trans += gaussian() * sqrt(a3*trans_squared + a4*rot1_squared + a4*rot2_squared);
	rot2 += gaussian() * sqrt(a1*rot2_squared + a2*trans_squared);

	var x = state.x + trans*cos(state.dir+rot1);
	var y = state.y + trans*sin(state.dir+rot1);

	var dir = state.dir + rot1 + rot2;

	return new RobotState(x, y, dir);
};<|endoftext|>


<commit_before>const _ = require('lodash/fp')
const fs = require('fs')
const dsl = require('./dsl')
const vm = require('vm')

module.exports = function (file) {
  return vm.runInNewContext(fs.readFileSync(file),
                            _.assign(dsl, { module }),
                            { filename: file })
}
<commit_msg>Fix missing globals in PureSpec modules<commit_after>const fs = require('fs')
const dsl = require('./dsl')
const vm = require('vm')

module.exports = function (file) {
  return vm.runInNewContext(fs.readFileSync(file),
                            Object.assign({ module, require }, global, dsl),
                            { filename: file })
}
<|endoftext|>


<commit_before>/*
 * Translation to JavaScript
 *
 * Requiring this module adds a gen() method to each of the AST classes.
 * Nothing is actually exported from this module.
 *
 * Generally, calling e.gen() where e is an expression node will return the
 * JavaScript translation as a string, while calling s.gen() where s is a
 * statement-level node will write its translation to standard output.
 *
 *   require("./backend/javascript-generator");
 *   program.gen();
 */
 // eslint-disable no-unused-vars

const Context = require("../ast/context");
const Program = require("../ast/program");
const Block = require("../ast/block");
const Return = require("../ast/return");
const Stmt = require("../ast/stmt");
const Argument = require("../ast/arg");
const Arguments = require("../ast/args");
const StringLiteral = require("../ast/stringLit");
const FuncCall = require("../ast/funcCall");
const AddExp = require("../ast/addExp");
const BinExp = require("../ast/binExp");
const Body = require("../ast/body");
const CharLit = require("../ast/charLit");
const Decl = require("../ast/decl");
const ExpBinary = require("../ast/exp_binary");
const ExpTernary = require("../ast/exp_ternary");
const ExpoExp = require("../ast/expoExp");
const ParenExp = require("../ast/parenExp");
const FuncDec = require("../ast/funcDec");
const List = require("../ast/list");
const Matches = require("../ast/matches");
const MullExp = require("../ast/mullExp");
const NumLit = require("../ast/numLit");
const Param = require("../ast/param");
const Params = require("../ast/params");
const PrefixExp = require("../ast/prefix_Exp");
const Print = require("../ast/print");
const StatementIfElse = require("../ast/statementIfElse");
const TupLit = require("../ast/tuplit");
const Type = require("../ast/type");

const indentPadding = 2;
let indentLevel = 0;

function emit(line) {
  console.log(`${" ".repeat(indentPadding * indentLevel)}${line}`);
}

function genStatementList(statements) {
  indentLevel += 1;
  statements.forEach(statement => statement.gen());
  indentLevel -= 1;
}

function makeOp(op) {
  return { not: "!", and: "&&", or: "||", "==": "===", "!=": "!==" }[op] || op;
}

// jsName(e) takes any PlainScript object with an id property, such as a
// Variable, Parameter, or FunctionDeclaration, and produces a JavaScript
// name by appending a unique indentifying suffix, such as "_1" or "_503".
// It uses a cache so it can return the same exact string each time it is
// called with a particular entity.
const jsName = (() => {
  let lastId = 0;
  const map = new Map();
  return (v) => {
    if (!(map.has(v))) {
      map.set(v, ++lastId); // eslint-disable-line no-plusplus
    }
    return `${v.id}_${map.get(v)}`;
  };
})();

// This is a nice helper for variable declarations and assignment statements.
// The AST represents both of these with lists of sources and lists of targets,
// but when writing out JavaScript it seems silly to write `[x] = [y]` when
// `x = y` suffices.
function bracketIfNecessary(a) {
  if (a.length === 1) {
    return `${a}`;
  }
  return `[${a.join(", ")}]`;
}

function generateLibraryFunctions() {
  function generateLibraryStub(name, params, body) {
    const entity = Context.INITIAL.localVariables[name];
    emit(`function ${jsName(entity)}(${params}) {${body}}`);
  }
  // This is sloppy. There should be a better way to do this.
  generateLibraryStub("print", "_", "console.log(_);");
}

Object.assign(Argument.prototype, {
  gen() {
    let translation = jsName(this);
    if (this.id) {
      translation += ` = ${this.id.gen()}`;
    }
    return translation;
  },
});

Object.assign(Arguments.prototype, {
  gen() { return this.args.forEach(arg => arg.gen()); },
});

Object.assign(Params.prototype, {
    gen() {
        this.params.forEach(param => param.gen());
    },
});

/*
Object.assign(AssignmentStatement.prototype, {
  gen() {
    const targets = this.targets.map(t => t.gen());
    const sources = this.sources.map(s => s.gen());
    emit(`${bracketIfNecessary(targets)} = ${bracketIfNecessary(sources)};`);
  },
});
*/

Object.assign(BinExp.prototype, {
  gen() { return `(${this.left.gen()} ${makeOp(this.op)} ${this.right.gen()})`; },
});

Object.assign(AddExp.prototype, {
  gen() { return `(${this.left.gen()} ${makeOp(this.op)} ${this.right.gen()})`; },
});

Object.assign(MullExp.prototype, {
  gen() { return `(${this.left.gen()} ${makeOp(this.op)} ${this.right.gen()})`; },
});

Object.assign(PrefixExp.prototype, {
  gen() { return `(${makeOp(this.op)} ${this.right.gen()})`; },
});

Object.assign(ExpoExp.prototype, {
  gen() { return `(${this.left.gen()} ${makeOp(this.op)} ${this.right.gen()})`; },
});

Object.assign(ParenExp.prototype, {
  gen() { return `(${this.addexp.gen()})`; },
});

/*
Object.assign(BooleanLiteral.prototype, {
  gen() { return `${this.value}`; },
});

Object.assign(BreakStatement.prototype, {
  gen() { return "break;"; },
});

Object.assign(CallStatement.prototype, {
  gen() { emit(`${this.call.gen()};`); },
});

Object.assign(Call.prototype, {
  gen() {
    const fun = this.callee.referent;
    const params = {};
    const args = Array(this.args.length).fill(undefined);
    fun.params.forEach((p, i) => { params[p.id] = i; });
    this.args.forEach((a, i) => { args[a.isPositionalArgument ? i : params[a.id]] = a; });
    return `${jsName(fun)}(${args.map(a => (a ? a.gen() : "undefined")).join(", ")})`;
  },
});
*/

Object.assign(FuncDec.prototype, {
  gen() {
      emit(`function ${this.id} {`);
      genStatementList(this.body);
      emit("}");
  },
});

Object.assign(List.prototype, {
  gen() {
      let eles = [];
      this.elements.forEach(element => {
          eles.push(element.gen());
      });
      emit(`[${eles}];`);
  },
});

/*

Object.assign(FunctionObject.prototype, {
  gen() {
    emit(`function ${jsName(this)}(${this.params.map(p => p.gen()).join(", ")}) {`);
    genStatementList(this.body);
    emit("}");
  },
});

Object.assign(IdentifierExpression.prototype, {
  gen() { return this.referent.gen(); },
});

Object.assign(IfStatement.prototype, {
  gen() {
    this.cases.forEach((c, index) => {
      const prefix = index === 0 ? "if" : "} else if";
      emit(`${prefix} (${c.test.gen()}) {`);
      genStatementList(c.body);
    });
    if (this.alternate) {
      emit("} else {");
      genStatementList(this.alternate);
    }
    emit("}");
  },
});
*/
Object.assign(NumLit.prototype, {
  gen() { return `${this.value}`; },
});

Object.assign(Param.prototype, {
  gen() {
    let translation = jsName(this);
    if (this.id) {
      translation += ` = ${this.id.gen()}`;
    }
    return translation;
  },
});

Object.assign(Program.prototype, {
  gen() {
    return `${this.block.gen()}`;
  },
});

Object.assign(Body.prototype, {
  gen() {
    return `${this.block.gen()}`;
  },
});

Object.assign(Block.prototype, {
    gen() {
        this.statements.forEach(statement => statement.gen());
    },
});
/*

*/
Object.assign(Return.prototype, {
  gen() {
    if (this.returnValue) {
      emit(`return ${this.returnValue.gen()};`);
    } else {
      emit("return;");
    }
  },
});

Object.assign(Print.prototype, {
  gen() {
    if (this.binexp) {
      emit(`console.log(${this.binexp.gen()});`);
    } else {
      emit("console.log();");
    }
  },
});

Object.assign(StringLiteral.prototype, {
  gen() { return `${this.value}`; },
});
/*

Object.assign(SubscriptedExpression.prototype, {
  gen() {
    const base = this.variable.gen();
    const subscript = this.subscript.gen();
    return `${base}[${subscript}]`;
  },
});

Object.assign(UnaryExpression.prototype, {
  gen() { return `(${makeOp(this.op)} ${this.operand.gen()})`; },
});
*/

Object.assign(Decl.prototype, {
  gen() {
    // const variables = this.variables.map(v => v.gen());
    // const initializers = this.initializers.map(i => i.gen());
    return `let ${this.id} = ${this.exp.gen()};`;
  },
});

/*
Object.assign(Variable.prototype, {
  gen() { return jsName(this); },
});

Object.assign(WhileStatement.prototype, {
  gen() {
    emit(`while (${this.test.gen()}) {`);
    genStatementList(this.body);
    emit("}");
  },
});
*/
<commit_msg>no semi colon<commit_after>/*
 * Translation to JavaScript
 *
 * Requiring this module adds a gen() method to each of the AST classes.
 * Nothing is actually exported from this module.
 *
 * Generally, calling e.gen() where e is an expression node will return the
 * JavaScript translation as a string, while calling s.gen() where s is a
 * statement-level node will write its translation to standard output.
 *
 *   require("./backend/javascript-generator");
 *   program.gen();
 */
 // eslint-disable no-unused-vars

const Context = require("../ast/context");
const Program = require("../ast/program");
const Block = require("../ast/block");
const Return = require("../ast/return");
const Stmt = require("../ast/stmt");
const Argument = require("../ast/arg");
const Arguments = require("../ast/args");
const StringLiteral = require("../ast/stringLit");
const FuncCall = require("../ast/funcCall");
const AddExp = require("../ast/addExp");
const BinExp = require("../ast/binExp");
const Body = require("../ast/body");
const CharLit = require("../ast/charLit");
const Decl = require("../ast/decl");
const ExpBinary = require("../ast/exp_binary");
const ExpTernary = require("../ast/exp_ternary");
const ExpoExp = require("../ast/expoExp");
const ParenExp = require("../ast/parenExp");
const FuncDec = require("../ast/funcDec");
const List = require("../ast/list");
const Matches = require("../ast/matches");
const MullExp = require("../ast/mullExp");
const NumLit = require("../ast/numLit");
const Param = require("../ast/param");
const Params = require("../ast/params");
const PrefixExp = require("../ast/prefix_Exp");
const Print = require("../ast/print");
const StatementIfElse = require("../ast/statementIfElse");
const TupLit = require("../ast/tuplit");
const Type = require("../ast/type");

const indentPadding = 2;
let indentLevel = 0;

function emit(line) {
  console.log(`${" ".repeat(indentPadding * indentLevel)}${line}`);
}

function genStatementList(statements) {
  indentLevel += 1;
  statements.forEach(statement => statement.gen());
  indentLevel -= 1;
}

function makeOp(op) {
  return { not: "!", and: "&&", or: "||", "==": "===", "!=": "!==" }[op] || op;
}

// jsName(e) takes any PlainScript object with an id property, such as a
// Variable, Parameter, or FunctionDeclaration, and produces a JavaScript
// name by appending a unique indentifying suffix, such as "_1" or "_503".
// It uses a cache so it can return the same exact string each time it is
// called with a particular entity.
const jsName = (() => {
  let lastId = 0;
  const map = new Map();
  return (v) => {
    if (!(map.has(v))) {
      map.set(v, ++lastId); // eslint-disable-line no-plusplus
    }
    return `${v.id}_${map.get(v)}`;
  };
})();

// This is a nice helper for variable declarations and assignment statements.
// The AST represents both of these with lists of sources and lists of targets,
// but when writing out JavaScript it seems silly to write `[x] = [y]` when
// `x = y` suffices.
function bracketIfNecessary(a) {
  if (a.length === 1) {
    return `${a}`;
  }
  return `[${a.join(", ")}]`;
}

function generateLibraryFunctions() {
  function generateLibraryStub(name, params, body) {
    const entity = Context.INITIAL.localVariables[name];
    emit(`function ${jsName(entity)}(${params}) {${body}}`);
  }
  // This is sloppy. There should be a better way to do this.
  generateLibraryStub("print", "_", "console.log(_);");
}

Object.assign(Argument.prototype, {
  gen() {
    let translation = jsName(this);
    if (this.id) {
      translation += ` = ${this.id.gen()}`;
    }
    return translation;
  },
});

Object.assign(Arguments.prototype, {
  gen() { return this.args.forEach(arg => arg.gen()); },
});

Object.assign(Params.prototype, {
    gen() {
        this.params.forEach(param => param.gen());
    },
});

/*
Object.assign(AssignmentStatement.prototype, {
  gen() {
    const targets = this.targets.map(t => t.gen());
    const sources = this.sources.map(s => s.gen());
    emit(`${bracketIfNecessary(targets)} = ${bracketIfNecessary(sources)};`);
  },
});
*/

Object.assign(BinExp.prototype, {
  gen() { return `(${this.left.gen()} ${makeOp(this.op)} ${this.right.gen()})`; },
});

Object.assign(AddExp.prototype, {
  gen() { return `(${this.left.gen()} ${makeOp(this.op)} ${this.right.gen()})`; },
});

Object.assign(MullExp.prototype, {
  gen() { return `(${this.left.gen()} ${makeOp(this.op)} ${this.right.gen()})`; },
});

Object.assign(PrefixExp.prototype, {
  gen() { return `(${makeOp(this.op)} ${this.right.gen()})`; },
});

Object.assign(ExpoExp.prototype, {
  gen() { return `(${this.left.gen()} ${makeOp(this.op)} ${this.right.gen()})`; },
});

Object.assign(ParenExp.prototype, {
  gen() { return `(${this.addexp.gen()})`; },
});

/*
Object.assign(BooleanLiteral.prototype, {
  gen() { return `${this.value}`; },
});

Object.assign(BreakStatement.prototype, {
  gen() { return "break;"; },
});

Object.assign(CallStatement.prototype, {
  gen() { emit(`${this.call.gen()};`); },
});

Object.assign(Call.prototype, {
  gen() {
    const fun = this.callee.referent;
    const params = {};
    const args = Array(this.args.length).fill(undefined);
    fun.params.forEach((p, i) => { params[p.id] = i; });
    this.args.forEach((a, i) => { args[a.isPositionalArgument ? i : params[a.id]] = a; });
    return `${jsName(fun)}(${args.map(a => (a ? a.gen() : "undefined")).join(", ")})`;
  },
});
*/

Object.assign(FuncDec.prototype, {
  gen() {
      emit(`function ${this.id} {`);
      genStatementList(this.body);
      emit("}");
  },
});

Object.assign(List.prototype, {
  gen() {
      let eles = [];
      this.elements.forEach(element => {
          eles.push(element.gen());
      });
      emit(`[${eles}]`);
  },
});

/*

Object.assign(FunctionObject.prototype, {
  gen() {
    emit(`function ${jsName(this)}(${this.params.map(p => p.gen()).join(", ")}) {`);
    genStatementList(this.body);
    emit("}");
  },
});

Object.assign(IdentifierExpression.prototype, {
  gen() { return this.referent.gen(); },
});

Object.assign(IfStatement.prototype, {
  gen() {
    this.cases.forEach((c, index) => {
      const prefix = index === 0 ? "if" : "} else if";
      emit(`${prefix} (${c.test.gen()}) {`);
      genStatementList(c.body);
    });
    if (this.alternate) {
      emit("} else {");
      genStatementList(this.alternate);
    }
    emit("}");
  },
});
*/
Object.assign(NumLit.prototype, {
  gen() { return `${this.value}`; },
});

Object.assign(Param.prototype, {
  gen() {
    let translation = jsName(this);
    if (this.id) {
      translation += ` = ${this.id.gen()}`;
    }
    return translation;
  },
});

Object.assign(Program.prototype, {
  gen() {
    return `${this.block.gen()}`;
  },
});

Object.assign(Body.prototype, {
  gen() {
    return `${this.block.gen()}`;
  },
});

Object.assign(Block.prototype, {
    gen() {
        this.statements.forEach(statement => statement.gen());
    },
});
/*

*/
Object.assign(Return.prototype, {
  gen() {
    if (this.returnValue) {
      emit(`return ${this.returnValue.gen()};`);
    } else {
      emit("return;");
    }
  },
});

Object.assign(Print.prototype, {
  gen() {
    if (this.binexp) {
      emit(`console.log(${this.binexp.gen()});`);
    } else {
      emit("console.log();");
    }
  },
});

Object.assign(StringLiteral.prototype, {
  gen() { return `${this.value}`; },
});
/*

Object.assign(SubscriptedExpression.prototype, {
  gen() {
    const base = this.variable.gen();
    const subscript = this.subscript.gen();
    return `${base}[${subscript}]`;
  },
});

Object.assign(UnaryExpression.prototype, {
  gen() { return `(${makeOp(this.op)} ${this.operand.gen()})`; },
});
*/

Object.assign(Decl.prototype, {
  gen() {
    // const variables = this.variables.map(v => v.gen());
    // const initializers = this.initializers.map(i => i.gen());
    return `let ${this.id} = ${this.exp.gen()};`;
  },
});

/*
Object.assign(Variable.prototype, {
  gen() { return jsName(this); },
});

Object.assign(WhileStatement.prototype, {
  gen() {
    emit(`while (${this.test.gen()}) {`);
    genStatementList(this.body);
    emit("}");
  },
});
*/
<|endoftext|>


<commit_before>var os = require("os");

module.exports = {};

switch (os.hostname()) {
    case "Tim-PC":
        module.exports = {
        	url: "localhost",
            port: "3000"
        };
        break;
    case "www":
        module.exports = {
        	url: "www.bzdbbb.co.uk",
            port: "3000"
        };
        break;
    default:
        throw new Error("Unknown host");
}<commit_msg>added new host<commit_after>var os = require("os");

module.exports = {};

switch (os.hostname()) {
    case "Tim-PC":
        module.exports = {
        	url: "localhost",
            port: "3000"
        };
        break;
    case "www":
        module.exports = {
        	url: "198.91.86.144",
            port: "3000"
        };
        break;
    default:
        throw new Error("Unknown host");
}<|endoftext|>


<commit_before>import angular from "angular";
import uiRouter from "@uirouter/angularjs";
import Authentication from "../../services/authentication/authentication";
import <%= name %>Component from "./<%= name %>.component";

let <%= name %>Module = angular.module("<%= name %>", [
  uiRouter,
  Authentication
])

.component("<%= name %>", <%= name %>Component)

.config(($stateProvider, hookProvider) => {
  "ngInject";
  $stateProvider
    .state("<%= name %>", {
      url: "/<%= name %>",
      component: "<%= name %>"
    });
  hookProvider.setup("<%= name %>", { authenticated: true, anonymous: "login" });
})

.name;

export default <%= name %>Module;
<commit_msg>remove hookProvider from template<commit_after>import angular from "angular";
import uiRouter from "@uirouter/angularjs";
import <%= name %>Component from "./<%= name %>.component";

let <%= name %>Module = angular.module("<%= name %>", [
  uiRouter,
])

.component("<%= name %>", <%= name %>Component)

.config(($stateProvider, hookProvider) => {
  "ngInject";
  $stateProvider
    .state("<%= name %>", {
      url: "/<%= name %>",
      component: "<%= name %>"
    });
})

.name;

export default <%= name %>Module;
<|endoftext|>


<commit_before>import { takeEvery } from 'redux-saga';
import { put, select } from 'redux-saga/effects';
import { dateToEpoch, timeStringToSeconds } from 'binary-utils';
import { updateMultipleTradeParams, updateTradeUIState, updateTradeError } from '../../_actions';
import { allTimeRelatedFieldValid } from '../TradeParamsValidation';
import * as paramUpdate from '../TradeParamsCascadingUpdates';
import { getParams, contractOfSymbol, getForceRenderCount } from './SagaSelectors';
import { subscribeProposal, unsubscribeProposal } from './ProposalSubscriptionSaga';

const CHANGE_DURATION = 'CHANGE_DURATION';

export const reqDurationChange = (index, duration) => ({
    type: CHANGE_DURATION,
    index,
    duration,
});

export function* handleDurationChange(action) {
    const { index, duration } = action;
    yield put(unsubscribeProposal(index));
    const params = yield select(getParams(index));
    const { symbol, tradeCategory, type, durationUnit, dateStart } = params;
    const contractNeeded = yield select(contractOfSymbol(symbol));
    const contractPerType = contractNeeded[tradeCategory][type];
    const isDurationAllowed = allTimeRelatedFieldValid(dateStart, duration, durationUnit, contractPerType);
    if (isDurationAllowed) {
        const updated = Object.assign(params, { duration });
        yield [
            put(subscribeProposal(index, updated)),
            put(updateMultipleTradeParams(index, updated)),
            put(updateTradeError(index, 'durationError')),
        ];
    } else {
        yield put(updateTradeError(index, 'durationError', 'Duration is out of range.'));
    }
}

const CHANGE_DURATION_UNIT = 'CHANGE_DURATION_UNIT';

export const reqDurationUnitChange = (index, durationUnit) => ({
    type: CHANGE_DURATION_UNIT,
    index,
    durationUnit,
});

export function* handleDurationUnitChange(action) {
    const { index, durationUnit } = action;
    yield put(unsubscribeProposal(index));
    const params = yield select(getParams(index));
    const contractNeeded = yield select(contractOfSymbol(params.symbol));
    const updated = paramUpdate.changeDurationUnit(durationUnit, contractNeeded, params);
    const renderCount = yield select(getForceRenderCount(index));
    yield [
        put(subscribeProposal(index, updated)),
        put(updateMultipleTradeParams(index, updated)),
        put(updateTradeError(index, 'durationError')),
        put(updateTradeUIState(index, 'forceRenderCount', renderCount + 1)),
    ];
}

const CHANGE_START_DATE_EPOCH = 'CHANGE_START_DATE_EPOCH';

export const reqStartEpochChange = (index, epoch) => ({
    type: CHANGE_START_DATE_EPOCH,
    index,
    epoch,
});

export function* handleStartEpochChange(action) {
    const { index, epoch } = action;
    yield put(unsubscribeProposal(index));
    const params = yield select(getParams(index));
    const { symbol } = params;
    const contractNeeded = yield select(contractOfSymbol(symbol));
    const updated = paramUpdate.changeStartDate(epoch, contractNeeded, params);
    const renderCount = yield select(getForceRenderCount(index));
    yield [
        put(subscribeProposal(index, updated)),
        put(updateMultipleTradeParams(index, updated)),
        put(updateTradeError(index, 'durationError')),
        put(updateTradeUIState(index, 'forceRenderCount', renderCount + 1)),
    ];
}

const CHANGE_START_DATE_STRING = 'CHANGE_START_DATE_STRING';

export const reqStartDateChange = (index, date) => ({
    type: CHANGE_START_DATE_STRING,
    index,
    date,
});

export function* handleStartDateChange(action) {
    const { index, date } = action;
    yield put(unsubscribeProposal(index));
    const params = yield select(getParams(index));
    const { symbol, tradeCategory, type, durationUnit, dateStart, duration } = params;

    const newDayEpoch = dateToEpoch(new Date(date));
    if (!newDayEpoch) {
        yield put(updateTradeError(index, 'durationError', 'Start date invalid, it needs to be five minutes or more in the future.'));
        return;
    }

    const secondsPerDay = 60 * 60 * 24;
    const intraDayEpoch = dateStart % secondsPerDay;
    const newDateStart = newDayEpoch + intraDayEpoch;

    const contractNeeded = yield select(contractOfSymbol(symbol));
    const contractPerType = contractNeeded[tradeCategory][type];
    const durationAllowed = allTimeRelatedFieldValid(newDateStart, duration, durationUnit, contractPerType);

    if (durationAllowed) {
        const updated = paramUpdate.changeStartDate(newDateStart, contractNeeded, params);
        yield [
            put(subscribeProposal(index, updated)),
            put(updateMultipleTradeParams(index, updated)),
            put(updateTradeError(index, 'durationError')),
        ];
    } else {
        yield put(updateTradeError(index, 'durationError', 'Start date invalid, it needs to be five minutes or more in the future.'));
    }
}

const CHANGE_START_TIME_STRING = 'CHANGE_START_TIME_STRING';

export const reqStartTimeChange = (index, time) => ({
    type: CHANGE_START_TIME_STRING,
    index,
    time,
});

export function* handleStartTimeChange(action) {
    const { index, time } = action;
    yield put(unsubscribeProposal(index));
    const params = yield select(getParams(index));
    const { symbol, tradeCategory, type, durationUnit, dateStart, duration } = params;

    const secondsPerDay = 60 * 60 * 24;
    const intraDayEpoch = dateStart % secondsPerDay;
    const dayEpoch = dateStart - intraDayEpoch;
    const newDateStart = dayEpoch + timeStringToSeconds(time);

    const contractNeeded = yield select(contractOfSymbol(symbol));
    const contractPerType = contractNeeded[tradeCategory][type];
    const durationAllowed = allTimeRelatedFieldValid(newDateStart, duration, durationUnit, contractPerType);

    if (durationAllowed) {
        const updated = paramUpdate.changeStartDate(newDateStart, contractNeeded, params);
        yield [
            put(subscribeProposal(index, updated)),
            put(updateMultipleTradeParams(index, updated)),
            put(updateTradeError(index, 'durationError')),
        ];
    } else {
        yield put(updateTradeError(index, 'durationError', 'Start date invalid, it needs to be five minutes or more in the future.'));
    }
}

export default function* watchDurationChange() {
    yield [
        takeEvery(CHANGE_DURATION, handleDurationChange),
        takeEvery(CHANGE_DURATION_UNIT, handleDurationUnitChange),
        takeEvery(CHANGE_START_DATE_STRING, handleStartDateChange),
        takeEvery(CHANGE_START_TIME_STRING, handleStartTimeChange),
        takeEvery(CHANGE_START_DATE_EPOCH, handleStartEpochChange),
    ];
}
<commit_msg>Warn user when a wrong time fromat is used (#457)<commit_after>import { takeEvery } from 'redux-saga';
import { put, select } from 'redux-saga/effects';
import { dateToEpoch, timeStringToSeconds, isValidTime } from 'binary-utils';
import { updateMultipleTradeParams, updateTradeUIState, updateTradeError } from '../../_actions';
import { allTimeRelatedFieldValid } from '../TradeParamsValidation';
import * as paramUpdate from '../TradeParamsCascadingUpdates';
import { getParams, contractOfSymbol, getForceRenderCount } from './SagaSelectors';
import { subscribeProposal, unsubscribeProposal } from './ProposalSubscriptionSaga';

const CHANGE_DURATION = 'CHANGE_DURATION';

export const reqDurationChange = (index, duration) => ({
    type: CHANGE_DURATION,
    index,
    duration,
});

export function* handleDurationChange(action) {
    const { index, duration } = action;
    yield put(unsubscribeProposal(index));
    const params = yield select(getParams(index));
    const { symbol, tradeCategory, type, durationUnit, dateStart } = params;
    const contractNeeded = yield select(contractOfSymbol(symbol));
    const contractPerType = contractNeeded[tradeCategory][type];
    const isDurationAllowed = allTimeRelatedFieldValid(dateStart, duration, durationUnit, contractPerType);
    if (isDurationAllowed) {
        const updated = Object.assign(params, { duration });
        yield [
            put(subscribeProposal(index, updated)),
            put(updateMultipleTradeParams(index, updated)),
            put(updateTradeError(index, 'durationError')),
        ];
    } else {
        yield put(updateTradeError(index, 'durationError', 'Duration is out of range.'));
    }
}

const CHANGE_DURATION_UNIT = 'CHANGE_DURATION_UNIT';

export const reqDurationUnitChange = (index, durationUnit) => ({
    type: CHANGE_DURATION_UNIT,
    index,
    durationUnit,
});

export function* handleDurationUnitChange(action) {
    const { index, durationUnit } = action;
    yield put(unsubscribeProposal(index));
    const params = yield select(getParams(index));
    const contractNeeded = yield select(contractOfSymbol(params.symbol));
    const updated = paramUpdate.changeDurationUnit(durationUnit, contractNeeded, params);
    const renderCount = yield select(getForceRenderCount(index));
    yield [
        put(subscribeProposal(index, updated)),
        put(updateMultipleTradeParams(index, updated)),
        put(updateTradeError(index, 'durationError')),
        put(updateTradeUIState(index, 'forceRenderCount', renderCount + 1)),
    ];
}

const CHANGE_START_DATE_EPOCH = 'CHANGE_START_DATE_EPOCH';

export const reqStartEpochChange = (index, epoch) => ({
    type: CHANGE_START_DATE_EPOCH,
    index,
    epoch,
});

export function* handleStartEpochChange(action) {
    const { index, epoch } = action;
    yield put(unsubscribeProposal(index));
    const params = yield select(getParams(index));
    const { symbol } = params;
    const contractNeeded = yield select(contractOfSymbol(symbol));
    const updated = paramUpdate.changeStartDate(epoch, contractNeeded, params);
    const renderCount = yield select(getForceRenderCount(index));
    yield [
        put(subscribeProposal(index, updated)),
        put(updateMultipleTradeParams(index, updated)),
        put(updateTradeError(index, 'durationError')),
        put(updateTradeUIState(index, 'forceRenderCount', renderCount + 1)),
    ];
}

const CHANGE_START_DATE_STRING = 'CHANGE_START_DATE_STRING';

export const reqStartDateChange = (index, date) => ({
    type: CHANGE_START_DATE_STRING,
    index,
    date,
});

export function* handleStartDateChange(action) {
    const { index, date } = action;
    yield put(unsubscribeProposal(index));
    const params = yield select(getParams(index));
    const { symbol, tradeCategory, type, durationUnit, dateStart, duration } = params;

    const newDayEpoch = dateToEpoch(new Date(date));
    if (!newDayEpoch) {
        yield put(updateTradeError(index, 'durationError', 'Start date invalid, it needs to be five minutes or more in the future.'));
        return;
    }

    const secondsPerDay = 60 * 60 * 24;
    const intraDayEpoch = dateStart % secondsPerDay;
    const newDateStart = newDayEpoch + intraDayEpoch;

    const contractNeeded = yield select(contractOfSymbol(symbol));
    const contractPerType = contractNeeded[tradeCategory][type];
    const durationAllowed = allTimeRelatedFieldValid(newDateStart, duration, durationUnit, contractPerType);

    if (durationAllowed) {
        const updated = paramUpdate.changeStartDate(newDateStart, contractNeeded, params);
        yield [
            put(subscribeProposal(index, updated)),
            put(updateMultipleTradeParams(index, updated)),
            put(updateTradeError(index, 'durationError')),
        ];
    } else {
        yield put(updateTradeError(index, 'durationError', 'Start date invalid, it needs to be five minutes or more in the future.'));
    }
}

const CHANGE_START_TIME_STRING = 'CHANGE_START_TIME_STRING';

export const reqStartTimeChange = (index, time) => ({
    type: CHANGE_START_TIME_STRING,
    index,
    time,
});

export function* handleStartTimeChange(action) {
    const { index, time } = action;
    yield put(unsubscribeProposal(index));

    if (isValidTime(time)) {
        yield put(updateTradeError(index, 'durationError', 'Time format is wrong!'));
        return;
    }

    const params = yield select(getParams(index));
    const { symbol, tradeCategory, type, durationUnit, dateStart, duration } = params;

    const secondsPerDay = 60 * 60 * 24;
    const intraDayEpoch = dateStart % secondsPerDay;
    const dayEpoch = dateStart - intraDayEpoch;
    const newDateStart = dayEpoch + timeStringToSeconds(time);

    const contractNeeded = yield select(contractOfSymbol(symbol));
    const contractPerType = contractNeeded[tradeCategory][type];
    const durationAllowed = allTimeRelatedFieldValid(newDateStart, duration, durationUnit, contractPerType);

    if (durationAllowed) {
        const updated = paramUpdate.changeStartDate(newDateStart, contractNeeded, params);
        yield [
            put(subscribeProposal(index, updated)),
            put(updateMultipleTradeParams(index, updated)),
            put(updateTradeError(index, 'durationError')),
        ];
    } else {
        yield put(updateTradeError(index, 'durationError', 'Start date invalid, it needs to be five minutes or more in the future.'));
    }
}

export default function* watchDurationChange() {
    yield [
        takeEvery(CHANGE_DURATION, handleDurationChange),
        takeEvery(CHANGE_DURATION_UNIT, handleDurationUnitChange),
        takeEvery(CHANGE_START_DATE_STRING, handleStartDateChange),
        takeEvery(CHANGE_START_TIME_STRING, handleStartTimeChange),
        takeEvery(CHANGE_START_DATE_EPOCH, handleStartEpochChange),
    ];
}
<|endoftext|>


<commit_before>import Transform from '../../Transform';
import TupleStore from './TupleStore';
import {createMeasure, compileMeasures} from './Measures';
import {ingest, replace} from '../../Tuple';
import {accessorName, array, error, inherits} from 'vega-util';

export var ValidAggregates = [
  'values', 'count', 'valid', 'missing', 'distinct',
  'min', 'max', 'argmin', 'argmax', 'sum', 'mean', 'average',
  'variance', 'variancep', 'stdev', 'stdevp', 'stderr',
  'median', 'q1', 'q3', 'ci0', 'ci1'
];

/**
 * Group-by aggregation operator.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {Array<function(object): *>} params.groupby - An array of accessors to groupby.
 * @param {Array<function(object): *>} params.fields - An array of accessors to aggregate.
 * @param {Array<string>} params.ops - An array of strings indicating aggregation operations.
 * @param {Array<string>} [params.as] - An array of output field names for aggregated values.
 * @param {boolean} [params.drop=true] - A flag indicating if empty cells should be removed.
 */
export default function Aggregate(params) {
  Transform.call(this, null, params);

  this._adds = []; // array of added output tuples
  this._mods = []; // array of modified output tuples
  this._alen = 0;  // number of active added tuples
  this._mlen = 0;  // number of active modified tuples
  this._drop = true;   // should empty aggregation cells be removed
  this._cross = false; // produce full cross-product of group-by values

  this._dims = [];   // group-by dimension accessors
  this._dnames = []; // group-by dimension names

  this._measures = []; // collection of aggregation monoids
  this._countOnly = false; // flag indicating only count aggregation
  this._counts = null; // collection of count fields
  this._prev = null;   // previous aggregation cells

  this._inputs = null;  // array of dependent input tuple field names
  this._outputs = null; // array of output tuple field names
}

var prototype = inherits(Aggregate, Transform);

prototype.transform = function(_, pulse) {
  var aggr = this,
      out = pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS),
      mod;

  this.stamp = out.stamp;

  if (this.value && ((mod = _.modified()) || pulse.modified(this._inputs))) {
    this._prev = this.value;
    this.value = mod ? this.init(_) : {};
    pulse.visit(pulse.SOURCE, function(t) { aggr.add(t); });
  } else {
    this.value = this.value || this.init(_);
    pulse.visit(pulse.REM, function(t) { aggr.rem(t); });
    pulse.visit(pulse.ADD, function(t) { aggr.add(t); });
  }

  // Indicate output fields and return aggregate tuples.
  out.modifies(this._outputs);

  // Should empty cells be dropped?
  aggr._drop = _.drop !== false;

  // If domain cross-product requested, generate empty cells as needed
  // and ensure that empty cells are not dropped
  if (_.cross && aggr._dims.length > 1) {
    aggr._drop = false;
    this.cross();
  }

  return aggr.changes(out);
};

prototype.cross = function() {
  var aggr = this,
      curr = aggr.value,
      dims = aggr._dnames,
      vals = dims.map(function() { return {}; }),
      n = dims.length;

  // collect all group-by domain values
  function collect(cells) {
    var key, i, t, v;
    for (key in cells) {
      t = cells[key].tuple;
      for (i=0; i<n; ++i) {
        vals[i][(v = t[dims[i]])] = v;
      }
    }
  }
  collect(aggr._prev);
  collect(curr);

  // iterate over key cross-product, create cells as needed
  function generate(base, tuple, index) {
    var name = dims[index],
        v = vals[index++],
        k, key;

    for (k in v) {
      tuple[name] = v[k];
      key = base ? base + '|' + k : k;
      if (index < n) generate(key, tuple, index);
      else if (!curr[key]) aggr.cell(key, tuple);
    }
  }
  generate('', {}, 0);
};

prototype.init = function(_) {
  // initialize input and output fields
  var inputs = (this._inputs = []),
      outputs = (this._outputs = []),
      inputMap = {};

  function inputVisit(get) {
    var fields = get.fields, i = 0, n = fields.length, f;
    for (; i<n; ++i) {
      if (!inputMap[f=fields[i]]) {
        inputMap[f] = 1;
        inputs.push(f);
      }
    }
  }

  // initialize group-by dimensions
  this._dims = array(_.groupby);
  this._dnames = this._dims.map(function(d) {
    var dname = accessorName(d);
    inputVisit(d);
    outputs.push(dname);
    return dname;
  });
  this.cellkey = _.key ? _.key
    : this._dims.length === 0 ? function() { return ''; }
    : this._dims.length === 1 ? this._dims[0]
    : cellkey;

  // initialize aggregate measures
  this._countOnly = true;
  this._counts = [];
  this._measures = [];

  var fields = _.fields || [null],
      ops = _.ops || ['count'],
      as = _.as || [],
      n = fields.length,
      map = {},
      field, op, m, mname, outname, i;

  if (n !== ops.length) {
    error('Unmatched number of fields and aggregate ops.');
  }

  for (i=0; i<n; ++i) {
    field = fields[i];
    op = ops[i];

    if (field == null && op !== 'count') {
      error('Null aggregate field specified.');
    }
    mname = accessorName(field);
    outname = measureName(op, mname, as[i]);
    outputs.push(outname);

    if (op === 'count') {
      this._counts.push(outname);
      continue;
    }

    m = map[mname];
    if (!m) {
      inputVisit(field);
      m = (map[mname] = []);
      m.field = field;
      this._measures.push(m);
    }

    if (op !== 'count') this._countOnly = false;
    m.push(createMeasure(op, outname));
  }

  this._measures = this._measures.map(function(m) {
    return compileMeasures(m, m.field);
  });

  return {}; // aggregation cells (this.value)
};

function measureName(op, mname, as) {
  return as || (op + (!mname ? '' : '_' + mname));
}

// -- Cell Management -----

function cellkey(x) {
  var d = this._dims,
      n = d.length, i,
      k = String(d[0](x));

  for (i=1; i<n; ++i) {
    k += '|' + d[i](x);
  }

  return k;
}

prototype.cellkey = cellkey;

prototype.cell = function(key, t) {
  var cell = this.value[key];
  if (!cell) {
    cell = this.value[key] = this.newcell(key, t);
    this._adds[this._alen++] = cell;
  } else if (cell.num === 0 && this._drop && cell.stamp < this.stamp) {
    cell.stamp = this.stamp;
    this._adds[this._alen++] = cell;
  } else if (cell.stamp < this.stamp) {
    cell.stamp = this.stamp;
    this._mods[this._mlen++] = cell;
  }
  return cell;
};

prototype.newcell = function(key, t) {
  var cell = {
    key:   key,
    num:   0,
    agg:   null,
    tuple: this.newtuple(t, this._prev && this._prev[key]),
    stamp: this.stamp,
    store: false
  };

  if (!this._countOnly) {
    var measures = this._measures,
        n = measures.length, i;

    cell.agg = Array(n);
    for (i=0; i<n; ++i) {
      cell.agg[i] = new measures[i](cell, cell.tuple);
    }
  }

  if (cell.store) {
    cell.data = new TupleStore();
  }

  return cell;
};

prototype.newtuple = function(t, p) {
  var names = this._dnames,
      dims = this._dims,
      x = {}, i, n;

  for (i=0, n=dims.length; i<n; ++i) {
    x[names[i]] = dims[i](t);
  }

  return p ? replace(p.tuple, x) : ingest(x);
};

// -- Process Tuples -----

prototype.add = function(t) {
  var key = this.cellkey(t),
      cell = this.cell(key, t),
      agg, i, n;

  cell.num += 1;
  if (this._countOnly) return;

  if (cell.store) cell.data.add(t);

  agg = cell.agg;
  for (i=0, n=agg.length; i<n; ++i) {
    agg[i].add(agg[i].get(t), t);
  }
};

prototype.rem = function(t) {
  var key = this.cellkey(t),
      cell = this.cell(key, t),
      agg, i, n;

  cell.num -= 1;
  if (this._countOnly) return;

  if (cell.store) cell.data.rem(t);

  agg = cell.agg;
  for (i=0, n=agg.length; i<n; ++i) {
    agg[i].rem(agg[i].get(t), t);
  }
};

prototype.celltuple = function(cell) {
  var tuple = cell.tuple,
      counts = this._counts,
      agg, i, n;

  // consolidate stored values
  if (cell.store) {
    cell.data.values();
  }

  // update tuple properties
  for (i=0, n=counts.length; i<n; ++i) {
    tuple[counts[i]] = cell.num;
  }
  if (!this._countOnly) {
    agg = cell.agg;
    for (i=0, n=agg.length; i<n; ++i) {
      agg[i].set();
    }
  }

  return tuple;
};

prototype.changes = function(out) {
  var adds = this._adds,
      mods = this._mods,
      prev = this._prev,
      drop = this._drop,
      add = out.add,
      rem = out.rem,
      mod = out.mod,
      cell, key, i, n;

  if (prev) for (key in prev) {
    rem.push(prev[key].tuple);
  }

  for (i=0, n=this._alen; i<n; ++i) {
    add.push(this.celltuple(adds[i]));
    adds[i] = null; // for garbage collection
  }

  for (i=0, n=this._mlen; i<n; ++i) {
    cell = mods[i];
    (cell.num === 0 && drop ? rem : mod).push(this.celltuple(cell));
    mods[i] = null; // for garbage collection
  }

  this._alen = this._mlen = 0; // reset list of active cells
  this._prev = null;
  return out;
};
<commit_msg>Fix cell access in Aggregate transform's rem (#28)<commit_after>import Transform from '../../Transform';
import TupleStore from './TupleStore';
import {createMeasure, compileMeasures} from './Measures';
import {ingest, replace} from '../../Tuple';
import {accessorName, array, error, inherits} from 'vega-util';

export var ValidAggregates = [
  'values', 'count', 'valid', 'missing', 'distinct',
  'min', 'max', 'argmin', 'argmax', 'sum', 'mean', 'average',
  'variance', 'variancep', 'stdev', 'stdevp', 'stderr',
  'median', 'q1', 'q3', 'ci0', 'ci1'
];

/**
 * Group-by aggregation operator.
 * @constructor
 * @param {object} params - The parameters for this operator.
 * @param {Array<function(object): *>} params.groupby - An array of accessors to groupby.
 * @param {Array<function(object): *>} params.fields - An array of accessors to aggregate.
 * @param {Array<string>} params.ops - An array of strings indicating aggregation operations.
 * @param {Array<string>} [params.as] - An array of output field names for aggregated values.
 * @param {boolean} [params.drop=true] - A flag indicating if empty cells should be removed.
 */
export default function Aggregate(params) {
  Transform.call(this, null, params);

  this._adds = []; // array of added output tuples
  this._mods = []; // array of modified output tuples
  this._alen = 0;  // number of active added tuples
  this._mlen = 0;  // number of active modified tuples
  this._drop = true;   // should empty aggregation cells be removed
  this._cross = false; // produce full cross-product of group-by values

  this._dims = [];   // group-by dimension accessors
  this._dnames = []; // group-by dimension names

  this._measures = []; // collection of aggregation monoids
  this._countOnly = false; // flag indicating only count aggregation
  this._counts = null; // collection of count fields
  this._prev = null;   // previous aggregation cells

  this._inputs = null;  // array of dependent input tuple field names
  this._outputs = null; // array of output tuple field names
}

var prototype = inherits(Aggregate, Transform);

prototype.transform = function(_, pulse) {
  var aggr = this,
      out = pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS),
      mod;

  this.stamp = out.stamp;

  if (this.value && ((mod = _.modified()) || pulse.modified(this._inputs))) {
    this._prev = this.value;
    this.value = mod ? this.init(_) : {};
    pulse.visit(pulse.SOURCE, function(t) { aggr.add(t); });
  } else {
    this.value = this.value || this.init(_);
    pulse.visit(pulse.REM, function(t) { aggr.rem(t); });
    pulse.visit(pulse.ADD, function(t) { aggr.add(t); });
  }

  // Indicate output fields and return aggregate tuples.
  out.modifies(this._outputs);

  // Should empty cells be dropped?
  aggr._drop = _.drop !== false;

  // If domain cross-product requested, generate empty cells as needed
  // and ensure that empty cells are not dropped
  if (_.cross && aggr._dims.length > 1) {
    aggr._drop = false;
    this.cross();
  }

  return aggr.changes(out);
};

prototype.cross = function() {
  var aggr = this,
      curr = aggr.value,
      dims = aggr._dnames,
      vals = dims.map(function() { return {}; }),
      n = dims.length;

  // collect all group-by domain values
  function collect(cells) {
    var key, i, t, v;
    for (key in cells) {
      t = cells[key].tuple;
      for (i=0; i<n; ++i) {
        vals[i][(v = t[dims[i]])] = v;
      }
    }
  }
  collect(aggr._prev);
  collect(curr);

  // iterate over key cross-product, create cells as needed
  function generate(base, tuple, index) {
    var name = dims[index],
        v = vals[index++],
        k, key;

    for (k in v) {
      tuple[name] = v[k];
      key = base ? base + '|' + k : k;
      if (index < n) generate(key, tuple, index);
      else if (!curr[key]) aggr.cell(key, tuple);
    }
  }
  generate('', {}, 0);
};

prototype.init = function(_) {
  // initialize input and output fields
  var inputs = (this._inputs = []),
      outputs = (this._outputs = []),
      inputMap = {};

  function inputVisit(get) {
    var fields = get.fields, i = 0, n = fields.length, f;
    for (; i<n; ++i) {
      if (!inputMap[f=fields[i]]) {
        inputMap[f] = 1;
        inputs.push(f);
      }
    }
  }

  // initialize group-by dimensions
  this._dims = array(_.groupby);
  this._dnames = this._dims.map(function(d) {
    var dname = accessorName(d);
    inputVisit(d);
    outputs.push(dname);
    return dname;
  });
  this.cellkey = _.key ? _.key
    : this._dims.length === 0 ? function() { return ''; }
    : this._dims.length === 1 ? this._dims[0]
    : cellkey;

  // initialize aggregate measures
  this._countOnly = true;
  this._counts = [];
  this._measures = [];

  var fields = _.fields || [null],
      ops = _.ops || ['count'],
      as = _.as || [],
      n = fields.length,
      map = {},
      field, op, m, mname, outname, i;

  if (n !== ops.length) {
    error('Unmatched number of fields and aggregate ops.');
  }

  for (i=0; i<n; ++i) {
    field = fields[i];
    op = ops[i];

    if (field == null && op !== 'count') {
      error('Null aggregate field specified.');
    }
    mname = accessorName(field);
    outname = measureName(op, mname, as[i]);
    outputs.push(outname);

    if (op === 'count') {
      this._counts.push(outname);
      continue;
    }

    m = map[mname];
    if (!m) {
      inputVisit(field);
      m = (map[mname] = []);
      m.field = field;
      this._measures.push(m);
    }

    if (op !== 'count') this._countOnly = false;
    m.push(createMeasure(op, outname));
  }

  this._measures = this._measures.map(function(m) {
    return compileMeasures(m, m.field);
  });

  return {}; // aggregation cells (this.value)
};

function measureName(op, mname, as) {
  return as || (op + (!mname ? '' : '_' + mname));
}

// -- Cell Management -----

function cellkey(x) {
  var d = this._dims,
      n = d.length, i,
      k = String(d[0](x));

  for (i=1; i<n; ++i) {
    k += '|' + d[i](x);
  }

  return k;
}

prototype.cellkey = cellkey;

prototype.cell = function(key, t) {
  var cell = this.value[key];
  if (!cell) {
    cell = this.value[key] = this.newcell(key, t);
    this._adds[this._alen++] = cell;
  } else if (cell.num === 0 && this._drop && cell.stamp < this.stamp) {
    cell.stamp = this.stamp;
    this._adds[this._alen++] = cell;
  } else if (cell.stamp < this.stamp) {
    cell.stamp = this.stamp;
    this._mods[this._mlen++] = cell;
  }
  return cell;
};

prototype.newcell = function(key, t) {
  var cell = {
    key:   key,
    num:   0,
    agg:   null,
    tuple: this.newtuple(t, this._prev && this._prev[key]),
    stamp: this.stamp,
    store: false
  };

  if (!this._countOnly) {
    var measures = this._measures,
        n = measures.length, i;

    cell.agg = Array(n);
    for (i=0; i<n; ++i) {
      cell.agg[i] = new measures[i](cell, cell.tuple);
    }
  }

  if (cell.store) {
    cell.data = new TupleStore();
  }

  return cell;
};

prototype.newtuple = function(t, p) {
  var names = this._dnames,
      dims = this._dims,
      x = {}, i, n;

  for (i=0, n=dims.length; i<n; ++i) {
    x[names[i]] = dims[i](t);
  }

  return p ? replace(p.tuple, x) : ingest(x);
};

// -- Process Tuples -----

prototype.add = function(t) {
  var key = this.cellkey(t),
      cell = this.cell(key, t),
      agg, i, n;

  cell.num += 1;
  if (this._countOnly) return;

  if (cell.store) cell.data.add(t);

  agg = cell.agg;
  for (i=0, n=agg.length; i<n; ++i) {
    agg[i].add(agg[i].get(t), t);
  }
};

prototype.rem = function(t) {
  var key = this.cellkey(t),
      cell = this.cell(key, t),
      agg, i, n;

  cell.num -= 1;
  if (this._countOnly) return;

  if (cell.store) cell.data.rem(t);

  agg = cell.agg;
  for (i=0, n=agg.length; i<n; ++i) {
    agg[i].rem(agg[i].get(t), t);
  }
};

prototype.celltuple = function(cell) {
  var tuple = cell.tuple,
      counts = this._counts,
      agg, i, n;

  // consolidate stored values
  if (cell.store) {
    cell.data.values();
  }

  // update tuple properties
  for (i=0, n=counts.length; i<n; ++i) {
    tuple[counts[i]] = cell.num;
  }
  if (!this._countOnly) {
    agg = cell.agg;
    for (i=0, n=agg.length; i<n; ++i) {
      agg[i].set();
    }
  }

  return tuple;
};

prototype.changes = function(out) {
  var adds = this._adds,
      mods = this._mods,
      prev = this._prev,
      drop = this._drop,
      add = out.add,
      rem = out.rem,
      mod = out.mod,
      cell, key, i, n;

  if (prev) for (key in prev) {
    cell = prev[key];
    if (!drop || cell.num) rem.push(cell.tuple);
  }

  for (i=0, n=this._alen; i<n; ++i) {
    add.push(this.celltuple(adds[i]));
    adds[i] = null; // for garbage collection
  }

  for (i=0, n=this._mlen; i<n; ++i) {
    cell = mods[i];
    (cell.num === 0 && drop ? rem : mod).push(this.celltuple(cell));
    mods[i] = null; // for garbage collection
  }

  this._alen = this._mlen = 0; // reset list of active cells
  this._prev = null;
  return out;
};
<|endoftext|>


<commit_before>const {app, BrowserWindow, ipcMain} = require('electron')

let mainWindow
let pickerDialog

app.on('ready', () => {
  mainWindow = new BrowserWindow({
    height: 320,
    width: 500
  });

  pickerDialog = new BrowserWindow({
    parent: mainWindow,
    modal: true,
    show: false,
    height: 340,
    width: 620
  })
  mainWindow.loadURL('file://' + __dirname + '/index.html')
  pickerDialog.loadURL('file://' + __dirname + '/picker.html')
});

ipcMain.on('show-picker', (event) => {
  pickerDialog.show()
  pickerDialog.webContents.send('get-sources')
})

ipcMain.on('source-id-selected', (event, sourceId) => {
  pickerDialog.hide()
  mainWindow.webContents.send('source-id-selected', sourceId)
})
<commit_msg>Don't show picker dialog icon on the taskbar.<commit_after>const {app, BrowserWindow, ipcMain} = require('electron')

let mainWindow
let pickerDialog

app.on('ready', () => {
  mainWindow = new BrowserWindow({
    height: 320,
    width: 500
  });

  pickerDialog = new BrowserWindow({
    parent: mainWindow,
    skipTaskbar: true,
    modal: true,
    show: false,
    height: 340,
    width: 620
  })
  mainWindow.loadURL('file://' + __dirname + '/index.html')
  pickerDialog.loadURL('file://' + __dirname + '/picker.html')
});

ipcMain.on('show-picker', (event) => {
  pickerDialog.show()
  pickerDialog.webContents.send('get-sources')
})

ipcMain.on('source-id-selected', (event, sourceId) => {
  pickerDialog.hide()
  mainWindow.webContents.send('source-id-selected', sourceId)
})
<|endoftext|>


<commit_before>const sceneName = `${Math.round(Math.random()) ? 'Normal' : 'Bright'} Living Room`
console.debug(sceneName)

const getScene = ({ name }) => name === sceneName
const isLightOn = ({ power }) => power === 'on'

const lightSettingsMatch = ({ lightSettings, sceneSettings }) => (
	lightSettings.power === sceneSettings.power
	&& lightSettings.color.hue === (sceneSettings.color.hue || 0)
	&& lightSettings.color.saturation === (sceneSettings.color.saturation || 0)
	&& lightSettings.color.kelvin === (sceneSettings.color.kelvin || 0)
	&& lightSettings.brightness === sceneSettings.brightness
)

const headers = {
	Authorization: 'Basic YzFjZDJhY2EyZDMzMmQ1NmI4MmY0ODQyNDIyN2Y5ZGIzNmY4NWE4YjU2ZWVhZmMwZjg2N2ZlMjkyMDY1ZmU4ODo='
}
const jsonHeaders = Object.assign({}, headers, {
	'Content-Type': 'application/json'
})

const getScenes = () => (
	fetch('https://api.lifx.com/v1/scenes', {
		method: 'GET',
		headers,
	})
	.then(response => response.json())
)

const getLightsInScene = scene => (
	fetch(`https://api.lifx.com/v1/lights/${scene.states.map(({ selector }) => selector).join(',')}`, {
		method: 'GET',
		headers,
	})
	.then(response => response.json())
)

const turnOnScene = ({ uuid }) => (
	fetch(`https://api.lifx.com/v1/scenes/scene_id:${uuid}/activate`, {
		method: 'PUT',
		headers: jsonHeaders,
	})
)

const turnOffScene = sceneAndLightSettings => {
	const body = JSON.stringify({
		states: (
			sceneAndLightSettings
			.map(({ lightSettings }) => lightSettings)
			.filter(isLightOn)
			.map(({ id }) => ({ selector: `id:${id}` }))
		),
		defaults: {
			power: 'off',
		},
	})

	return fetch('https://api.lifx.com/v1/lights/states', {
		method: 'PUT',
		headers: jsonHeaders,
		body,
	})
}

const toggleScene = ([lights, scene]) => {
	const sceneAndLightSettings = (
		scene.states
		.map((sceneSettings, index) => ({
			lightSettings: lights[index],
			sceneSettings,
		}))
	)

	const isSceneActive = sceneAndLightSettings.every(lightSettingsMatch)

	if (isSceneActive) {
		console.debug('turn off lights')
		return turnOffScene(sceneAndLightSettings)

	} else {
		console.debug('turn on scene')
		return turnOnScene(scene)
	}
}

const promise = (
	Promise.resolve()
	.then(getScenes)
	.then(scenes => scenes.find(getScene))
	.then(scene => Promise.all([
		getLightsInScene(scene),
		Promise.resolve(scene),
	]))
	.then(toggleScene)
)
<commit_msg>Delete toggle-scene-lights-faster.js<commit_after><|endoftext|>


<commit_before>require('./main.css');

//for hiding sidenav after click
require("font-awesome-webpack");
//require("../node_modules/materialize-css/dist/css/materialize.css")
require("../node_modules/materialize-css/dist/js/materialize.js")

require("../assets/date.format.js")

//customize right top dropdown
setTimeout(function () {
    jQuery(".dropdown-button").dropdown({hover: false, belowOrigin: true, constrain_width: false, alignment: 'right'});
}, 1);

//detect if browser is native android browser
var ua = navigator.userAgent;
var is_native_android = ((ua.indexOf('Mozilla/5.0') > -1 && ua.indexOf('Android ') > -1 && ua.indexOf('AppleWebKit') > -1) && (ua.indexOf('Version') > -1));
if(is_native_android) {
    alert('Ta przeglądarka jest niewspierana :(')
}

//=== VUE ===
var Vue = require('vue');

var Router = require('vue-router');
Vue.use(Router);

var Resource = require('vue-resource');
Vue.use(Resource);

window.permissions = [];
window.baseurl = "http://192.168.33.33:3131"

//main vm(viewmodel)
var root = Vue.extend({
    components: require('./components'),
    data: function () {
        return {
            logged: false,
            router: router,
            email: '',
            title: 'Panel',
            menu: [
                {"name": "Serwery MC", "href": "mc", perm: "", enabled: true},
                {"name": "Serwery TS3", "href": "ts3", perm: "", enabled: true},
                {"name": "Licencja", "href": "license", perm: "", enabled: true},
                {"name": "Informacje", "href": "about", perm: "", enabled: true},
                //{"name": "Strona główna", href: "", perm: "", enabled: true},
                //{"name": "Hosty", "href": "hosts", perm: "HOSTS", enabled: false},
                //{"name": "Serwery MC", "href": "hosts/mc/list", perm: "", enabled: false},
                //{"name": "Użytkownicy", "href": "users", perm: "USERS", enabled: false},
                //{"name": "Zmiana hasła", "href": "change-password", perm: "", enabled: true}
            ]
        }
    },
    methods: {
        doLogout: function () {
            delete window.localStorage.token;
            delete window.localStorage.username;
            delete window.localStorage.email;
            this.logged = false;

            //hack for working menu collapsible
            setTimeout(function () {
                jQuery('.collapsible').collapsible();
            }, 1);

            router.go('/');
        },
        routeContains: function (name) {
            var path = this.route.path;
            if (path.indexOf(name) != -1) {
                return true;
            }
            return false;
        },
        updateMenu: function(perms) {
            var menu = this.menu;

            menu.forEach(function(item) {
                if (perms.indexOf(item.perm) != -1 || item.perm == '' || perms.indexOf('ADMIN') != -1) {
                    item.enabled = true;
                } else {
                    item.enabled = false;
                }
            });
        },
        checkPerm: function(perm) {
            var permissions = window.permissions;

            if(permissions.indexOf(perm) > -1 || permissions.indexOf('ADMIN') > -1) {
                return false
            }
            //
            return false//
            //
            Materialize.toast('Brak uprawnień do wyświetlenia tej strony', 4000)
            router.replace('/')
        }
    },
    created: function () {
        if (window.localStorage.token != null) {
            this.logged = true;
            this.$http.headers.common["Authorization"] = "Bearer " + window.localStorage.token;

            //get permissions
//            this.$http.get('/api/users/info', function (data) {
//                var permissions = window.permissions;
//                var perms = data.data.permissions;
//                perms.forEach(function (item) {
//                    permissions.push(item.perm);
//                });
//
//                this.updateMenu(permissions);
//            });
        }

        if (window.localStorage.email != null) {
            this.email = window.localStorage.email;
        }
    }
});

//routing
var router = new Router({
    root: '/',
    hashbang: false
});

router.beforeEach(function (from, to) {
    //if logged
    if (window.localStorage.token != null) {
        if (to.path.indexOf('auth') != -1) {
            return false
        }
    }

    //if not logged
    if (window.localStorage.token == null) {
        if (to.path.indexOf('auth') == -1) {
            //router.replace('/auth/login');
        }
    }
});

router.map(require('./routes'));
router.start(root, 'html');
<commit_msg>Debug mode on<commit_after>require('./main.css');

//for hiding sidenav after click
require("font-awesome-webpack");
//require("../node_modules/materialize-css/dist/css/materialize.css")
require("../node_modules/materialize-css/dist/js/materialize.js")

require("../assets/date.format.js")

//customize right top dropdown
setTimeout(function () {
    jQuery(".dropdown-button").dropdown({hover: false, belowOrigin: true, constrain_width: false, alignment: 'right'});
}, 1);

//detect if browser is native android browser
var ua = navigator.userAgent;
var is_native_android = ((ua.indexOf('Mozilla/5.0') > -1 && ua.indexOf('Android ') > -1 && ua.indexOf('AppleWebKit') > -1) && (ua.indexOf('Version') > -1));
if(is_native_android) {
    alert('Twoja przeglądarka jest przestarzała, niektóre elementy mogą nie działać poprawnie')
}

//=== VUE ===
var Vue = require('vue');
Vue.config.debug = true;

var Router = require('vue-router');
Vue.use(Router);

var Resource = require('vue-resource');
Vue.use(Resource);

window.permissions = [];
window.baseurl = "http://192.168.33.33:3131"

//main vm(viewmodel)
var root = Vue.extend({
    components: require('./components'),
    data: function () {
        return {
            logged: false,
            router: router,
            email: '',
            title: 'Panel',
            menu: [
                {"name": "Serwery MC", "href": "mc", perm: "", enabled: true},
                {"name": "Serwery TS3", "href": "ts3", perm: "", enabled: true},
                {"name": "Licencja", "href": "license", perm: "", enabled: true},
                {"name": "Informacje", "href": "about", perm: "", enabled: true},
                //{"name": "Strona główna", href: "", perm: "", enabled: true},
                //{"name": "Hosty", "href": "hosts", perm: "HOSTS", enabled: false},
                //{"name": "Serwery MC", "href": "hosts/mc/list", perm: "", enabled: false},
                //{"name": "Użytkownicy", "href": "users", perm: "USERS", enabled: false},
                //{"name": "Zmiana hasła", "href": "change-password", perm: "", enabled: true}
            ]
        }
    },
    methods: {
        doLogout: function () {
            delete window.localStorage.token;
            delete window.localStorage.username;
            delete window.localStorage.email;
            this.logged = false;

            //hack for working menu collapsible
            setTimeout(function () {
                jQuery('.collapsible').collapsible();
            }, 1);

            router.go('/');
        },
        routeContains: function (name) {
            var path = this.route.path;
            if (path.indexOf(name) != -1) {
                return true;
            }
            return false;
        },
        updateMenu: function(perms) {
            var menu = this.menu;

            menu.forEach(function(item) {
                if (perms.indexOf(item.perm) != -1 || item.perm == '' || perms.indexOf('ADMIN') != -1) {
                    item.enabled = true;
                } else {
                    item.enabled = false;
                }
            });
        },
        checkPerm: function(perm) {
            var permissions = window.permissions;

            if(permissions.indexOf(perm) > -1 || permissions.indexOf('ADMIN') > -1) {
                return false
            }
            //
            return false//
            //
            Materialize.toast('Brak uprawnień do wyświetlenia tej strony', 4000)
            router.replace('/')
        }
    },
    created: function () {
        if (window.localStorage.token != null) {
            this.logged = true;
            this.$http.headers.common["Authorization"] = "Bearer " + window.localStorage.token;

            //get permissions
//            this.$http.get('/api/users/info', function (data) {
//                var permissions = window.permissions;
//                var perms = data.data.permissions;
//                perms.forEach(function (item) {
//                    permissions.push(item.perm);
//                });
//
//                this.updateMenu(permissions);
//            });
        }

        if (window.localStorage.email != null) {
            this.email = window.localStorage.email;
        }
    }
});

//routing
var router = new Router({
    root: '/',
    hashbang: false
});

router.beforeEach(function (from, to) {
    //if logged
    if (window.localStorage.token != null) {
        if (to.path.indexOf('auth') != -1) {
            return false
        }
    }

    //if not logged
    if (window.localStorage.token == null) {
        if (to.path.indexOf('auth') == -1) {
            //router.replace('/auth/login');
        }
    }
});

router.map(require('./routes'));
router.start(root, 'html');<|endoftext|>