<commit_before>var html5Player = function() {
    var video;

    function init(videoUrl, containerId) {
        video = document.createElement("video");
        video.setAttribute("src", videoUrl);
        video.setAttribute("width", 512);
        video.setAttribute('controls', true);
        document.getElementById(containerId).appendChild(video);
    }

    function play() {
        video.play();
    }

    function pause() {
        video.pause();
    }

    function destroy() {
        video.remove();
    }

    function paused() {
        return video.paused;
    }

    function duration() {
        return video.duration;
    }

    function currentTime() {
        return video.currentTime;
    }

    function setCurrentTime(time) {
        video.currentTime = time;
    }

    function ended() {
        return video.ended;
    }

    function volume() {
        return video.volume;
    }

    function setVolume(volume) {
        video.volume = volume;
    }

    function muted() {
        return video.muted;
    }

    function mute() {
        video.muted = true;
    }

    function unmute() {
        video.muted = false;
    }

    function onLoadedMetadata() {
    }

    function onPlay() {
    }

    function onPause() {
    }

    function onPlayTimeChange() {
    }

    function onEnded() {
    }

    return {
        init: init,
        play: play,
        pause: pause,
        destroy: destroy,
        paused: paused,
        duration: duration,
        currentTime: currentTime,
        setCurrentTime: setCurrentTime,
        ended: ended,
        volume: volume,
        setVolume: setVolume,
        muted: muted,
        mute: mute,
        unmute: unmute,
        onLoadedMetadata: onLoadedMetadata,
        onPlay: onPlay,
        onPause: onPause,
        onPlayTimeChange: onPlayTimeChange,
        onEnded: onEnded
    };
}

var vimeoPlayer = function() {
    var video,
        divWrapper;

    function init(videoUrl, containerId) {
        var vimeoApi = (function(){
            function Froogaloop(iframe) {
                return new Froogaloop.fn.init(iframe);
            }

            var eventCallbacks = {},
                hasWindowEvent = false,
                isReady = false,
                slice = Array.prototype.slice,
                playerOrigin = '*';

            Froogaloop.fn = Froogaloop.prototype = {
                element: null,

                init: function(iframe) {
                    if (typeof iframe === "string") {
                        iframe = document.getElementById(iframe);
                    }

                    this.element = iframe;

                    return this;
                },

                api: function(method, valueOrCallback) {
                    if (!this.element || !method) {
                        return false;
                    }

                    var self = this,
                        element = self.element,
                        target_id = element.id !== '' ? element.id : null,
                        params = !isFunction(valueOrCallback) ? valueOrCallback : null,
                        callback = isFunction(valueOrCallback) ? valueOrCallback : null;

                    if (callback) {
                        storeCallback(method, callback, target_id);
                    }

                    postMessage(method, params, element);
                    return self;
                },

                addEvent: function(eventName, callback) {
                    if (!this.element) {
                        return false;
                    }

                    var self = this,
                        element = self.element,
                        target_id = element.id !== '' ? element.id : null;

                    storeCallback(eventName, callback, target_id);

                    if (eventName != 'ready') {
                        postMessage('addEventListener', eventName, element);
                    }
                    else if (eventName == 'ready' && isReady) {
                        callback.call(null, target_id);
                    }

                    return self;
                },

                removeEvent: function(eventName) {
                    if (!this.element) {
                        return false;
                    }

                    var self = this,
                        element = self.element,
                        target_id = element.id !== '' ? element.id : null,
                        removed = removeCallback(eventName, target_id);

                    if (eventName != 'ready' && removed) {
                        postMessage('removeEventListener', eventName, element);
                    }
                }
            };

            function postMessage(method, params, target) {
                if (!target.contentWindow.postMessage) {
                    return false;
                }

                var data = JSON.stringify({
                    method: method,
                    value: params
                });

                target.contentWindow.postMessage(data, playerOrigin);
            }

            function onMessageReceived(event) {
                var data, method;

                try {
                    data = JSON.parse(event.data);
                    method = data.event || data.method;
                }
                catch(e)  {
                }

                if (method == 'ready' && !isReady) {
                    isReady = true;
                }

                if (!(/^https?:\/\/player.vimeo.com/).test(event.origin)) {
                    return false;
                }

                if (playerOrigin === '*') {
                    playerOrigin = event.origin;
                }

                var value = data.value,
                    eventData = data.data,
                    target_id = target_id === '' ? null : data.player_id,

                    callback = getCallback(method, target_id),
                    params = [];

                if (!callback) {
                    return false;
                }

                if (value !== undefined) {
                    params.push(value);
                }

                if (eventData) {
                    params.push(eventData);
                }

                if (target_id) {
                    params.push(target_id);
                }

                return params.length > 0 ? callback.apply(null, params) : callback.call();
            }

            function storeCallback(eventName, callback, target_id) {
                if (target_id) {
                    if (!eventCallbacks[target_id]) {
                        eventCallbacks[target_id] = {};
                    }
                    eventCallbacks[target_id][eventName] = callback;
                }
                else {
                    eventCallbacks[eventName] = callback;
                }
            }

            function getCallback(eventName, target_id) {
                if (target_id) {
                    return eventCallbacks[target_id][eventName];
                }
                else {
                    return eventCallbacks[eventName];
                }
            }

            function removeCallback(eventName, target_id) {
                if (target_id && eventCallbacks[target_id]) {
                    if (!eventCallbacks[target_id][eventName]) {
                        return false;
                    }
                    eventCallbacks[target_id][eventName] = null;
                }
                else {
                    if (!eventCallbacks[eventName]) {
                        return false;
                    }
                    eventCallbacks[eventName] = null;
                }

                return true;
            }

            function isFunction(obj) {
                return !!(obj && obj.constructor && obj.call && obj.apply);
            }

            function isArray(obj) {
                return toString.call(obj) === '[object Array]';
            }

            Froogaloop.fn.init.prototype = Froogaloop.fn;

            if (window.addEventListener) {
                window.addEventListener('message', onMessageReceived, false);
            }
            else {
                window.attachEvent('onmessage', onMessageReceived);
            }

            return Froogaloop;

        })();

        this.baseUrl = 'https://player.vimeo.com/video/';
        this.videoId = videoUrl.split('//player.vimeo.com/video/')[1];

        this.iframe = document.createElement('iframe');
        this.iframe.setAttribute('title', 'Vimeo Video Player');
        this.iframe.setAttribute('class', 'vimeoplayer');
        this.iframe.setAttribute('src', this.baseUrl + this.videoId + '?api=1');
        this.iframe.setAttribute('frameborder', '0');
        this.iframe.setAttribute('scrolling', 'no');
        this.iframe.setAttribute('marginWidth', '0');
        this.iframe.setAttribute('marginHeight', '0');
        this.iframe.setAttribute('webkitAllowFullScreen', '0');
        this.iframe.setAttribute('mozallowfullscreen', '0');
        this.iframe.setAttribute('allowFullScreen', '0');

        video = vimeoApi(this.iframe);

        divWrapper = document.createElement('div');
        divWrapper.setAttribute('style', 'margin:0 auto;padding-bottom:56.25%;width:100%;height:0;position:relative;overflow:hidden;');
        divWrapper.setAttribute('class', 'vimeoFrame');
        divWrapper.appendChild(this.iframe);
        document.getElementById(containerId).appendChild(divWrapper);
    }

    function play() {
        video.api('play');
    }

    function pause() {
        video.api('pause');
    }

    function destroy() {
        divWrapper.remove();
    }

    return {init: init, play: play, pause: pause, destroy: destroy};
}

var pybossaPlayer = function(videoUrl, containerId) {
    var player;

    if (videoUrl.split('.').indexOf('vimeo') !== -1) {
        player = vimeoPlayer();
    }
    else {
        player = html5Player();
    }

    player.init(videoUrl, containerId);

    function play() {
        player.play();
    }

    function pause() {
        player.pause();
    }

    function destroy() {
        player.destroy();
    }

    function paused() {
        return player.paused();
    }

    function duration() {
        return player.duration();
    }

    function currentTime() {
        return player.currentTime();
    }

    function setCurrentTime(time) {
        player.setCurrentTime(time);
    }

    function ended() {
        return player.ended();
    }

    function volume() {
        return player.volume();
    }

    function setVolume(volume) {
        player.setVolume(volume);
    }

    function muted() {
        return player.muted();
    }

    function mute() {
        player.mute();
    }

    function unmute() {
        player.unmute();
    }

    function onLoadedMetadata() {
    }

    function onPlay() {
    }

    function onPause() {
    }

    function onPlayTimeChange() {
    }

    function onEnded() {
    }

    return {
        play: play,
        pause: pause,
        destroy: destroy,
        paused: paused,
        duration: duration,
        currentTime: currentTime,
        setCurrentTime: setCurrentTime,
        ended: ended,
        volume: volume,
        setVolume: setVolume,
        muted: muted,
        mute: mute,
        unmute: unmute,
        onLoadedMetadata: onLoadedMetadata,
        onPlay: onPlay,
        onPause: onPause,
        onPlayTimeChange: onPlayTimeChange,
        onEnded: onEnded
    };
}
<commit_msg>Implement queries and commands for Vimeo<commit_after>var html5Player = function() {
    var video;

    function init(videoUrl, containerId) {
        video = document.createElement("video");
        video.setAttribute("src", videoUrl);
        video.setAttribute("width", 512);
        video.setAttribute('controls', true);
        document.getElementById(containerId).appendChild(video);
    }

    function play() {
        video.play();
    }

    function pause() {
        video.pause();
    }

    function destroy() {
        video.remove();
    }

    function paused() {
        return video.paused;
    }

    function duration() {
        return video.duration;
    }

    function currentTime() {
        return video.currentTime;
    }

    function setCurrentTime(time) {
        video.currentTime = time;
    }

    function ended() {
        return video.ended;
    }

    function volume() {
        return video.volume;
    }

    function setVolume(volume) {
        video.volume = volume;
    }

    function muted() {
        return video.muted;
    }

    function mute() {
        video.muted = true;
    }

    function unmute() {
        video.muted = false;
    }

    function onLoadedMetadata() {
    }

    function onPlay() {
    }

    function onPause() {
    }

    function onPlayTimeChange() {
    }

    function onEnded() {
    }

    return {
        init: init,
        play: play,
        pause: pause,
        destroy: destroy,
        paused: paused,
        duration: duration,
        currentTime: currentTime,
        setCurrentTime: setCurrentTime,
        ended: ended,
        volume: volume,
        setVolume: setVolume,
        muted: muted,
        mute: mute,
        unmute: unmute,
        onLoadedMetadata: onLoadedMetadata,
        onPlay: onPlay,
        onPause: onPause,
        onPlayTimeChange: onPlayTimeChange,
        onEnded: onEnded
    };
}

