<commit_before>/**
 * A texture of a [playing] Video.
 *
 * See the ["deus" demo](http://www.goodboydigital.com/pixijs/examples/deus/).
 *
 * @class VideoTexture
 * @extends BaseTexture
 * @constructor
 * @param source {HTMLVideoElement}
 * @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values
 */
PIXI.VideoTexture = function(source, scaleMode)
{
    if (!source)
    {
        throw new Error( 'No video source element specified.' );
    }

    // hook in here to check if video is already available.
    // PIXI.BaseTexture looks for a source.complete boolean, plus width & height.

    if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA ) && source.width && source.height)
    {
        source.complete = true;
    }

    this.video = this.source;

    this.ended = false;

    PIXI.BaseTexture.call(this, source, scaleMode);

    this.autoUpdate = false;
    this.updateBound = this._onUpdate.bind(this);

    if (!source.complete)
    {
        this._onCanPlay = this.onCanPlay.bind(this);

        source.addEventListener('canplay', this._onCanPlay);
        source.addEventListener('canplaythrough', this._onCanPlay);
        source.addEventListener('ended', this._onEnded.bind(this));

        // started playing..
        source.addEventListener('play', this.onPlayStart.bind(this));
        source.addEventListener('pause', this.onPlayStop.bind(this));
    }

    this.onPlay = new Phaser.Signal();
    this.onComplete = new Phaser.Signal();

};

PIXI.VideoTexture.prototype = Object.create(PIXI.BaseTexture.prototype);
PIXI.VideoTexture.constructor = PIXI.VideoTexture;

PIXI.VideoTexture.prototype.play = function()
{
    this.source.play();
    this.onPlay.dispatch();
};

PIXI.VideoTexture.prototype.stop = function()
{
    this.source.stop();
    this.onComplete.dispatch();
};

PIXI.VideoTexture.prototype._onEnded = function()
{
    this.ended = true;
    this.onComplete.dispatch();
};

PIXI.VideoTexture.prototype._onUpdate = function()
{
    if (this.autoUpdate)
    {
        window.requestAnimationFrame(this.updateBound);
        this.dirty();
    }
};

PIXI.VideoTexture.prototype.onPlayStart = function()
{
    if (!this.autoUpdate)
    {
        window.requestAnimationFrame(this.updateBound);
        this.autoUpdate = true;
    }
};

PIXI.VideoTexture.prototype.onPlayStop = function()
{
    this.autoUpdate = false;
};

PIXI.VideoTexture.prototype.onCanPlay = function()
{
    if (event.type === 'canplaythrough')
    {
        this.hasLoaded = true;

        if (this.source)
        {
            this.source.removeEventListener('canplay', this._onCanPlay);
            this.source.removeEventListener('canplaythrough', this._onCanPlay);

            this.width = this.source.videoWidth;
            this.height = this.source.videoHeight;

            // prevent multiple loaded dispatches..
            if (!this.__loaded )
            {
                this.__loaded = true;
                this.dispatchEvent( { type: 'loaded', content: this } );
            }
        }
    }
};

PIXI.VideoTexture.prototype.destroy = function()
{
    if (this.source && this.source._pixiId)
    {
        PIXI.BaseTextureCache[ this.source._pixiId ] = null;
        delete PIXI.BaseTextureCache[this.source._pixiId];

        this.source._pixiId = null;
        delete this.source._pixiId;
    }

    PIXI.BaseTexture.prototype.destroy.call( this );
};

/**
 * Mimic Pixi BaseTexture.from.... method.
 *
 * @static
 * @method baseTextureFromVideo
 * @param video {HTMLVideoElement}
 * @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values
 * @return {VideoTexture}
 */
PIXI.VideoTexture.baseTextureFromVideo = function(video, scaleMode)
{
    if (!video._pixiId)
    {
        video._pixiId = 'video_' + PIXI.TextureCacheIdGenerator++;
    }

    var baseTexture = PIXI.BaseTextureCache[video._pixiId];

    if (!baseTexture)
    {
        baseTexture = new PIXI.VideoTexture(video, scaleMode);
        PIXI.BaseTextureCache[video._pixiId] = baseTexture;
    }

    return baseTexture;
};

/**
 * Mimic Pixi BaseTexture.from.... method.
 *
 * @static
 * @method textureFromVideo
 * @param video {HTMLVideoElement}
 * @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values
 * @return {Texture} A Texture, but not a VideoTexture.
 */
PIXI.VideoTexture.textureFromVideo = function(video, scaleMode)
{
    var baseTexture = PIXI.VideoTexture.baseTextureFromVideo(video, scaleMode);

    return new PIXI.Texture(baseTexture);
};

/**
 * Mimic Pixi BaseTexture.from.... method.
 *
 * @static
 * @method fromUrl
 * @param videoSrc {String} The URL for the video.
 * @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values
 * @param autoPlay {boolean} Automatically start the video playing? Until you do this you can't get the width / height of the resulting texture.
 * @return {VideoTexture}
 */
PIXI.VideoTexture.fromUrl = function(videoSrc, scaleMode, autoPlay)
{
    if (typeof scaleMode === 'undefined') { scaleMode = PIXI.scaleModes.DEFAULT; }
    if (typeof autoPlay === 'undefined') { autoPlay = true; }

    var video = document.createElement('video');

    video.src = videoSrc;

    if (autoPlay)
    {
        video.autoPlay = true;
        video.play();
    }
    else
    {
        video.autoPlay = false;
    }

    return PIXI.VideoTexture.textureFromVideo(video, scaleMode);
};
<commit_msg>pause not stop.<commit_after>/**
 * A texture of a [playing] Video.
 *
 * See the ["deus" demo](http://www.goodboydigital.com/pixijs/examples/deus/).
 *
 * @class VideoTexture
 * @extends BaseTexture
 * @constructor
 * @param source {HTMLVideoElement}
 * @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values
 */
PIXI.VideoTexture = function(source, scaleMode)
{
    if (!source)
    {
        throw new Error( 'No video source element specified.' );
    }

    // hook in here to check if video is already available.
    // PIXI.BaseTexture looks for a source.complete boolean, plus width & height.

    if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA ) && source.width && source.height)
    {
        source.complete = true;
    }

    this.video = this.source;

    this.ended = false;

    PIXI.BaseTexture.call(this, source, scaleMode);

    this.autoUpdate = false;
    this.updateBound = this._onUpdate.bind(this);

    if (!source.complete)
    {
        this._onCanPlay = this.onCanPlay.bind(this);

        source.addEventListener('canplay', this._onCanPlay);
        source.addEventListener('canplaythrough', this._onCanPlay);
        source.addEventListener('ended', this._onEnded.bind(this));

        // started playing..
        source.addEventListener('play', this.onPlayStart.bind(this));
        source.addEventListener('pause', this.onPlayStop.bind(this));
    }

    this.onPlay = new Phaser.Signal();
    this.onComplete = new Phaser.Signal();

};

PIXI.VideoTexture.prototype = Object.create(PIXI.BaseTexture.prototype);
PIXI.VideoTexture.constructor = PIXI.VideoTexture;

PIXI.VideoTexture.prototype.play = function()
{
    this.source.play();
    this.onPlay.dispatch();
};

PIXI.VideoTexture.prototype.stop = function()
{
    if (this.source && !this.source.paused)
    {
        this.source.pause();
        this.onComplete.dispatch();
    }
};

PIXI.VideoTexture.prototype._onEnded = function()
{
    this.ended = true;
    this.onComplete.dispatch();
};

PIXI.VideoTexture.prototype._onUpdate = function()
{
    if (this.autoUpdate)
    {
        window.requestAnimationFrame(this.updateBound);
        this.dirty();
    }
};

PIXI.VideoTexture.prototype.onPlayStart = function()
{
    if (!this.autoUpdate)
    {
        window.requestAnimationFrame(this.updateBound);
        this.autoUpdate = true;
    }
};

PIXI.VideoTexture.prototype.onPlayStop = function()
{
    this.autoUpdate = false;
};

PIXI.VideoTexture.prototype.onCanPlay = function()
{
    if (event.type === 'canplaythrough')
    {
        this.hasLoaded = true;

        if (this.source)
        {
            this.source.removeEventListener('canplay', this._onCanPlay);
            this.source.removeEventListener('canplaythrough', this._onCanPlay);

            this.width = this.source.videoWidth;
            this.height = this.source.videoHeight;

            // prevent multiple loaded dispatches..
            if (!this.__loaded )
            {
                this.__loaded = true;
                this.dispatchEvent( { type: 'loaded', content: this } );
            }
        }
    }
};

PIXI.VideoTexture.prototype.destroy = function()
{
    if (this.source && this.source._pixiId)
    {
        PIXI.BaseTextureCache[ this.source._pixiId ] = null;
        delete PIXI.BaseTextureCache[this.source._pixiId];

        this.source._pixiId = null;
        delete this.source._pixiId;
    }

    PIXI.BaseTexture.prototype.destroy.call( this );
};

/**
 * Mimic Pixi BaseTexture.from.... method.
 *
 * @static
 * @method baseTextureFromVideo
 * @param video {HTMLVideoElement}
 * @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values
 * @return {VideoTexture}
 */
PIXI.VideoTexture.baseTextureFromVideo = function(video, scaleMode)
{
    if (!video._pixiId)
    {
        video._pixiId = 'video_' + PIXI.TextureCacheIdGenerator++;
    }

    var baseTexture = PIXI.BaseTextureCache[video._pixiId];

    if (!baseTexture)
    {
        baseTexture = new PIXI.VideoTexture(video, scaleMode);
        PIXI.BaseTextureCache[video._pixiId] = baseTexture;
    }

    return baseTexture;
};

/**
 * Mimic Pixi BaseTexture.from.... method.
 *
 * @static
 * @method textureFromVideo
 * @param video {HTMLVideoElement}
 * @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values
 * @return {Texture} A Texture, but not a VideoTexture.
 */
PIXI.VideoTexture.textureFromVideo = function(video, scaleMode)
{
    var baseTexture = PIXI.VideoTexture.baseTextureFromVideo(video, scaleMode);

    return new PIXI.Texture(baseTexture);
};

/**
 * Mimic Pixi BaseTexture.from.... method.
 *
 * @static
 * @method fromUrl
 * @param videoSrc {String} The URL for the video.
 * @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values
 * @param autoPlay {boolean} Automatically start the video playing? Until you do this you can't get the width / height of the resulting texture.
 * @return {VideoTexture}
 */
