<commit_before>let File = require('../File');
let path = require('path');
let spawn = require('child_process').spawn;
let notifier = require('node-notifier');

class StandaloneSass {
    /**
     * Create a new StandaloneSass instance.
     *
     * @param {string} src
     * @param {string} output
     * @param {object} pluginOptions
     */
    constructor(src, output, pluginOptions) {
        src = new File(path.resolve(src)).parsePath();
        output = new File(output).parsePath();

        if (output.isDir) {
            output = new File(
                path.join(output.path, src.name + '.css')
            ).parsePath();
        }

        this.src = src;
        this.output = output;
        this.pluginOptions = pluginOptions;
        this.shouldWatch = process.argv.includes('--watch');
    }

    /**
     * Run the node-sass compiler.
     */
    run() {
        this.compile();

        if (this.shouldWatch) this.watch();
    }

    /**
     * Compile Sass.
     *
     * @param {Boolean} watch
     */
    compile(watch = false) {
        let output = this.output.path;

        if (! output.startsWith(options.publicPath)) {
            output = path.join(options.publicPath, output);
        }

        this.command = spawn(
            'node-sass', [this.src.path, output].concat(this.options(watch)), { shell: true }
        );

        this.whenOutputIsAvailable((output, event) => {
            if (event === 'error') this.onFail(output);
            if (event === 'success') this.onSuccess(output);
        });

        return this;
    }

    /**
     * Fetch the node-sass options.
     *
     * @param {Boolean} watch
     */
    options(watch) {
        let sassOptions = [
            '--precision=8',
            '--output-style=' + (global.options.production ? 'compressed' : 'expanded'),
        ];

        if (watch) sassOptions.push('--watch');

        if (this.pluginOptions.includePaths) {
            this.pluginOptions.includePaths.forEach(
                path => sassOptions.push('--include-path=' + path)
            );
        }

        if (global.options.sourcemaps && ! global.options.production) {
            sassOptions.push('--source-map-embed');
        }

        return sassOptions;
    }

    /**
     * Compile Sass, while registering a watcher.
     */
    watch() {
        return this.compile(true);
    }

    /**
     * Register a callback for when output is available.
     *
     * @param {Function} callback
     */
    whenOutputIsAvailable(callback) {
        this.command.stderr.on('data', output => {
            output = output.toString();

            let event = 'change';
            if (/Error/.test(output)) event = 'error';
            if (/Wrote CSS/.test(output)) event = 'success';

            callback(output, event);
        });
    }

    /**
     * Handle successful compilation.
     *
     * @param {string} output
     */
    onSuccess(output) {
        console.log("\n");
        console.log(output);

        notifier.notify({
            title: 'Laravel Mix',
            message: 'Sass Compilation Successful',
            contentImage: 'node_modules/laravel-mix/icons/laravel.png'
        });

        global.events.fire(
            'standalone-sass-compiled', File.find(this.output.path)
        );
    }

    /**
     * Handle failed compilation.
     *
     * @param {string} output
     */
    onFail(output) {
        console.log("\n");
        console.log('Sass Compilation Failed!');
        console.log();
        console.log(output);

        notifier.notify({
            title: 'Laravel Mix',
            subtitle: 'Sass Compilation Failed',
            message: JSON.parse(output).message,
            contentImage: 'node_modules/laravel-mix/icons/laravel.png'
        });

        if (! this.shouldWatch) process.exit();
    }
}

module.exports = StandaloneSass;
<commit_msg>Fix StandaloneSass ignoring notifications option<commit_after>let File = require('../File');
let path = require('path');
let spawn = require('child_process').spawn;
let notifier = require('node-notifier');

class StandaloneSass {
    /**
     * Create a new StandaloneSass instance.
     *
     * @param {string} src
     * @param {string} output
     * @param {object} pluginOptions
     */
    constructor(src, output, pluginOptions) {
        src = new File(path.resolve(src)).parsePath();
        output = new File(output).parsePath();

        if (output.isDir) {
            output = new File(
                path.join(output.path, src.name + '.css')
            ).parsePath();
        }

        this.src = src;
        this.output = output;
        this.pluginOptions = pluginOptions;
        this.shouldWatch = process.argv.includes('--watch');
    }

    /**
     * Run the node-sass compiler.
     */
    run() {
        this.compile();

        if (this.shouldWatch) this.watch();
    }

    /**
     * Compile Sass.
     *
     * @param {Boolean} watch
     */
    compile(watch = false) {
        let output = this.output.path;

        if (! output.startsWith(options.publicPath)) {
            output = path.join(options.publicPath, output);
        }

        this.command = spawn(
            'node-sass', [this.src.path, output].concat(this.options(watch)), { shell: true }
        );

        this.whenOutputIsAvailable((output, event) => {
            if (event === 'error') this.onFail(output);
            if (event === 'success') this.onSuccess(output);
        });

        return this;
    }

    /**
     * Fetch the node-sass options.
     *
     * @param {Boolean} watch
     */
    options(watch) {
        let sassOptions = [
            '--precision=8',
            '--output-style=' + (global.options.production ? 'compressed' : 'expanded'),
        ];

        if (watch) sassOptions.push('--watch');

        if (this.pluginOptions.includePaths) {
            this.pluginOptions.includePaths.forEach(
                path => sassOptions.push('--include-path=' + path)
            );
        }

        if (global.options.sourcemaps && ! global.options.production) {
            sassOptions.push('--source-map-embed');
        }

        return sassOptions;
    }

    /**
     * Compile Sass, while registering a watcher.
     */
    watch() {
        return this.compile(true);
    }

    /**
     * Register a callback for when output is available.
     *
     * @param {Function} callback
     */
    whenOutputIsAvailable(callback) {
        this.command.stderr.on('data', output => {
            output = output.toString();

            let event = 'change';
            if (/Error/.test(output)) event = 'error';
            if (/Wrote CSS/.test(output)) event = 'success';

            callback(output, event);
        });
    }

    /**
     * Handle successful compilation.
     *
     * @param {string} output
     */
    onSuccess(output) {
        console.log("\n");
        console.log(output);

        if (global.options.notifications) {
            notifier.notify({
                title: 'Laravel Mix',
                message: 'Sass Compilation Successful',
                contentImage: 'node_modules/laravel-mix/icons/laravel.png'
            });
        }

        global.events.fire(
            'standalone-sass-compiled', File.find(this.output.path)
        );
    }

    /**
     * Handle failed compilation.
     *
     * @param {string} output
     */
    onFail(output) {
        console.log("\n");
        console.log('Sass Compilation Failed!');
        console.log();
        console.log(output);

        if (global.options.notifications) {
            notifier.notify({
                title: 'Laravel Mix',
                subtitle: 'Sass Compilation Failed',
                message: JSON.parse(output).message,
                contentImage: 'node_modules/laravel-mix/icons/laravel.png'
            });
        }

        if (! this.shouldWatch) process.exit();
    }
}

module.exports = StandaloneSass;
<|endoftext|>


<commit_before>/**
 * EffectComposer class.
 *
 * Used to feed time to shader when uniform is declared
 *
 * @constructor FORGE.EffectComposer
 * @param {string} type - effect composer type
 * @param {THREE.WebGLRenderer} renderer - WebGL renderer
 * @param {THREE.WebGLRenderTarget=} renderTarget - render target
 * @extends {THREE.EffectComposer}
 */
FORGE.EffectComposer = function(type, renderer, renderTarget)
{
    /**
     * Effect composer type
     * @name FORGE.EffectComposer#_type
     * @type {string}
     * @private
     */
    this._type = type || FORGE.EffectComposerType.RENDER;

    /**
     * Rendering target
     * @name FORGE.EffectComposer#_renderTarget
     * @type {?THREE.WebGLRenderTarget}
     * @private
     */
    this._renderTarget = renderTarget || null;

    /**
     * Name
     * @name FORGE.EffectComposer#_name
     * @type {string}
     * @private
     */
    this._name = "";

    /**
     * Enabled flag
     * @name FORGE.EffectComposer#_enabled
     * @type {boolean}
     * @private
     */
    this._enabled = true;

    /**
     * Sum of clock deltas.
     * @name FORGE.ShaderPass#_deltaSum
     * @type {number}
     * @private
     */
    this._deltaSum = 0;

    THREE.EffectComposer.call(this, renderer, renderTarget);

    this._boot();
};

FORGE.EffectComposer.prototype = Object.create(THREE.EffectComposer.prototype);
FORGE.EffectComposer.prototype.constructor = FORGE.EffectComposer;

/**
 * Boot sequence
 * @method FORGE.EffectComposer#_boot
 * @private
 */
FORGE.EffectComposer.prototype._boot = function()
{
    this._name = FORGE.EffectComposer.getUniqueName(this._type);
};

/**
 * Render
 * Set time for all passes
 * @method FORGE.EffectComposer#render
 */
FORGE.EffectComposer.prototype.render = function(delta)
{
    this._deltaSum += delta;

    var time = this._deltaSum;
    for (var i=0, ii=this.passes.length; i<ii; i++)
    {
        var pass = this.passes[i];

        if (typeof pass.uniforms !== "undefined")
        {
            if (typeof pass.uniforms.time !== "undefined")
            {
                pass.uniforms.time.value = time;
            }
        }

        if (typeof pass.time !== "undefined")
        {
            pass.time = time;
        }
    }
    THREE.EffectComposer.prototype.render.call(this, delta);
};