var vimeoPlayer = function() {
    var video,
        divWrapper;

    function init(videoUrl, containerId) {
        var vimeoApi = (function(){
            function Froogaloop(iframe) {
                return new Froogaloop.fn.init(iframe);
            }

            var eventCallbacks = {},
                hasWindowEvent = false,
                isReady = false,
                slice = Array.prototype.slice,
                playerOrigin = '*';

            Froogaloop.fn = Froogaloop.prototype = {
                element: null,

                init: function(iframe) {
                    if (typeof iframe === "string") {
                        iframe = document.getElementById(iframe);
                    }

                    this.element = iframe;

                    return this;
                },

                api: function(method, valueOrCallback) {
                    if (!this.element || !method) {
                        return false;
                    }

                    var self = this,
                        element = self.element,
                        target_id = element.id !== '' ? element.id : null,
                        params = !isFunction(valueOrCallback) ? valueOrCallback : null,
                        callback = isFunction(valueOrCallback) ? valueOrCallback : null;

                    if (callback) {
                        storeCallback(method, callback, target_id);
                    }

                    postMessage(method, params, element);
                    return self;
                },

                addEvent: function(eventName, callback) {
                    if (!this.element) {
                        return false;
                    }

                    var self = this,
                        element = self.element,
                        target_id = element.id !== '' ? element.id : null;

                    storeCallback(eventName, callback, target_id);

                    if (eventName != 'ready') {
                        postMessage('addEventListener', eventName, element);
                    }
                    else if (eventName == 'ready' && isReady) {
                        callback.call(null, target_id);
                    }

                    return self;
                },

                removeEvent: function(eventName) {
                    if (!this.element) {
                        return false;
                    }

                    var self = this,
                        element = self.element,
                        target_id = element.id !== '' ? element.id : null,
                        removed = removeCallback(eventName, target_id);

                    if (eventName != 'ready' && removed) {
                        postMessage('removeEventListener', eventName, element);
                    }
                }
            };

            function postMessage(method, params, target) {
                if (!target.contentWindow.postMessage) {
                    return false;
                }

                var data = JSON.stringify({
                    method: method,
                    value: params
                });

                target.contentWindow.postMessage(data, playerOrigin);
            }

            function onMessageReceived(event) {
                var data, method;

                try {
                    data = JSON.parse(event.data);
                    method = data.event || data.method;
                }
                catch(e) {
                }

                if (method == 'ready' && !isReady) {
                    isReady = true;
                }

                if (!(/^https?:\/\/player.vimeo.com/).test(event.origin)) {
                    return false;
                }

                if (playerOrigin === '*') {
                    playerOrigin = event.origin;
                }

                var value = data.value,
                    eventData = data.data,
                    target_id = target_id === '' ? null : data.player_id,

                    callback = getCallback(method, target_id),
                    params = [];

                if (!callback) {
                    return false;
                }

                if (value !== undefined) {
                    params.push(value);
                }

                if (eventData) {
                    params.push(eventData);
                }

                if (target_id) {
                    params.push(target_id);
                }

                return params.length > 0 ? callback.apply(null, params) : callback.call();
            }

            function storeCallback(eventName, callback, target_id) {
                if (target_id) {
                    if (!eventCallbacks[target_id]) {
                        eventCallbacks[target_id] = {};
                    }
                    eventCallbacks[target_id][eventName] = callback;
                }
                else {
                    eventCallbacks[eventName] = callback;
                }
            }

            function getCallback(eventName, target_id) {
                if (target_id) {
                    return eventCallbacks[target_id][eventName];
                }
                else {
                    return eventCallbacks[eventName];
                }
            }

            function removeCallback(eventName, target_id) {
                if (target_id && eventCallbacks[target_id]) {
                    if (!eventCallbacks[target_id][eventName]) {
                        return false;
                    }
                    eventCallbacks[target_id][eventName] = null;
                }
                else {
                    if (!eventCallbacks[eventName]) {
                        return false;
                    }
                    eventCallbacks[eventName] = null;
                }

                return true;
            }

            function isFunction(obj) {
                return !!(obj && obj.constructor && obj.call && obj.apply);
            }

            function isArray(obj) {
                return toString.call(obj) === '[object Array]';
            }

            Froogaloop.fn.init.prototype = Froogaloop.fn;

            if (window.addEventListener) {
                window.addEventListener('message', onMessageReceived, false);
            }
            else {
                window.attachEvent('onmessage', onMessageReceived);
            }

            return Froogaloop;

        })();

        this.baseUrl = 'https://player.vimeo.com/video/';
        this.videoId = videoUrl.split('//player.vimeo.com/video/')[1];

        this.iframe = document.createElement('iframe');
        this.iframe.setAttribute('title', 'Vimeo Video Player');
        this.iframe.setAttribute('class', 'vimeoplayer');
        this.iframe.setAttribute('src', this.baseUrl + this.videoId + '?api=1');
        this.iframe.setAttribute('frameborder', '0');
        this.iframe.setAttribute('scrolling', 'no');
        this.iframe.setAttribute('marginWidth', '0');
        this.iframe.setAttribute('marginHeight', '0');
        this.iframe.setAttribute('webkitAllowFullScreen', '0');
        this.iframe.setAttribute('mozallowfullscreen', '0');
        this.iframe.setAttribute('allowFullScreen', '0');

        video = vimeoApi(this.iframe);

        divWrapper = document.createElement('div');
        divWrapper.setAttribute('style', 'margin:0 auto;padding-bottom:56.25%;width:100%;height:0;position:relative;overflow:hidden;');
        divWrapper.setAttribute('class', 'vimeoFrame');
        divWrapper.appendChild(this.iframe);
        document.getElementById(containerId).appendChild(divWrapper);
        video.addEvent('ready', setPlayerInformationCallbacks);
    }

    var _volume = 1.0,
        _duration = 0,
        _currentTime = 0,
        _paused = true,
        _mutedPreviousVolume = 1.0;

    function setPlayerInformationCallbacks() {
        video.addEvent('pause', function() {_paused = true;});
        video.addEvent('play', function() {_paused = false;});
        video.addEvent('playProgress', function(value) {_currentTime = value.seconds;});
        video.addEvent('loadProgress', function(value) {_duration = value.duration});
        video.api('getVolume', function(value) {_volume = value;});
        video.api('getDuration', function(value) {_duration = value;});
    }

    function play() {
        video.api('play');
    }

    function pause() {
        video.api('pause');
    }

    function destroy() {
        divWrapper.remove();
    }
    function paused() {
        return _paused;
    }

    function duration() {
        return _duration;
    }

    function currentTime() {
        return _currentTime;
    }

    function setCurrentTime(time) {
        var wasPaused = _paused;
        video.api('seekTo', time);
        if (wasPaused) player.pause();
    }

    function ended() {
        return currentTime() === duration();
    }

    function volume() {
        return _volume;
    }

    function setVolume(vol) {
        video.api('setVolume', vol);
        _volume = vol;
    }

    function muted() {
        return volume() === 0;
    }

    function mute() {
        _mutedPreviousVolume = volume();
        setVolume(0);
    }

    function unmute() {
        video.api('setVolume', _mutedPreviousVolume);
        _volume = _mutedPreviousVolume;
    }

    function onLoadedMetadata() {
    }

    function onPlay() {
    }

    function onPause() {
    }

    function onPlayTimeChange() {
    }

    function onEnded() {
    }

    return {
        init: init,
        play: play,
        pause: pause,
        destroy: destroy,
        paused: paused,
        duration: duration,
        currentTime: currentTime,
        setCurrentTime: setCurrentTime,
        ended: ended,
        volume: volume,
        setVolume: setVolume,
        muted: muted,
        mute: mute,
        unmute: unmute,
        onLoadedMetadata: onLoadedMetadata,
        onPlay: onPlay,
        onPause: onPause,
        onPlayTimeChange: onPlayTimeChange,
        onEnded: onEnded
    };
}

var pybossaPlayer = function(videoUrl, containerId) {
    var player;

    if (videoUrl.split('.').indexOf('vimeo') !== -1) {
        player = vimeoPlayer();
    }
    else {
        player = html5Player();
    }

    player.init(videoUrl, containerId);

    function play() {
        player.play();
    }

    function pause() {
        player.pause();
    }

    function destroy() {
        player.destroy();
    }

    function paused() {
        return player.paused();
    }

    function duration() {
        return player.duration();
    }

    function currentTime() {
        return player.currentTime();
    }

    function setCurrentTime(time) {
        player.setCurrentTime(time);
    }

    function ended() {
        return player.ended();
    }

    function volume() {
        return player.volume();
    }

    function setVolume(volume) {
        player.setVolume(volume);
    }

    function muted() {
        return player.muted();
    }

    function mute() {
        player.mute();
    }

    function unmute() {
        player.unmute();
    }

    function onLoadedMetadata() {
    }

    function onPlay() {
    }

    function onPause() {
    }

    function onPlayTimeChange() {
    }

    function onEnded() {
    }

    return {
        play: play,
        pause: pause,
        destroy: destroy,
        paused: paused,
        duration: duration,
        currentTime: currentTime,
        setCurrentTime: setCurrentTime,
        ended: ended,
        volume: volume,
        setVolume: setVolume,
        muted: muted,
        mute: mute,
        unmute: unmute,
        onLoadedMetadata: onLoadedMetadata,
        onPlay: onPlay,
        onPause: onPause,
        onPlayTimeChange: onPlayTimeChange,
        onEnded: onEnded
    };
}
<|endoftext|>


<commit_before>/**
 * carte blanche implementation for angular2
 */
const path = require('path');
const isString = require('lodash/isString');
const isNaN = require('lodash/isNaN');
const defaults = require('lodash/defaults');

const type_doc_parser = require('./typedocparser.js').getComponentData;

/**
 * Initial plugin function
 *
 * @params {Object} options
 * The options the user sends to the plugin
 *
 * We should get from the user :
 *
 * hostname - hostname for the server
 * port - Port where the server will run
 * variationFolderName - The folder where the variants area
 * files - Files where to look for components? * question
 *
 */
function Angular2Plugin(options) {
    // Make sure the plugin was instantiated as a constructor, i.e. new Angular2Plugin()
    if (!(this instanceof Angular2Plugin)) {
        throw new Error(
            'The Angular2Plugin must be instantiated with the "new" keyword, i.e. "new Angular2Plugin()"\n\n'
        );
    }

    this.options = options || {};

    // The hostname option must be a string
    if (this.options.hostname && !isString(this.options.hostname)) {
        throw new Error('The "hostname" option of the Angular2Plugin must be a string!\n\n');
    }

    const parsedPort = parseFloat(this.options.port);
    // The port option must be something that can be made a number
    if (this.options.port && isNaN(parsedPort)) {
        throw new Error('The "port" option of the Angular2Plugin must be a number!\n\n');
    }

    // If the port can be interpreted as a number, it must be above 0 and below 65535
    if (parsedPort < 0 || parsedPort > 65535) {
        throw new Error('The "port" must be between 0 and 65535 (inc)!\n\n');
    }

    // The variationFolderName option must be a string
    if (this.options.variationFolderName && !isString(this.options.variationFolderName)) {
        throw new Error(
            'The "variationFolderName" option of the Angular2Plugin must be a string!\n\n'
        );
    }

    // The files option must be an Array or a String
    if (this.options.files
        && !isString(this.options.files)
        && (!Array.isArray(this.options.files))) {
        throw new Error(
            'The "files" option of the Angular2Plugin must be an array!\n\n'
        );
    }
}