PIXI.VideoTexture.fromUrl = function(videoSrc, scaleMode, autoPlay)
{
    if (typeof scaleMode === 'undefined') { scaleMode = PIXI.scaleModes.DEFAULT; }
    if (typeof autoPlay === 'undefined') { autoPlay = true; }

    var video = document.createElement('video');

    video.src = videoSrc;
    video.controls = true;

    if (autoPlay)
    {
        video.autoplay = true;
        video.play();
    }
    else
    {
        video.autoplay = false;
    }

    return PIXI.VideoTexture.textureFromVideo(video, scaleMode);
};
<|endoftext|>


<commit_before>import getOrdinalDomain from '../../utils/domains/get_ordinal_domain.js'
import getMaxDomain from '../../utils/domains/get_max_domain.js'
import getScale from '../../utils/scales/get_scale.js'
import drawBars from '../../utils/draw/bars.js'

export default {
  plays: {
    xTransform: d => d,
    getXDomain: getOrdinalDomain.bind({col: 'x'}),
    getYDomain: getMaxDomain.bind({col: 'y', min: 0}),
    getXScale: getScale.bind({kind: 'scaleBand'}),
    drawData: drawBars
  },
  defaults:  {
    barMargin: 0,
    barWidth: false
  }
}
<commit_msg>fix data transform settings for barChart<commit_after>import getOrdinalDomain from '../../utils/domains/get_ordinal_domain.js'
import getMaxDomain from '../../utils/domains/get_max_domain.js'
import getScale from '../../utils/scales/get_scale.js'
import drawBars from '../../utils/draw/bars.js'

export default {
  plays: {
    getXDomain: getOrdinalDomain.bind({col: 'x'}),
    getYDomain: getMaxDomain.bind({col: 'y', min: 0}),
    getXScale: getScale.bind({kind: 'scaleBand'}),
    drawData: drawBars
  },
  defaults:  {
    xTransform: d => d,
    barMargin: 0,
    barWidth: false
  }
}
<|endoftext|>


<commit_before>/**
 * An API returned game mode stats
 * @class GameModeStats
 */
class GameModeStats {
    constructor(content) {
        /**
         * Assists
         * @type {Number}
         */
        this.assists = content.assists;

        /**
         * Boosts
         * @type {Number}
         */
        this.boosts = content.boosts;

        /**
         * Downs but not out
         * @type {Number}
         */
        this.dBNOs = content.dBNOs;

        /**
         * Daily kills
         * @type {Number}
         */
        this.dailyKills = content.dailyKills;

        /**
         * Damage dealt
         * @type {Number}
         */
        this.damageDealt = content.damageDealt;

        /**
         * Days
         * @type {string}
         */
        this.days = content.days;

        /**
         * Headshot kills
         * @type {string}
         */
        this.headshotKills = content.headshotKills;

        /**
         * Total HP healed
         * @type {string}
         */
        this.heals = content.heals;

        /**
         * Kills
         * @type {string}
         */
        this.kills = content.kills;

        /**
         * Longest kill
         * @type {string}
         */
        this.longestKill = content.longKill;

        /**
         * Longest time survived
         * @type {string}
         */
        this.longestTimeSurvived = content.longestTimeSurvived;

        /**
         * Losses
         * @type {string}
         */
        this.losses = content.losses;

        /**
         * Maximum kill streaks
         * @type {string}
         */
        this.maxKillStreaks = content.maxKillStreaks;

        /**
         * Most survival time
         * @type {string}
         */
        this.mostSurvivalTime = content.mostSurvivalTime;

        /**
         * Revives
         * @type {string}
         */
        this.revives = content.revives;

        /**
         * Ride distance
         * @type {string}
         */
        this.rideDistance = content.rideDistance;

        /**
         * Road kills
         * @type {string}
         */
        this.roadKills = content.roadKills;

        /**
         * Round most kills
         * @type {string}
         */
        this.roundMostKills = content.roundMostKills;

        /**
         * Rounds played
         * @type {string}
         */
        this.roundsPlayed = content.roundsPlayed;

        /**
         * Suicides
         * @type {string}
         */
        this.suicides = content.suicides;

        /**
         * Team kills
         * @type {string}
         */
        this.teamKills = content.teamKills;

        /**
         * Time survived
         * @type {string}
         */
        this.timeSurvived = content.timeSurvived;

        /**
         * Top 10s
         * @type {string}
         */
        this.top10s = content.top10s;

        /**
         * Vehicles Destroyed
         * @type {string}
         */
        this.vehicleDestroys = content.vehicleDestroys;

        /**
         * Walk distance
         * @type {string}
         */
        this.walkDistance = content.walkDistance;

        /**
         * Weapon Acquired
         * @type {string}
         */
        this.weaponAcquired = content.weaponAcquired;

        /**
         * Weekly kills
         * @type {string}
         */
        this.weeklyKills = content.weeklyKills;

        /**
         * Win points
         * @type {string}
         */
        this.winPoints = content.winPoints;

        /**
         * Win ratio
         * @type {string}
         */
        this.winRatio = content.winRatio;

        /**
         * Wins
         * @type {string}
         */
        this.wins = content.wins;
    }
}

module.exports = GameModeStats;
<commit_msg>Fixed GameModeStats undefined values<commit_after>/**
 * An API returned game mode stats
 * @class GameModeStats
 */
class GameModeStats {
    constructor(content) {
        /**
         * Assists
         * @type {Number}
         */
        this.assists = content.assists;

        /**
         * Boosts
         * @type {Number}
         */
        this.boosts = content.boosts;

        /**
         * Downs but not out
         * @type {Number}
         */
        this.dBNOs = content.dBNOs;

        /**
         * Daily kills
         * @type {Number}
         */
        this.dailyKills = content.dailyKills;

        /**
         * Damage dealt
         * @type {Number}
         */
        this.damageDealt = content.damageDealt;

        /**
         * Days
         * @type {string}
         */
        this.days = content.days;

        /**
         * Headshot kills
         * @type {string}
         */
        this.headshotKills = content.headshotKills;

        /**
         * Total HP healed
         * @type {string}
         */
        this.heals = content.heals;

        /**
         * Points from kills
         * @type {string}
         */
        this.killPoints = content.killPoints;

        /**
         * Kills
         * @type {string}
         */
        this.kills = content.kills;

        /**
         * Longest kill
         * @type {string}
         */
        this.longestKill = content.longestKill;

        /**
         * Longest time survived
         * @type {string}
         */
        this.longestTimeSurvived = content.longestTimeSurvived;

        /**
         * Losses
         * @type {string}
         */
        this.losses = content.losses;

        /**
         * Maximum kill streaks
         * @type {string}
         */
        this.maxKillStreaks = content.maxKillStreaks;

        /**
         * Most survival time
         * @type {string}
         */
        this.mostSurvivalTime = content.mostSurvivalTime;

        /**
         * Revives
         * @type {string}
         */
        this.revives = content.revives;

        /**
         * Ride distance
         * @type {string}
         */
        this.rideDistance = content.rideDistance;

        /**
         * Road kills
         * @type {string}
         */
        this.roadKills = content.roadKills;

        /**
         * Round most kills
         * @type {string}
         */
        this.roundMostKills = content.roundMostKills;

        /**
         * Rounds played
         * @type {string}
         */
        this.roundsPlayed = content.roundsPlayed;

        /**
         * Suicides
         * @type {string}
         */
        this.suicides = content.suicides;

        /**
         * Team kills
         * @type {string}
         */
        this.teamKills = content.teamKills;

        /**
         * Time survived
         * @type {string}
         */
        this.timeSurvived = content.timeSurvived;

        /**
         * Top 10s
         * @type {string}
         */
        this.top10s = content.top10s;

        /**
         * Vehicles Destroyed
         * @type {string}
         */
        this.vehicleDestroys = content.vehicleDestroys;

        /**
         * Walk distance
         * @type {string}
         */
        this.walkDistance = content.walkDistance;

        /**
         * Weapon Acquired
         * @type {string}
         */
        this.weaponsAcquired = content.weaponsAcquired;

        /**
         * Weekly kills
         * @type {string}
         */
        this.weeklyKills = content.weeklyKills;

        /**
         * Win points
         * @type {string}
         */
        this.winPoints = content.winPoints;

        /**
         * Win ratio
         * @type {string}
         */
        this.winRatio = content.winRatio;

        /**
         * Wins
         * @type {string}
         */
        this.wins = content.wins;
    }
}

module.exports = GameModeStats;
<|endoftext|>


<commit_before>'use strict';

const execa = require('execa');
const fs = require('fs-extra');
const Listr = require('listr');
const path = require('path');

const common = require('./common');

exports.doBackport = function doBackport(options) {
    const todo = [
        common.checkCwd(),
        common.getCurrentV8Version(),
        generatePatch(),
        applyPatch()
    ];
    if (options.bump !== false) {
        todo.push(incrementV8Version());
    }
    return {
        title: 'V8 commit backport',
        task: () => {
            return new Listr(todo);
        }
    };
};

exports.commitBackport = function commitBackport() {
    return {
        title: 'Commit patch',
        task: (ctx) => {
            const messageTitle = `deps: cherry-pick ${ctx.sha.substring(0, 7)} from upstream V8`;
            const messageBody = `Original commit message:\n\n    ` +
                ctx.message.replace(/\n/g, '\n    ');

            return execGitNode('add', 'deps/v8')
                .then(() => execGitNode('commit', '-m', messageTitle, '-m', messageBody));

            function execGitNode(...options) {
                return execa('git', options, {cwd: ctx.nodeDir});
            }
        }
    }
};

function generatePatch() {
    return {
        title: 'Generate patch',
        task: (ctx) => {
            const sha = ctx.sha;
            if (!sha) {
                throw new Error('Commit SHA is required');
            }
            return Promise.all([
                execGitV8('format-patch', '--stdout', `${sha}^..${sha}`),
                execGitV8('log', '--format=%B', '-n', '1', sha),
            ]).then(([patch, message]) => {
                ctx.patch = patch.stdout;
                ctx.message = message.stdout;
            }).catch(function (e) {
                throw new Error(e.stderr);
            });

            function execGitV8(...options) {
                return execa('git', options, {cwd: ctx.v8CloneDir});
            }
        }
    };
}

function applyPatch() {
    return {
        title: 'Apply patch to deps/v8',
        task: (ctx) => {
            const patch = ctx.patch;
            return execa('git', ['apply', '-3', '--directory=deps/v8'], {
                cwd: ctx.nodeDir,
                input: patch
            }).catch(function (e) {
                const file = path.join(ctx.nodeDir, `${ctx.sha}.diff`);
                return fs.writeFile(file, ctx.patch)
                    .then(function () {
                        throw new Error(`Could not apply patch.\n${e}\nDiff was stored in ${file}`);
                    });
            });
        }
    }
}