/**
 * Destroy sequence
 * @method FORGE.EffectComposer#destroy
 */
FORGE.EffectComposer.prototype.destroy = function()
{
    this._renderTarget = null;

    this.writeBuffer.dispose();
    this.writeBuffer = null;

    this.readBuffer.dispose();
    this.readBuffer = null;
};

/**
 * Static EffectComposer uid
 * @name FORGE.EffectComposer#uid
 * @type {number}
 */
FORGE.EffectComposer.uid = 0;

/**
 * Get EffectComposer unique name
 * @name FORGE.EffectComposer#getUniqueName
 * @param {string} type effect composer type
 * @return {string} unique name
 */
FORGE.EffectComposer.getUniqueName = function(type)
{
    return "FORGE.EffectComposer." + type + "." + (FORGE.EffectComposer.uid++);
};

/**
 * Get EffectComposer type
 * @name FORGE.EffectComposer#type
 * @type {string}
 */
Object.defineProperty(FORGE.EffectComposer.prototype, "type",
{
    /** @this {FORGE.EffectComposer} */
    get: function()
    {
        return this._type;
    }
});

/**
 * EffectComposer render target
 * @name FORGE.EffectComposer#renderTarget
 * @type {THREE.WebGLRenderTarget}
 */
Object.defineProperty(FORGE.EffectComposer.prototype, "renderTarget",
{
    /** @this {FORGE.EffectComposer} */
    get: function()
    {
        return this.readBuffer;
    },

    /** @this {FORGE.EffectComposer} */
    set: function(value)
    {
        if (this.readBuffer !== null)
        {
            this.readBuffer.dispose();
        }
        this.readBuffer = value;
    }
});

/**
 * EffectComposer enabled flag
 * @name FORGE.EffectComposer#enabled
 * @type {boolean}
 */
Object.defineProperty(FORGE.EffectComposer.prototype, "enabled",
{
    /** @this {FORGE.EffectComposer} */
    get: function()
    {
        return this._enabled;
    },

    /** @this {FORGE.EffectComposer} */
    set: function(value)
    {
        this._enabled = value;
    }
});

/**
 * Get EffectComposer name
 * @name FORGE.EffectComposer#name
 * @type {string}
 */
Object.defineProperty(FORGE.EffectComposer.prototype, "name",
{
    /** @this {FORGE.EffectComposer} */
    get: function()
    {
        return this._name;
    }
});
<commit_msg>Code cleaning<commit_after>/**
 * EffectComposer class.
 *
 * Used to feed time to shader when uniform is declared
 *
 * @constructor FORGE.EffectComposer
 * @param {string} type - effect composer type
 * @param {THREE.WebGLRenderer} renderer - WebGL renderer
 * @param {THREE.WebGLRenderTarget=} renderTarget - render target
 * @extends {THREE.EffectComposer}
 */
FORGE.EffectComposer = function(type, renderer, renderTarget)
{
    /**
     * Effect composer type
     * @name FORGE.EffectComposer#_type
     * @type {string}
     * @private
     */
    this._type = type || FORGE.EffectComposerType.RENDER;

    /**
     * Rendering target
     * @name FORGE.EffectComposer#_renderTarget
     * @type {?THREE.WebGLRenderTarget}
     * @private
     */
    this._renderTarget = renderTarget || null;

    /**
     * Name
     * @name FORGE.EffectComposer#_name
     * @type {string}
     * @private
     */
    this._name = "";

    /**
     * Enabled flag
     * @name FORGE.EffectComposer#_enabled
     * @type {boolean}
     * @private
     */
    this._enabled = true;

    /**
     * Sum of clock deltas.
     * @name FORGE.ShaderPass#_deltaSum
     * @type {number}
     * @private
     */
    this._deltaSum = 0;

    THREE.EffectComposer.call(this, renderer, renderTarget);

    this._boot();
};

FORGE.EffectComposer.prototype = Object.create(THREE.EffectComposer.prototype);
FORGE.EffectComposer.prototype.constructor = FORGE.EffectComposer;

/**
 * Boot sequence
 * @method FORGE.EffectComposer#_boot
 * @private
 */
FORGE.EffectComposer.prototype._boot = function()
{
    this._name = FORGE.EffectComposer.getUniqueName(this._type);
};

/**
 * Render
 * Set time for all passes
 * @method FORGE.EffectComposer#render
 */
FORGE.EffectComposer.prototype.render = function(delta)
{
    this._deltaSum += delta;
    var time = this._deltaSum;

    for (var i=0, ii=this.passes.length; i<ii; i++)
    {
        var pass = this.passes[i];

        if (typeof pass.uniforms !== "undefined")
        {
            if (typeof pass.uniforms.time !== "undefined")
            {
                pass.uniforms.time.value = time;
            }
        }

        if (typeof pass.time !== "undefined")
        {
            pass.time = time;
        }
    }

    THREE.EffectComposer.prototype.render.call(this, delta);
};

/**
 * Destroy sequence
 * @method FORGE.EffectComposer#destroy
 */
FORGE.EffectComposer.prototype.destroy = function()
{
    this._renderTarget = null;

    this.writeBuffer.dispose();
    this.writeBuffer = null;

    this.readBuffer.dispose();
    this.readBuffer = null;
};

/**
 * Static EffectComposer uid
 * @name FORGE.EffectComposer#uid
 * @type {number}
 */
FORGE.EffectComposer.uid = 0;

/**
 * Get EffectComposer unique name
 * @name FORGE.EffectComposer#getUniqueName
 * @param {string} type effect composer type
 * @return {string} unique name
 */
FORGE.EffectComposer.getUniqueName = function(type)
{
    return "FORGE.EffectComposer." + type + "." + (FORGE.EffectComposer.uid++);
};

/**
 * Get EffectComposer type
 * @name FORGE.EffectComposer#type
 * @type {string}
 */
Object.defineProperty(FORGE.EffectComposer.prototype, "type",
{
    /** @this {FORGE.EffectComposer} */
    get: function()
    {
        return this._type;
    }
});

/**
 * EffectComposer render target
 * @name FORGE.EffectComposer#renderTarget
 * @type {THREE.WebGLRenderTarget}
 */
Object.defineProperty(FORGE.EffectComposer.prototype, "renderTarget",
{
    /** @this {FORGE.EffectComposer} */
    get: function()
    {
        return this.readBuffer;
    },

    /** @this {FORGE.EffectComposer} */
    set: function(value)
    {
        if (this.readBuffer !== null)
        {
            this.readBuffer.dispose();
        }
        this.readBuffer = value;
    }
});

/**
 * EffectComposer enabled flag
 * @name FORGE.EffectComposer#enabled
 * @type {boolean}
 */
Object.defineProperty(FORGE.EffectComposer.prototype, "enabled",
{
    /** @this {FORGE.EffectComposer} */
    get: function()
    {
        return this._enabled;
    },

    /** @this {FORGE.EffectComposer} */
    set: function(value)
    {
        this._enabled = value;
    }
});

/**
 * Get EffectComposer name
 * @name FORGE.EffectComposer#name
 * @type {string}
 */
Object.defineProperty(FORGE.EffectComposer.prototype, "name",
{
    /** @this {FORGE.EffectComposer} */
    get: function()
    {
        return this._name;
    }
});
<|endoftext|>


<commit_before>/**
 * For the takeEval and preview views
 */
$(document).ready(function() {
    $("div.JSevalComment").evalComment();   //Bind comment boxes toggle link action
    var instrSel = $('div[@rel=evalinstructorSelector]');
    var assSel = $('div[@rel=evalassistantSelector]');
    instrSel.evalSelector({type:0});
    assSel.evalSelector({type:1});
    $('[id=form-branch::submitEvaluation]').bind('click', function() {
        var valid;
        if (instrSel.find('input[type=checkbox]').length !== 0) {
            var selectedInstrDomArray = instrSel.find('input:checked').get();
            if (selectedInstrDomArray.length > 0) {
                instrSel.find("fieldset").css({
                    background:'#fff'
                });
            } else {
                return  error("LECTURER", instrSel);
            }
        }
        if (assSel.find('input[type=checkbox]').length !== 0) {
            var selectedassistantDomArray = assSel.find('input:checked').get();
            if (selectedassistantDomArray.length > 0) {
                assSel.find("fieldset").css({
                    background:'#fff'
                });
			} else {
                return error("TUTOR", assSel);
            }
        }
        if (assSel.find('select').length !== 0) {
            valid = true;
            assSel.find('select').each(function() {
                if (this.selectedIndex === 0) {
                    valid = false;
                }
            });
            if (!valid) {
                return error("TUTOR", assSel);
            } else {
                assSel.find("fieldset").css({
                    background:'#fff'
                });
            }
        }
        if (instrSel.find('select').length !== 0) {
            valid = true;
            instrSel.find('select').each(function() {
                if (this.selectedIndex === 0) {
                    valid = false;
                }
            });
            if (!valid) {
                return  error("LECTURER", instrSel);
            } else {
                instrSel.find("fieldset").css({
                    background:'#fff'
                });
            }
        }
        $(this).hide();
        $('input[name=submit_process]').show();
    });

    function error(type, that) {
        alert('Please evaluate at least one ' + type + '.');
        that.find("fieldset").css({
            background:'#fee'
        });
        return false;
    }

});