/**
 * Initializes the plugin, called after the main function above
 */
Angular2Plugin.prototype.apply = function apply(compiler) {
    // Setting Default options for the plugin
    const options = defaults({}, this.options, {
        hostname: 'localhost',
        files: [],
        injectTags: [],
        port: 8082,
        variationFolderName: 'variations',
    });

    // Variations folder path
    const projectBasePath = compiler.options.context;
    const variationBasePath = path.join(projectBasePath, options.variationFolderName);
    options.variationBasePath = variationBasePath;

    // TODO - Run the server to get list and save variations
    compiler.plugin('compilation', (compilation) => {
        // Called before processing the components, mutate data to pass it around
        compilation.plugin('carte-blanche-plugin-before-processing', (data) => {
            // Read the data from this component
            var parsedData = type_doc_parser(data.source, (parsedComponent) => {
                data.AngularSouce = parsedComponent;
            });
        });
        // Called after the processing, gets the renderToClient API to visually
        compilation.plugin(
            'carte-blanche-plugin-processing',
            (renderToClient) => {
                renderToClient({
                    // TODO the name is used in the iframe & playground list
                    // best to pass it in there instead of hardcoding it
                    name: 'angular2',
                    frontendData: { options },
                    frontendPlugin: `${require.resolve('./frontend/index.js')}`, // eslint-disable-line global-require,max-len
                });
            }
        );
    });

};

module.exports = Angular2Plugin;
<commit_msg>Added polyfills in assets hook<commit_after>/**
 * carte blanche implementation for angular2
 */
const path = require('path');
const isString = require('lodash/isString');
const isNaN = require('lodash/isNaN');
const defaults = require('lodash/defaults');

const type_doc_parser = require('./typedocparser.js').getComponentData;

/**
 * Initial plugin function
 *
 * @params {Object} options
 * The options the user sends to the plugin
 *
 * We should get from the user :
 *
 * hostname - hostname for the server
 * port - Port where the server will run
 * variationFolderName - The folder where the variants area
 * files - Files where to look for components? * question
 *
 */
function Angular2Plugin(options) {
    // Make sure the plugin was instantiated as a constructor, i.e. new Angular2Plugin()
    if (!(this instanceof Angular2Plugin)) {
        throw new Error(
            'The Angular2Plugin must be instantiated with the "new" keyword, i.e. "new Angular2Plugin()"\n\n'
        );
    }

    this.options = options || {};

    // The hostname option must be a string
    if (this.options.hostname && !isString(this.options.hostname)) {
        throw new Error('The "hostname" option of the Angular2Plugin must be a string!\n\n');
    }

    const parsedPort = parseFloat(this.options.port);
    // The port option must be something that can be made a number
    if (this.options.port && isNaN(parsedPort)) {
        throw new Error('The "port" option of the Angular2Plugin must be a number!\n\n');
    }

    // If the port can be interpreted as a number, it must be above 0 and below 65535
    if (parsedPort < 0 || parsedPort > 65535) {
        throw new Error('The "port" must be between 0 and 65535 (inc)!\n\n');
    }

    // The variationFolderName option must be a string
    if (this.options.variationFolderName && !isString(this.options.variationFolderName)) {
        throw new Error(
            'The "variationFolderName" option of the Angular2Plugin must be a string!\n\n'
        );
    }

    // The files option must be an Array or a String
    if (this.options.files
        && !isString(this.options.files)
        && (!Array.isArray(this.options.files))) {
        throw new Error(
            'The "files" option of the Angular2Plugin must be an array!\n\n'
        );
    }
}

/**
 * Initializes the plugin, called after the main function above
 */
Angular2Plugin.prototype.apply = function apply(compiler) {
    // Setting Default options for the plugin
    const options = defaults({}, this.options, {
        hostname: 'localhost',
        files: [],
        injectTags: [],
        port: 8082,
        variationFolderName: 'variations',
    });

    // Variations folder path
    const projectBasePath = compiler.options.context;
    const variationBasePath = path.join(projectBasePath, options.variationFolderName);
    options.variationBasePath = variationBasePath;

    // TODO - Run the server to get list and save variations
    compiler.plugin('compilation', (compilation) => {
        // Called before processing the components, mutate data to pass it around
        compilation.plugin('carte-blanche-plugin-before-processing', (data) => {
            // Read the data from this component
            var parsedData = type_doc_parser(data.source, (parsedComponent) => {
                data.AngularSouce = parsedComponent;
            });
        });
        compilation.plugin('carte-blanche-plugin-assets-processing', function (assets) {
            assets.push(path.join(__dirname, './frontend/polyfills.js'));
        });
        // Called after the processing, gets the renderToClient API to visually
        compilation.plugin(
            'carte-blanche-plugin-processing',
            (renderToClient) => {
                renderToClient({
                    // TODO the name is used in the iframe & playground list
                    // best to pass it in there instead of hardcoding it
                    name: 'angular2',
                    frontendData: { options },
                    frontendPlugin: `${require.resolve('./frontend/index.js')}`, // eslint-disable-line global-require,max-len
                });
            }
        );
    });

};

module.exports = Angular2Plugin;
<|endoftext|>


<commit_before>/**
 * Add/Remove Module
 *
 * Usage:
 *
 *

 *
 *
 *
 *
 *
 *

 *

 *        <input type="text" value="Value 1" name="redirectUris[0]" data-add-remove-unique/>
 *

 *

 *        <input type="text" value="Value 2" name="redirectUris[1]" data-add-remove-unique/>
 *

 *

 *        <input type="text" value="Value 3" name="redirectUris[2]" data-add-remove-unique/>
 *

 *

 *
 *

 *
 */

var addRemoveContainer = '[data-add-remove]',
    addRemoveList      = '[data-add-remove-list]',
    addRemoveItem      = '[data-add-remove-item]',
    addButton          = '[data-add-btn]',
    removeButton       = '[data-remove-btn]',
    maxItems           = 'data-add-remove-max';

var itemTemplate       = '[data-item-template]',
    addBtnTemplate     = '[data-add-btn-template]',
    removeBtnTemplate  = '[data-remove-btn-template]';

/**
 * Init add/remove, where necessary
 *
 * @param
 */
module.exports = function() {

  var $addRemoveContainers = $(addRemoveContainer);

  // only continue if counter html exists
  if($addRemoveContainers.length === 0) return;

  // for each add/remove container on the page
  $addRemoveContainers.each(function() {
    var $container = $(this);

    $container.find('[data-removable]').each(function() {
      var $item = $(this);

      // add html for remove button
      insertRemoveButton($container, $item);

      // bind remove click event
      bindRemoveEvent($container, $item);

    });

    // only insert Add button if list has space
    if(!isListFull($container)) {

      // add html for add button
      insertAddButton($container);

    }

    // bind add click
    bindAddEvent($container);

  });

};

/**
 * Insert a Remove button in the item
 *
 * @param $container
 * @param $item
 */
var insertRemoveButton = function($container, $item) {

  var html = $container.find(removeBtnTemplate).html();

  $item.append(html);

};

/**
 * Bind click event on Remove button for an item
 *
 * @param $container
 * @param $item
 */
var bindRemoveEvent = function($container, $item) {

  $item.on('click', removeButton, function(e) {
    e.preventDefault();

    // remove list item
    $item.remove();

    // if there's no Add button
    if($container.find(addButton).length === 0) {

      // insert Add button as there must be at least one available slot
      insertAddButton($container);

    }

  });

};

/**
 * Insert a Add button after the list of items
 *
 * @param $container
 */
var insertAddButton = function($container) {

  var html = $container.find(addBtnTemplate).html();

  $container.append(html);

};

/**
 * Bind a click event to the Add button
 *
 * @param $container
 */
var bindAddEvent = function($container) {

  $container.on('click', addButton, function(e) {

    e.preventDefault();

    addItem($container);

  });

};

/**
 * Add a new item to the list
 *
 * @param $container
 */
var addItem = function($container) {

  var $list    = $container.find(addRemoveList),
      $newItem = createItem($container);

  // only insert Remove button if item should be removable
  if($newItem.is('[data-removable]')) {

    // add the Remove button
    insertRemoveButton($container, $newItem);

    // bind click event on Remove button
    bindRemoveEvent($container, $newItem);

  }

  // append new item to list
  $list.append($newItem);

  // if max length reached
  if(isListFull($container)) {
    $container.find(addButton).remove();
  }

};

/**
 * Create new item based off template
 */
var createItem = function($container) {

  var listCount = $container.find('[data-add-remove-item]').length,      // get count of items
      nameAttr  = $container.attr('data-attr-name'),                     // get pattern for unique name attribute
      $newItem,
      $unique;

  // get clone of template item wrapped in LI
  $newItem = $($container.find(itemTemplate).html());

  // get unique item (e.g. input, textarea) within item
  $unique = $newItem.find('[data-add-remove-unique]');

  // prepare unique attributes for unique element (e.g. input, textarea), if specified
  if(nameAttr) {
    nameAttr = nameAttr.replace(/\$/, listCount);
    $unique.attr({name: nameAttr});
  }

  return $newItem;

};

/**
 * Returns whether or not list is full based on maxItems attribute
 *
 * @param $container
 * @returns {boolean}
 */
var isListFull = function($container) {
  return $container.find(addRemoveItem).length === parseInt($container.attr(maxItems), 10);
};
<commit_msg>add-remove-refactor: bring template script functionality into JavaScript, add ability to send in custom delete and add button text, added ablity to turn on/off delete functionaility, updated usage comments, fix bug to do with order of inputs and deletion<commit_after>/*
Add Remove

A component to add and remove inputs on a page. You have the option of sending in custom attributes for:
- `data-can-delete="true"` to add delete buttons
- `data-delete-btn-text` to send in custom delete button text, this defaults to **Delete** and will only work when the
 `data-can-delete="true"` is set
- `data-add-btn-text` to send in custom add button text, this defaults to **Add another redirect URI**
- `data-max` Maximum items allowed in the list

Markup:

      <input name="example[]"
             type="text"
             class="form-input input--medium"
             data-add-remove-input />

      <input name="example[]"
             type="text"
             class="form-input input--medium"
             data-add-remove-input />

 */

var DEFAULT_ADD_BTN_TEXT = 'Add another redirect URI',
    DEFAULT_DELETE_BTN_TEXT = 'Delete',
    addRemoveContainer = '[data-add-remove]',
    addRemoveList = '[data-add-remove-list]',
    addRemoveItem = '[data-add-remove-item]',
    addRemoveInput = '[data-add-remove-input]',
    addButton = '[data-add-btn]',
    maxItems = 'data-max';