function incrementV8Version() {
    return {
        title: 'Increment V8 version',
        task: (ctx) => {
            const incremented = ctx.currentVersion[3] + 1;
            const versionHPath = ctx.nodeDir + '/deps/v8/include/v8-version.h';
            return fs.readFile(versionHPath, 'utf8')
                .then(versionH => {
                    versionH = versionH.replace(/V8_PATCH_LEVEL (\d+)/, `V8_PATCH_LEVEL ${incremented}`);
                    return fs.writeFile(versionHPath, versionH);
                });
        }
    };
}
<commit_msg>feat: add Refs URL for commit backports<commit_after>'use strict';

const execa = require('execa');
const fs = require('fs-extra');
const Listr = require('listr');
const path = require('path');

const common = require('./common');

exports.doBackport = function doBackport(options) {
    const todo = [
        common.checkCwd(),
        common.getCurrentV8Version(),
        generatePatch(),
        applyPatch()
    ];
    if (options.bump !== false) {
        todo.push(incrementV8Version());
    }
    return {
        title: 'V8 commit backport',
        task: () => {
            return new Listr(todo);
        }
    };
};

exports.commitBackport = function commitBackport() {
    return {
        title: 'Commit patch',
        task: (ctx) => {
            const messageTitle = `deps: cherry-pick ${ctx.sha.substring(0, 7)} from upstream V8`;
            const messageBody = `Original commit message:\n\n    ` +
                ctx.message.replace(/\n/g, '\n    ') +
                `\n\nRefs: https://github.com/v8/v8/commit/${ctx.sha}`;

            return execGitNode('add', 'deps/v8')
                .then(() => execGitNode('commit', '-m', messageTitle, '-m', messageBody));

            function execGitNode(...options) {
                return execa('git', options, {cwd: ctx.nodeDir});
            }
        }
    }
};

function generatePatch() {
    return {
        title: 'Generate patch',
        task: (ctx) => {
            const sha = ctx.sha;
            if (!sha || sha.length !== 40) {
                throw new Error('--sha option is required and must be 40 characters long');
            }
            return Promise.all([
                execGitV8('format-patch', '--stdout', `${sha}^..${sha}`),
                execGitV8('log', '--format=%B', '-n', '1', sha),
            ]).then(([patch, message]) => {
                ctx.patch = patch.stdout;
                ctx.message = message.stdout;
            }).catch(function (e) {
                throw new Error(e.stderr);
            });

            function execGitV8(...options) {
                return execa('git', options, {cwd: ctx.v8CloneDir});
            }
        }
    };
}

function applyPatch() {
    return {
        title: 'Apply patch to deps/v8',
        task: (ctx) => {
            const patch = ctx.patch;
            return execa('git', ['apply', '-3', '--directory=deps/v8'], {
                cwd: ctx.nodeDir,
                input: patch
            }).catch(function (e) {
                const file = path.join(ctx.nodeDir, `${ctx.sha}.diff`);
                return fs.writeFile(file, ctx.patch)
                    .then(function () {
                        throw new Error(`Could not apply patch.\n${e}\nDiff was stored in ${file}`);
                    });
            });
        }
    }
}

function incrementV8Version() {
    return {
        title: 'Increment V8 version',
        task: (ctx) => {
            const incremented = ctx.currentVersion[3] + 1;
            const versionHPath = ctx.nodeDir + '/deps/v8/include/v8-version.h';
            return fs.readFile(versionHPath, 'utf8')
                .then(versionH => {
                    versionH = versionH.replace(/V8_PATCH_LEVEL (\d+)/, `V8_PATCH_LEVEL ${incremented}`);
                    return fs.writeFile(versionHPath, versionH);
                });
        }
    };
}
<|endoftext|>


<commit_before>import inBrowser from '../../util/inBrowser'

class SurfaceManager {

  constructor(editorSession) {
    this.editorSession = editorSession
    this.surfaces = {}
    this._state = {
      focusedSurfaceId: null,
      selection: null,
    }
    editorSession.onUpdate('selection', this._onSelectionChanged, this)
    editorSession.onPostRender(this._recoverDOMSelection, this)
  }

  dispose() {
    this.editorSession.off(this)
  }

  /**
   * Get Surface instance
   *
   * @param {String} name Name under which the surface is registered
   * @return {ui/Surface} The surface instance
   */
  getSurface(name) {
    if (name) {
      return this.surfaces[name]
    }
  }

  /**
   * Get the currently focused Surface.
   *
   * @return {ui/Surface} Surface instance
   */
  getFocusedSurface() {
    if (this._state.focusedSurfaceId) {
      return this.getSurface(this._state.focusedSurfaceId)
    }
  }

  getSurfaces() {
    // HACK: not yet. we would need a polyfill
    // return Object.values(this.surfaces)
    return Object.keys(this.surfaces).map(key => this.surfaces[key])
  }

  /**
   * Register a surface
   *
   * @param surface {ui/Surface} A new surface instance to register
   */
  registerSurface(surface) {
    this.surfaces[surface.getId()] = surface
  }

  /**
   * Unregister a surface
   *
   * @param surface {ui/Surface} A surface instance to unregister
   */
  unregisterSurface(surface) {
    surface.off(this)
    let surfaceId = surface.getId()
    if (surface === this.getFocusedSurface()) {
      this.editorSession.setSelection(null)
    }
    let registeredSurface = this.surfaces[surfaceId]
    if (registeredSurface === surface) {
      let focusedSurface = this.getFocusedSurface()
      delete this.surfaces[surfaceId]
      if (surface && focusedSurface === surface) {
        this._state.focusedSurfaceId = null
      }
    }
  }

  _onSelectionChanged(selection) {
    const state = this._state
    state.selection = selection
    state.focusedSurfaceId = selection.surfaceId
    // HACK: removing DOM selection *and* blurring when having a CustomSelection
    // otherwise we will receive events on the wrong surface
    // instead of bubbling up to GlobalEventManager
    if (selection && selection.isCustomSelection() && inBrowser) {
      window.getSelection().removeAllRanges()
      window.document.activeElement.blur()
    }
  }

  _recoverDOMSelection() {
    // at the end of the update flow, make sure the surface is focused
    // and displays the right DOM selection.
    let focusedSurface = this.getFocusedSurface()
    if (focusedSurface && !focusedSurface.isDisabled()) {
      // console.log('Rendering selection on surface', focusedSurface.getId(), this.editorSession.getSelection().toString());
      focusedSurface.focus()
      focusedSurface.rerenderDOMSelection()
    }
  }
}

export default SurfaceManager
<commit_msg>Roll back change that sets selection to null after deregistration.<commit_after>import inBrowser from '../../util/inBrowser'

class SurfaceManager {

  constructor(editorSession) {
    this.editorSession = editorSession
    this.surfaces = {}
    this._state = {
      focusedSurfaceId: null,
      selection: null,
    }
    editorSession.onUpdate('selection', this._onSelectionChanged, this)
    editorSession.onPostRender(this._recoverDOMSelection, this)
  }

  dispose() {
    this.editorSession.off(this)
  }

  /**
   * Get Surface instance
   *
   * @param {String} name Name under which the surface is registered
   * @return {ui/Surface} The surface instance
   */
  getSurface(name) {
    if (name) {
      return this.surfaces[name]
    }
  }

  /**
   * Get the currently focused Surface.
   *
   * @return {ui/Surface} Surface instance
   */
  getFocusedSurface() {
    if (this._state.focusedSurfaceId) {
      return this.getSurface(this._state.focusedSurfaceId)
    }
  }

  getSurfaces() {
    // HACK: not yet. we would need a polyfill
    // return Object.values(this.surfaces)
    return Object.keys(this.surfaces).map(key => this.surfaces[key])
  }

  /**
   * Register a surface
   *
   * @param surface {ui/Surface} A new surface instance to register
   */
  registerSurface(surface) {
    this.surfaces[surface.getId()] = surface
  }

  /**
   * Unregister a surface
   *
   * @param surface {ui/Surface} A surface instance to unregister
   */
  unregisterSurface(surface) {
    surface.off(this)
    let surfaceId = surface.getId()
    // TODO: this is not working, has side-effects
    // with inline-nodes (see #985)
    // if (surface === this.getFocusedSurface()) {
    //   this.editorSession.setSelection(null)
    // }
    let registeredSurface = this.surfaces[surfaceId]
    if (registeredSurface === surface) {
      let focusedSurface = this.getFocusedSurface()
      delete this.surfaces[surfaceId]
      if (surface && focusedSurface === surface) {
        this._state.focusedSurfaceId = null
      }
    }
  }

  _onSelectionChanged(selection) {
    const state = this._state
    state.selection = selection
    state.focusedSurfaceId = selection.surfaceId
    // HACK: removing DOM selection *and* blurring when having a CustomSelection
    // otherwise we will receive events on the wrong surface
    // instead of bubbling up to GlobalEventManager
    if (selection && selection.isCustomSelection() && inBrowser) {
      window.getSelection().removeAllRanges()
      window.document.activeElement.blur()
    }
  }

  _recoverDOMSelection() {
    // at the end of the update flow, make sure the surface is focused
    // and displays the right DOM selection.
    let focusedSurface = this.getFocusedSurface()
    if (focusedSurface && !focusedSurface.isDisabled()) {
      // console.log('Rendering selection on surface', focusedSurface.getId(), this.editorSession.getSelection().toString());
      focusedSurface.focus()
      focusedSurface.rerenderDOMSelection()
    }
  }
}

export default SurfaceManager
<|endoftext|>


<commit_before>function BaseMap(){
}
BaseMap.prototype.distanceBetween = function(waypoint1, waypoint2) {
  var rm = 6371*1000; //radius in meters
  var rad_per_deg = Math.PI/180;
  var lat1 = waypoint1[0]*rad_per_deg;
  var lng1 = waypoint1[1]*rad_per_deg;
  var lat2 = waypoint2[0]*rad_per_deg;
  var lng2 = waypoint2[1]*rad_per_deg;
  var dlat = lat2 - lat1;
  var dlng = lng2 - lng1;
  var a = Math.pow((dlat/2), 2) + Math.cos(lat1) * Math.cos(lat2) * Math.pow((dlng/2), 2);
  var c = 2 * Math.asin(Math.sqrt(a));
  return rm * c; //Delta in meters
};