(function($) {
    $.fn.evalSelector = function(opts) {
        var options = $.extend({}, $.fn.evalSelector.settings, opts);
        init($(this), options);
    };
    /**
     * Public variables. Once init() has ran, do not reference directly to these, use variables.options instead.
     */
    $.fn.evalSelector.settings = {
        css:{
            activeCheckbox: {background:'#eee'}
        },
        type: 1, //Type is for type of category we are handling. ie: 0 = instructor, 1 = assistant (TA)
        debug: false,
        fields: ['input', 'select', 'textarea'] //Array of fields in the form
    };
    /**
     * Private methods and variables
     */

    var variables = {
        typeOfSelector:{
            one: false,
            multiple: false
        },
        questionsToShow: [],
        questionsToHide: [],
        get:{
            typeOfBranch:function() {
                //log("Active code type is: " + variables.options.type);
                switch (variables.options.type) {
                    case 0: return "instructor";
                    case 1: return "assistant";
                }
            } ,
            shownQuestions: function() {
                //log("Getting questions for type: " + variables.get.typeOfBranch());
                var str = 'div.' + variables.get.typeOfBranch() + 'Branch:visible';
                var temp = [];
                $.each($(str).get(), function(i, item) {
                    temp.push($(item).attr("name"));
                    //log("Search found: " + $(item).attr("name"));
                });
                //log("Search found total: " + temp.length);
                return temp;
            },

            selectedBoxesArray:function(that) {
                var checked = [];
                that.find('input[@type=checkbox]').each(function() {
                    if (this.checked){
                        checked.push(this);
                    }
                });
                //log("Found " + checked.length + " checked boxes");
                return checked;
            } ,
            selectedBoxesBool:function(that) {
                return variables.get.selectedBoxesArray(that).length > 0;
            }
        },
        set:{
            typeOfBranch:function(that) {
                var temp;
                if (that.attr('name').search(/instructor/i) != -1){
                    temp = 0;
                }
                else if (that.attr('name').search(/assistant/i) != -1){
                    temp = 1;
                }
                variables.options.type = temp;
                //log("Active type is: " + variables.get.typeOfBranch());

            }
        },
        options:null,
        savedIds:[],
        that:null,
        foundArray: function() {
            var temp = [];
            $.each(variables.questionsToShow, function(s, shown) {
                //log("Checking if " + shown + " is already showing in dom. Dom has:" + variables.get.shownQuestions().length + " visible.");
                $.each(variables.get.shownQuestions(), function(h, hidden) {
                    if (shown == hidden) {
                        temp.push(shown);
                        //log("Found visible field: " + shown);
                    }
                });
            });
            return temp;
        },
        foundBool: function() {
            var temp = variables.foundArray();
            //log("Found " + temp.length + " with IDs: " + temp.toString());
            return (temp.length > 0);
        },
        foundSplice:function(item) {
            if (variables.foundBool()) {
                $.each(variables.questionsToShow, function(s, show) {
                    if (show == item) {
                        variables.questionsToShow.splice(parseInt(s, 10), 1);
                        //log("Spliced: " + show + " from selected list.");
                        return true;
                    }
                });
            }
            return false;
        },
        isVisible:function(item) {
            var visible = false;
            if (variables.foundBool) {
                $.each(variables.get.shownQuestions(), function(i, found) {
                    if (item == found) {
                        visible = true;
                    }
                });
            }
            return visible;
        }
    };

    function init(that, options) {
        //Handle reSelecting previous selections
        $.each(['instructor','assistant'], function(i, type) {

            $('div[@rel=eval' + type + 'Selector] input[type=checkbox]:checked').each(function() {
                var _id = $(this).val();
                $('div[name=' + _id + '].' + type + 'Branch').show();
                frameGrow($('div[name=' + _id + '].' + type + 'Branch').height(), 'grow');
            });

            var index = 0;
            $('div[@rel=eval' + type + 'Selector]').find('select').each(function() {
                index = this.selectedIndex;
            });
            if (index !== 0) {
                var _id = $('div[@rel=eval' + type + 'Selector]').find('select').find('option').eq(index);
                $('div[name=' + $(_id).val() + '].' + type + 'Branch').show();
                frameGrow($('div[name=' + _id + '].' + type + 'Branch').height(), 'grow');
            }

        });

        //copy options to this class
        variables.options = options;
        var temp = $('input#selectedPeopleInResponse').val();
        variables.savedIds = typeof temp === "undefined" ? '' : temp.replace('[', '').replace(']', '').split(', ');
        return that.each(function() {
            if ($(this).find('select').length > 0) {
                variables.typeOfSelector.one = true;
                //log("Found a selector for: " + variables.get.typeOfBranch());
            } else {
                variables.typeOfSelector.multiple = true;
                //log("Found a checkbox list for: " + variables.get.typeOfBranch());
            }
            initControls($(this));
            initClassVars();
        });
    }

    function initClassVars() {
        variables.questionsToHide = [];
        variables.questionsToShow = [];
        variables.savedIds = [];
        variables.that = null;
    }

    function initControls(that) {
        variables.that = that;
        if (variables.typeOfSelector.multiple) {
            //Working with checkboxes
            that.find('input[type=checkbox]').each(function() {
                var elem = $(this);
                var elemId = elem.val();
                var elemLabel = elem.parent().find('label').text();
                //log("Attaching event listener for: " + elemLabel + " with id: " + elemId);
                elem.bind('click', function() {
                    variables.set.typeOfBranch($(this));
                    if (this.checked) {
                        //Fn for Check
                        elem.parent().css('background', variables.options.css.activeCheckbox.background);
                        //log("SELECTED: " + elemLabel + " with id: " + elemId);
                        if (!variables.isVisible(elemId)) {
                            variables.questionsToShow.push(elemId);
                            //log("ADDED: " + elemLabel + " with id: " + elemId);
                            showQuestions();
                            initClassVars();
                        } else {
                            //log("Person: " + elemLabel + " with id: " + elemId + " is already visible.");
                        }
                    }
                    else {
                        this.checked = true;
                        if (variables.isVisible(elemId) && confirmSelection(elemLabel)) {
                            elem.parent().css('background', '');
                            //log("DESELECTED: " + elemLabel + " with id: " + elemId);
                            variables.questionsToHide.push(elemId);
                            variables.foundSplice(elemId);
                            //log("DELETED: " + elemLabel + " with id: " + elemId);
                            showQuestions();
                            initClassVars();
                            this.checked = false;
                        }
                    }
                });
                checkSavedPeople(elemId, this, '', 'checkbox');
            });
        }
        var elem = that.find('select');
        $.each(elem.find('option'), function(i, item) {
            //checkValidity($(item).val(), item, i);
            checkSavedPeople($(item).val(), item, i, 'select');
        });
        elem.bind('change', function() {
            variables.set.typeOfBranch(elem);
            if (variables.typeOfSelector.one) {
                //Working with dropdown
                var elemId = elem.val();
                var render = false;
                //log("Selected guy with id: " + elemId);
                if (variables.get.shownQuestions().length === 0) {
                    render = true;
                }
                else if (variables.isVisible(elemId)) {
                    //log("Person with id: " + elemId + " is already visible.");
                    return false;
                } else
                {
                    var temp = 'div[name=' + variables.get.shownQuestions()[0] + '].' + variables.get.typeOfBranch() + 'Branch';
                    render = confirmSelection($(temp).find('legend').attr('title'));
                }
                if (render) {
                    variables.questionsToHide = variables.get.shownQuestions();
                    variables.questionsToShow = [];
                    variables.questionsToShow.push(elemId);
                    //log("Added item " + elemId + " to array. Now Array has this number of elements: " + variables.questionsToShow.length);
                    showQuestions();
                    initClassVars();
                }
            }
        });
    }

    function showQuestions() {
        hideQuestions(0);
        //log("Showing " + variables.questionsToShow.length + " items in dom.");
        $.each(variables.questionsToShow, function(i, item) {
            var tempFound = 0;
            $.each(variables.get.shownQuestions(), function(s, toSkip) {
                if (item == toSkip) {
                    tempFound++;
                }
            });
            if (tempFound === 0) {
                var str = 'div[name=' + item + '].' + variables.get.typeOfBranch() + 'Branch';
                frameGrow($(str).height(), 'grow');
                $(str).slideDown('normal');
            }
        });
    }

    function hideQuestions(all) {
        var temp = [];
        temp = (all && all == 1) ? variables.get.shownQuestions() : variables.questionsToHide;
        $.each(temp, function(i, item) {
            var str = 'div[name=' + item + '].' + variables.get.typeOfBranch() + 'Branch';
            $(str).slideUp('normal', function() {
                //log("WARN: Hiding " + item + " in dom.");
                clearFieldsFor($(this));
            });
            frameGrow($(str).height(), 'shrink');
        });
    }

    function confirmSelection(name) {
        return confirm($('div#evalSelectWarn').text().replace(/XXX/, name));
    }

    function clearFieldsFor(item) {
        item.find('div.validFail').removeClass('validFail');
        $.each(variables.options.fields, function(f, field) {
            //log("Clearing all " + field.toLowerCase() + " fields.");
            item.find(field.toLowerCase()).each(function() {
                var t = this.type, tag = this.tagName.toLowerCase();
                if (t == 'text' || t == 'password' || tag == 'textarea'){
                    this.value = '';
                }
                else if (t == 'checkbox' || t == 'radio'){
                    this.checked = false;
                }
                else if (tag == 'select'){
                        this.selectedIndex = -1;
                }
            });
        });
    }

    function checkSavedPeople(elemId, that, num, tag) {
        var savedIds = variables.savedIds;
        if (savedIds.length > 0) {
            for (var i = 0; i < savedIds.length; i++) {
                if (elemId == savedIds[i]) {
                    if (tag == 'checkbox') {
                        that.checked = true;
                    }
                    if (tag == 'select') {
                        variables.that.find('select:eq(0)').each(function() {
                            this.selectedIndex = (parseInt(num, 10));
                        });
                    }
                }
            }
        }
    }

    function frameGrow(height, updown){
        var h = height == "" ? 250 : parseInt(height, 10),
            windowName = window.name,
            frame = null;
        if (windowName !== null && windowName.length > 0){
            frame = parent.document.getElementById(windowName);
            try {
                if (frame){
                    var clientH;
                    if (updown == 'shrink'){
                        clientH = document.body.clientHeight - h;
                    }else{
                        clientH = document.body.clientHeight + h;
                    }
                    $(frame).height(clientH);
                }
            } catch(e) {}
        }
    }

    // Debugging
    function log($obj) {
        if (variables.options.debug) {
            if (window.console && window.console.log) {
                window.console.log('INFO: ' + $obj);
            }
        }
    }
})($);
<commit_msg>EVALSYS-914 merge-updates: make take eval JS use fieldset and legend classes not tag names.<commit_after>/**
 * For the takeEval and preview views
 */