var init = function () {
  var $addRemoveContainers = $(addRemoveContainer);

  if ($addRemoveContainers.length) {

    $addRemoveContainers.each(function (i, container) {
      var $container = $(container);

      if (deleteIsEnabled($container)) {
        $container.find(addRemoveItem).each(function (index, listItem) {
          if (index > 0) {
            addDeleteBtn($(listItem), $container);
          }
        });
      }

      // only insert Add button if list has space
      if (!maxLengthReached($container)) {
        insertAddButton($container);
      }
    });
  }
};

/**
 * Insert a Add button after the list of items
 * @param $container
 */
var insertAddButton = function ($container) {
  var addBtnText = $container.attr('data-add-btn-text') || DEFAULT_ADD_BTN_TEXT;
  var $addInputBtn = $('' + addBtnText + '')
    .click(function (event) {
      event.preventDefault();
      addListItem($container);
    });

  $container.append($addInputBtn);
};

/**
 * Show the add input button
 * @param $container
 */
var showAddButton = function ($container) {
  if (!maxLengthReached($container)) {
    $container.find(addButton).show();
  }
};

/**
 * Hide the add input button
 * @param $container
 */
var hideAddButton = function ($container) {
  if (maxLengthReached($container)) {
    $container.find(addButton).hide();
  }
};

/**
 * Add a new list item to list
 * @param $container
 */
var addListItem = function ($container) {
  var $list = $container.find(addRemoveList),
      $lisItem = createItem($container);

  $list.append($lisItem);
  hideAddButton($container);
};

/**
 * Create new list item containing input. If the attribute data-can-delete="true" has been added to the container
 * then the list item will have the delete functionality added.
 * @param $container
 * @returns {*}
 */
var createItem = function ($container) {
  var $listItemClone,
      $input;

  $listItemClone = $container.find(addRemoveItem).first().clone();
  $input = $listItemClone.find(addRemoveInput);
  $input.val('');

  if (deleteIsEnabled($container)) {
    addDeleteBtn($listItemClone, $container);
  }

  return $listItemClone;
};

var deleteIsEnabled = function ($container) {
  return !!$container.attr('data-can-delete');
};

var addDeleteBtn = function ($listItem, $container) {
  var deleteBtnText = $container.attr('data-delete-btn-text') || DEFAULT_DELETE_BTN_TEXT,
      $deleteBtn;

  $deleteBtn = $('' + deleteBtnText + '')
    .click(function (event) {
      event.preventDefault();
      $listItem.remove();
      showAddButton($container);
    });

  $listItem.append($deleteBtn);
};

/**
 * Returns whether or not list is full based on data-max attribute
 * @param $container
 * @returns {boolean}
 */
var maxLengthReached = function ($container) {
  var listLength = $container.find(addRemoveItem).length;
  var maxListsAllowed = parseInt($container.attr(maxItems), 10);

  return listLength === maxListsAllowed;
};

module.exports = init;
<|endoftext|>


<commit_before>define(function () {
	'use strict';

	function getRequest(data) {
		var xhr =  new ('onload' in new XMLHttpRequest()) XMLHttpRequest : XDomainRequest,
			baseUrl = 'https://www.google.com.ua/search?q=',
			tailUrl = '&tbm=isch';

		xhr.open('GET', baseUrl + encodeURIComponent(data) + tailUrl, true);

		xhr.send();

		xhr.onreadystatechange = function () {
			if (xhr.readyState !== 4) {
				return;
			}

			if (xhr.status !== 200) {
				console.log(xhr.status, ': ', xhr.statusText);
			} else {
				console.log(xhr.responseText);
			}
		};
	}

	/**
	 *	@exports
	 */
	return {
		getRequest: getRequest
	};
});<commit_msg>[Fix] Fix syntax error in AJAX interface detection.<commit_after>define(function () {
	'use strict';

	function getRequest(data) {
		var xhr =  new ('onload' in new XMLHttpRequest() ? XMLHttpRequest : XDomainRequest),
			baseUrl = 'https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=';

		xhr.open('GET', baseUrl + encodeURIComponent(data), true);

		xhr.send();

		xhr.onload = function () {
			console.log(xhr.responseText);
		};
	}

	/**
	 *	@exports
	 */
	return {
		getRequest: getRequest
	};
});<|endoftext|>


<commit_before>(function() {
    /* Start angularLocalStorage */
    'use strict';
    var vocabularyFactory = angular.module('milan.vocabulary.factory', ['penguin.LocalStorageService']);

    vocabularyFactory.factory('vocabularyFactory', function($http, localStorageService) {
        var words = [];
        var usedWords = [];
        var wordsIds = [];
        var MAX_IN_SET = 8;
        var CURRENT_WORDS = 1001;

        function getWords(lesson, learn, native, cb){
            if(words[lesson]){
                cb(words[lesson], wordsIds[lesson]);
            } else {
                if(learn == 'cz'){
                    learn = 'cs';
                }

                if(native == 'cz'){
                    native = 'cs';
                }
                // who created this?????
                // >>> not deleted : 1 - show all (not deleted and unaproved)
                // >>>             0 - NOT show deleted files
                requestGET($http, '/words/get/'+lesson+'/'+learn+'/'+native+'?fields=link,word%20as%20w&nd=0&type=api',function(data){
                    words[lesson] = data.words;
                    wordsIds[lesson] = {};
                    words[lesson].forEach(function(word){
                        wordsIds[lesson][word.link] = word;
                    });

                    cb(words[lesson], wordsIds[lesson]);
                });
            }
        }

        function getNextWords(lesson){
            var rw = [];

            // set first time
            if(!usedWords[lesson]){
                usedWords[lesson] = [];
            }

            do{
                var w = words[lesson].shift();

                // words empty lets use usedWords again
                // TODO: implement load next lang
                if(!w){
                    w = usedWords[lesson].shift();
                    words[lesson] = usedWords[lesson];
                    usedWords[lesson] = [];
                }

                rw.push(w);
                usedWords[lesson].push(w);
            } while(rw.length < MAX_IN_SET)

            return rw;
        }

        function getVocabularyRandomSet(lesson, learn, native, cb){
            getWords(lesson, learn, native,  function(w,i){
                var s1 = getNextWords(lesson);

                var ret = {};
                ret.word1 = [];
                ret.word2 = [];
                s1.forEach(function(w){
                    var w1 = {
                        word : w.w1,
                        link : w.link
                    }

                    var w2 = {
                        word : w.w2,
                        link : w.link
                    }

                    ret.word1.push(w1);
                    ret.word2.push(w2);
                });

                console.log('ret before rand: ', ret);

                ret.word1= shuffle(ret.word1);
                ret.word2 = shuffle(ret.word2);

                console.log('ret after rand: ', ret);
                cb(ret);

            })
        }

        function numEmpty(words){
            var countEmpty = 0;
            words.forEach(function(w){
                if(w==null){
                    countEmpty++;
                }
            });

            return countEmpty;
        }

        function putToEmptyIndex(words, word, index){
            var countEmpty = 0;
            words.some(function(w, realIndex){
                if(w==null){
                    if(countEmpty == index){
                        words.splice(realIndex, 1, word);
                        return true;
                    }
                    countEmpty++;
                }

                return false;
            });

            return countEmpty;
        }

        function shuffle(words){
            var ret = [];
            words.forEach(function(w){
                ret.push(null);
            });

            words.forEach(function(w){
                var countEmpty = numEmpty(ret);

                var randpos1 = 0;
                if(countEmpty > 1){
                    randpos1 = Math.floor((Math.random() * 1000)) % (countEmpty);
                }
                putToEmptyIndex(ret, w, randpos1);
                console.log(countEmpty,randpos1);
            });

            return ret;

        }

        return {
            getVocabularyRandomSet:getVocabularyRandomSet
           };
    });
}).call(this);<commit_msg>put words for one heap<commit_after>(function() {
    /* Start angularLocalStorage */
    'use strict';
    var vocabularyFactory = angular.module('milan.vocabulary.factory', ['penguin.LocalStorageService']);

    vocabularyFactory.factory('vocabularyFactory', function($http, localStorageService) {
        var words = [];
        var usedWords = [];
        var wordsIds = {};
        var loadedLessons = [];
        var MAX_IN_SET = 8;
        var CURRENT_WORDS = 1001;

        function getWords(lesson, learn, native, cb){
            if(loadedLessons.indexOf(lesson) != -1){
                cb(words, wordsIds);
            } else {
                if(learn == 'cz'){
                    learn = 'cs';
                }

                if(native == 'cz'){
                    native = 'cs';
                }
                // who created this?????
                // >>> not deleted : 1 - show all (not deleted and unaproved)
                // >>>             0 - NOT show deleted files
                requestGET($http, '/words/get/'+lesson+'/'+learn+'/'+native+'?fields=link,word%20as%20w&nd=0&type=api',function(data){
                    data.words.forEach(function(word, idx){
                        words.unshift(word);
                        wordsIds[word.link] = word;
                    });

                    // add to list for control if this lesson already downloaded
                    loadedLessons.push(lesson);

                    /* old version
                    words[lesson] = data.words;
                    wordsIds[lesson] = {};
                    words[lesson].forEach(function(word){
                        wordsIds[lesson][word.link] = word;
                    }); */

                    cb(words, wordsIds);
                });
            }
        }

        function getNextWords(lesson){
            var rw = [];

            // set first time
            if(!usedWords){
                usedWords = [];
            }

            do{
                var w = words.shift();

                // words empty lets use usedWords again
                if(!w){
                    w = usedWords.shift();
                    words = usedWords;
                    usedWords = [];
                }

                rw.push(w);
                usedWords.push(w);
            } while(rw.length < MAX_IN_SET)

            return rw;
        }

        function getVocabularyRandomSet(lesson, learn, native, cb){
            getWords(lesson, learn, native,  function(w,i){
                var s1 = getNextWords(lesson);

                var ret = {};
                ret.word1 = [];
                ret.word2 = [];
                s1.forEach(function(w){
                    var w1 = {
                        word : w.w1,
                        link : w.link
                    }

                    var w2 = {
                        word : w.w2,
                        link : w.link
                    }

                    ret.word1.push(w1);
                    ret.word2.push(w2);
                });

                console.log('ret before rand: ', ret);

                ret.word1= shuffle(ret.word1);
                ret.word2 = shuffle(ret.word2);

                console.log('ret after rand: ', ret);
                cb(ret);

            })
        }

        function numEmpty(words){
            var countEmpty = 0;
            words.forEach(function(w){
                if(w==null){
                    countEmpty++;
                }
            });

            return countEmpty;
        }

        function putToEmptyIndex(words, word, index){
            var countEmpty = 0;
            words.some(function(w, realIndex){
                if(w==null){
                    if(countEmpty == index){
                        words.splice(realIndex, 1, word);
                        return true;
                    }
                    countEmpty++;
                }

                return false;
            });

            return countEmpty;
        }

        function shuffle(words){
            var ret = [];
            words.forEach(function(w){
                ret.push(null);
            });

            words.forEach(function(w){
                var countEmpty = numEmpty(ret);

                var randpos1 = 0;
                if(countEmpty > 1){
                    randpos1 = Math.floor((Math.random() * 1000)) % (countEmpty);
                }
                putToEmptyIndex(ret, w, randpos1);
                console.log(countEmpty,randpos1);
            });

            return ret;

        }

        return {
            getVocabularyRandomSet:getVocabularyRandomSet
           };
    });
}).call(this);<|endoftext|>