BaseMap.prototype.lineDistance = function(waypoints) {
  var distance = 0;
  for(var i = 0; i< waypoints.length - 1; i++){
    distance = distance +  this.distanceBetween(waypoints[i], waypoints[i + 1]);
  }
  return distance;
};

// Add a marker to the map.
// Options:
// {
//   lat: <latitude (required)>,
//   lng: <longitude (required)>,
//   infoWindow: <info window content>,
//   label: <label text>,
//   icon: {
//           image: <url path>,
//           size: [<width>, <height>],
//           sprite_position: [<width>, <height>],
//           anchor: [<width>, <height>],
//           popup_anchor: [<width>, <height>]
//   },
//   click: {
//             active: <clickable>,
//             callback: <click function>
//   },
//   drag: {
//           active: <draggable>,
//           callback: <drag end function ( obj = { position: {lat: <float>, lng: <float> } } )>
//   }
// }
BaseMap.prototype.addMarker = function(options) {
  throw 'Method undefined';
};

// Remove a marker from the map.
// Marker: Map marker object
BaseMap.prototype.removeMarker = function(marker) {
  throw 'Method undefined';
};

// Remove all markers from the map.
BaseMap.prototype.removeMarkers = function() {
  throw 'Method undefined';
};

// Close all info windows
BaseMap.prototype.hideInfoWindows = function() {
  throw 'Method undefined';
};

// Close all info windows and open only the info window
// of the given marker
BaseMap.prototype.showInfoWindows = function(marker) {
  throw 'Method undefined';
};

// Find the latitude and longitude from a given input.
// Options:
// {
//   input: <html input>,
//   callback: <geocode end function ( { position: {lat: <float>, lng: <float> } } , status: "OK" | "ERROR" )>
// }
BaseMap.prototype.geocode = function(options) {
  throw 'Method undefined';
};

// Add a circle to the map
// Options:
// {
//   lat: <latitude (required)>,
//   lng: <longitude (required)>,
//   radius: <circle radius (require)>,
//   strokeColor: <stroke color>,
//   strokeOpacity: <strike opacity>,
//   strokeWeight: <stroke line weight>,
//   fillColor: <fill color>,
//   fillOpacity: <fill opacity>
// }
BaseMap.prototype.addCircle= function(options) {
  throw 'Method undefined';
};

// Add a drawPolyline to the map
// Options:
//   {
//     path: <bounds (required)>,
//     strokeColor: <stroke color>,
//     strokeOpacity: <stroke opacity>,
//     strokeWeight:  <stroke weight>,
//     fillColor: <fill color>,
//     fillOpacity: <fill opacity>
//   }

BaseMap.prototype.drawPolyline= function(options) {
  throw 'Method undefined';
};

// Center map based on the markers given
BaseMap.prototype.fitBoundsWithMarkers = function(markers) {
  throw 'Method undefined';
};
<commit_msg>add documentation<commit_after>function BaseMap(){
}
BaseMap.prototype.distanceBetween = function(waypoint1, waypoint2) {
  var rm = 6371*1000; //radius in meters
  var rad_per_deg = Math.PI/180;
  var lat1 = waypoint1[0]*rad_per_deg;
  var lng1 = waypoint1[1]*rad_per_deg;
  var lat2 = waypoint2[0]*rad_per_deg;
  var lng2 = waypoint2[1]*rad_per_deg;
  var dlat = lat2 - lat1;
  var dlng = lng2 - lng1;
  var a = Math.pow((dlat/2), 2) + Math.cos(lat1) * Math.cos(lat2) * Math.pow((dlng/2), 2);
  var c = 2 * Math.asin(Math.sqrt(a));
  return rm * c; //Delta in meters
};

BaseMap.prototype.lineDistance = function(waypoints) {
  var distance = 0;
  for(var i = 0; i< waypoints.length - 1; i++){
    distance = distance +  this.distanceBetween(waypoints[i], waypoints[i + 1]);
  }
  return distance;
};

// Add a marker to the map.
// Options:
// {
//   lat: <latitude (required)>,
//   lng: <longitude (required)>,
//   infoWindow: <info window content>,
//   label: <label text>,
//   icon: {
//           image: <url path>,
//           size: [<width>, <height>],
//           sprite_position: [<width>, <height>],
//           anchor: [<width>, <height>],
//           popup_anchor: [<width>, <height>]
//   },
//   click: {
//             active: <clickable>,
//             callback: <click function>
//   },
//   drag: {
//           active: <draggable>,
//           callback: <drag end function ( obj = { position: {lat: <float>, lng: <float> } } )>
//   }
// }
BaseMap.prototype.addMarker = function(options) {
  throw 'Method undefined';
};

// Remove a marker from the map.
// Marker: Map marker object
BaseMap.prototype.removeMarker = function(marker) {
  throw 'Method undefined';
};

// Remove all markers from the map.
BaseMap.prototype.removeMarkers = function() {
  throw 'Method undefined';
};

// Close all info windows
BaseMap.prototype.hideInfoWindows = function() {
  throw 'Method undefined';
};

// Close all info windows and open only the info window
// of the given marker
BaseMap.prototype.showInfoWindows = function(marker) {
  throw 'Method undefined';
};

// Find the latitude and longitude from a given input.
// Options:
// {
//   input: <html input>,
//   callback: <geocode end function ( { position: {lat: <float>, lng: <float> } } , status: "OK" | "ERROR" )>
//   drag : {
//    active: true | false,
//    callback: <drag end function>
//    },
//    position: {
//      lat: lat,
//      lng: lng
//      }
//    }
// }
BaseMap.prototype.geocode = function(options) {
  throw 'Method undefined';
};

// Add a circle to the map
// Options:
// {
//   lat: <latitude (required)>,
//   lng: <longitude (required)>,
//   radius: <circle radius (require)>,
//   strokeColor: <stroke color>,
//   strokeOpacity: <strike opacity>,
//   strokeWeight: <stroke line weight>,
//   fillColor: <fill color>,
//   fillOpacity: <fill opacity>
// }
BaseMap.prototype.addCircle= function(options) {
  throw 'Method undefined';
};

// Add a drawPolyline to the map
// Options:
//   {
//     path: <bounds (required)>,
//     strokeColor: <stroke color>,
//     strokeOpacity: <stroke opacity>,
//     strokeWeight:  <stroke weight>,
//     fillColor: <fill color>,
//     fillOpacity: <fill opacity>
//   }

BaseMap.prototype.drawPolyline= function(options) {
  throw 'Method undefined';
};

// Center map based on the markers given
BaseMap.prototype.fitBoundsWithMarkers = function(markers) {
  throw 'Method undefined';
};
<|endoftext|>


<commit_before>var _ = require("lodash");
var Chan = require("../../models/chan");
var Msg = require("../../models/msg");
var Helper = require("../../helper");

module.exports = function(irc, network) {
	var client = this;
	var config = Helper.getConfig();

	irc.on("notice", function(data) {
		data.type = Msg.Type.NOTICE;
		handleMessage(data);
	});

	irc.on("action", function(data) {
		data.type = Msg.Type.ACTION;
		handleMessage(data);
	});

	irc.on("privmsg", function(data) {
		data.type = Msg.Type.MESSAGE;
		handleMessage(data);
	});

	function handleMessage(data) {
		var target = data.target;
		if (target.toLowerCase() === irc.user.nick.toLowerCase()) {
			target = data.nick;
		}

		var chan = _.find(network.channels, {name: target});
		if (typeof chan === "undefined") {
			chan = new Chan({
				type: Chan.Type.QUERY,
				name: data.nick
			});
			network.channels.push(chan);
			client.emit("join", {
				network: network.id,
				chan: chan
			});
		}

		var self = data.nick === irc.user.nick;

		// Self messages are never highlighted
		// Non-self messages are highlighted as soon as the nick is detected
		var highlight = !self && data.msg.split(" ").some(function(w) {
			return (w.replace(/^@/, "").toLowerCase().indexOf(irc.user.nick.toLowerCase()) === 0);
		});

		if (chan.id !== client.activeChannel) {
			chan.unread++;

			if (highlight) {
				chan.highlight = true;
			}
		}

		var msg = new Msg({
			type: data.type,
			mode: chan.getMode(data.nick),
			from: data.nick,
			text: data.msg,
			self: self,
			highlight: highlight
		});
		chan.messages.push(msg);

		if (config.maxHistory >= 0 && chan.messages.length > config.maxHistory) {
			chan.messages.splice(0, chan.messages.length - config.maxHistory);
		}

		client.emit("msg", {
			chan: chan.id,
			msg: msg
		});
	}
};
<commit_msg>Fix creating duplicate query windows when our nick is not known<commit_after>var _ = require("lodash");
var Chan = require("../../models/chan");
var Msg = require("../../models/msg");
var Helper = require("../../helper");

module.exports = function(irc, network) {
	var client = this;
	var config = Helper.getConfig();

	irc.on("notice", function(data) {
		data.type = Msg.Type.NOTICE;
		handleMessage(data);
	});

	irc.on("action", function(data) {
		data.type = Msg.Type.ACTION;
		handleMessage(data);
	});

	irc.on("privmsg", function(data) {
		data.type = Msg.Type.MESSAGE;
		handleMessage(data);
	});

	function handleMessage(data) {
		// First, try to find current target
		var chan = _.find(network.channels, {name: data.target});
		if (typeof chan === "undefined") {
			// If current target doesn't exist, try to find by nick
			chan = _.find(network.channels, {name: data.nick});
			// If neither target or nick channels exist, create one for the nick
			if (typeof chan === "undefined") {
				chan = new Chan({
					type: Chan.Type.QUERY,
					name: data.nick
				});
				network.channels.push(chan);
				client.emit("join", {
					network: network.id,
					chan: chan
				});
			}
		}

		var self = data.nick === irc.user.nick;

		// Self messages are never highlighted
		// Non-self messages are highlighted as soon as the nick is detected
		var highlight = !self && data.msg.split(" ").some(function(w) {
			return (w.replace(/^@/, "").toLowerCase().indexOf(irc.user.nick.toLowerCase()) === 0);
		});

		if (chan.id !== client.activeChannel) {
			chan.unread++;

			if (highlight) {
				chan.highlight = true;
			}
		}

		var msg = new Msg({
			type: data.type,
			mode: chan.getMode(data.nick),
			from: data.nick,
			text: data.msg,
			self: self,
			highlight: highlight
		});
		chan.messages.push(msg);

		if (config.maxHistory >= 0 && chan.messages.length > config.maxHistory) {
			chan.messages.splice(0, chan.messages.length - config.maxHistory);
		}

		client.emit("msg", {
			chan: chan.id,
			msg: msg
		});
	}
};
<|endoftext|>