$(document).ready(function() {
    $("div.JSevalComment").evalComment();   //Bind comment boxes toggle link action
    var instrSel = $('div[@rel=evalinstructorSelector]');
    var assSel = $('div[@rel=evalassistantSelector]');
    instrSel.evalSelector({type:0});
    assSel.evalSelector({type:1});
    $('[id=form-branch::submitEvaluation]').bind('click', function() {
        var valid;
        if (instrSel.find('input[type=checkbox]').length !== 0) {
            var selectedInstrDomArray = instrSel.find('input:checked').get();
            if (selectedInstrDomArray.length > 0) {
                instrSel.find("div.fieldset").css({
                    background:'#fff'
                });
            } else {
                return  error("LECTURER", instrSel);
            }
        }
        if (assSel.find('input[type=checkbox]').length !== 0) {
            var selectedassistantDomArray = assSel.find('input:checked').get();
            if (selectedassistantDomArray.length > 0) {
                assSel.find("div.fieldset").css({
                    background:'#fff'
                });
			} else {
                return error("TUTOR", assSel);
            }
        }
        if (assSel.find('select').length !== 0) {
            valid = true;
            assSel.find('select').each(function() {
                if (this.selectedIndex === 0) {
                    valid = false;
                }
            });
            if (!valid) {
                return error("TUTOR", assSel);
            } else {
                assSel.find("div.fieldset").css({
                    background:'#fff'
                });
            }
        }
        if (instrSel.find('select').length !== 0) {
            valid = true;
            instrSel.find('select').each(function() {
                if (this.selectedIndex === 0) {
                    valid = false;
                }
            });
            if (!valid) {
                return  error("LECTURER", instrSel);
            } else {
                instrSel.find("div.fieldset").css({
                    background:'#fff'
                });
            }
        }
        $(this).hide();
        $('input[name=submit_process]').show();
    });

    function error(type, that) {
        alert('Please evaluate at least one ' + type + '.');
        that.find("div.fieldset").css({
            background:'#fee'
        });
        return false;
    }

});

(function($) {
    $.fn.evalSelector = function(opts) {
        var options = $.extend({}, $.fn.evalSelector.settings, opts);
        init($(this), options);
    };
    /**
     * Public variables. Once init() has ran, do not reference directly to these, use variables.options instead.
     */
    $.fn.evalSelector.settings = {
        css:{
            activeCheckbox: {background:'#eee'}
        },
        type: 1, //Type is for type of category we are handling. ie: 0 = instructor, 1 = assistant (TA)
        debug: false,
        fields: ['input', 'select', 'textarea'] //Array of fields in the form
    };
    /**
     * Private methods and variables
     */

    var variables = {
        typeOfSelector:{
            one: false,
            multiple: false
        },
        questionsToShow: [],
        questionsToHide: [],
        get:{
            typeOfBranch:function() {
                //log("Active code type is: " + variables.options.type);
                switch (variables.options.type) {
                    case 0: return "instructor";
                    case 1: return "assistant";
                }
            } ,
            shownQuestions: function() {
                //log("Getting questions for type: " + variables.get.typeOfBranch());
                var str = 'div.' + variables.get.typeOfBranch() + 'Branch:visible';
                var temp = [];
                $.each($(str).get(), function(i, item) {
                    temp.push($(item).attr("name"));
                    //log("Search found: " + $(item).attr("name"));
                });
                //log("Search found total: " + temp.length);
                return temp;
            },

            selectedBoxesArray:function(that) {
                var checked = [];
                that.find('input[@type=checkbox]').each(function() {
                    if (this.checked){
                        checked.push(this);
                    }
                });
                //log("Found " + checked.length + " checked boxes");
                return checked;
            } ,
            selectedBoxesBool:function(that) {
                return variables.get.selectedBoxesArray(that).length > 0;
            }
        },
        set:{
            typeOfBranch:function(that) {
                var temp;
                if (that.attr('name').search(/instructor/i) != -1){
                    temp = 0;
                }
                else if (that.attr('name').search(/assistant/i) != -1){
                    temp = 1;
                }
                variables.options.type = temp;
                //log("Active type is: " + variables.get.typeOfBranch());

            }
        },
        options:null,
        savedIds:[],
        that:null,
        foundArray: function() {
            var temp = [];
            $.each(variables.questionsToShow, function(s, shown) {
                //log("Checking if " + shown + " is already showing in dom. Dom has:" + variables.get.shownQuestions().length + " visible.");
                $.each(variables.get.shownQuestions(), function(h, hidden) {
                    if (shown == hidden) {
                        temp.push(shown);
                        //log("Found visible field: " + shown);
                    }
                });
            });
            return temp;
        },
        foundBool: function() {
            var temp = variables.foundArray();
            //log("Found " + temp.length + " with IDs: " + temp.toString());
            return (temp.length > 0);
        },
        foundSplice:function(item) {
            if (variables.foundBool()) {
                $.each(variables.questionsToShow, function(s, show) {
                    if (show == item) {
                        variables.questionsToShow.splice(parseInt(s, 10), 1);
                        //log("Spliced: " + show + " from selected list.");
                        return true;
                    }
                });
            }
            return false;
        },
        isVisible:function(item) {
            var visible = false;
            if (variables.foundBool) {
                $.each(variables.get.shownQuestions(), function(i, found) {
                    if (item == found) {
                        visible = true;
                    }
                });
            }
            return visible;
        }
    };

    function init(that, options) {
        //Handle reSelecting previous selections
        $.each(['instructor','assistant'], function(i, type) {

            $('div[@rel=eval' + type + 'Selector] input[type=checkbox]:checked').each(function() {
                var _id = $(this).val();
                $('div[name=' + _id + '].' + type + 'Branch').show();
                frameGrow($('div[name=' + _id + '].' + type + 'Branch').height(), 'grow');
            });

            var index = 0;
            $('div[@rel=eval' + type + 'Selector]').find('select').each(function() {
                index = this.selectedIndex;
            });
            if (index !== 0) {
                var _id = $('div[@rel=eval' + type + 'Selector]').find('select').find('option').eq(index);
                $('div[name=' + $(_id).val() + '].' + type + 'Branch').show();
                frameGrow($('div[name=' + _id + '].' + type + 'Branch').height(), 'grow');
            }

        });

        //copy options to this class
        variables.options = options;
        var temp = $('input#selectedPeopleInResponse').val();
        variables.savedIds = typeof temp === "undefined" ? '' : temp.replace('[', '').replace(']', '').split(', ');
        return that.each(function() {
            if ($(this).find('select').length > 0) {
                variables.typeOfSelector.one = true;
                //log("Found a selector for: " + variables.get.typeOfBranch());
            } else {
                variables.typeOfSelector.multiple = true;
                //log("Found a checkbox list for: " + variables.get.typeOfBranch());
            }
            initControls($(this));
            initClassVars();
        });
    }

    function initClassVars() {
        variables.questionsToHide = [];
        variables.questionsToShow = [];
        variables.savedIds = [];
        variables.that = null;
    }

    function initControls(that) {
        variables.that = that;
        if (variables.typeOfSelector.multiple) {
            //Working with checkboxes
            that.find('input[type=checkbox]').each(function() {
                var elem = $(this);
                var elemId = elem.val();
                var elemLabel = elem.parent().find('label').text();
                //log("Attaching event listener for: " + elemLabel + " with id: " + elemId);
                elem.bind('click', function() {
                    variables.set.typeOfBranch($(this));
                    if (this.checked) {
                        //Fn for Check
                        elem.parent().css('background', variables.options.css.activeCheckbox.background);
                        //log("SELECTED: " + elemLabel + " with id: " + elemId);
                        if (!variables.isVisible(elemId)) {
                            variables.questionsToShow.push(elemId);
                            //log("ADDED: " + elemLabel + " with id: " + elemId);
                            showQuestions();
                            initClassVars();
                        } else {
                            //log("Person: " + elemLabel + " with id: " + elemId + " is already visible.");
                        }
                    }
                    else {
                        this.checked = true;
                        if (variables.isVisible(elemId) && confirmSelection(elemLabel)) {
                            elem.parent().css('background', '');
                            //log("DESELECTED: " + elemLabel + " with id: " + elemId);
                            variables.questionsToHide.push(elemId);
                            variables.foundSplice(elemId);
                            //log("DELETED: " + elemLabel + " with id: " + elemId);
                            showQuestions();
                            initClassVars();
                            this.checked = false;
                        }
                    }
                });
                checkSavedPeople(elemId, this, '', 'checkbox');
            });
        }
        var elem = that.find('select');
        $.each(elem.find('option'), function(i, item) {
            //checkValidity($(item).val(), item, i);
            checkSavedPeople($(item).val(), item, i, 'select');
        });
        elem.bind('change', function() {
            variables.set.typeOfBranch(elem);
            if (variables.typeOfSelector.one) {
                //Working with dropdown
                var elemId = elem.val();
                var render = false;
                //log("Selected guy with id: " + elemId);
                if (variables.get.shownQuestions().length === 0) {
                    render = true;
                }
                else if (variables.isVisible(elemId)) {
                    //log("Person with id: " + elemId + " is already visible.");
                    return false;
                } else
                {
                    var temp = 'div[name=' + variables.get.shownQuestions()[0] + '].' + variables.get.typeOfBranch() + 'Branch';
                    render = confirmSelection($(temp).find('.legend').attr('title'));
                }
                if (render) {
                    variables.questionsToHide = variables.get.shownQuestions();
                    variables.questionsToShow = [];
                    variables.questionsToShow.push(elemId);
                    //log("Added item " + elemId + " to array. Now Array has this number of elements: " + variables.questionsToShow.length);
                    showQuestions();
                    initClassVars();
                }
            }
        });
    }

    function showQuestions() {
        hideQuestions(0);
        //log("Showing " + variables.questionsToShow.length + " items in dom.");
        $.each(variables.questionsToShow, function(i, item) {
            var tempFound = 0;
            $.each(variables.get.shownQuestions(), function(s, toSkip) {
                if (item == toSkip) {
                    tempFound++;
                }
            });
            if (tempFound === 0) {
                var str = 'div[name=' + item + '].' + variables.get.typeOfBranch() + 'Branch';
                frameGrow($(str).height(), 'grow');
                $(str).slideDown('normal');
            }
        });
    }

    function hideQuestions(all) {
        var temp = [];
        temp = (all && all == 1) ? variables.get.shownQuestions() : variables.questionsToHide;
        $.each(temp, function(i, item) {
            var str = 'div[name=' + item + '].' + variables.get.typeOfBranch() + 'Branch';
            $(str).slideUp('normal', function() {
                //log("WARN: Hiding " + item + " in dom.");
                clearFieldsFor($(this));
            });
            frameGrow($(str).height(), 'shrink');
        });
    }

    function confirmSelection(name) {
        return confirm($('div#evalSelectWarn').text().replace(/XXX/, name));
    }

    function clearFieldsFor(item) {
        item.find('div.validFail').removeClass('validFail');
        $.each(variables.options.fields, function(f, field) {
            //log("Clearing all " + field.toLowerCase() + " fields.");
            item.find(field.toLowerCase()).each(function() {
                var t = this.type, tag = this.tagName.toLowerCase();
                if (t == 'text' || t == 'password' || tag == 'textarea'){
                    this.value = '';
                }
                else if (t == 'checkbox' || t == 'radio'){
                    this.checked = false;
                }
                else if (tag == 'select'){
                        this.selectedIndex = -1;
                }
            });
        });
    }

    function checkSavedPeople(elemId, that, num, tag) {
        var savedIds = variables.savedIds;
        if (savedIds.length > 0) {
            for (var i = 0; i < savedIds.length; i++) {
                if (elemId == savedIds[i]) {
                    if (tag == 'checkbox') {
                        that.checked = true;
                    }
                    if (tag == 'select') {
                        variables.that.find('select:eq(0)').each(function() {
                            this.selectedIndex = (parseInt(num, 10));
                        });
                    }
                }
            }
        }
    }

    function frameGrow(height, updown){
        var h = height == "" ? 250 : parseInt(height, 10),
            windowName = window.name,
            frame = null;
        if (windowName !== null && windowName.length > 0){
            frame = parent.document.getElementById(windowName);
            try {
                if (frame){
                    var clientH;
                    if (updown == 'shrink'){
                        clientH = document.body.clientHeight - h;
                    }else{
                        clientH = document.body.clientHeight + h;
                    }
                    $(frame).height(clientH);
                }
            } catch(e) {}
        }
    }

    // Debugging
    function log($obj) {
        if (variables.options.debug) {
            if (window.console && window.console.log) {
                window.console.log('INFO: ' + $obj);
            }
        }
    }
})($);
<|endoftext|>