<commit_before>'use strict';

import { h, Component } from 'preact';
import * as numbers from '../lib/numbers.js';
import { bind } from 'decko';

class CountWidget extends Component {
  constructor(props) {
    super(props)

    this.state = {
      value: "-"
    }
  }

  componentWillReceiveProps(newProps, newState) {
    if(newProps.value == this.props.value) {
      return;
    }

    this.countUp(newProps.value);
  }

  // TODO: Move to component of its own
  @bind
  countUp(toValue) {
    const duration = 1000;
    const easeOutQuint = function (t) { return 1+(--t)*t*t*t*t };
    const setState = this.setState.bind(this);
    const startValue = isFinite(this.state.value) ? this.state.value : 0;
    const diff = toValue - startValue;
    let startTime = performance.now();

    const tick = function(t) {
      let progress = Math.min(( t - startTime ) / duration, 1);
      let newValue = startValue + (easeOutQuint(progress) * diff);
      setState({
        value: newValue,
      })

      if(progress < 1) {
        window.requestAnimationFrame(tick);
      }
    }

    window.requestAnimationFrame(tick);
  }

  render(props, state) {
    let formattedValue = "-";

    if(isFinite(state.value)) {
      switch(props.format) {
        case "percentage":
          formattedValue = numbers.formatPercentage(state.value)
        break;

        default:
        case "number":
            formattedValue = numbers.formatPretty(Math.round(state.value))
        break;

        case "duration":
          formattedValue = numbers.formatDuration(state.value)
        break;
      }
    }

    return (

{props.title}

{formattedValue}

    )
  }
}

export default CountWidget
<commit_msg>improve animation performance of countup by reffing element directly (vs state update)<commit_after>'use strict';

import { h, Component } from 'preact';
import * as numbers from '../lib/numbers.js';
import { bind } from 'decko';

const duration = 1000;
const easeOutQuint = function (t) { return 1+(--t)*t*t*t*t };

class CountWidget extends Component {
  componentWillReceiveProps(newProps, newState) {
    if(newProps.value == this.props.value) {
      return;
    }

    this.countUp(this.props.value || 0, newProps.value);
  }

  // TODO: Move to component of its own
  @bind
  countUp(fromValue, toValue) {
    const format = this.formatValue.bind(this);
    const startValue = isFinite(fromValue) ? fromValue : 0;
    const numberEl = this.numberEl;
    const diff = toValue - startValue;
    let startTime = performance.now();

    const tick = function(t) {
      let progress = Math.min(( t - startTime ) / duration, 1);
      let newValue = startValue + (easeOutQuint(progress) * diff);
      numberEl.textContent = format(newValue)

      if(progress < 1) {
        window.requestAnimationFrame(tick);
      }
    }

    window.requestAnimationFrame(tick);
  }

  @bind
  formatValue(value) {
    let formattedValue = "-";

    if(isFinite(value)) {
      switch(this.props.format) {
        case "percentage":
          formattedValue = numbers.formatPercentage(value)
        break;

        default:
        case "number":
          formattedValue = numbers.formatPretty(Math.round(value))
        break;

        case "duration":
          formattedValue = numbers.formatDuration(value)
        break;
      }
    }

    return formattedValue;
  }

  render(props, state) {
    return (

{props.title}

 { this.numberEl = e; }}>{this.formatValue(props.value)}

    )
  }
}

export default CountWidget
<|endoftext|>