<commit_before>
/*!
 *   @namespace BAT
 *   @element   bat.ajax
 *   @homepage  batjs.github.io
 *
 *   @status    beta
 *   @version   0.0.2
 *   @author    Jo Santana
 *   @license   Released under the MIT license
 *
 *   @usage:
 *
 *      Bat.ajax.getJSON(
 *      {
 *        url:  'http://www.some-rest-api.com/data',
 *        data: { 'number': 123 }
 *      }, function (response) { console.log(response); });
 *
 *      Bat.ajax.getJSONP(
 *      {
 *        url:  'http://www.some-rest-api.com/data',
 *        callback: 'jsonpResponse',
 *        beforeSend: function (request)
 *        {
 *          request.setRequestHeader('key', 'value');
 *        }
 *      }, function (response) { console.log(response); });
 *
 *      Bat.ajax.getHTML(
 *      {
 *        url:  'http://www.some-website.com/page',
 *        data: { 'number': 123 }
 *      }, function (response) { console.log(response); });
 *
*/

(function()
{
    'use strict';

    // Declare root variable - window in the browser, global on the server
    // Get already define BAT object (if available) or create a new object

    var root = this,
    Bat  = root.Bat || {};

    /*
     *   BAT ajax
     */

     Bat.ajax = (function ()
     {
        var xhr = function ()
        {
            var instance = new XMLHttpRequest();
            return instance;
        },

        serializeData = function (obj)
        {
            var data = '';

            for (var key in obj) {
                data += key + '=' + encodeURIComponent(obj[key]) + '&';
            }

            data = data.slice(0,-1);

            return data;
        },

        extendOptions = function (options, callback)
        {
            options.url = options.url || location.href;
            options.data = options.data ? serializeData(options.data) : null;
            options.beforeSend = options.beforeSend || function() {};

            callback = callback || function() {};
        },

        insertScript = function (options, callback)
        {
            var jsonpCallback = options.callback || ('JSONP_' + new Date().getTime());

            options.url += ((options.url.indexOf('?') === -1) ? '?' : '&') + 'callback=' + jsonpCallback;

            window[jsonpCallback] = callback; // Now our callback method is globally visible

            var script = document.createElement('script');
            script.src = options.url;
            document.body.appendChild(script);
        },

        sendData = function (options, callback)
        {
            var xhttp = xhr(),
                uri = options.data ? (options.url + '?' + options.data) : options.url;

            xhttp.open('GET', uri, true);

            options.beforeSend(xhttp);

            xhttp.onreadystatechange = function ()
            {
                if (xhttp.status === 200 && xhttp.readyState === 4)
                {
                    callback(xhttp.responseText);
                }
            };

            xhttp.send(options.data);
        };

        return {

            /*
             *   Function to get a JSON response
             *
             *   @attribute options
             *   @type object
             *
             *   @attribute callback
             *   @type function
             */

             getJSON: function (options, callback)
             {
                extendOptions (options, callback);
                sendData (options, callback);
            },

            /*
             *   Function to get a JSONP response
             */

             getJSONP: function (options, callback)
             {
                extendOptions (options, callback);
                insertScript (options, callback);
                sendData (options, callback);
            },

            /*
             *   Function to get a HTML response
             *
             *   @attribute options
             *   @type object
             *
             *   @attribute callback
             *   @type function
             */

             getHTML: function (options, callback)
             {
                extendOptions (options, callback);
                sendData (options, callback);
            }

        };
    })();

    // Return a new element to BAT object

    root.Bat = Bat;

}).call(this);
<commit_msg>Ajax Module Update<commit_after>
/*!
 *   @namespace BAT
 *   @element   bat.ajax
 *   @homepage  batjs.github.io
 *
 *   @status    beta
 *   @version   0.0.2
 *   @author    Jo Santana
 *   @license   Released under the MIT license
 *
 *   @usage:
 *
 *      Bat.ajax.getJSON(
 *      {
 *        url:  'http://www.some-rest-api.com/data',
 *        data: { 'number': 123 }
 *      }, function (response) { console.log(response); });
 *
 *      Bat.ajax.getJSONP(
 *      {
 *        url:  'http://www.some-rest-api.com/data',
 *        callback: 'jsonpResponse',
 *        beforeSend: function (request)
 *        {
 *          request.setRequestHeader('key', 'value');
 *        }
 *      }, function (response) { console.log(response); });
 *
 *      Bat.ajax.getHTML(
 *      {
 *        url:  'http://www.some-website.com/page',
 *        data: { 'number': 123 }
 *      }, function (response) { console.log(response); });
 *
*/

(function()
{
    'use strict';

    // Declare root variable - window in the browser, global on the server
    // Get already define BAT object (if available) or create a new object

    var root = this,
    Bat  = root.Bat || {};

    /*
     *   BAT ajax
     */

     Bat.ajax = (function ()
     {
        var xhr = function ()
        {
            var instance = new XMLHttpRequest();
            return instance;
        },

        serializeData = function (obj)
        {
            var data = '';

            for (var key in obj) {
                data += key + '=' + encodeURIComponent(obj[key]) + '&';
            }

            data = data.slice(0,-1);

            return data;
        },

        extendOptions = function (options, callback)
        {
            options.url = options.url || location.href;
            options.data = options.data ? serializeData(options.data) : null;
            options.beforeSend = options.beforeSend || function() {};

            callback = callback || function() {};
        },

        insertScript = function (options, callback)
        {
            var jsonpCallback = options.callback || ('JSONP_' + new Date().getTime());

            options.url += ((options.url.indexOf('?') === -1) ? '?' : '&') + 'callback=' + jsonpCallback;

            window[jsonpCallback] = callback; // Now our callback method is globally visible

            var script = document.createElement('script');
            script.src = options.url;
            document.body.appendChild(script);
        },

        sendData = function (options, callback)
        {
            var xhttp = xhr(),
                uri = options.data ? (options.url + '?' + options.data) : options.url;

            xhttp.open('GET', uri, true);

            options.beforeSend(xhttp);

            xhttp.onreadystatechange = function ()
            {
                if ((xhttp.status === 200 || xhttp.status === 206) && xhttp.readyState === 4)
                {
                    callback(xhttp.responseText);
                }
            };

            xhttp.send(options.data);
        };

        return {

            /*
             *   Function to get a JSON response
             *
             *   @attribute options
             *   @type object
             *
             *   @attribute callback
             *   @type function
             */

             getJSON: function (options, callback)
             {
                extendOptions (options, callback);
                sendData (options, callback);
            },

            /*
             *   Function to get a JSONP response
             */

             getJSONP: function (options, callback)
             {
                extendOptions (options, callback);
                insertScript (options, callback);
                sendData (options, callback);
            },

            /*
             *   Function to get a HTML response
             *
             *   @attribute options
             *   @type object
             *
             *   @attribute callback
             *   @type function
             */

             getHTML: function (options, callback)
             {
                extendOptions (options, callback);
                sendData (options, callback);
            }

        };
    })();

    // Return a new element to BAT object

    root.Bat = Bat;

}).call(this);
<|endoftext|>


<commit_before>// tinix.js
//
// Copyright 2013 - Santosh Rajan - santoshrajan.com
//

function tinix(selector, elem) {
    elem = elem || document
    return elem.querySelector(selector)
}

tinix.version = "0.2.0"

tinix.supported = !!document.addEventListener

if (tinix.supported && !Element.prototype.on) {
  Element.prototype.on = Element.prototype.addEventListener
}

tinix.all = function(selector, elem) {
    elem = elem || document
    return elem.querySelectorAll(selector)
}

tinix.forEach = function(selector, func) {
    Array.prototype.forEach.call(this.all(selector), func)
}

tinix.map = function(selector, func) {
    return Array.prototype.map.call(this.all(selector), func)
}

tinix.style = function(selector, iteratee, val) {
    this.forEach(s, function(elem) {
       elem.style[iteratee] = val
    })
}

tinix.display = function(selector, val) {
    this.style(selector, "display", val)
}

tinix.ready = function(func) {
    if (document.readyState == "loading") {
        document.onreadystatechange = function() {
            if (document.readyState == "interactive") func()
        }
    } else {
        func()
    }
}

tinix.getR = function(callback) {
    var request = new XMLHttpRequest()
    responseText.onload = function() {
        if (request.status == 200) {
            if (request.getResponseHeader("Content-Type") == "application/json") {
                callback(null, JSON.parse(request.responseText))
            } else {
                callback(null, request.responseText)
            }
        } else {
            callback(request)
        }
    }
    return request
}

// get(url, callback [,overrideMimeType])
tinix.get = function(url, callback, overrideMimeType) {
    var request = this.getR(callback)
    request.open("GET", url)
    if (overrideMimeType) {
      request.overrideMimeType(overrideMimeType)
    }
    request.send()
}

// post(url, body, contenttype, callback)
tinix.post = function(url, body, contenttype, callback) {
    var request = this.getR(contenttype)
    request.open("POST", url)
    request.setRequestHeader("Content-Type", contenttype)
    request.send(body)
}

// postJSON(url, body, callback)
tinix.postJSON = function(url, body, callback) {
    this.post(url, JSON.stringify(body), "application/json", callback)
}

module.exports = tinix
<commit_msg>rewritee device ready<commit_after>// tinix.js
//
// Copyright 2013 - Santosh Rajan - santoshrajan.com
//

function tinix(selector, elem) {
    elem = elem || document
    return elem.querySelector(selector)
}

tinix.version = "0.2.0"

tinix.supported = !!document.addEventListener

if (tinix.supported && !Element.prototype.on) {
  Element.prototype.on = Element.prototype.addEventListener
}

tinix.all = function(selector, elem) {
    elem = elem || document
    return elem.querySelectorAll(selector)
}

tinix.forEach = function(selector, func) {
    Array.prototype.forEach.call(this.all(selector), func)
}

tinix.map = function(selector, func) {
    return Array.prototype.map.call(this.all(selector), func)
}

tinix.style = function(selector, iteratee, val) {
    this.forEach(s, function(elem) {
       elem.style[iteratee] = val
    })
}

tinix.display = function(selector, val) {
    this.style(selector, "display", val)
}

tinix.ready = function(func) {
  document.addEventListener('DOMContentLoaded', function() {func()})
}