<commit_before>var config    = require("./config/config")
  , Sequelize = require("../index")
  , sequelize = new Sequelize(config.database, config.username, config.password, { logging: false })
  , Helpers   = new (require("./config/helpers"))(sequelize)

describe('Associations', function() {
  beforeEach(function() { Helpers.sync() })
  afterEach(function() { Helpers.drop() })

  /////////// many-to-many with same prefix ////////////

  describe('many-to-many', function() {
    describe('where tables have the same prefix', function() {
      var Table2 = sequelize.define('wp_table2', {foo: Sequelize.STRING})
        , Table1 = sequelize.define('wp_table1', {foo: Sequelize.STRING})

      Table1.hasMany(Table2)
      Table2.hasMany(Table1)

      it("should create a table wp_table1wp_table2s", function() {
        expect(sequelize.modelManager.getModel('wp_table1swp_table2s')).toBeDefined()
      })
    })
  })

})
<commit_msg>async<commit_after>var config    = require("./config/config")
  , Sequelize = require("../index")
  , sequelize = new Sequelize(config.database, config.username, config.password, { logging: false })
  , Helpers   = new (require("./config/helpers"))(sequelize)

describe('Associations', function() {
  beforeEach(function() { Helpers.sync() })
  afterEach(function() { Helpers.drop() })

  /////////// many-to-many with same prefix ////////////

  describe('many-to-many', function() {
    describe('where tables have the same prefix', function() {
      var Table2 = sequelize.define('wp_table2', {foo: Sequelize.STRING})
        , Table1 = sequelize.define('wp_table1', {foo: Sequelize.STRING})

      Table1.hasMany(Table2)
      Table2.hasMany(Table1)

      it("should create a table wp_table1wp_table2s", function() {
        Helpers.async(function(done) {
          expect(sequelize.modelManager.getModel('wp_table1swp_table2s')).toBeDefined()
          done()
        })
      })
    })
  })

})
<|endoftext|>


<commit_before>#!/usr/bin/env node

let cordova = require('cordova');
let exec = require('child_process').exec;
let fs = require('fs');
let CONFIG = require('./../lib/config');

/**
 * @author Sven Hedström-Lang
 *
 * @requires npm install -g cordova
 *
 * @param {string} projectPath
 * @param {string} bundleId
 * @param {string} title
 */
let projectPath = CONFIG.getKey('projectPath');
let bundleId = CONFIG.getKey('bundleId');
let title = CONFIG.getKey('title');

fs.stat(projectPath, function (err, stats) {
	if (err) {

		// bugfix: if folder not exists, also create empty one
		let app = projectPath.replace(/\/$/, '').split('/');

		for (let i = 1; i <= app.length; i++) {
			let segment = app.slice(0, i).join('/');
			!fs.existsSync(segment) ? fs.mkdirSync(segment) : null;
		}
	}

	exec(
		`cordova create ${projectPath} ${bundleId} '${title}'`,
		CONFIG.onCallback
	);

});
<commit_msg>rename<commit_after>#!/usr/bin/env node

let cordova = require('cordova');
let exec = require('child_process').exec;
let fs = require('fs');
let CONFIG = require('./../lib/config');

/**
 * @author Sven Hedström-Lang
 *
 * @requires npm install -g cordova
 *
 * @param {string} projectPath
 * @param {string} bundleId
 * @param {string} title
 */
let projectPath = CONFIG.getKey('projectPath');
let bundleId = CONFIG.getKey('bundleId');
let title = CONFIG.getKey('title');

fs.stat(projectPath, function (err, stats) {
	if (err) {

		// bugfix: if folder not exists, create empty one
		let appPath = projectPath.replace(/\/$/, '').split('/');

		for (let i = 1; i <= appPath.length; i++) {
			let segment = appPath.slice(0, i).join('/');
			!fs.existsSync(segment) ? fs.mkdirSync(segment) : null;
		}
	}

	exec(
		`cordova create ${projectPath} ${bundleId} '${title}'`,
		CONFIG.onCallback
	);

});
<|endoftext|>


<commit_before>const $ = require('jquery');
const ga = require('../common/ga.js');
const spData = require('../common/sp-data');

amsPageInit();

function getQueryArgs(str = window.location.toString()) {
    let qstring = str || window.location.toString();
    const qmark = qstring.indexOf('?');
    if (qmark < 0)
        return {};

    qstring = qstring.substring(qmark);
    if (qstring.includes('#')) {
        qstring = qstring.substring(0, qstring.lastIndexOf('#'));
    }

    let qs = qstring.split('&');
    let args = {};
    for (let q of qs) {
        let parts = q.split('=');
        args[parts[0]] = parts[1];
    }
    return args;
}