<commit_before>import linearSystem from '../index.js'
import sinon from 'sinon'
describe('linearSystem', () => {
    let linSys;
    let data;
    beforeEach(function() {
        linSys = new linearSystem();
        data = {
          s : [[2,2,6],[9,9,30]]
        };
    });

    describe('_switch', () => {
      it('should exchange places of two diffrent rows', () => {
        let thing = linSys._switch(data,0,1);
        expect(thing.s).toEqual([[9,9,30],[2,2,6]]);
        //mutation check
      });

      it('mutation check', () => {
        let thing = linSys._switch(data,0,1);
        expect(thing.s).toEqual([[9,9,30],[2,2,6]]);
        expect(data).toEqual({ s : [[2,2,6],[9,9,30]]});
      });
    });

    describe("_getRowScaledBy", () => {
      it('should return array mulitplied by scale', () => {
        let row = linSys._getRowScaledBy([2,0,6],2);
        expect(row).toEqual([4,0,12]);
      });

      it('should return array mulitplied to negitive scale', () => {
        let row = linSys._getRowScaledBy([2,0,-6],-1);
        expect(row).toEqual([-2,0,6]);
      });

      it('mutation check', () => {
        let row = linSys._getRowScaledBy([2,0,-6],-1);
        expect(data).toEqual({s : [[2,2,6],[9,9,30]]});
      });
    });

    describe("_rowReplacement", () => {
      it('should call _getRowScaledBy with data', () => {
        let scaledBy = sinon.spy(linSys, '_getRowScaledBy');
        let rowToBeReplaced = 0, otherRow = 1, scale = 2;
        linSys._rowReplacement(data, rowToBeReplaced, otherRow, scale);
        scaledBy.restore();
        sinon.assert.calledWith(scaledBy, [9,9,30], 2);
      });

      it('should return array with a row replaced by itself mulitplied to scale', () => {
        let rowToBeReplaced = 0,otherRow = 1,scale = 2;
        let newthing = linSys._rowReplacement(data, rowToBeReplaced, otherRow, scale);
        expect(newthing).toEqual({s : [[20,20,66],[9,9,30]]});
      });

      it('mutation test', () => {
        let rowToBeReplaced = 0, otherRow = 1, scale = 2;
        linSys._rowReplacement(data, rowToBeReplaced, otherRow, scale);
        expect(data).toEqual({ s : [[2,2,6],[9,9,30]]});
      });
    });

    describe("_largestAbsoluteMovedToTopOfColumn", () => {
      it('should return array with largest absolute value to top of each pivot', () => {
        let inputSystem = {
          s : [
            [0,1,2,3],
            [1,2,3,4],
            [-3,2,1,5]
          ],
          pivot : {
            column : 0,
            row : 0
          }
        };
        let expectedOutput = {
          s : [
            [-3,2,1,5],
            [1,2,3,4],
            [0,1,2,3]
          ],
          pivot : {
            column : 0,
            row : 0
          }
        };
        let output = linSys._largestAbsoluteMovedToTopOfColumn(inputSystem);
        expect(output).toEqual(expectedOutput);
      });

      it("calls _switch with correct values", () => {
        let switchy = sinon.spy(linSys, '_switch');
        let inputSystem = {
          s : [
            [0,1,2,3],
            [1,2,3,4],
            [-3,2,1,5]
          ],
          pivot : {
            column : 0,
            row : 0
          }
        };
        let output = linSys._largestAbsoluteMovedToTopOfColumn(inputSystem);
        switchy.restore();
        sinon.assert.calledWith(switchy, {
          s : [
            [0,1,2,3],
            [1,2,3,4],
            [-3,2,1,5]
          ],
          pivot : {
            column : 0,
            row : 0
          }
        });
      });

      it("mutation check", () => {
        let inputSystem = {
          s : [
            [0,1,2,3],
            [1,2,3,4],
            [-3,2,1,5]
          ],
          pivot : {
            column : 0,
            row : 0
          }
        };
        linSys._largestAbsoluteMovedToTopOfColumn(inputSystem);
        expect(inputSystem).toEqual({
          s : [
            [0,1,2,3],
            [1,2,3,4],
            [-3,2,1,5]
          ],
          pivot : {
            column : 0,
            row : 0
          }
        });
      });
    });

    describe("_zeroAllRowsUnderThePivot", () => {
      it('returns correct value', () => {
        let inputSystem = {
          s : [
            [5,1,1,10],
            [-1,1,1,-2],
            [1,1,1,2]
          ],
          pivot : {
            column : 0,
            row : 0
          }
        };
        let outSystem = linSys._zeroAllRowsUnderThePivot(inputSystem);
        expect(outSystem.s).toEqual(
          [
            [ 5, 1, 1, 10 ],
            [ 0, 1.2, 1.2, 0 ],
            [ 0, 0.8, 0.8, 0 ]
          ]);
      });

      it('mutation check', () => {
        let inputSystem = {
          s : [
            [5,1,1,10],
            [-1,1,1,-2],
            [1,1,1,2]
          ],
          pivot : {
            column : 0,
            row : 0
          }
        };
        let outSystem = linSys._zeroAllRowsUnderThePivot(inputSystem);
        expect(inputSystem).toEqual({
          s : [
            [5,1,1,10],
            [-1,1,1,-2],
            [1,1,1,2]
          ],
          pivot : {
            column : 0,
            row : 0
          }
        });
      });

      it("calls _rowReplacementRemover with correct values", () => {
        let replacer = sinon.spy(linSys, '_rowReplacementRemover');
        let inputSystem = {
          s : [
            [0,1,2,3],
            [1,2,3,4],
            [-3,2,1,5]
          ],
          pivot : {
            column : 0,
            row : 0
          }
        };
        let outSystem = linSys._zeroAllRowsUnderThePivot(inputSystem);
        replacer.restore();
        sinon.assert.calledWithExactly(replacer, {
          s : [
            [0,1,2,3],
            [1,2,3,4],
            [-3,2,1,5]
          ],
          pivot : {
            column : 0,
            row : 0
          }
        },
      1);
      });
    });

    describe("_zeroAllRowsAboveThePivot", () => {
      it("should return correct output", () => {
        let inputSystem = {
          s : [
            [5,3,4,10],
            [0,5,7,14],
            [0,0,2,54],
          ],
          pivot:{row:2,column:2}
        };
        let outputSystem = linSys._zeroAllRowsAboveThePivot(inputSystem);
        expect(outputSystem).toEqual({
          s:[
            [ 5, 3, 0, -98 ],
            [ 0, 5, 0, -175 ],
            [ 0, 0, 2, 54 ]
          ],
          pivot:{row:2,column:2}});
      });
    });

    it('mutation check', () => {
      let inputSystem = {
        s : [
          [5,3,4,10],
          [0,5,7,14],
          [0,0,2,54],
        ],
        pivot:{row:2,column:2}
      };
      let outputSystem = linSys._zeroAllRowsAboveThePivot(inputSystem);
      expect(inputSystem).toEqual({
        s : [
          [5,3,4,10],
          [0,5,7,14],
          [0,0,2,54],
        ],
        pivot:{row:2,column:2}
      });
    });

    it("calls _rowReplacementRemover with correct values", () => {
      let replacer = sinon.spy(linSys, '_rowReplacementRemover');
      let inputSystem = {
        s : [
          [1,2,3,5],
          [0,2,1,5],
          [0,0,5,5]
        ],
        pivot : {row:2,column:2}
      };
      let outSystem = linSys._zeroAllRowsUnderThePivot(inputSystem);
      replacer.restore();
      sinon.assert.calledWithExactly(replacer, {
        s : [
          [1,2,3,5],
          [0,2,1,5],
          [0,0,5,5]
        ],
        pivot : {row:2,column:2}
      },
    1);
    });
    describe("_scalePivotToOne", () => {
      it("returns expected value", () => {
        let testSystem = {
          s : [
            [3,0,0,3],
            [0,2,1,5],
            [0,5,6,7,]
          ],
          pivot : {row:0,column:0}
        };
        let outSystem = linSys._scalePivotToOne(testSystem);
        expect(outSystem).toEqual({
          s : [
            [1,0,0,1],
            [0,2,1,5],
            [0,5,6,7,]
          ],
          pivot : {row:0,column:0}
        });
      });
    });

});
<commit_msg>fixed closure bug in tests<commit_after>import linearSystem from '../index.js'
import sinon from 'sinon'
describe('linearSystem', () => {
    let linSys;
    let data;
    beforeEach(function() {
        linSys = new linearSystem();
        data = {
          s : [[2,2,6],[9,9,30]]
        };
    });

    describe('_switch', () => {
      it('should exchange places of two diffrent rows', () => {
        let thing = linSys._switch(data,0,1);
        expect(thing.s).toEqual([[9,9,30],[2,2,6]]);
        //mutation check
      });

      it('mutation check', () => {
        let thing = linSys._switch(data,0,1);
        expect(thing.s).toEqual([[9,9,30],[2,2,6]]);
        expect(data).toEqual({ s : [[2,2,6],[9,9,30]]});
      });
    });

    describe("_getRowScaledBy", () => {
      it('should return array mulitplied by scale', () => {
        let row = linSys._getRowScaledBy([2,0,6],2);
        expect(row).toEqual([4,0,12]);
      });

      it('should return array mulitplied to negitive scale', () => {
        let row = linSys._getRowScaledBy([2,0,-6],-1);
        expect(row).toEqual([-2,0,6]);
      });

      it('mutation check', () => {
        let row = linSys._getRowScaledBy([2,0,-6],-1);
        expect(data).toEqual({s : [[2,2,6],[9,9,30]]});
      });
    });

    describe("_rowReplacement", () => {
      it('should call _getRowScaledBy with data', () => {
        let scaledBy = sinon.spy(linSys, '_getRowScaledBy');
        let rowToBeReplaced = 0, otherRow = 1, scale = 2;
        linSys._rowReplacement(data, rowToBeReplaced, otherRow, scale);
        scaledBy.restore();
        sinon.assert.calledWith(scaledBy, [9,9,30], 2);
      });

      it('should return array with a row replaced by itself mulitplied to scale', () => {
        let rowToBeReplaced = 0,otherRow = 1,scale = 2;
        let newthing = linSys._rowReplacement(data, rowToBeReplaced, otherRow, scale);
        expect(newthing).toEqual({s : [[20,20,66],[9,9,30]]});
      });

      it('mutation test', () => {
        let rowToBeReplaced = 0, otherRow = 1, scale = 2;
        linSys._rowReplacement(data, rowToBeReplaced, otherRow, scale);
        expect(data).toEqual({ s : [[2,2,6],[9,9,30]]});
      });
    });

    describe("_largestAbsoluteMovedToTopOfColumn", () => {
      it('should return array with largest absolute value to top of each pivot', () => {
        let inputSystem = {
          s : [
            [0,1,2,3],
            [1,2,3,4],
            [-3,2,1,5]
          ],
          pivot : {
            column : 0,
            row : 0
          }
        };
        let expectedOutput = {
          s : [
            [-3,2,1,5],
            [1,2,3,4],
            [0,1,2,3]
          ],
          pivot : {
            column : 0,
            row : 0
          }
        };
        let output = linSys._largestAbsoluteMovedToTopOfColumn(inputSystem);
        expect(output).toEqual(expectedOutput);
      });

      it("calls _switch with correct values", () => {
        let switchy = sinon.spy(linSys, '_switch');
        let inputSystem = {
          s : [
            [0,1,2,3],
            [1,2,3,4],
            [-3,2,1,5]
          ],
          pivot : {
            column : 0,
            row : 0
          }
        };
        let output = linSys._largestAbsoluteMovedToTopOfColumn(inputSystem);
        switchy.restore();
        sinon.assert.calledWith(switchy, {
          s : [
            [0,1,2,3],
            [1,2,3,4],
            [-3,2,1,5]
          ],
          pivot : {
            column : 0,
            row : 0
          }
        });
      });

      it("mutation check", () => {
        let inputSystem = {
          s : [
            [0,1,2,3],
            [1,2,3,4],
            [-3,2,1,5]
          ],
          pivot : {
            column : 0,
            row : 0
          }
        };
        linSys._largestAbsoluteMovedToTopOfColumn(inputSystem);
        expect(inputSystem).toEqual({
          s : [
            [0,1,2,3],
            [1,2,3,4],
            [-3,2,1,5]
          ],
          pivot : {
            column : 0,
            row : 0
          }
        });
      });
    });

    describe("_zeroAllRowsUnderThePivot", () => {
      it('returns correct value', () => {
        let inputSystem = {
          s : [
            [5,1,1,10],
            [-1,1,1,-2],
            [1,1,1,2]
          ],
          pivot : {
            column : 0,
            row : 0
          }
        };
        let outSystem = linSys._zeroAllRowsUnderThePivot(inputSystem);
        expect(outSystem.s).toEqual(
          [
            [ 5, 1, 1, 10 ],
            [ 0, 1.2, 1.2, 0 ],
            [ 0, 0.8, 0.8, 0 ]
          ]);
      });

      it('mutation check', () => {
        let inputSystem = {
          s : [
            [5,1,1,10],
            [-1,1,1,-2],
            [1,1,1,2]
          ],
          pivot : {
            column : 0,
            row : 0
          }
        };
        let outSystem = linSys._zeroAllRowsUnderThePivot(inputSystem);
        expect(inputSystem).toEqual({
          s : [
            [5,1,1,10],
            [-1,1,1,-2],
            [1,1,1,2]
          ],
          pivot : {
            column : 0,
            row : 0
          }
        });
      });

      it("calls _rowReplacementRemover with correct values", () => {
        let replacer = sinon.spy(linSys, '_rowReplacementRemover');
        let inputSystem = {
          s : [
            [0,1,2,3],
            [1,2,3,4],
            [-3,2,1,5]
          ],
          pivot : {
            column : 0,
            row : 0
          }
        };
        let outSystem = linSys._zeroAllRowsUnderThePivot(inputSystem);
        replacer.restore();
        sinon.assert.calledWithExactly(replacer, {
          s : [
            [0,1,2,3],
            [1,2,3,4],
            [-3,2,1,5]
          ],
          pivot : {
            column : 0,
            row : 0
          }
        },
      1);
      });
    });

    describe("_zeroAllRowsAboveThePivot", () => {
      it("should return correct output", () => {
        let inputSystem = {
          s : [
            [5,3,4,10],
            [0,5,7,14],
            [0,0,2,54],
          ],
          pivot:{row:2,column:2}
        };
        let outputSystem = linSys._zeroAllRowsAboveThePivot(inputSystem);
        expect(outputSystem).toEqual({
          s:[
            [ 5, 3, 0, -98 ],
            [ 0, 5, 0, -175 ],
            [ 0, 0, 2, 54 ]
          ],
          pivot:{row:2,column:2}});
      });
    });

    it('mutation check', () => {
      let inputSystem = {
        s : [
          [5,3,4,10],
          [0,5,7,14],
          [0,0,2,54],
        ],
        pivot:{row:2,column:2}
      };
      let outputSystem = linSys._zeroAllRowsAboveThePivot(inputSystem);
      expect(inputSystem).toEqual({
        s : [
          [5,3,4,10],
          [0,5,7,14],
          [0,0,2,54],
        ],
        pivot:{row:2,column:2}
      });

    it("calls _rowReplacementRemover with correct values", () => {
      let replacer = sinon.spy(linSys, '_rowReplacementRemover');
      let inputSystem = {
        s : [
          [1,2,3,5],
          [0,2,1,5],
          [0,0,5,5]
        ],
        pivot : {row:2,column:2}
      };
      let outSystem = linSys._zeroAllRowsUnderThePivot(inputSystem);
      replacer.restore();
      sinon.assert.calledWithExactly(replacer, {
        s : [
          [1,2,3,5],
          [0,2,1,5],
          [0,0,5,5]
        ],
        pivot : {row:2,column:2}
      },
    1);
    });
    });

    describe("_scalePivotToOne", () => {
      it("returns expected value", () => {
        let testSystem = {
          s : [
            [3,0,0,3],
            [0,2,1,5],
            [0,5,6,7,]
          ],
          pivot : {row:0,column:0}
        };
        let outSystem = linSys._scalePivotToOne(testSystem);
        expect(outSystem).toEqual({
          s : [
            [1,0,0,1],
            [0,2,1,5],
            [0,5,6,7,]
          ],
          pivot : {row:0,column:0}
        });
      });
    });

});
<|endoftext|>


<commit_before>'use babel';

import RestartAtom from '../lib/restart-atom';

// Use the command `window:run-package-specs` (cmd-alt-ctrl-p) to run specs.
//
// To run a specific `it` or `describe` block add an `f` to the front (e.g. `fit`
// or `fdescribe`). Remove the `f` to unfocus the block.