tinix.getR = function(callback) {
    var request = new XMLHttpRequest()
    responseText.onload = function() {
        if (request.status == 200) {
            if (request.getResponseHeader("Content-Type") == "application/json") {
                callback(null, JSON.parse(request.responseText))
            } else {
                callback(null, request.responseText)
            }
        } else {
            callback(request)
        }
    }
    return request
}

// get(url, callback [,overrideMimeType])
tinix.get = function(url, callback, overrideMimeType) {
    var request = this.getR(callback)
    request.open("GET", url)
    if (overrideMimeType) {
      request.overrideMimeType(overrideMimeType)
    }
    request.send()
}

// post(url, body, contenttype, callback)
tinix.post = function(url, body, contenttype, callback) {
    var request = this.getR(contenttype)
    request.open("POST", url)
    request.setRequestHeader("Content-Type", contenttype)
    request.send(body)
}

// postJSON(url, body, callback)
tinix.postJSON = function(url, body, callback) {
    this.post(url, JSON.stringify(body), "application/json", callback)
}

module.exports = tinix
<|endoftext|>


<commit_before>bilby = bilby
    .method('<', isFunction, function(a, b) {
        return compose(b, a);
    })
    .method('*', isFunction, function(a, b) {
        return function(x) {
            return a(x)(b(x));
        };
    });

bilby = bilby
    .method('>>', isFunction, function(a, b) {
        var env = this;
        return function(x) {
            return env['>='](a(x), b);
        };
    })

    .method('equal', isBoolean, strictEquals)
    .method('equal', isNumber, strictEquals)
    .method('equal', isString, strictEquals)
    .method('equal', isArray, function(a, b) {
        var env = this;
        return env.fold(zip(a, b), true, function(a, t) {
            return a && env.equal(t[0], t[1]);
        });
    })

    .method('fold', isArray, function(a, b, c) {
        var i;
        for(i = 0; i < a.length; i++) {
            b = c(b, a[i]);
        }
        return b;
    })

    .method('>=', isArray, function(a, b) {
        var accum = [],
            i;

        for(i = 0; i < a.length; i++) {
            accum = accum.concat(b(a[i]));
        }

        return accum;
    })
    .method('<', isArray, function(a, b) {
        var accum = [],
            i;

        for(i = 0; i < a.length; i++) {
            accum[i] = b(a[i]);
        }

        return accum;
    })
    .method('*', isArray, function(a, b) {
        var accum = [],
            i,
            j;

        for(i = 0; i < a.length; i++) {
            for(j = 0; j < b.length; j++) {
                accum.push(a[i](b[j]));
            }
        }

        return accum;
    })
    .method('+', isArray, function(a, b) {
        return a.concat(b);
    })
    .method('pure', strictEquals(Array), function(m, a) {
        return [a];
    })

    .method('+', bilby.liftA2(or, isNumber, isString), function(a, b) {
        return a + b;
    })

    .property('oneOf', function(a) {
        return a[Math.floor(this.randomRange(0, a.length))];
    })
    .property('randomRange', function(a, b) {
        return Math.random() * (b - a) + a;
    })

    .method('arb', isArrayOf, function(a, s) {
        var accum = [],
            length = this.randomRange(0, s),
            i;

        for(i = 0; i < length; i++) {
            accum.push(this.arb(a.type, s - 1));
        }

        return accum;
    })
    .method('arb', isObjectLike, function(a, s) {
        var o = {},
            i;

        for(i in a.props) {
            o[i] = this.arb(a.props[i]);
        }

        return o;
    })
    .method('arb', strictEquals(AnyVal), function(a, s) {
        var types = [Boolean, Number, String];
        return this.arb(this.oneOf(types), s - 1);
    })
    .method('arb', strictEquals(Array), function(a, s) {
        return this.arb(arrayOf(AnyVal), s - 1);
    })
    .method('arb', strictEquals(Boolean), function(a, s) {
        return Math.random() < 0.5;
    })
    .method('arb', strictEquals(Char), function(a, s) {
        return String.fromCharCode(Math.floor(this.randomRange(32, 127)));
    })
    .method('arb', strictEquals(Number), function(a, s) {
        // Half the number of bits to represent Number.MAX_VALUE
        var bits = 511,
            variance = Math.pow(2, (s * bits) / this.goal);
        return this.randomRange(-variance, variance);
    })
    .method('arb', strictEquals(Object), function(a, s) {
        var o = {},
            length = this.randomRange(0, s),
            i;

        for(i = 0; i < length; i++) {
            o[this.arb(String, s - 1)] = this.arb(arrayOf(AnyVal), s - 1);
        }

        return o;
    })
    .method('arb', strictEquals(String), function(a, s) {
        return this.arb(arrayOf(Char), s - 1).join('');
    })

    .method('shrink', isBoolean, function() {
        return function(b) {
            return b ? [False] : [];
        };
    })
    .method('shrink', isNumber, function(n) {
        var accum = [0],
            x = n;

        if(n < 0)
            accum.push(-n);

        while(x) {
            x = x / 2;
            x = x < 0 ? Math.ceil(x) : Math.floor(x);
            if(x) {
                accum.push(n - x);
            }
        }

        return accum;
    });

Do.setValueOf(Array.prototype);
Do.setValueOf(Function.prototype);
<commit_msg>Add shrink instance for String<commit_after>bilby = bilby
    .method('<', isFunction, function(a, b) {
        return compose(b, a);
    })
    .method('*', isFunction, function(a, b) {
        return function(x) {
            return a(x)(b(x));
        };
    });

bilby = bilby
    .method('>>', isFunction, function(a, b) {
        var env = this;
        return function(x) {
            return env['>='](a(x), b);
        };
    })

    .method('equal', isBoolean, strictEquals)
    .method('equal', isNumber, strictEquals)
    .method('equal', isString, strictEquals)
    .method('equal', isArray, function(a, b) {
        var env = this;
        return env.fold(zip(a, b), true, function(a, t) {
            return a && env.equal(t[0], t[1]);
        });
    })

    .method('fold', isArray, function(a, b, c) {
        var i;
        for(i = 0; i < a.length; i++) {
            b = c(b, a[i]);
        }
        return b;
    })

    .method('>=', isArray, function(a, b) {
        var accum = [],
            i;

        for(i = 0; i < a.length; i++) {
            accum = accum.concat(b(a[i]));
        }

        return accum;
    })
    .method('<', isArray, function(a, b) {
        var accum = [],
            i;

        for(i = 0; i < a.length; i++) {
            accum[i] = b(a[i]);
        }

        return accum;
    })
    .method('*', isArray, function(a, b) {
        var accum = [],
            i,
            j;

        for(i = 0; i < a.length; i++) {
            for(j = 0; j < b.length; j++) {
                accum.push(a[i](b[j]));
            }
        }

        return accum;
    })
    .method('+', isArray, function(a, b) {
        return a.concat(b);
    })
    .method('pure', strictEquals(Array), function(m, a) {
        return [a];
    })

    .method('+', bilby.liftA2(or, isNumber, isString), function(a, b) {
        return a + b;
    })

    .property('oneOf', function(a) {
        return a[Math.floor(this.randomRange(0, a.length))];
    })
    .property('randomRange', function(a, b) {
        return Math.random() * (b - a) + a;
    })

    .method('arb', isArrayOf, function(a, s) {
        var accum = [],
            length = this.randomRange(0, s),
            i;

        for(i = 0; i < length; i++) {
            accum.push(this.arb(a.type, s - 1));
        }

        return accum;
    })
    .method('arb', isObjectLike, function(a, s) {
        var o = {},
            i;

        for(i in a.props) {
            o[i] = this.arb(a.props[i]);
        }

        return o;
    })
    .method('arb', strictEquals(AnyVal), function(a, s) {
        var types = [Boolean, Number, String];
        return this.arb(this.oneOf(types), s - 1);
    })
    .method('arb', strictEquals(Array), function(a, s) {
        return this.arb(arrayOf(AnyVal), s - 1);
    })
    .method('arb', strictEquals(Boolean), function(a, s) {
        return Math.random() < 0.5;
    })
    .method('arb', strictEquals(Char), function(a, s) {
        return String.fromCharCode(Math.floor(this.randomRange(32, 127)));
    })
    .method('arb', strictEquals(Number), function(a, s) {
        // Half the number of bits to represent Number.MAX_VALUE
        var bits = 511,
            variance = Math.pow(2, (s * bits) / this.goal);
        return this.randomRange(-variance, variance);
    })
    .method('arb', strictEquals(Object), function(a, s) {
        var o = {},
            length = this.randomRange(0, s),
            i;

        for(i = 0; i < length; i++) {
            o[this.arb(String, s - 1)] = this.arb(arrayOf(AnyVal), s - 1);
        }

        return o;
    })
    .method('arb', strictEquals(String), function(a, s) {
        return this.arb(arrayOf(Char), s - 1).join('');
    })

    .method('shrink', isBoolean, function() {
        return function(b) {
            return b ? [False] : [];
        };
    })
    .method('shrink', isNumber, function(n) {
        var accum = [0],
            x = n;

        if(n < 0)
            accum.push(-n);

        while(x) {
            x = x / 2;
            x = x < 0 ? Math.ceil(x) : Math.floor(x);
            if(x) {
                accum.push(n - x);
            }
        }

        return accum;
    })
    .method('shrink', isString, function(s) {
        var accum = [''],
            x = s.length;

        while(x) {
            x = Math.floor(x / 2);
            if(x) {
                accum.push(s.substring(0, s.length - x));
            }
        }

        return accum;
    });

Do.setValueOf(Array.prototype);
Do.setValueOf(Function.prototype);
<|endoftext|>


<commit_before>'use strict';
var CarouselPanels = require('./carousel-panels');
var CarouselThumbs = require('./carousel-thumbs');
var CarouselArrows = require('./carousel-arrows');
var ElementKit = require('element-kit');
var utils = ElementKit.utils;
var Module = require('module.js');
var _ = require('underscore');
/**
 * A callback function that fires after a new active panel is set
 * @callback Carousel~onPanelChange
 * @param {Number} index - The index of the new panel
 */

/**
 * Adds carousel functionality to a set up pre-determined HTML markup.
 * @class Carousel
 * @param {object} options - Options passed into instance
 * @param {HTMLCollection} options.panels - The panels in which to use for the carousel (an array of photos)
 * @param {string} [options.assetLoadingClass] - The CSS class that gets added to an asset when it is loading
 * @param {boolean} [options.autoLoadAssets] - Whether or not to automatically load assets when active
 * @param {string} [options.panelActiveClass] - The CSS class that gets added to an panel when it becomes active
 * @param {Carousel~onPanelChange} [options.onPanelChange] - When the current panel is changed
 * @param {string} [options.lazyLoadAttr] - The attribute containing the url path to content that is to be lazy loaded
 * @param {HTMLCollection} [options.thumbnails] - A collection of elements that are the thumbnails
 * @param {string} [options.thumbnailActiveClass] - The CSS class that gets added to a thumbnail element when it becomes active
 * @param {Number} [options.initialIndex] - The index of the panel to go to upon instantiation (if not declared, goTo() must be called manually).
 */