function getEntityId(href = window.location.toString()) {
    let entityId = getQueryArgs(href).entityId;
    if (entityId) {
        return entityId;
    }

    let navLink = $('.topNavLogo')[0];
    if (navLink) {
        let navHref = navLink.href;
        let query = navHref.substring(navHref.indexOf('?') + 1);
        entityId = getQueryArgs(query).entityId;
        if (entityId) {
            return entityId;
        }
    }

    throw new Error('could not discover entityId from ' + href);
}

function getCampaignId(href = window.location.toString()) {
    let campaignId = getQueryArgs(href).campaignId;
    if (campaignId) {
        return spData.stripPrefix(campaignId);
    }

    if (href) {
        const rawId = spData.getUriPathChunk(href, 'campaigns');
        return spData.stripPrefix(rawId);
    }

    campaignId = $('input[name=campaignId]').val();
    if (campaignId)
        return spData.stripPrefix(campaignId);

    throw new Error('could not discover campaignId from ' + href);
}

function amsPageInit() {
    try {
        getEntityId();
    }
    catch (ex) {
        console.warn(ex);
        return false;
    }

    window.setInterval(addDashboardLinks, 250);
    return true;
}

function dashboardLink(entityId, campaignId, linkClass) {
    const entity = entityId ? `entityId=${entityId}` : '';
    const query = campaignId ? `${entity}&ckey=id&cval=${spData.stripPrefix(campaignId)}` : entity;
    return $(`
        View on Machete

    `);
}

function addDashboardLinks() {
    try {
        for (const link of $('a[data-e2e-id]')) {
            if ($(link).attr('data-machete-link'))
                continue;

            try {
                const entityId = getEntityId(link.href);
                const campaignId = getCampaignId(link.href);

                if (entityId && campaignId) {
                    $(link).after([dashboardLink(entityId, campaignId, 'dashboard-small')]);
                }
                $(link).attr('data-machete-link', true);
            }
            catch (ex) {
                console.log(`Couldn't discover entityId/campaignId for ${link} (probably expected)`);
            }
        }

        // there should typically only be 1 headline, but just in case...
        let entityId = null;
        try {
            entityId = getEntityId();
        }
        catch (ex) {
            ga.merror(ex);
        }

        let headlines = Array.from($("[data-e2e-id='headline']"));
        headlines = headlines.concat(...Array.from($("[data-e2e-id='aac-page-name']")));
        for (const headline of headlines) {
            if ($(headline).attr('data-machete-link'))
                continue;

            try {
                const campaignId = getCampaignId();

                if (entityId && campaignId) {
                    $(headline).append(dashboardLink(entityId, campaignId, 'dashboard-headline'));
                }
                $(headline).attr('data-machete-link', true);
            }
            catch (ex) {
                console.log(`Couldn't discover entityId/campaignId for headline`);
            }
        }

        for (const title of $("[data-e2e-id='title']")) {
            if ($(title).attr('data-machete-link'))
                continue;

            $(title).append(dashboardLink(entityId, null, 'dashboard-headline'));
            $(title).attr('data-machete-link', true);
        }
    }
    catch (ex) {
        ga.merror(ex);
    }
}
<commit_msg>fixed minor bug that makes things fail to parse the first element in the query string<commit_after>const $ = require('jquery');
const ga = require('../common/ga.js');
const spData = require('../common/sp-data');

amsPageInit();

function getQueryArgs(str = window.location.toString()) {
    let qstring = str || window.location.toString();
    const qmark = qstring.indexOf('?');
    if (qmark < 0)
        return {};

    qstring = qstring.substring(qmark + 1);
    if (qstring.includes('#')) {
        qstring = qstring.substring(0, qstring.lastIndexOf('#'));
    }

    let qs = qstring.split('&');
    let args = {};
    for (let q of qs) {
        let parts = q.split('=');
        args[parts[0]] = parts[1];
    }
    return args;
}

function getEntityId(href = window.location.toString()) {
    let entityId = getQueryArgs(href).entityId;
    if (entityId) {
        return entityId;
    }

    let navLink = $('.topNavLogo')[0];
    if (navLink) {
        let navHref = navLink.href;
        let query = navHref.substring(navHref.indexOf('?') + 1);
        entityId = getQueryArgs(query).entityId;
        if (entityId) {
            return entityId;
        }
    }

    throw new Error('could not discover entityId from ' + href);
}

function getCampaignId(href = window.location.toString()) {
    let campaignId = getQueryArgs(href).campaignId;
    if (campaignId) {
        return spData.stripPrefix(campaignId);
    }

    if (href) {
        const rawId = spData.getUriPathChunk(href, 'campaigns');
        return spData.stripPrefix(rawId);
    }

    campaignId = $('input[name=campaignId]').val();
    if (campaignId)
        return spData.stripPrefix(campaignId);

    throw new Error('could not discover campaignId from ' + href);
}

function amsPageInit() {
    try {
        getEntityId();
    }
    catch (ex) {
        console.warn(ex);
        return false;
    }

    window.setInterval(addDashboardLinks, 250);
    return true;
}

function dashboardLink(entityId, campaignId, linkClass) {
    const entity = entityId ? `entityId=${entityId}` : '';
    const query = campaignId ? `${entity}&ckey=id&cval=${spData.stripPrefix(campaignId)}` : entity;
    return $(`
        View on Machete

    `);
}

function addDashboardLinks() {
    try {
        for (const link of $('a[data-e2e-id]')) {
            if ($(link).attr('data-machete-link'))
                continue;

            try {
                const entityId = getEntityId(link.href);
                const campaignId = getCampaignId(link.href);

                if (entityId && campaignId) {
                    $(link).after([dashboardLink(entityId, campaignId, 'dashboard-small')]);
                }
                $(link).attr('data-machete-link', true);
            }
            catch (ex) {
                console.log(`Couldn't discover entityId/campaignId for ${link} (probably expected)`);
            }
        }

        // there should typically only be 1 headline, but just in case...
        let entityId = null;
        try {
            entityId = getEntityId();
        }
        catch (ex) {
            ga.merror(ex);
        }

        let headlines = Array.from($("[data-e2e-id='headline']"));
        headlines = headlines.concat(...Array.from($("[data-e2e-id='aac-page-name']")));
        for (const headline of headlines) {
            if ($(headline).attr('data-machete-link'))
                continue;

            try {
                const campaignId = getCampaignId();

                if (entityId && campaignId) {
                    $(headline).append(dashboardLink(entityId, campaignId, 'dashboard-headline'));
                }
                $(headline).attr('data-machete-link', true);
            }
            catch (ex) {
                console.log(`Couldn't discover entityId/campaignId for headline`);
            }
        }

        for (const title of $("[data-e2e-id='title']")) {
            if ($(title).attr('data-machete-link'))
                continue;

            $(title).append(dashboardLink(entityId, null, 'dashboard-headline'));
            $(title).attr('data-machete-link', true);
        }
    }
    catch (ex) {
        ga.merror(ex);
    }
}
<|endoftext|>


<commit_before>/**
 * On load, get all the internationalization strings and combine them into one object
 */
const translations = Object.assign({}, ...window.translations);
window.translations = null;

/**
 * Get the translation for the key from the global window.translations
 * @param {string} key
 * @returns {*}
 */
const getTranslation = key => {
  if (translations && translations[key]) return translations[key];
  throw new Error(`No internationalization string for key: ${key}`);
};

/**
 * Replace placeholders in the translation with provided values.
 * @param {string} text
 * @param {array} args - value to inject into the placeholder in the translation
 * @returns {*}
 */
const replaceKeys = (text, args) =>
  text.replace(/{([0-9]+)}/g, (_, index) => args[index]);

/**
 * Globally exposed function to allow to internationalization.
 * @param {string} key
 * @param {array} args - list of strings to inject into the translation.
 * @returns {string}
 */
function i18n(key, ...args) {
  try {
    const text = getTranslation(key);
    return replaceKeys(text, args);
  } catch (e) {
    console.error(e);
    return `__${key}__`;
  }
}

/*
This is a special case for scripts that are not compiled by webpack.
 */
window.__i18n = i18n;
module.exports = i18n;
<commit_msg>Don't need to make window.translations null since there could be multiple<commit_after>/**
 * On load, get all the internationalization strings and combine them into one object
 */
const translations = Object.assign({}, ...window.translations);

/**
 * Get the translation for the key from the global window.translations
 * @param {string} key
 * @returns {*}
 */
const getTranslation = key => {
  if (translations && translations[key]) return translations[key];
  throw new Error(`No internationalization string for key: ${key}`);
};

/**
 * Replace placeholders in the translation with provided values.
 * @param {string} text
 * @param {array} args - value to inject into the placeholder in the translation
 * @returns {*}
 */
const replaceKeys = (text, args) =>
  text.replace(/{([0-9]+)}/g, (_, index) => args[index]);

/**
 * Globally exposed function to allow to internationalization.
 * @param {string} key
 * @param {array} args - list of strings to inject into the translation.
 * @returns {string}
 */
function i18n(key, ...args) {
  try {
    const text = getTranslation(key);
    return replaceKeys(text, args);
  } catch (e) {
    console.error(e);
    return `__${key}__`;
  }
}

/*
This is a special case for scripts that are not compiled by webpack.
 */
window.__i18n = i18n;
module.exports = i18n;
<|endoftext|>


<commit_before>/* eslint-disable react/forbid-prop-types */