describe('RestartAtom', () => {
  let workspaceElement, activationPromise;

  beforeEach(() => {
    workspaceElement = atom.views.getView(atom.workspace);
    activationPromise = atom.packages.activatePackage('restart-atom');
  });

  describe('when the restart-atom:toggle event is triggered', () => {
    it('hides and shows the modal panel', () => {
      // Before the activation event the view is not on the DOM, and no panel
      // has been created
      expect(workspaceElement.querySelector('.restart-atom')).not.toExist();

      // This is an activation event, triggering it will cause the package to be
      // activated.
      atom.commands.dispatch(workspaceElement, 'restart-atom:toggle');

      waitsForPromise(() => {
        return activationPromise;
      });

      runs(() => {
        expect(workspaceElement.querySelector('.restart-atom')).toExist();

        let restartAtomElement = workspaceElement.querySelector('.restart-atom');
        expect(restartAtomElement).toExist();

        let restartAtomPanel = atom.workspace.panelForItem(restartAtomElement);
        expect(restartAtomPanel.isVisible()).toBe(true);
        atom.commands.dispatch(workspaceElement, 'restart-atom:toggle');
        expect(restartAtomPanel.isVisible()).toBe(false);
      });
    });

    it('hides and shows the view', () => {
      // This test shows you an integration test testing at the view level.

      // Attaching the workspaceElement to the DOM is required to allow the
      // `toBeVisible()` matchers to work. Anything testing visibility or focus
      // requires that the workspaceElement is on the DOM. Tests that attach the
      // workspaceElement to the DOM are generally slower than those off DOM.
      jasmine.attachToDOM(workspaceElement);

      expect(workspaceElement.querySelector('.restart-atom')).not.toExist();

      // This is an activation event, triggering it causes the package to be
      // activated.
      atom.commands.dispatch(workspaceElement, 'restart-atom:toggle');

      waitsForPromise(() => {
        return activationPromise;
      });

      runs(() => {
        // Now we can test for view visibility
        let restartAtomElement = workspaceElement.querySelector('.restart-atom');
        expect(restartAtomElement).toBeVisible();
        atom.commands.dispatch(workspaceElement, 'restart-atom:toggle');
        expect(restartAtomElement).not.toBeVisible();
      });
    });
  });
});
<commit_msg>Remove non-functioning test<commit_after><|endoftext|>


<commit_before>/************************************
* Copyright (c) 2014 AnsibleWorks, Inc.
*
*  Sockets.js
*  SocketsController- simple test of socket connection
*
*/

'use strict';

function SocketsController ($scope, $compile, ClearScope, Socket) {

    ClearScope();

    var test_scope = $scope.$new(),
        jobs_scope = $scope.$new(),
        job_events_scope = $scope.$new(),
        test_socket = Socket({ scope: test_scope, endpoint: "test" }),
        jobs_socket = Socket({ scope: jobs_scope, endpoint: "jobs" }),
        job_events_socket = Socket({ scope: job_events_scope, endpoint: "job_events" }),
        e, html;

    test_scope.messages = [];
    jobs_scope.messages = [];
    job_events_scope.messages = [];

    html = "
Socket url: {{ socket_url }}  Status: {{ socket_status }} {{ socket_reason }}
\n" +
        "
\n" +
        "
Received Messages:
\n" +
        "
\n" +
        "
{{ message }}
\n" +
        "
\n" +
        "
\n";

    e = angular.element(document.getElementById('test-container'));
    e.append(html);
    $compile(e)(test_scope);
    e = angular.element(document.getElementById('jobs-container'));
    e.append(html);
    $compile(e)(jobs_scope);
    e = angular.element(document.getElementById('job-events-container'));
    e.append(html);
    $compile(e)(job_events_scope);

    test_socket.init();
    jobs_socket.init();
    job_events_socket.init();

    test_scope.messages.push('Message Displayed Before Connection');

    test_socket.on('test', function(data) {
        test_scope.messages.push(data);
    });

    jobs_socket.on("status_changed", function(data) {
        jobs_scope.messages.push(data);
    });
}

SocketsController.$inject = [ '$scope', '$compile', 'ClearScope', 'Socket'];
<commit_msg>Job events subscription form- subscribe to events for a specific job.<commit_after>/************************************
* Copyright (c) 2014 AnsibleWorks, Inc.
*
*  Sockets.js
*  SocketsController- simple test of socket connection
*
*/

'use strict';

function SocketsController ($scope, $compile, ClearScope, Socket) {

    ClearScope();

    var test_scope = $scope.$new(),
        jobs_scope = $scope.$new(),
        job_events_scope = $scope.$new(),
        test_socket = Socket({ scope: test_scope, endpoint: "test" }),
        jobs_socket = Socket({ scope: jobs_scope, endpoint: "jobs" }),
        job_events_socket = Socket({ scope: job_events_scope, endpoint: "job_events" }),
        e, html;

    test_scope.messages = [];
    jobs_scope.messages = [];
    job_events_scope.messages = [];

    html = "
Socket url: {{ socket_url }}  Status: {{ socket_status }} {{ socket_reason }}
\n" +
        "
\n" +
        "
Received Messages:
\n" +
        "
\n" +
        "
{{ message }}
\n" +
        "
\n" +
        "
\n";

    e = angular.element(document.getElementById('test-container'));
    e.append(html);
    $compile(e)(test_scope);
    e = angular.element(document.getElementById('jobs-container'));
    e.append(html);
    $compile(e)(jobs_scope);

    html = "
Socket url: {{ socket_url }}  Status: {{ socket_status }} {{ socket_reason }}
\n" +
            "<form class=\"form-inline\">\n" +
                "
\n" +
                   "Job Id\n" +
                   "<input type=\"text\" name=\"job_id\" id=\"job_id\" ng-model=\"job_id\" class=\"input-sm form-control\">\n" +
                "
\n" +
                "<button type=\"submit\" ng-disabled=\"!job_id\" ng-click=\"subscribeToJobEvent()\" class=\"btn btn-sm btn-primary\"> Subscribe</button>\n" +
            "</form>\n" +
            "
\n" +
               "
Subscribed to events for job: {{ jobs_list }}
\n" +
               "
Received Messages:
\n" +
               "
\n" +
                  "
{{ message }}
\n" +
               "
\n" +
            "
\n";

    e = angular.element(document.getElementById('job-events-container'));
    e.append(html);
    $compile(e)(job_events_scope);

    test_socket.init();
    jobs_socket.init();
    job_events_socket.init();

    test_scope.messages.push('Message Displayed Before Connection');

    test_socket.on('test', function(data) {
        test_scope.messages.push(data);
    });

    jobs_socket.on("status_changed", function(data) {
        jobs_scope.messages.push(data);
    });

    job_events_scope.jobs_list = [];

    job_events_scope.subscribeToJobEvent = function() {
        job_events_scope.jobs_list.push(job_events_scope.job_id);
        job_events_socket.on("job_events-" + job_events_scope.job_id, function(data) {
            jobs_scope.messages.push(data);
        });
    };
}

SocketsController.$inject = [ '$scope', '$compile', 'ClearScope', 'Socket'];
<|endoftext|>


<commit_before>const axios = require('axios')
const { test } = require('tap')

const fixtures = require('../../..')

test('paginate issues', async (t) => {
  const mock = fixtures.mock('api.github.com/paginate-issues')

  // https://developer.github.com/v3/issues/#list-issues-for-a-repository
  // Get pages 1 - 5.
  const baseUrl = 'https://api.github.com/repos/octokit-fixture-org/paginate-issues/issues?per_page=3'
  const options = {
    method: 'get',
    headers: {
      Accept: 'application/vnd.github.v3+json',
      Authorization: 'token 0000000000000000000000000000000000000001'
    }
  }

  await axios.request(Object.assign(options, {
    url: `${baseUrl}&page=1`
  })).catch(mock.explain)

  for (let i = 2; i <= 5; i++) {
    await axios.request(Object.assign(options, {
      url: `${baseUrl}&page=${i}`
    })).catch(mock.explain)
  }

  t.doesNotThrow(mock.done.bind(mock), 'satisfies all mocks')
  t.end()
})
<commit_msg>test: use URLs from "Link" response header for pagination<commit_after>const axios = require('axios')
const { test } = require('tap')

const fixtures = require('../../..')

test('paginate issues', async (t) => {
  const mock = fixtures.mock('api.github.com/paginate-issues')

  // https://developer.github.com/v3/issues/#list-issues-for-a-repository
  // Get pages 1 - 5.
  const options = {
    method: 'get',
    headers: {
      Accept: 'application/vnd.github.v3+json',
      Authorization: 'token 0000000000000000000000000000000000000001'
    }
  }

  const urls = [
    'https://api.github.com/repos/octokit-fixture-org/paginate-issues/issues?per_page=3',
    'https://api.github.com/repositories/1000/issues?per_page=3&page=2',
    'https://api.github.com/repositories/1000/issues?per_page=3&page=3',
    'https://api.github.com/repositories/1000/issues?per_page=3&page=4',
    'https://api.github.com/repositories/1000/issues?per_page=3&page=5'
  ]

  for (var i = 0; i < urls.length; i++) {
    await axios.request(Object.assign(options, {
      url: urls[i]
    })).catch(mock.explain)
  }

  t.doesNotThrow(mock.done.bind(mock), 'satisfies all mocks')
  t.end()
})
<|endoftext|>


<commit_before>
// Instrumentation Header
{
    var fs = require('fs');
    var <%= instrumented.names.statement %>, <%= instrumented.names.expression %>, <%= instrumented.names.block %>;
    var store = require('<%= coverageStorePath %>');

    <%= instrumented.names.statement %> = function(i) {
        var fd = store.register('<%= filename %>');
        fs.writeSync(fd, '{"statement": {"node": ' + i + '}},\n');
    };

    <%= instrumented.names.expression %> = function(i) {
        var fd = store.register('<%= filename %>');
        fs.writeSync(fd, '{"expression": {"node": ' + i + '}},\n');
    };

    <%= instrumented.names.block %> = function(i) {
        var fd = store.register('<%= filename %>');
        fs.writeSync(fd, '{"block": ' + i + '},\n');
    };
    <%= instrumented.names.intro %> = function(id, obj) {
        // console.log('__intro: ', id, ', obj.__instrumented_miss: ', obj.__instrumented_miss, ', obj.length: ', obj.length);
        obj.__instrumented_miss = obj.__instrumented_miss || [];
        if ('undefined' !== typeof obj && 'undefined' !== typeof obj.__instrumented_miss) {
            if (obj.length === 0) {
                // console.log('interim miss: ', id);
                obj.__instrumented_miss[id] = true;
            } else {
                obj.__instrumented_miss[id] = false;
            }
        }
        return obj;
    };
    function isProbablyChainable(obj, id) {
        return obj &&
            obj.__instrumented_miss[id] !== undefined &&
            'number' === typeof obj.length;
    }
    <%= instrumented.names.extro %> = function(id, obj) {
        var fd = store.register('<%= filename %>');
        // console.log('__extro: ', id, ', obj.__instrumented_miss: ', obj.__instrumented_miss, ', obj.length: ', obj.length);
        if ('undefined' !== typeof obj && 'undefined' !== typeof obj.__instrumented_miss) {
            if (isProbablyChainable(obj, id) && obj.length === 0 && obj.__instrumented_miss[id]) {
                // if the call was not a "constructor" - i.e. it did not add things to the chainable
                // and it did not return anything from the chainable, it is a miss
                // console.log('miss: ', id);
            } else {
                fs.writeSync(fd, '{"chain": {"node": ' + id + '}},\n');
            }
            obj.__instrumented_miss[id] = undefined;
        } else {
            fs.writeSync(fd, '{"chain": {"node": ' + id + '}},\n');
        }
        return obj;
    };
};
////////////////////////