var Carousel = Module.extend({

    /**
     * Sets up stuff.
     * @param options
     */
    initialize: function (options) {

        options = options || {};

        // if undefined or null is passed in options for panels or thumbnails,
        // we need to sanitize it to an empty array to prevent a crash
        if (!options.panels) {
            options.panels = [];
        }
        if (!options.thumbnails) {
            options.thumbnails = [];
        }

        this.options = utils.extend({
            panels: [],
            assetLoadingClass: 'carousel-asset-loading',
            autoLoadAssets: true,
            panelActiveClass: 'carousel-panel-active',
            onPanelChange: null,
            lazyLoadAttr: 'data-src',
            thumbnails: [],
            thumbnailActiveTriggerEvent: 'click',
            thumbnailActiveClass: 'carousel-thumbnail-active',
            initialIndex: 0,
            leftArrow: null,
            rightArrow: null,
            arrowActiveClass: 'carousel-arrow-active',
            arrowDisabledClass: 'carousel-arrow-disabled',
            onLeftArrowClick: null,
            onRightArrowClick: null
        }, options);

        this._checkForInitErrors();

        Module.prototype.initialize.call(this, this.options);

        this.setup();
    },

    /**
     * Sets up the carousel instance and all controls.
     * @memberOf Carousel
     */
    setup: function () {
        if (!this.subModules.panels) {
            this.subModules.panels = this.setupPanels(this.options);
        }

        if (this.options.thumbnails.length && !this.subModules.thumbnails) {
            this.subModules.thumbnails = this.setupThumbs(this.options);
        }

        if ((this.options.leftArrow || this.options.rightArrow) && !this.subModules.arrows) {
            this.subModules.arrows = this.setupArrows(this.options);
        }

        if (typeof this.options.initialIndex === 'number') {
            this.goTo(this.options.initialIndex);
        }
    },

    /**
     * Sets up the carousel thumbs.
     * @param {Object} options - The initialize options
     * @return {CarouselThumbs} Returns thumbnail instance
     */
    setupThumbs: function (options) {
         return new CarouselThumbs(utils.extend({}, options, {
            onChange: this.onThumbnailChange.bind(this)
        }));
    },

    /**
     * Sets up the carousel panels.
     * @param {Object} options - The initialize options
     * @return {CarouselPanels} Returns panels instance
     */
    setupPanels: function (options) {
        return new CarouselPanels(utils.extend({}, options, {
            onChange: this.onPanelChange.bind(this)
        }));
    },

    /**
     * Sets up the carousel arrows.
     * @param {Object} options - The initialize options
     * @return {CarouselArrows} Returns arrows instance
     */
    setupArrows: function (options) {
        var internalOptions;
        // make clone of original options
        internalOptions = _.extend({}, options);

        internalOptions.onLeftArrowClick = this.onLeftArrowClick.bind(this);
        internalOptions.onRightArrowClick = this.onRightArrowClick.bind(this);
        return new CarouselArrows(internalOptions);
    },

    /**
     * Checks for errors upon initialize.
     * @private
     * @memberOf Carousel
     */
    _checkForInitErrors: function () {
        var options = this.options,
            panelCount = options.panels.length,
            thumbnailCount = options.thumbnails.length;
        if (thumbnailCount && thumbnailCount !== panelCount) {
            console.warn('carousel warning: number of thumbnails passed in constructor do not equal the number of panels' + '\n' +
            'panels: ' + panelCount + '\n' +
            'thumbnails: ' + thumbnailCount + '\n');
        }
    },

    /**
     * When a panel index changes.
     * @param {Number} index - The new index
     * @memberOf Carousel
     */
    onPanelChange: function (index) {
        if (this.subModules.thumbnails) {
            this.subModules.thumbnails.goTo(index);
        }

        if (this.subModules.arrows) {
            this.subModules.arrows.update(index);
        }

        if (this.options.onPanelChange) {
            this.options.onPanelChange(index)
        }
    },

    /**
     * When the thumbnail index changes.
     * @param {Number} index - The new index
     * @memberOf Carousel
     */
    onThumbnailChange: function (index) {
        this.goTo(index);
    },

    /**
     * When the right arrow of the carousel is clicked.
     * @param e
     */
    onRightArrowClick: function (e) {
        this.goTo(this.subModules.panels.getCurrentIndex() + 1);
        if (this.options.onRightArrowClick) {
            this.options.onRightArrowClick(e);
        }
    },

    /**
     * When the left arrow of the carousel is clicked.
     * @param e
     */
    onLeftArrowClick: function (e) {
        this.goTo(this.subModules.panels.getCurrentIndex() - 1);
        if (this.options.onLeftArrowClick) {
            this.options.onLeftArrowClick(e);
        }
    },

    /**
     * Transition to a new panel and thumbnail.
     * @param {Number} index - The index number to go to
     * @memberOf Carousel
     */
    goTo: function (index) {
        var options = this.options,
            maxIndex = options.panels.length - 1,
            minIndex = 0;

        if (index > maxIndex) {
            // set to first index if too high
            index = minIndex;
        } else if (index < minIndex) {
            // set to last index if too low
            index = maxIndex;
        }

        if (this.subModules.thumbnails) {
            this.subModules.thumbnails.goTo(index);
        }
        if (this.subModules.arrows) {
            this.subModules.arrows.update(index);
        }
        return this.subModules.panels.goTo(index);
    },

    /**
     * Gets the current index that is showing.
     * @returns {Number} Returns the index
     * @memberOf Carousel
     */
    getCurrentIndex: function () {
        return this.subModules.panels.getCurrentIndex();
    },

    /**
     * Moves carousel to next panel.
     */
    next: function () {
        this.goTo(this.getCurrentIndex() + 1);
    },

    /**
     * Moves to previous carousel panel.
     */
    prev: function () {
        this.goTo(this.getCurrentIndex() - 1);
    }
});

module.exports = Carousel;<commit_msg>Converting carousel class to a real javascript class<commit_after>'use strict';
var CarouselPanels = require('./carousel-panels');
var CarouselThumbs = require('./carousel-thumbs');
var CarouselArrows = require('./carousel-arrows');
var ElementKit = require('element-kit');
var utils = ElementKit.utils;
var _ = require('underscore');
import Module from 'module-js';
/**
 * A callback function that fires after a new active panel is set
 * @callback Carousel~onPanelChange
 * @param {Number} index - The index of the new panel
 */

/**
 * Adds carousel functionality to a set up pre-determined HTML markup.
 * @class Carousel
 * @param {object} options - Options passed into instance
 * @param {HTMLCollection} options.panels - The panels in which to use for the carousel (an array of photos)
 * @param {string} [options.assetLoadingClass] - The CSS class that gets added to an asset when it is loading
 * @param {boolean} [options.autoLoadAssets] - Whether or not to automatically load assets when active
 * @param {string} [options.panelActiveClass] - The CSS class that gets added to an panel when it becomes active
 * @param {Carousel~onPanelChange} [options.onPanelChange] - When the current panel is changed
 * @param {string} [options.lazyLoadAttr] - The attribute containing the url path to content that is to be lazy loaded
 * @param {HTMLCollection} [options.thumbnails] - A collection of elements that are the thumbnails
 * @param {string} [options.thumbnailActiveClass] - The CSS class that gets added to a thumbnail element when it becomes active
 * @param {Number} [options.initialIndex] - The index of the panel to go to upon instantiation (if not declared, goTo() must be called manually).
 */

class Carousel extends Module {

    /**
     * Sets up stuff.
     * @param options
     */
    constructor (options) {

        options = options || {};

        // if undefined or null is passed in options for panels or thumbnails,
        // we need to sanitize it to an empty array to prevent a crash
        if (!options.panels) {
            options.panels = [];
        }
        if (!options.thumbnails) {
            options.thumbnails = [];
        }

        options = utils.extend({
            panels: [],
            assetLoadingClass: 'carousel-asset-loading',
            autoLoadAssets: true,
            panelActiveClass: 'carousel-panel-active',
            onPanelChange: null,
            lazyLoadAttr: 'data-src',
            thumbnails: [],
            thumbnailActiveTriggerEvent: 'click',
            thumbnailActiveClass: 'carousel-thumbnail-active',
            initialIndex: 0,
            leftArrow: null,
            rightArrow: null,
            arrowActiveClass: 'carousel-arrow-active',
            arrowDisabledClass: 'carousel-arrow-disabled',
            onLeftArrowClick: null,
            onRightArrowClick: null
        }, options);

        super(options);

        this.options = options;
        this._checkForInitErrors();
        this.setup();
    }

    /**
     * Sets up the carousel instance and all controls.
     * @memberOf Carousel
     */
    setup () {
        if (!this.subModules.panels) {
            this.subModules.panels = this.setupPanels(this.options);
        }

        if (this.options.thumbnails.length && !this.subModules.thumbnails) {
            this.subModules.thumbnails = this.setupThumbs(this.options);
        }

        if ((this.options.leftArrow || this.options.rightArrow) && !this.subModules.arrows) {
            this.subModules.arrows = this.setupArrows(this.options);
        }

        if (typeof this.options.initialIndex === 'number') {
            this.goTo(this.options.initialIndex);
        }
    }

    /**
     * Sets up the carousel thumbs.
     * @param {Object} options - The initialize options
     * @return {CarouselThumbs} Returns thumbnail instance
     */
    setupThumbs (options) {
         return new CarouselThumbs(utils.extend({}, options, {
            onChange: this.onThumbnailChange.bind(this)
        }));
    }

    /**
     * Sets up the carousel panels.
     * @param {Object} options - The initialize options
     * @return {CarouselPanels} Returns panels instance
     */
    setupPanels (options) {
        return new CarouselPanels(utils.extend({}, options, {
            onChange: this.onPanelChange.bind(this)
        }));
    }

    /**
     * Sets up the carousel arrows.
     * @param {Object} options - The initialize options
     * @return {CarouselArrows} Returns arrows instance
     */
    setupArrows (options) {
        var internalOptions;
        // make clone of original options
        internalOptions = _.extend({}, options);

        internalOptions.onLeftArrowClick = this.onLeftArrowClick.bind(this);
        internalOptions.onRightArrowClick = this.onRightArrowClick.bind(this);
        return new CarouselArrows(internalOptions);
    }