import React, { useEffect } from 'react';
import { connect } from 'react-redux';
import { ActivityIndicator, FlatList } from 'react-native';
import PropTypes from 'prop-types';
import { useIsFocused } from '@react-navigation/native';

import { TabContainer } from './TabContainer';
import { ScanRow } from './ScanRow';
import { Paper } from '../../widgets';
import { TextWithIcon } from '../../widgets/Typography';

import { vaccineStrings } from '../../localization';
import { VaccineActions } from '../../actions/VaccineActions';
import { selectScannedSensors } from '../../selectors/vaccine';
import { SUSSOL_ORANGE } from '../../globalStyles';

const Spinner = () => (
  <TextWithIcon left Icon={<ActivityIndicator color={SUSSOL_ORANGE} />}>
    {vaccineStrings.scanning}
  </TextWithIcon>
);

export const NewSensorStepOneComponent = ({ startScan, stopScan, macAddresses }) => {
  const isFocused = useIsFocused();

  useEffect(() => {
    if (isFocused) startScan();
    else stopScan();
    return stopScan;
  }, [startScan, isFocused]);

  return (
    <TabContainer>
      <Paper height={420} headerText={vaccineStrings.new_sensor_step_one_title}>
        <FlatList
          ListFooterComponent={<Spinner containerStyle={{ flex: 1, backgroundColor: 'red' }} />}
          keyExtractor={item => item}
          style={{ height: 360 }}
          data={macAddresses}
          renderItem={({ item }) => <ScanRow macAddress={item} />}
        />
      </Paper>
    </TabContainer>
  );
};

NewSensorStepOneComponent.propTypes = {
  macAddresses: PropTypes.array.isRequired,
  startScan: PropTypes.func.isRequired,
  stopScan: PropTypes.func.isRequired,
};

const dispatchToProps = dispatch => {
  const startScan = () => dispatch(VaccineActions.startSensorScan());
  const stopScan = () => dispatch(VaccineActions.stopSensorScan());

  return { startScan, stopScan };
};

const stateToProps = state => {
  const macAddresses = selectScannedSensors(state);
  return { macAddresses };
};

export const NewSensorStepOne = connect(stateToProps, dispatchToProps)(NewSensorStepOneComponent);
<commit_msg>Center loading icon on NewSensorStepOne<commit_after>/* eslint-disable react/forbid-prop-types */

import React, { useEffect } from 'react';
import { connect } from 'react-redux';
import { ActivityIndicator, FlatList } from 'react-native';
import PropTypes from 'prop-types';
import { useIsFocused } from '@react-navigation/native';

import { TabContainer } from './TabContainer';
import { ScanRow } from './ScanRow';
import { Paper } from '../../widgets';
import { TextWithIcon } from '../../widgets/Typography';

import { vaccineStrings } from '../../localization';
import { VaccineActions } from '../../actions/VaccineActions';
import { selectScannedSensors } from '../../selectors/vaccine';
import { SUSSOL_ORANGE } from '../../globalStyles';

const Spinner = () => (
  <TextWithIcon
    left
    Icon={<ActivityIndicator color={SUSSOL_ORANGE} />}
    containerStyle={{ justifyContent: 'center' }}
  >
    {vaccineStrings.scanning}
  </TextWithIcon>
);

export const NewSensorStepOneComponent = ({ startScan, stopScan, macAddresses }) => {
  const isFocused = useIsFocused();

  useEffect(() => {
    if (isFocused) startScan();
    else stopScan();
    return stopScan;
  }, [startScan, isFocused]);

  return (
    <TabContainer>
      <Paper height={420} headerText={vaccineStrings.new_sensor_step_one_title}>
        <FlatList
          data={macAddresses}
          renderItem={({ item }) => <ScanRow macAddress={item} />}
          keyExtractor={item => item}
          style={{ height: 360 }}
          ListFooterComponent={<Spinner />}
        />
      </Paper>
    </TabContainer>
  );
};

NewSensorStepOneComponent.propTypes = {
  macAddresses: PropTypes.array.isRequired,
  startScan: PropTypes.func.isRequired,
  stopScan: PropTypes.func.isRequired,
};

const dispatchToProps = dispatch => {
  const startScan = () => dispatch(VaccineActions.startSensorScan());
  const stopScan = () => dispatch(VaccineActions.stopSensorScan());

  return { startScan, stopScan };
};

const stateToProps = state => {
  const macAddresses = selectScannedSensors(state);
  return { macAddresses };
};

export const NewSensorStepOne = connect(stateToProps, dispatchToProps)(NewSensorStepOneComponent);
<|endoftext|>


<commit_before>require('../support/spec_helper');

describe("Cucumber.Cli", function() {
  var Cucumber = requireLib('cucumber');

  var cli, argv;

  beforeEach(function() {
    argv = createSpy("process argv array");
    cli  = Cucumber.Cli(argv);
  });

  describe("run()", function() {
    var configuration, callback;

    beforeEach(function() {
      configuration = createSpyWithStubs("CLI configuration", {isVersionRequested: false, isHelpRequested: false});
      callback      = createSpy("callback");
      spyOn(Cucumber.Cli, 'Configuration').andReturn(configuration);
      spyOn(cli, 'displayHelp');
      spyOn(cli, 'displayVersion');
      spyOn(cli, 'runSuiteWithConfiguration');
    });

    it("creates a new CLI configuration", function() {
      cli.run(callback);
      expect(Cucumber.Cli.Configuration).toHaveBeenCalledWith(argv);
    });

    it("checks whether the help is requested or not", function() {
      cli.run(callback);
      expect(configuration.isHelpRequested).toHaveBeenCalled();
    });

    describe("when the help is requested", function() {
      beforeEach(function() {
        configuration.isHelpRequested.andReturn(true);
      });

      it("displays the help", function() {
        cli.run(callback);
        expect(cli.displayHelp).toHaveBeenCalledWith(callback);
      });

      it("does not run the suite", function() {
        cli.run(callback);
        expect(cli.runSuiteWithConfiguration).not.toHaveBeenCalledWith(callback);
      });

      it("does not display the version", function() {
        cli.run(callback);
        expect(cli.displayVersion).not.toHaveBeenCalledWith(callback);
      });
    });

    describe("when the help is not requested", function() {
      beforeEach(function() {
        configuration.isHelpRequested.andReturn(false);
      });

      it("checks whether the version is requested or not", function() {
        cli.run(callback);
        expect(configuration.isVersionRequested).toHaveBeenCalled();
      });

      describe("when the version is requested", function() {
        beforeEach(function() {
          configuration.isVersionRequested.andReturn(true);
        });

        it("displays the version", function() {
          cli.run(callback);
          expect(cli.displayVersion).toHaveBeenCalledWith(callback);
        });

        it("does not display the help", function() {
          cli.run(callback);
          expect(cli.displayHelp).not.toHaveBeenCalled();
        });

        it("does not run the suite", function() {
          cli.run(callback);
          expect(cli.runSuiteWithConfiguration).not.toHaveBeenCalled();
        });
      });

      describe("when the version is not requested", function() {
        beforeEach(function() {
          configuration.isVersionRequested.andReturn(false);
        });

        it("runs the suite", function() {
          cli.run(callback);
          expect(cli.runSuiteWithConfiguration).toHaveBeenCalledWith(configuration, callback);
        });

        it("does not display the help", function() {
          cli.run(callback);
          expect(cli.displayHelp).not.toHaveBeenCalled();
        });

        it("does not display the version", function() {
          cli.run(callback);
          expect(cli.displayVersion).not.toHaveBeenCalledWith(callback);
        });
      });
    });
  });

  describe("runSuiteWithConfiguration()", function() {
    var configuration, runtime, callback;
    var formatter;

    beforeEach(function() {
      formatter     = createSpy("formatter");
      configuration = createSpyWithStubs("CLI configuration", {getFormatter: formatter});
      runtime       = createSpyWithStubs("runtime", {start: null, attachListener: null});
      callback      = createSpy("callback");
      spyOn(Cucumber, 'Runtime').andReturn(runtime);
    });

    it("creates a Cucumber runtime with the CLI configuration", function() {
      cli.runSuiteWithConfiguration(configuration, callback);
      expect(Cucumber.Runtime).toHaveBeenCalledWith(configuration);
    });

    it("gets the formatter from the configuration", function() {
      cli.runSuiteWithConfiguration(configuration, callback);
      expect(configuration.getFormatter).toHaveBeenCalled();
    });

    it("attaches the formatter to the runtime", function() {
      cli.runSuiteWithConfiguration(configuration, callback);
      expect(runtime.attachListener).toHaveBeenCalledWith(formatter);
    });

    it("runs the runtime with the callback", function() {
      cli.runSuiteWithConfiguration(configuration, callback);
      expect(runtime.start).toHaveBeenCalledWith(callback);
    });
  });

  describe("displayVersion()", function() {
    var callback;

    beforeEach(function() {
      callback = createSpy("callback");
      spyOn(process.stdout, 'write');
    });

    it("outputs the version of Cucumber to STDOUT", function() {
      cli.displayVersion(callback);
      expect(process.stdout.write).toHaveBeenCalledWith(Cucumber.VERSION + "\n");
    });

    it("calls back and tells it succeeded", function() {
      cli.displayVersion(callback);
      expect(callback).toHaveBeenCalledWith(true);
    });
  });

  describe("displayHelp()", function() {
    var callback;

    beforeEach(function() {
      callback = createSpy("callback");
      spyOn(process.stdout, 'write');
    });

    it("outputs the usage of Cucumber to STDOUT", function() {
      cli.displayHelp(callback);
      expect(process.stdout.write).toHaveBeenCalledWithStringMatching("Usage: cucumber.js ");
    });

    it("calls back and tells it succeeded", function() {
      cli.displayHelp(callback);
      expect(callback).toHaveBeenCalledWith(true);
    });
  });
});
<commit_msg>Abstract shared test step into beforeEach<commit_after>require('../support/spec_helper');