// Instrumented Code
<%= source %><commit_msg>make the chainable instrumentation work with null objects<commit_after>
// Instrumentation Header
{
    var fs = require('fs');
    var <%= instrumented.names.statement %>, <%= instrumented.names.expression %>, <%= instrumented.names.block %>;
    var store = require('<%= coverageStorePath %>');

    <%= instrumented.names.statement %> = function(i) {
        var fd = store.register('<%= filename %>');
        fs.writeSync(fd, '{"statement": {"node": ' + i + '}},\n');
    };

    <%= instrumented.names.expression %> = function(i) {
        var fd = store.register('<%= filename %>');
        fs.writeSync(fd, '{"expression": {"node": ' + i + '}},\n');
    };

    <%= instrumented.names.block %> = function(i) {
        var fd = store.register('<%= filename %>');
        fs.writeSync(fd, '{"block": ' + i + '},\n');
    };
    <%= instrumented.names.intro %> = function(id, obj) {
        // console.log('__intro: ', id, ', obj.__instrumented_miss: ', obj.__instrumented_miss, ', obj.length: ', obj.length);
        obj.__instrumented_miss = obj.__instrumented_miss || [];
        if ('undefined' !== typeof obj && null !== obj && 'undefined' !== typeof obj.__instrumented_miss) {
            if (obj.length === 0) {
                // console.log('interim miss: ', id);
                obj.__instrumented_miss[id] = true;
            } else {
                obj.__instrumented_miss[id] = false;
            }
        }
        return obj;
    };
    function isProbablyChainable(obj, id) {
        return obj &&
            obj.__instrumented_miss[id] !== undefined &&
            'number' === typeof obj.length;
    }
    <%= instrumented.names.extro %> = function(id, obj) {
        var fd = store.register('<%= filename %>');
        // console.log('__extro: ', id, ', obj.__instrumented_miss: ', obj.__instrumented_miss, ', obj.length: ', obj.length);
        if ('undefined' !== typeof obj && null !== obj && 'undefined' !== typeof obj.__instrumented_miss) {
            if (isProbablyChainable(obj, id) && obj.length === 0 && obj.__instrumented_miss[id]) {
                // if the call was not a "constructor" - i.e. it did not add things to the chainable
                // and it did not return anything from the chainable, it is a miss
                // console.log('miss: ', id);
            } else {
                fs.writeSync(fd, '{"chain": {"node": ' + id + '}},\n');
            }
            obj.__instrumented_miss[id] = undefined;
        } else {
            fs.writeSync(fd, '{"chain": {"node": ' + id + '}},\n');
        }
        return obj;
    };
};
////////////////////////

// Instrumented Code
<%= source %><|endoftext|>


<commit_before>//= require jquery

var // The iFrame
    showFrame = document.getElementById("frame"),
    xdm = window.easyXDM.noConflict("FACTLINK"),
    // The global remote object
    remote = new xdm.Rpc({}, {
      remote: {
        hide: {},
        show: {},
        highlightNewFactlink: {},
        stopHighlightingFactlink: {},
        createdNewFactlink: {},
        trigger: {}
      },
      local: {
        showFactlink: function(id, successFn) {
          var successCalled  = 0;
          var onLoadSuccess = function(){
            if (! successCalled ){
              successCalled++;
              successFn();
            }

          };
          showFrame.onload = onLoadSuccess;

          // Somehow only lower case letters seem to work for those events --mark
          $(document).bind("modalready", onLoadSuccess);

          showFrame.src = "/facts/" + id + "?layout=client";

          // Show the overlay
          showFrame.className = "overlay";
        },

        prepareNewFactlink: function(text, siteUrl, siteTitle, successFn, errorFn) {

          var successCalled = 0;
          var onLoadSuccess = function() {
            if (! successCalled ){
              successCalled++;

              if ( $.isFunction( successFn ) ) {
                successFn();
              }
            }
          };

          showFrame.onload = onLoadSuccess;

          // Somehow only lower case letters seem to work for those events --mark
          $(document).bind("modalready", onLoadSuccess);

          showFrame.src = "/facts/new" +
                                      "?fact="  + encodeURIComponent(text) +
                                      "&url="   + encodeURIComponent(siteUrl) +
                                      "&title=" + encodeURIComponent(siteTitle) +
                                      "&layout=client";
          // Show the overlay
          showFrame.className = "overlay";

          var onFactlinkCreated = function(e, id) {
            remote.highlightNewFactlink(text, id);
          };
          $(document).bind("factlinkCreated", onFactlinkCreated);

        },

        position: function(top, left) {
          try {
            showFrame.contentWindow.position(top, left);
          } catch (e) { // Window not yet loaded
            showFrame.onload = function() {
              showFrame.contentWindow.position(top, left);
            };
          }
        }
      }
    });
<commit_msg>Prevent scroll propagation in JS Lib<commit_after>//= require jquery
//= require jquery.prevent_scroll_propagation

var // The iFrame
    showFrame = document.getElementById("frame"),
    xdm = window.easyXDM.noConflict("FACTLINK"),
    // The global remote object
    remote = new xdm.Rpc({}, {
      remote: {
        hide: {},
        show: {},
        highlightNewFactlink: {},
        stopHighlightingFactlink: {},
        createdNewFactlink: {},
        trigger: {}
      },
      local: {
        showFactlink: function(id, successFn) {
          var successCalled  = 0;
          var onLoadSuccess = function(){
            if (! successCalled ){
              successCalled++;
              successFn();
            }

          };
          showFrame.onload = onLoadSuccess;

          // Somehow only lower case letters seem to work for those events --mark
          $(document).bind("modalready", onLoadSuccess);

          showFrame.src = "/facts/" + id + "?layout=client";

          // Show the overlay
          showFrame.className = "overlay";
        },

        prepareNewFactlink: function(text, siteUrl, siteTitle, successFn, errorFn) {

          var successCalled = 0;
          var onLoadSuccess = function() {
            if (! successCalled ){
              successCalled++;

              if ( $.isFunction( successFn ) ) {
                successFn();
              }
            }
          };

          showFrame.onload = onLoadSuccess;

          // Somehow only lower case letters seem to work for those events --mark
          $(document).bind("modalready", onLoadSuccess);

          showFrame.src = "/facts/new" +
                                      "?fact="  + encodeURIComponent(text) +
                                      "&url="   + encodeURIComponent(siteUrl) +
                                      "&title=" + encodeURIComponent(siteTitle) +
                                      "&layout=client";
          // Show the overlay
          showFrame.className = "overlay";

          var onFactlinkCreated = function(e, id) {
            remote.highlightNewFactlink(text, id);
          };
          $(document).bind("factlinkCreated", onFactlinkCreated);

        },

        position: function(top, left) {
          try {
            showFrame.contentWindow.position(top, left);
          } catch (e) { // Window not yet loaded
            showFrame.onload = function() {
              showFrame.contentWindow.position(top, left);
            };
          }
        }
      }
    });

$('iframe').preventScrollPropagation();
<|endoftext|>


<commit_before>import Component from 'ember-component';
import { bool } from 'ember-computed';
import layout from '../templates/components/basic-info';
import RSVP from 'rsvp';
import Changeset from 'ember-changeset';
import lookupValidator from 'ember-changeset-validations';
import validations from 'nypr-account-settings/validators/basic-info';

export default Component.extend({
  layout,
  tagName: '',
  isShowingModal: bool('resolveModal'),
  user: {},

  init() {
    this._super(...arguments);
    let user = this.get('user');
    let changeset = new Changeset(user, lookupValidator(validations), validations);
    this.changeset = changeset;
  },

  emailRequirement(component) {
    return new RSVP.Promise((resolve, reject) => {
      component.setProperties({
        resolveModal: resolve,
        rejectModal: reject
      });
    });
  },

  rollbackEmailField(changeset) {
    // work around to rollback specific fields
    let snapshot = changeset.snapshot();
    changeset.rollback();
    delete snapshot.changes.email;
    delete snapshot.changes.confirmEmail;
    changeset.restore(snapshot);
  },

  actions: {
    save(changeset) {
      let verifyEmail = changeset.get('change.email');

      if (!verifyEmail) {
        // if we're not editing email, manually confirm it so changeset passes
        changeset.set('confirmEmail', changeset.get('email'));
      }
      return changeset.validate().then(() => {
        if (changeset.get('isValid') && verifyEmail) {
          return this.get('emailRequirement')(this)
            .then(() => {
              return changeset.save().then(() => this.set('isEditing', false));
            })
            .catch(() => {
              this.rollbackEmailField(changeset);
            });
        } else if (changeset.get('isValid')) {
          return changeset.save().then(() => this.set('isEditing', false));
        } else {
          return changeset.get('errors');
        }
      });
    },
    rollback(changeset) {
      changeset.rollback();
      this.set('isEditing', false);
    },

    closeModal() {
      this.get('rejectModal')();
      this.setProperties({
        resolveModal: null,
        rejectModal: null
      });
    }
  }
});
<commit_msg>rearrange save action so validation is deferred until required<commit_after>import Component from 'ember-component';
import { bool } from 'ember-computed';
import layout from '../templates/components/basic-info';
import RSVP from 'rsvp';
import Changeset from 'ember-changeset';
import lookupValidator from 'ember-changeset-validations';
import validations from 'nypr-account-settings/validators/basic-info';

export default Component.extend({
  layout,
  tagName: '',
  isShowingModal: bool('resolveModal'),
  user: {},

  init() {
    this._super(...arguments);
    let user = this.get('user');
    let changeset = new Changeset(user, lookupValidator(validations), validations);
    this.changeset = changeset;
  },

  emailRequirement() {
    return new RSVP.Promise((resolve, reject) => {
      this.setProperties({
        resolveModal: resolve,
        rejectModal: reject
      });
    });
  },

  rollbackEmailField(changeset) {
    // work around to rollback specific fields
    let snapshot = changeset.snapshot();
    changeset.rollback();
    delete snapshot.changes.email;
    delete snapshot.changes.confirmEmail;
    changeset.restore(snapshot);
  },

  actions: {
    save(changeset) {
      let stepOne;
      let verifyEmail = changeset.get('change.email');

      if (!verifyEmail) {
        // if we're not editing email, manually confirm it so changeset passes
        changeset.set('confirmEmail', changeset.get('email'));
        stepOne = changeset.validate();
      } else {
        // otherwise do the email requirement first before moving onto the rest
        // of the validations. this lets us show the modal w/o incurring the delay
        // of doing the username remote validation.
        stepOne = this.emailRequirement();
        stepOne.then(() => changeset.validate());
        stepOne.catch(() => {
          this._canceled = true;
          this.rollbackEmailField(changeset);
        });
      }
      return stepOne.then(() => {
        if (changeset.get('isValid')) {
          return changeset.save().then(() => this.set('isEditing', false));
        } else if (!this._canceled){
          return changeset.get('errors');
        } else if (this._canceled){
          this._canceled = null;
        }
      });
    },
    rollback(changeset) {
      changeset.rollback();
      this.set('isEditing', false);
    },

    closeModal() {
      this.get('rejectModal')();
      this.setProperties({
        resolveModal: null,
        rejectModal: null
      });
    }
  }
});
<|endoftext|>