    /**
     * Checks for errors upon initialize.
     * @private
     * @memberOf Carousel
     */
    _checkForInitErrors () {
        var options = this.options,
            panelCount = options.panels.length,
            thumbnailCount = options.thumbnails.length;
        if (thumbnailCount && thumbnailCount !== panelCount) {
            console.warn('carousel warning: number of thumbnails passed in constructor do not equal the number of panels' + '\n' +
            'panels: ' + panelCount + '\n' +
            'thumbnails: ' + thumbnailCount + '\n');
        }
    }

    /**
     * When a panel index changes.
     * @param {Number} index - The new index
     * @memberOf Carousel
     */
    onPanelChange (index) {
        if (this.subModules.thumbnails) {
            this.subModules.thumbnails.goTo(index);
        }

        if (this.subModules.arrows) {
            this.subModules.arrows.update(index);
        }

        if (this.options.onPanelChange) {
            this.options.onPanelChange(index)
        }
    }

    /**
     * When the thumbnail index changes.
     * @param {Number} index - The new index
     * @memberOf Carousel
     */
    onThumbnailChange (index) {
        this.goTo(index);
    }

    /**
     * When the right arrow of the carousel is clicked.
     * @param e
     */
    onRightArrowClick (e) {
        this.goTo(this.subModules.panels.getCurrentIndex() + 1);
        if (this.options.onRightArrowClick) {
            this.options.onRightArrowClick(e);
        }
    }

    /**
     * When the left arrow of the carousel is clicked.
     * @param e
     */
    onLeftArrowClick (e) {
        this.goTo(this.subModules.panels.getCurrentIndex() - 1);
        if (this.options.onLeftArrowClick) {
            this.options.onLeftArrowClick(e);
        }
    }

    /**
     * Transition to a new panel and thumbnail.
     * @param {Number} index - The index number to go to
     * @memberOf Carousel
     */
    goTo (index) {
        var options = this.options,
            maxIndex = options.panels.length - 1,
            minIndex = 0;

        if (index > maxIndex) {
            // set to first index if too high
            index = minIndex;
        } else if (index < minIndex) {
            // set to last index if too low
            index = maxIndex;
        }

        if (this.subModules.thumbnails) {
            this.subModules.thumbnails.goTo(index);
        }
        if (this.subModules.arrows) {
            this.subModules.arrows.update(index);
        }
        return this.subModules.panels.goTo(index);
    }

    /**
     * Gets the current index that is showing.
     * @returns {Number} Returns the index
     * @memberOf Carousel
     */
    getCurrentIndex () {
        return this.subModules.panels.getCurrentIndex();
    }

    /**
     * Moves carousel to next panel.
     */
    next () {
        this.goTo(this.getCurrentIndex() + 1);
    }

    /**
     * Moves to previous carousel panel.
     */
    prev () {
        this.goTo(this.getCurrentIndex() - 1);
    }
}

module.exports = Carousel;
<|endoftext|>


<commit_before>import Events from './events.js';
import _ from './utils/underscore.js';
import Collection from './collection.js';

/**
 * @class
 * @name Two.Group.Children
 * @extends Two.Collection
 * @description A children collection which is accesible both by index and by object `id`.
 */
class Children extends Collection {

  /**
   * @name Two.Group.Children#ids
   * @property {Object} - Map of all elements in the list keyed by `id`s.
   */
  ids = {};

  constructor(children) {

    children = Array.isArray(children)
      ? children : Array.prototype.slice.call(arguments);

    super(children);

    this.attach(children);

    this.on(Events.Types.insert, this.attach);
    this.on(Events.Types.remove, this.detach);

  }

  /**
   * @function
   * @name Two.Group.Children#attach
   * @param {Two.Shape[]} children - The objects which extend {@link Two.Shape} to be added.
   * @description Adds elements to the `ids` map.
   */
  attach(children) {
    for (var i = 0; i < children.length; i++) {
      var child = children[i];
      if (child && child.id) {
        this.ids[child.id] = child;
      }
    }
    return this;
  }

  /**
   * @function
   * @name Two.Group.Children#detach
   * @param {Two.Shape[]} children - The objects which extend {@link Two.Shape} to be removed.
   * @description Removes elements to the `ids` map.
   */
  detach(children) {
    for (var i = 0; i < children.length; i++) {
      delete this.ids[children[i].id];
    }
    return this;
  }

}

export default Children;
<commit_msg>Updated Linting<commit_after>import Events from './events.js';
import Collection from './collection.js';

/**
 * @class
 * @name Two.Group.Children
 * @extends Two.Collection
 * @description A children collection which is accesible both by index and by object `id`.
 */
class Children extends Collection {

  /**
   * @name Two.Group.Children#ids
   * @property {Object} - Map of all elements in the list keyed by `id`s.
   */
  ids = {};

  constructor(children) {

    children = Array.isArray(children)
      ? children : Array.prototype.slice.call(arguments);

    super(children);

    this.attach(children);

    this.on(Events.Types.insert, this.attach);
    this.on(Events.Types.remove, this.detach);

  }

  /**
   * @function
   * @name Two.Group.Children#attach
   * @param {Two.Shape[]} children - The objects which extend {@link Two.Shape} to be added.
   * @description Adds elements to the `ids` map.
   */
  attach(children) {
    for (let i = 0; i < children.length; i++) {
      const child = children[i];
      if (child && child.id) {
        this.ids[child.id] = child;
      }
    }
    return this;
  }

  /**
   * @function
   * @name Two.Group.Children#detach
   * @param {Two.Shape[]} children - The objects which extend {@link Two.Shape} to be removed.
   * @description Removes elements to the `ids` map.
   */
  detach(children) {
    for (let i = 0; i < children.length; i++) {
      delete this.ids[children[i].id];
    }
    return this;
  }

}

export default Children;
<|endoftext|>


<commit_before>// ==UserScript==
// @author      rslifka
// @connect     docs.google.com
// @connect     rslifka.github.io
// @copyright   2020, Robert Slifka (https://github.com/rslifka/fate_of_all_fools)
// @description Enhancements to the Destiny Item Manager
// @grant       GM_addStyle
// @grant       GM_getResourceText
// @grant       GM_getValue
// @grant       GM_log
// @grant       GM_setValue
// @grant       GM_xmlhttpRequest
// @homepageURL https://github.com/rslifka/fate_of_all_fools
// @license     MIT; https://raw.githubusercontent.com/rslifka/fate_of_all_fools/master/LICENSE.txt
// @match       https://*.destinyitemmanager.com/*
// @name        FateOfAllFools - DIM Customization
// @require     https://rslifka.github.io/fate_of_all_fools/fateOfAllFools.js
// @resource    fateOfAllFoolsCSS https://rslifka.github.io/fate_of_all_fools/fateOfAllFools.css
// @run-at      document-start
// @supportURL  https://github.com/rslifka/fate_of_all_fools/issues
// @updateURL   https://openuserjs.org/meta/rslifka/FateOfAllFools_-_DIM_Customization.meta.js
// @version     2697
// ==/UserScript==
<commit_msg>[skip ci] Publishing build 2699<commit_after>// ==UserScript==
// @author      rslifka
// @connect     docs.google.com
// @connect     rslifka.github.io
// @copyright   2020, Robert Slifka (https://github.com/rslifka/fate_of_all_fools)
// @description Enhancements to the Destiny Item Manager
// @grant       GM_addStyle
// @grant       GM_getResourceText
// @grant       GM_getValue
// @grant       GM_log
// @grant       GM_setValue
// @grant       GM_xmlhttpRequest
// @homepageURL https://github.com/rslifka/fate_of_all_fools
// @license     MIT; https://raw.githubusercontent.com/rslifka/fate_of_all_fools/master/LICENSE.txt
// @match       https://*.destinyitemmanager.com/*
// @name        FateOfAllFools - DIM Customization
// @require     https://rslifka.github.io/fate_of_all_fools/fateOfAllFools.js
// @resource    fateOfAllFoolsCSS https://rslifka.github.io/fate_of_all_fools/fateOfAllFools.css
// @run-at      document-start
// @supportURL  https://github.com/rslifka/fate_of_all_fools/issues
// @updateURL   https://openuserjs.org/meta/rslifka/FateOfAllFools_-_DIM_Customization.meta.js
// @version     2699
// ==/UserScript==
<|endoftext|>


<commit_before>var CommentBox = React.createClass({
  render: function() {
    return (

Result Table: {this.props.id}

          id
          message
          type

        <CommentList />

    );
  }
});

var CommentList = React.createClass({
  render: function() {
    return (

        <CommentItemID />
        <CommentItemMessage />
        <CommentItemType />

    );
  }
});

var CommentItemID = React.createClass({
  render: function() {
    return (
      {this.props.id}
    );
  }
});

var CommentItemMessage = React.createClass({
  render: function() {
    return (
      {this.props.message}
    );
  }
});

var CommentItemType = React.createClass({
  render: function() {
    return (
      {this.props.type}
    );
  }
});

var Comment = React.createClass({
  render: function() {
    return (
      <CommentBox />
    );
  }
});

window.ReactRender = function(_data) {

  console.log("==ReactRender==");

  // if(_data) {
    var data = {
      id: "test",
      message: "testtest"
    };
    ReactDOM.render( <Comment { ...data } />, document.getElementById('resulttable') );
  // }
};
<commit_msg>add datalink<commit_after>var CommentBox = React.createClass({
  render: function() {
    return (

Result Table: {this.props.id}

          id
          message
          type

        <CommentList />

    );
  }
});

var CommentList = React.createClass({
  render: function() {
    return (

        <CommentItemID />
        <CommentItemMessage />
        <CommentItemType />

    );
  }
});

var CommentItemID = React.createClass({
  render: function() {
    return (
      {this.props.id}
    );
  }
});

var CommentItemMessage = React.createClass({
  render: function() {
    return (
      {this.props.message}
    );
  }
});

var CommentItemType = React.createClass({
  render: function() {
    return (
      {this.props.type}
    );
  }
});

var Comment = React.createClass({
  render: function() {
    return (
      <CommentBox { ...data } />
    );
  }
});

window.ReactRender = function(_data) {

  console.log("==ReactRender==");

  // if(_data) {
    var data = {
      id: "test",
      message: "testtest"
    };
    ReactDOM.render( <Comment { ...data } />, document.getElementById('resulttable') );
  // }
};
<|endoftext|>