describe("Cucumber.Cli", function() {
  var Cucumber = requireLib('cucumber');

  var cli, argv;

  beforeEach(function() {
    argv = createSpy("process argv array");
    cli  = Cucumber.Cli(argv);
  });

  describe("run()", function() {
    var configuration, callback;

    beforeEach(function() {
      configuration = createSpyWithStubs("CLI configuration", {isVersionRequested: false, isHelpRequested: false});
      callback      = createSpy("callback");
      spyOn(Cucumber.Cli, 'Configuration').andReturn(configuration);
      spyOn(cli, 'displayHelp');
      spyOn(cli, 'displayVersion');
      spyOn(cli, 'runSuiteWithConfiguration');
    });

    it("creates a new CLI configuration", function() {
      cli.run(callback);
      expect(Cucumber.Cli.Configuration).toHaveBeenCalledWith(argv);
    });

    it("checks whether the help is requested or not", function() {
      cli.run(callback);
      expect(configuration.isHelpRequested).toHaveBeenCalled();
    });

    describe("when the help is requested", function() {
      beforeEach(function() {
        configuration.isHelpRequested.andReturn(true);
      });

      it("displays the help", function() {
        cli.run(callback);
        expect(cli.displayHelp).toHaveBeenCalledWith(callback);
      });

      it("does not run the suite", function() {
        cli.run(callback);
        expect(cli.runSuiteWithConfiguration).not.toHaveBeenCalledWith(callback);
      });

      it("does not display the version", function() {
        cli.run(callback);
        expect(cli.displayVersion).not.toHaveBeenCalledWith(callback);
      });
    });

    describe("when the help is not requested", function() {
      beforeEach(function() {
        configuration.isHelpRequested.andReturn(false);
      });

      it("checks whether the version is requested or not", function() {
        cli.run(callback);
        expect(configuration.isVersionRequested).toHaveBeenCalled();
      });

      describe("when the version is requested", function() {
        beforeEach(function() {
          configuration.isVersionRequested.andReturn(true);
          cli.run(callback);
        });

        it("displays the version", function() {
          expect(cli.displayVersion).toHaveBeenCalledWith(callback);
        });

        it("does not display the help", function() {
          expect(cli.displayHelp).not.toHaveBeenCalled();
        });

        it("does not run the suite", function() {
          expect(cli.runSuiteWithConfiguration).not.toHaveBeenCalled();
        });
      });

      describe("when the version is not requested", function() {
        beforeEach(function() {
          configuration.isVersionRequested.andReturn(false);
          cli.run(callback);
        });

        it("runs the suite", function() {
          expect(cli.runSuiteWithConfiguration).toHaveBeenCalledWith(configuration, callback);
        });

        it("does not display the help", function() {
          expect(cli.displayHelp).not.toHaveBeenCalled();
        });

        it("does not display the version", function() {
          expect(cli.displayVersion).not.toHaveBeenCalledWith(callback);
        });
      });
    });
  });

  describe("runSuiteWithConfiguration()", function() {
    var configuration, runtime, callback;
    var formatter;

    beforeEach(function() {
      formatter     = createSpy("formatter");
      configuration = createSpyWithStubs("CLI configuration", {getFormatter: formatter});
      runtime       = createSpyWithStubs("runtime", {start: null, attachListener: null});
      callback      = createSpy("callback");
      spyOn(Cucumber, 'Runtime').andReturn(runtime);
      cli.runSuiteWithConfiguration(configuration, callback);
    });

    it("creates a Cucumber runtime with the CLI configuration", function() {
      expect(Cucumber.Runtime).toHaveBeenCalledWith(configuration);
    });

    it("gets the formatter from the configuration", function() {
      expect(configuration.getFormatter).toHaveBeenCalled();
    });

    it("attaches the formatter to the runtime", function() {
      expect(runtime.attachListener).toHaveBeenCalledWith(formatter);
    });

    it("runs the runtime with the callback", function() {
      expect(runtime.start).toHaveBeenCalledWith(callback);
    });
  });

  describe("displayVersion()", function() {
    var callback;

    beforeEach(function() {
      callback = createSpy("callback");
      spyOn(process.stdout, 'write');
      cli.displayVersion(callback);
    });

    it("outputs the version of Cucumber to STDOUT", function() {
      expect(process.stdout.write).toHaveBeenCalledWith(Cucumber.VERSION + "\n");
    });

    it("calls back and tells it succeeded", function() {
      expect(callback).toHaveBeenCalledWith(true);
    });
  });

  describe("displayHelp()", function() {
    var callback;

    beforeEach(function() {
      callback = createSpy("callback");
      spyOn(process.stdout, 'write');
      cli.displayHelp(callback);
    });

    it("outputs the usage of Cucumber to STDOUT", function() {
      expect(process.stdout.write).toHaveBeenCalledWithStringMatching("Usage: cucumber.js ");
    });

    it("calls back and tells it succeeded", function() {
      expect(callback).toHaveBeenCalledWith(true);
    });
  });
});
<|endoftext|>


<commit_before>/*
 * js-upload-manager
 * https://github.com/bgard6977/js-upload-manager/
 *
 * Copyright (c) 2014 Brent Gardner
 * Licensed under the MIT license.
 */
define([
    'webdav/File',
    'mock/WebFile'
], function (File, WebFile) {
    describe('File', function () {

        var MAP = {
            getcontenttype: '2',
            getcontentlength: '3',
            creationdate: '4',
            getlastmodified: '5'
        };

        it('should get properties from XML', function () {
            var response = {
                getElementsByTagName: function (prop) {
                    if (prop === 'href') {
                        return [
                            {innerHTML: '/webdav1/test/'}
                        ];
                    }
                    if (prop === 'prop') {
                        return [
                            {
                                getElementsByTagName: function (prop) {
                                    return [
                                        {innerHTML: MAP[prop]}
                                    ];
                                }
                            }
                        ];
                    }
                }
            };
            var rootPath = '/webdav1/';

            var file = new File(response, rootPath);

            expect(file.getPath()).toEqual('/webdav1/test/');
            expect(file.getRelativePath()).toEqual('test/');
            expect(file.getContentType()).toEqual('2');
            expect(file.getContentLength()).toEqual('3');
            expect(file.getCreationDate()).toEqual('4');
            expect(file.getLastModified()).toEqual('5');
        });

        it('should compare properly', function () {
            var files = [
                new WebFile('z', 'd'),
                new WebFile('z', 'c'),
                new WebFile('a', 'b'),
                null
            ];

            files.sort(File.COMPARATOR);

            expect(files[0]).toBeNull();
            expect(files[1].getContentType()).toEqual('a');
            expect(files[2].getRelativePath()).toEqual('c');
            expect(files[3].getRelativePath()).toEqual('d');
        });

    });
});
<commit_msg>Better tests<commit_after>/*
 * js-upload-manager
 * https://github.com/bgard6977/js-upload-manager/
 *
 * Copyright (c) 2014 Brent Gardner
 * Licensed under the MIT license.
 */
define([
    'webdav/File',
    'mock/WebFile'
], function (File, WebFile) {
    describe('File', function () {

        it('should get properties from XML', function () {
            var text = '\
<?xml version="1.0" encoding="UTF-8"?>\
<D:multistatus xmlns:D="DAV:" xmlns:ns0="DAV:">\
	<D:response xmlns:lp1="DAV:" xmlns:lp2="http://apache.org/dav/props/">\
		<D:href>/webdav1/test/</D:href>\
		<D:propstat>\
			<D:prop>\
				<lp1:creationdate>4</lp1:creationdate>\
				<lp1:getlastmodified>5</lp1:getlastmodified>\
				<D:getcontenttype>2</D:getcontenttype>\
				<lp1:getcontentlength>3</lp1:getcontentlength>\
			</D:prop>\
			<D:status>HTTP/1.1 200 OK</D:status>\
		</D:propstat>\
	</D:response>\
</D:multistatus>\
            ';
            var response = $(text);
            var rootPath = '/webdav1/';

            var file = new File(response, rootPath);

            expect(file.getPath()).toEqual('/webdav1/test/');
            expect(file.getRelativePath()).toEqual('test/');
            expect(file.getContentType()).toEqual('2');
            expect(file.getContentLength()).toEqual('3');
            expect(file.getCreationDate()).toEqual('4');
            expect(file.getLastModified()).toEqual('5');
        });

        it('should compare properly', function () {
            var files = [
                new WebFile('z', 'd'),
                new WebFile('z', 'c'),
                new WebFile('a', 'b'),
                null
            ];

            files.sort(File.COMPARATOR);

            expect(files[0]).toBeNull();
            expect(files[1].getContentType()).toEqual('a');
            expect(files[2].getRelativePath()).toEqual('c');
            expect(files[3].getRelativePath()).toEqual('d');
        });

    });
});
<|endoftext|>