<commit_before>var WelcomeScreen = Class.create(Scene, {
  initialize: function() {
    var game, bg, title, start, particleGroup, playerSprite, music, selectFX;

    Scene.apply(this);
    game = Game.instance;

    music = enchant.DOMSound.load('sounds/hyper.mp3');
    music.volume = 0.15;
    music.play();
    this.music = music;

    selectFX = game.assets['sounds/select.wav'];
    //selectFX.volume = 0.15;
    this.selectFX = selectFX;

    // Set Background
    bg = new Sprite(game.width, game.height);
    bg.image = game.assets['images/space.jpg'];

    start = new Sprite(315, 29);
    start.image = game.assets['images/start1.png'];
    start.x = game.width/2 - start.width/2;
    start.y = 500;
    this.start = start;

    title = new Sprite(596, 49);
    title.image = game.assets['images/stringtheory.png'];
    title.x = game.width/2 - title.width/2;
    title.y = -300;
    this.title = title;

    title.tl.moveTo(title.x, 100, 70);

    playerSprite = new PlayerSprite();

    particleGroup = new Group();

    this.addEventListener(Event.ENTER_FRAME, function() {
      if (this.music.currentTime >= this.music.duration){
         this.music.play();
      }

      if (this.age % 2 == 0) {
	 //particleGroup.addChild(new Particle(800, 800, 100));
	 //particleGroup.addChild(new ParticleStream(0, 800, 100));
	 //particleGroup.addChild(new ParticleStream(400, 1200, 100));
	particleGroup.addChild(new ParticleBlast(400, 300, 90, 95));
	particleGroup.addChild(new ParticleBlast(400, 300, 90, 95));

      }
      start.tl.fadeIn(30);
      start.tl.fadeOut(30);
    });

    this.addChild(bg);
    this.addChild(particleGroup);
    this.addChild(title);
    this.addChild(start);
    this.addChild(playerSprite);
  },

  onenterframe: function(evt) {
    this.addEventListener(Event.TOUCH_START, this.handleClick);

  },

  handleClick: function() {
    this.selectFX.play();
    this.music.stop();
    game.pushScene(new StringTheoryScene(0));
  }
});

var PlayerSprite = Class.create(Sprite, {
  initialize: function() {
    Sprite.call(this, 192, 192);
    this.image = game.assets['images/nwomatri.png'];
    this.x = game.width/2 - this.width/2;
    this.y = game.height/2 - this.height/2;
	this.omega = 2;
    this.addEventListener(Event.ENTER_FRAME, this.update);
  },

  update: function(evt) {
    if (this.age % 4 === 0) {
      this.frame += this.increment;
    }

    if (this.frame >=11) {
      this.increment = -1;
    }

    if (this.frame <= 7) {
      this.increment = 1;
    }

	this.rotate(this.omega);
  }
});

var ParticleStream = Class.create(Sprite, {
   initialize: function(xA, yA, speed) {
      Sprite.call(this, 4, 15);
      this.image = game.assets['images/particle0.png'];
      this.x = xA;
      this.y = yA;
      this.scaleX = 0.5;
      this.scaleY = 0.5;
      this.tl.moveTo(Math.floor(Math.random() * 1000), Math.floor(Math.random() * -600), speed);
      this.addEventListener(Event.ENTER_FRAME, this.update);
   },

   update: function(evt) {
      if (this.y < 10) {
         this.parentNode.removeChild(this);
      }
   }
});

var ParticleBlast = Class.create(Sprite, {
   initialize: function(xA, yA, speed, blast) {
      Sprite.call(this, 4, 15);
      this.image = game.assets['images/particle0.png'];
      this.x = xA;
      this.y = yA;
      this.blast = blast;
      this.scaleX = 0.5;
      this.scaleY = 0.3;
      this.tl.moveTo(Math.floor(Math.random() * 800), Math.floor(Math.random() * 600), speed).and().fadeOut(100);
      this.addEventListener(Event.ENTER_FRAME, this.update);
   },

   update: function(evt) {
      if (this.age > this.blast) {
	this.parentNode.removeChild(this);
      }
      if (this.y < 10 || this.y > 590) {
	 this.parentNode.removeChild(this);
      }
   }
});
<commit_msg>fixed particle blast radius and position<commit_after>var WelcomeScreen = Class.create(Scene, {
  initialize: function() {
    var game, bg, title, start, particleGroup, playerSprite, music, selectFX;

    Scene.apply(this);
    game = Game.instance;

    music = enchant.DOMSound.load('sounds/hyper.mp3');
    music.volume = 0.15;
    music.play();
    this.music = music;

    selectFX = game.assets['sounds/select.wav'];
    //selectFX.volume = 0.15;
    this.selectFX = selectFX;

    // Set Background
    bg = new Sprite(game.width, game.height);
    bg.image = game.assets['images/space.jpg'];

    start = new Sprite(315, 29);
    start.image = game.assets['images/start1.png'];
    start.x = game.width/2 - start.width/2;
    start.y = 500;
    this.start = start;

    title = new Sprite(596, 49);
    title.image = game.assets['images/stringtheory.png'];
    title.x = game.width/2 - title.width/2;
    title.y = -300;
    this.title = title;

    title.tl.moveTo(title.x, 100, 70);

    playerSprite = new PlayerSprite();

    particleGroup = new Group();

    this.addEventListener(Event.ENTER_FRAME, function() {
      if (this.music.currentTime >= this.music.duration){
         this.music.play();
      }

      if (this.age % 2 == 0) {
	 //particleGroup.addChild(new Particle(800, 800, 100));
	 //particleGroup.addChild(new ParticleStream(0, 800, 100));
	 //particleGroup.addChild(new ParticleStream(400, 1200, 100));
	particleGroup.addChild(new ParticleBlast(475, 350, 90, 100));
	particleGroup.addChild(new ParticleBlast(475, 350, 90, 100));

      }
      start.tl.fadeIn(30);
      start.tl.fadeOut(30);
    });

    this.addChild(bg);
    this.addChild(particleGroup);
    this.addChild(title);
    this.addChild(start);
    this.addChild(playerSprite);
  },

  onenterframe: function(evt) {
    this.addEventListener(Event.TOUCH_START, this.handleClick);

  },

  handleClick: function() {
    this.selectFX.play();
    this.music.stop();
    game.pushScene(new StringTheoryScene(0));
  }
});

var PlayerSprite = Class.create(Sprite, {
  initialize: function() {
    Sprite.call(this, 192, 192);
    this.image = game.assets['images/nwomatri.png'];
    this.x = game.width/2 - this.width/2;
    this.y = game.height/2 - this.height/2;
	this.omega = 2;
    this.addEventListener(Event.ENTER_FRAME, this.update);
  },

  update: function(evt) {
    if (this.age % 4 === 0) {
      this.frame += this.increment;
    }

    if (this.frame >=11) {
      this.increment = -1;
    }

    if (this.frame <= 7) {
      this.increment = 1;
    }

	this.rotate(this.omega);
  }
});

var ParticleStream = Class.create(Sprite, {
   initialize: function(xA, yA, speed) {
      Sprite.call(this, 4, 15);
      this.image = game.assets['images/particle0.png'];
      this.x = xA;
      this.y = yA;
      this.scaleX = 0.5;
      this.scaleY = 0.5;
      this.tl.moveTo(Math.floor(Math.random() * 1000), Math.floor(Math.random() * -600), speed);
      this.addEventListener(Event.ENTER_FRAME, this.update);
   },

   update: function(evt) {
      if (this.y < 10) {
         this.parentNode.removeChild(this);
      }
   }
});

var ParticleBlast = Class.create(Sprite, {
   initialize: function(xA, yA, speed, blast) {
      Sprite.call(this, 4, 15);
      this.image = game.assets['images/particle0.png'];
      this.x = xA;
      this.y = yA;
      this.blast = blast;
      this.scaleX = 0.5;
      this.scaleY = 0.3;
      this.tl.moveTo(Math.floor(Math.random() * 950), Math.floor(Math.random() * 700), speed).and().fadeOut(100);
      this.addEventListener(Event.ENTER_FRAME, this.update);
   },

   update: function(evt) {
      if (this.age > this.blast) {
	this.parentNode.removeChild(this);
      }
      if (this.y < 10 || this.y > 690) {
	 this.parentNode.removeChild(this);
      }
   }
});
<|endoftext|>


<commit_before>define(function() {
    function IArray(array,offset) {
	this.array = array;
	this.offset = offset;
    }
    IArray.prototype.head = function() { return this.array[this.offset]; }
    IArray.prototype.tail = function() { return new IArray(this.array,this.offset+1); }
    IArray.prototype.cons = function(x) {
	var offset = this.offset - 1;
	var array;
        if (this.array[offset] === undefined) {
	    array = this.array;
	} else {
	    array = this.array.slice(0);
	}
	array[offset] = x;
	return new IArray(array,offset);
    }
    return {
	iarray: function(array,offset) {
	    offset = offset || 0;
	    return new IArray(array,offset);
	},
	iempty: function(offset) {
	    return new IArray(new Array(offset),offset);
	},
	equals: function(as,bs,p) {
	    p = p || function(a,b) { return a == b; };
	    if (as.length != bs.length) { return false; }
	    function q(a,i) { return p(a,bs[i]); }
	    return as.every(q);
	},
	subseteq: function(as,bs,p) {
	    p = p || function(a,b) { return a == b; };
	    if (as.length > bs.length) { return false; }
	    function q(a,i) { return p(a,bs[i]); }
	    return as.every(q);
	},
        lookup: function(as,i) {
	    return as[i];
	},
        singleton: function(a) {
	    return [a];
	},
	empty: []
    };
});<commit_msg>Minor tidy-up of agda.array.js.<commit_after>define(function() {
    function IArray(array,offset) {
	this.array = array;
	this.offset = offset;
    }
    IArray.prototype.head = function() { return this.array[this.offset]; }
    IArray.prototype.tail = function() { return new IArray(this.array,this.offset+1); }
    IArray.prototype.cons = function(x) {
	var offset = this.offset - 1;
	var array = this.array;
        if ((array[offset] !== undefined) && (array[offset] !== x)) {
	    array = array.slice(0);
	}
	array[offset] = x;
	return new IArray(array,offset);
    }
    return {
	iarray: function(array,offset) {
	    offset = offset || 0;
	    return new IArray(array,offset);
	},
	iempty: function(offset) {
	    return new IArray(new Array(offset),offset);
	},
	equals: function(as,bs,p) {
	    p = p || function(a,b) { return a == b; };
	    if (as.length != bs.length) { return false; }
	    function q(a,i) { return p(a,bs[i]); }
	    return as.every(q);
	},
	subseteq: function(as,bs,p) {
	    p = p || function(a,b) { return a == b; };
	    if (as.length > bs.length) { return false; }
	    function q(a,i) { return p(a,bs[i]); }
	    return as.every(q);
	},
        lookup: function(as,i) {
	    return as[i];
	},
        singleton: function(a) {
	    return [a];
	},
	empty: []
    };
});<|endoftext|>


<commit_before>var log = require('./log.js');
require('../core/string-helpers.js');

var Router = function () { };

Router.prototype = {
    _routes: [
        { name: 'game-directory.index', url: '^https?://streams.twitch.tv/kraken/streams/?$' },
        { name: 'channels.all', url: '^https?://streams.twitch.tv/kraken/streams/?$' },
        { name: 'channels.random', url: '^https?://api.twitch.tv/kraken/beta/streams/random/?$' },
        { name: 'channels.psFour', url: '^https?://streams.twitch.tv/kraken/streams/?$' },
        { name: 'channels.xbOne', url: '^https?://streams.twitch.tv/kraken/streams/?$' },
        { name: 'csgo.channels.index', url: '^https?://api.twitch.tv/api/cs/?$' },
        { name: 'csgo.channels.filtered', url: '^https?://api.twitch.tv/api/cs/?$' }
    ],
    _getTwitchRouter: function() {
        return App.__container__.lookup('router:main');
    },
    _getCurrentRouteName: function () {
        var twitchRouter = this._getTwitchRouter();

        // Return Target Route if it's found since Current Route might be not up to date.
        // Usually Current Route is "Loading" or something like that in such cases.

        var targetRouteName = '';
        if (twitchRouter.targetState.routerJs.activeTransition !== null)
            targetRouteName = twitchRouter.targetState.routerJs.activeTransition.targetName;

        if (targetRouteName !== '')
            return targetRouteName;

        // Otherwise return Current Route
        if (!twitchRouter.currentRouteName)
            throw 'Unable to fetch current route from Twitch Ember Router.';
        else
            return twitchRouter.currentRouteName;
    },
    _getCurrentRoute: function() {
        var name = this._getCurrentRouteName();

        return this._routes.find(function (x) {
            return x.name.toLowerCase() === name.toLowerCase();
        });
    },
    isRouteSupported: function () {
        return (typeof this._getCurrentRoute() !== 'undefined');
    },
    getRequestUrlRegExp: function () {
        var route = this._getCurrentRoute();

        if (typeof route !== 'undefined')
            return route.url;
    }
};

module.exports = Router;<commit_msg>Removed support for Random and CS:GO pages due to technical problems with Twitch API.<commit_after>var log = require('./log.js');
require('../core/string-helpers.js');

var Router = function () { };

Router.prototype = {
    _routes: [
        { name: 'game-directory.index', url: '^https?://streams.twitch.tv/kraken/streams/?$' },
        { name: 'channels.all', url: '^https?://streams.twitch.tv/kraken/streams/?$' },
        { name: 'channels.psFour', url: '^https?://streams.twitch.tv/kraken/streams/?$' },
        { name: 'channels.xbOne', url: '^https?://streams.twitch.tv/kraken/streams/?$' }
    ],
    _getTwitchRouter: function() {
        return App.__container__.lookup('router:main');
    },
    _getCurrentRouteName: function () {
        var twitchRouter = this._getTwitchRouter();

        // Return Target Route if it's found since Current Route might be not up to date.
        // Usually Current Route is "Loading" or something like that in such cases.

        var targetRouteName = '';
        if (twitchRouter.targetState.routerJs.activeTransition !== null)
            targetRouteName = twitchRouter.targetState.routerJs.activeTransition.targetName;

        if (targetRouteName !== '')
            return targetRouteName;

        // Otherwise return Current Route
        if (!twitchRouter.currentRouteName)
            throw 'Unable to fetch current route from Twitch Ember Router.';
        else
            return twitchRouter.currentRouteName;
    },
    _getCurrentRoute: function() {
        var name = this._getCurrentRouteName();

        return this._routes.find(function (x) {
            return x.name.toLowerCase() === name.toLowerCase();
        });
    },
    isRouteSupported: function () {
        return (typeof this._getCurrentRoute() !== 'undefined');
    },
    getRequestUrlRegExp: function () {
        var route = this._getCurrentRoute();

        if (typeof route !== 'undefined')
            return route.url;
    }
};

module.exports = Router;<|endoftext|>


<commit_before>'use strict'

const Settings = require('./settings').Settings
    , browserapi = require('./browserapi')
    , validator = require('./rule_validator')
    , sharer = require('./sharer')

class Controller {
    constructor() {
        this.disabledIcon = {
            16: 'img/icon-disabled16.png',
            32: 'img/icon-disabled32.png',
        }

        this.settings = new Settings(browserapi.storage, () => { this._check_enabled() })

        browserapi.runtime.onMessage.addListener((message, sender, callback) => this._handleMessage(message, sender, callback))

        browserapi.runtime.onInstalled.addListener((details) => this._handleInstalled(details))
    }

    _handleInstalled(details) {
        this.settings.set_defaults()
    }

    _check_enabled() {
        this._set_browser_icon(this.settings.enabled)
    }

    _set_browser_icon(enabled) {
        const manifest = browserapi.runtime.getManifest()
        const icons = enabled ? manifest.browser_action.default_icon : this.disabledIcon
        browserapi.browserAction.setIcon({ path: icons })
    }

    _handleMessage(message, sender, callback) {
        if (message.action === 'import_url') {
            const res = this._importTableFromUrl(sender.url)
            callback(res)
        }
    }

    _importTableFromUrl(url) {
        try {
            const table = sharer.decodeShareLink(url)
            table.title = browserapi.i18n.getMessage('options_table_title_import_prefix') + new Date().toLocaleString()
            table.rules = validator.filter(table.rules)

            this.settings.import_table(table)

            const canonical = sharer.makeShareLink(table)
            if (canonical !== url) {
                return {title: table.title, error: 'Imported with errors'}
            }

            return {title: table.title}
        }
        catch (e) {
            console.log(e)
            return {error: e.toString()}
        }
    }
}

const ctl = new Controller()
<commit_msg>:woman_shrugging: keep default icon unchanged<commit_after>'use strict'

const Settings = require('./settings').Settings
    , browserapi = require('./browserapi')
    , validator = require('./rule_validator')
    , sharer = require('./sharer')

class Controller {
    constructor() {
        this.settings = new Settings(browserapi.storage, () => {})

        browserapi.runtime.onMessage.addListener((message, sender, callback) => this._handleMessage(message, sender, callback))

        browserapi.runtime.onInstalled.addListener((details) => this._handleInstalled(details))
    }

    _handleInstalled(details) {
        this.settings.set_defaults()
    }

    _handleMessage(message, sender, callback) {
        if (message.action === 'import_url') {
            const res = this._importTableFromUrl(sender.url)
            callback(res)
        }
    }

    _importTableFromUrl(url) {
        try {
            const table = sharer.decodeShareLink(url)
            table.title = browserapi.i18n.getMessage('options_table_title_import_prefix') + new Date().toLocaleString()
            table.rules = validator.filter(table.rules)

            this.settings.import_table(table)

            const canonical = sharer.makeShareLink(table)
            if (canonical !== url) {
                return {title: table.title, error: 'Imported with errors'}
            }

            return {title: table.title}
        }
        catch (e) {
            console.log(e)
            return {error: e.toString()}
        }
    }
}

const ctl = new Controller()
<|endoftext|>


<commit_before>var CHESS = CHESS || {};

CHESS.BoardMover = function ($) {

    /**
     * @class
     * @param {Position} position - An initial position for moving pieces.
     */
    function BoardMover (position) {
        this.move = function (move, promotion) {
            var capturedPiece,
                piece,
                startSquare = move.getStartSquare().clone(),
                endSquare = move.getEndSquare().clone();

            if (!isMoveLegal(move)) {
                return false;
            }

            capturedPiece = position.getPiece(endSquare);
            piece = position.getPiece(startSquare);

            movePiece(startSquare, endSquare, piece);

            if (piece.isPawn()) {
                if (startSquare.compareRank(endSquare) === 2) {
                    setNewEnPassantSquare(startSquare);
                } else if (endSquare.getRank() === '1' || endSquare.getRank() === '8') {
                    promotePawn(endSquare, promotion);
                } else if (!startSquare.isSameFile(endSquare) && capturedPiece.isNull()) {
                    removeEnPassantPiece(endSquare);
                }
            }

            if (piece.isKing()) {
                disableKingsideCastling(piece);
                disableQueensideCastling(piece);

                if (piece.isKing() && startSquare.getFile() === 'e') {
                    if (endSquare.getFile() === 'g') {
                        castleKingsideWithRook(startSquare);
                    } else if (endSquare.getFile() === 'c') {
                        castleQueensideWithRook(startSquare);
                    }
                }
            }

            if (piece.isRook()) {
                if (startSquare.getName() === 'h1' || startSquare.getName() === 'h8') {
                    disableKingsideCastling(piece);
                } else if (startSquare.getName() === 'a1' || startSquare.getName() === 'a8') {
                    disableQueensideCastling(piece);
                }
            }

            if (capturedPiece.isRook()) {
                if (endSquare.getName() === 'a1' || endSquare.getName() === 'a8') {
                    disableQueensideCastling(capturedPiece);
                } else if (endSquare.getName() === 'h1' || endSquare.getName() === 'h8') {
                    disableKingsideCastling(capturedPiece);
                }
            }

            if (position.isWhiteToMove()) {
                position.setBlackToMove();
            } else {
                position.setWhiteToMove();
            }

            return true;
        };

        var isMoveLegal = function (move) {
            return $.Engine.isLegal(position, move);
        };

        var movePiece = function (startSquare, endSquare, piece) {
            position.setPiece(endSquare, '', piece.toString());
            position.setPiece(startSquare, '', '');
            position.setEnPassantSquare();
        };

        var promotePawn = function (endSquare, promotion) {
            var color = (endSquare.getRank() === '8' ? 'w' : 'b');

            if (/^[QRBN]$/.test(promotion)) {
                promotion = promotion.toLowerCase();
                position.setPiece(endSquare, '', color + promotion);
            } else {
                // throw error
            }
        };

        var setNewEnPassantSquare = function (startSquare) {
            var newEnPassantSquare = startSquare.clone(),
                pawnDirection = (startSquare.getRank() === '2' ? 1 : -1);
            newEnPassantSquare.addRank(pawnDirection);
            position.setEnPassantSquare(newEnPassantSquare);
        };

        var removeEnPassantPiece = function (endSquare) {
            var newEnPassantSquare = endSquare.clone(),
                pawnDirection = (endSquare.getRank() === '6' ? 1 : -1);
            newEnPassantSquare.addRank(-pawnDirection);
            position.setPiece(newEnPassantSquare, '', '');
        };

        var castleKingsideWithRook = function (startSquare) {
            var rank = startSquare.getRank(),
                piece = position.getPiece(new $.Square('h' + rank));
            position.setPiece(new $.Square('f' + rank), '', piece.toString());
            position.setPiece(new $.Square('h' + rank), '', '');
        };

        var castleQueensideWithRook = function (startSquare) {
            var rank = startSquare.getRank(),
                piece = position.getPiece(new $.Square('a' + rank));
            position.setPiece(new $.Square('d' + rank), '', piece.toString());
            position.setPiece(new $.Square('a' + rank), '', '');
        };

        var disableKingsideCastling = function (piece) {
            if (piece.isWhite()) {
                position.setWhiteCastleKingside(false);
            } else {
                position.setBlackCastleKingside(false);
            }
        };

        var disableQueensideCastling = function (piece) {
            if (piece.isWhite()) {
                position.setWhiteCastleQueenside(false);
            } else {
                position.setBlackCastleQueenside(false);
            }
        };
    }

    return BoardMover;

}(CHESS);
<commit_msg>Pawn auto-promotion to queen<commit_after>var CHESS = CHESS || {};

CHESS.BoardMover = function ($) {

    /**
     * @class
     * @param {Position} position - An initial position for moving pieces.
     */
    function BoardMover (position) {
        this.move = function (move, promotion) {
            var capturedPiece,
                piece,
                startSquare = move.getStartSquare().clone(),
                endSquare = move.getEndSquare().clone();

            if (!isMoveLegal(move)) {
                return false;
            }

            capturedPiece = position.getPiece(endSquare);
            piece = position.getPiece(startSquare);

            movePiece(startSquare, endSquare, piece);

            if (piece.isPawn()) {
                if (startSquare.compareRank(endSquare) === 2) {
                    setNewEnPassantSquare(startSquare);
                } else if (endSquare.getRank() === '1' || endSquare.getRank() === '8') {
                    promotePawn(endSquare, promotion || 'Q');
                } else if (!startSquare.isSameFile(endSquare) && capturedPiece.isNull()) {
                    removeEnPassantPiece(endSquare);
                }
            }

            if (piece.isKing()) {
                disableKingsideCastling(piece);
                disableQueensideCastling(piece);

                if (piece.isKing() && startSquare.getFile() === 'e') {
                    if (endSquare.getFile() === 'g') {
                        castleKingsideWithRook(startSquare);
                    } else if (endSquare.getFile() === 'c') {
                        castleQueensideWithRook(startSquare);
                    }
                }
            }

            if (piece.isRook()) {
                if (startSquare.getName() === 'h1' || startSquare.getName() === 'h8') {
                    disableKingsideCastling(piece);
                } else if (startSquare.getName() === 'a1' || startSquare.getName() === 'a8') {
                    disableQueensideCastling(piece);
                }
            }

            if (capturedPiece.isRook()) {
                if (endSquare.getName() === 'a1' || endSquare.getName() === 'a8') {
                    disableQueensideCastling(capturedPiece);
                } else if (endSquare.getName() === 'h1' || endSquare.getName() === 'h8') {
                    disableKingsideCastling(capturedPiece);
                }
            }

            if (position.isWhiteToMove()) {
                position.setBlackToMove();
            } else {
                position.setWhiteToMove();
            }

            return true;
        };

        var isMoveLegal = function (move) {
            return $.Engine.isLegal(position, move);
        };

        var movePiece = function (startSquare, endSquare, piece) {
            position.setPiece(endSquare, '', piece.toString());
            position.setPiece(startSquare, '', '');
            position.setEnPassantSquare();
        };

        var promotePawn = function (endSquare, promotion) {
            var color = (endSquare.getRank() === '8' ? 'w' : 'b');

            if (/^[QRBN]$/.test(promotion)) {
                promotion = promotion.toLowerCase();
                position.setPiece(endSquare, '', color + promotion);
            } else {
                // throw error
            }
        };

        var setNewEnPassantSquare = function (startSquare) {
            var newEnPassantSquare = startSquare.clone(),
                pawnDirection = (startSquare.getRank() === '2' ? 1 : -1);
            newEnPassantSquare.addRank(pawnDirection);
            position.setEnPassantSquare(newEnPassantSquare);
        };

        var removeEnPassantPiece = function (endSquare) {
            var newEnPassantSquare = endSquare.clone(),
                pawnDirection = (endSquare.getRank() === '6' ? 1 : -1);
            newEnPassantSquare.addRank(-pawnDirection);
            position.setPiece(newEnPassantSquare, '', '');
        };

        var castleKingsideWithRook = function (startSquare) {
            var rank = startSquare.getRank(),
                piece = position.getPiece(new $.Square('h' + rank));
            position.setPiece(new $.Square('f' + rank), '', piece.toString());
            position.setPiece(new $.Square('h' + rank), '', '');
        };

        var castleQueensideWithRook = function (startSquare) {
            var rank = startSquare.getRank(),
                piece = position.getPiece(new $.Square('a' + rank));
            position.setPiece(new $.Square('d' + rank), '', piece.toString());
            position.setPiece(new $.Square('a' + rank), '', '');
        };

        var disableKingsideCastling = function (piece) {
            if (piece.isWhite()) {
                position.setWhiteCastleKingside(false);
            } else {
                position.setBlackCastleKingside(false);
            }
        };

        var disableQueensideCastling = function (piece) {
            if (piece.isWhite()) {
                position.setWhiteCastleQueenside(false);
            } else {
                position.setBlackCastleQueenside(false);
            }
        };
    }

    return BoardMover;

}(CHESS);
<|endoftext|>


<commit_before>Conditions = function()
{
  this.currentsStation = null;
  this.tidesStation = null;

  this.current = {
    speed: 0,
    direction: 0
  };

  this.tide = {
    type: '',
    height: 0,
    date: null
  };

  this.getCurrentsStationId = function() {
    if (this.currentsStation) {
      return this.currentsStation.id;
    }
    return null;
  };

  this.getCurrentsStationName = function() {
    if (this.currentsStation) {
      return this.currentsStation.name;
    }
    return null;
  };

  this.getTidesStationId = function() {
    if (this.tidesStation) {
      return this.tidesStation.id;
    }
    return null;
  };

  this.getTidesStationName = function() {
    if (this.tidesStation) {
      return this.tidesStation.name;
    }
    return null;
  };

  this.getTideString = function()
  {
    if (!this.tide.date)
    {
      return '';
    }
    var msecondsToChange = this.tide.date - Date.now();
    var minutesToChange = msecondsToChange / 1000 / 60;
    tideChange =  this.tide.type + minutesToChange.toFixed(0);
    return tideChange;
  };

  this.setTide = function(predictions)
  {
    if (predictions.length < 2)
    {
      return;
    }

    var initialDelta =
      parseFloat(predictions[0].v) - parseFloat(predictions[1].v);
    for (var index = 2; index < predictions.length; index++) {
      var delta = parseFloat(predictions[index - 1].v) -
        parseFloat(predictions[index].v);
      // Does the slope change signs?
      if (initialDelta * delta < 0) {
        var type = initialDelta < 0 ? 'L' : 'H';
        this.tide.type = type;
        this.tide.height = parseFloat(predictions[index - 1].v);
        // CoOps gives us: YYY-MM-DD HH:mm. We need to convert it to the
        // simplified ISO, which is supported by most JS implementations.
        // http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.15
        var simplified_iso = predictions[index - 1].t.replace(' ', 'T') + 'Z';
        this.tide.date = new Date(simplified_iso);
        return;
      }
    }
  };

  this.setCurrents = function(currents)
  {
    this.current.speed = parseFloat(currents[0].s);
    this.current.direction = parseFloat(currents[0].d);
  };
};
<commit_msg>Fix a bugo with calculating tide change.<commit_after>Conditions = function()
{
  this.currentsStation = null;
  this.tidesStation = null;

  this.current = {
    speed: 0,
    direction: 0
  };

  this.tide = {
    type: '',
    height: 0,
    date: null
  };

  this.getCurrentsStationId = function() {
    if (this.currentsStation) {
      return this.currentsStation.id;
    }
    return null;
  };

  this.getCurrentsStationName = function() {
    if (this.currentsStation) {
      return this.currentsStation.name;
    }
    return null;
  };

  this.getTidesStationId = function() {
    if (this.tidesStation) {
      return this.tidesStation.id;
    }
    return null;
  };

  this.getTidesStationName = function() {
    if (this.tidesStation) {
      return this.tidesStation.name;
    }
    return null;
  };

  this.getTideString = function()
  {
    if (!this.tide.date)
    {
      return '';
    }
    var msecondsToChange = this.tide.date - Date.now();
    var minutesToChange = msecondsToChange / 1000 / 60;
    tideChange =  this.tide.type + minutesToChange.toFixed(0);
    return tideChange;
  };

  this.setTide = function(predictions)
  {
    if (predictions.length < 2)
    {
      return;
    }

    var initialDelta =
      parseFloat(predictions[0].v) - parseFloat(predictions[1].v);
    for (var index = 2; index < predictions.length; index++) {
      var delta = parseFloat(predictions[index - 1].v) -
        parseFloat(predictions[index].v);
      // Does the slope change signs?
      if (initialDelta * delta < 0) {
        var type = initialDelta < 0 ? 'H' : 'L';
        this.tide.type = type;
        this.tide.height = parseFloat(predictions[index - 1].v);
        // CoOps gives us: YYY-MM-DD HH:mm. We need to convert it to the
        // simplified ISO, which is supported by most JS implementations.
        // http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.15
        var simplified_iso = predictions[index - 1].t.replace(' ', 'T') + 'Z';
        this.tide.date = new Date(simplified_iso);
        return;
      }
    }
  };

  this.setCurrents = function(currents)
  {
    this.current.speed = parseFloat(currents[0].s);
    this.current.direction = parseFloat(currents[0].d);
  };
};
<|endoftext|>


<commit_before>/**
 * Copyright 2019 The AMP HTML Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS-IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import {
  findElements,
  resetAllElements,
  verifyElementsBuilt,
  verifyPromptsHidden,
} from './common';

describes.endtoend(
  'amp-consent',
  {
    testUrl:
      'http://localhost:8000/test/manual/amp-consent/amp-consent-basic-uses.amp.html#amp-geo=us',
    // TODO (micajuineho): Add shadow-demo after #25985 is fixed and viewer-demo when...
    environments: ['single'],
  },
  (env) => {
    let controller;

    beforeEach(() => {
      controller = env.controller;
    });

    it('should respect server side decision and persist it', async () => {
      resetAllElements();

      const currentUrl = await controller.getCurrentUrl();

      // Block/unblock elements based off of 'reject' from response
      await findElements(controller);
      await verifyElementsBuilt(controller, {
        'tillResponded': true,
        'accepted': false,
        'autoReject': true,
        'defaultBlock': false,
        'notBlocked': true,
        'twitter': false,
      });
      await verifyPromptsHidden(controller, {
        'ui1': true,
        'ui2': true,
        'postPromptUi': false,
      });

      // Navigate away to random page
      await controller.navigateTo('http://localhost:8000/');
      // Visit website again
      await controller.navigateTo(currentUrl);

      // Verify same behavior after refresh
      await findElements(controller);
      await verifyElementsBuilt(controller, {
        'tillResponded': true,
        'accepted': false,
        'autoReject': true,
        'defaultBlock': false,
        'notBlocked': true,
        'twitter': false,
      });
      await verifyPromptsHidden(controller, {
        'ui1': true,
        'ui2': true,
        'postPromptUi': false,
      });

      // Check the analytics request consentState
      await expect(
        'http://localhost:8000/amp4test/request-bank/e2e/deposit/tracking?consentState=insufficient'
      ).to.have.been.sent;
    });
  }
);
<commit_msg>Skip amp-consent flaky e2e test (#27582)<commit_after>/**
 * Copyright 2019 The AMP HTML Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS-IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import {
  findElements,
  resetAllElements,
  verifyElementsBuilt,
  verifyPromptsHidden,
} from './common';

describes.endtoend(
  'amp-consent',
  {
    testUrl:
      'http://localhost:8000/test/manual/amp-consent/amp-consent-basic-uses.amp.html#amp-geo=us',
    // TODO (micajuineho): Add shadow-demo after #25985 is fixed and viewer-demo when...
    environments: ['single'],
  },
  (env) => {
    let controller;

    beforeEach(() => {
      controller = env.controller;
    });

    //TODO (micajuineho): Unskip flaky test
    it.skip('should respect server side decision and persist it', async () => {
      resetAllElements();

      const currentUrl = await controller.getCurrentUrl();

      // Block/unblock elements based off of 'reject' from response
      await findElements(controller);
      await verifyElementsBuilt(controller, {
        'tillResponded': true,
        'accepted': false,
        'autoReject': true,
        'defaultBlock': false,
        'notBlocked': true,
        'twitter': false,
      });
      await verifyPromptsHidden(controller, {
        'ui1': true,
        'ui2': true,
        'postPromptUi': false,
      });

      // Navigate away to random page
      await controller.navigateTo('http://localhost:8000/');
      // Visit website again
      await controller.navigateTo(currentUrl);

      // Verify same behavior after refresh
      await findElements(controller);
      await verifyElementsBuilt(controller, {
        'tillResponded': true,
        'accepted': false,
        'autoReject': true,
        'defaultBlock': false,
        'notBlocked': true,
        'twitter': false,
      });
      await verifyPromptsHidden(controller, {
        'ui1': true,
        'ui2': true,
        'postPromptUi': false,
      });

      // Check the analytics request consentState
      await expect(
        'http://localhost:8000/amp4test/request-bank/e2e/deposit/tracking?consentState=insufficient'
      ).to.have.been.sent;
    });
  }
);
<|endoftext|>


<commit_before>/*
 *
 */
"use strict";

goog.provide("Entry.PyAstGenerator");

Entry.PyAstGenerator = function() {

};

(function(p){
    p.generate = function(code) {
    	var filbertParse = filbert.parse;
        var locations = true;
        var ranges = true;
        var options = { locations: locations, ranges: ranges };
        try {
            var astTree = filbertParse(code, options);
            return astTree;
        }
        catch (error) {
            var msgTokens = error.message.split('\'');
            var title = Entry.TextCodingError.TITLE_SYNTAX;
            console.log("msgTokens", msgTokens);

            var message, subject;
            if (error.expectedType && error.tokType) {
                if (error.tokType === "eof" || error.tokType === "newline")
                    message = Lang.TextCoding.message_conv_is_expect1 +
                        this.getTokenLang(error.expectedType) + Lang.TextCoding.message_conv_is_expect2;
                else
                    message = Lang.TextCoding.message_conv_instead.replace(
                        "%1", this.getTokenLang(error.tokType)
                    ).replace(
                        "%2", this.getTokenLang(error.expectedType));
                    subject = Entry.TextCodingError.SUBJECT_SYNTAX_TOKEN;
            } else if (error.tokType) {
                if (error.tokType === "eof" || error.tokType === "newline")
                    message = Entry.TextCodingError.MESSAGE_SYNTAX_UNEXPECTED_TOKEN;
                else
                    message = Lang.TextCoding.message_conv_is_wrong1 + this.getTokenLang(error.tokType) +
                        Lang.TextCoding.message_conv_is_wrong1;
                subject = Entry.TextCodingError.SUBJECT_SYNTAX_TOKEN;
            } else if (msgTokens[0].trim() == "Unexpected token") {
                message = Entry.TextCodingError.MESSAGE_SYNTAX_UNEXPECTED_TOKEN;
                subject = Entry.TextCodingError.SUBJECT_SYNTAX_TOKEN;
            } else if (msgTokens[0].trim() == "Unexpected character") {
                message = Entry.TextCodingError.MESSAGE_SYNTAX_UNEXPECTED_CHARACTER;
                subject = Entry.TextCodingError.SUBJECT_SYNTAX_CHARACTER;
            } else if(msgTokens[0].trim() == "Reserved variable word") {
                message = Entry.TextCodingError.MESSAGE_SYNTAX_RESERVED_TOKEN;
                subject = Entry.TextCodingError.SUBJECT_CONV_VARIABLE;
            } else if(msgTokens[0].trim() == "Reserved list word") {
                message = Entry.TextCodingError.MESSAGE_SYNTAX_RESERVED_TOKEN_LIST;
                subject = Entry.TextCodingError.SUBJECT_CONV_LIST;
            } else if(msgTokens[0].trim() == "Unexpected indent") {
                message = Entry.TextCodingError.MESSAGE_SYNTAX_UNEXPECTED_CHARACTER;
                subject = Entry.TextCodingError.SUBJECT_SYNTAX_INDENT;
            } else {
                message = Entry.TextCodingError.MESSAGE_SYNTAX_DEFAULT;
                subject = Entry.TextCodingError.SUBJECT_SYNTAX_DEFAULT;
            }

            if(msgTokens[1])
                var keyword = msgTokens[1];

            error.title = Lang.TextCoding[title] || title;
            error.message = Lang.TextCoding[message] || message;
            error.keyword = keyword || "";
            error.subject = Lang.TextCoding[subject] || subject;

            throw error;
        }
    };

    p.getTokenLang = function(token) {
        if (Array.isArray(token)) {
            var tokens = token.map(this._getTokenLang);
            var lastToken = tokens.pop();
            return tokens.join(", ") + " 나 " + lastToken;
        }
        else
            return this._getTokenLang(token);
    };

    p._getTokenLang = function(token) {
        return Lang.TextCoding[token] || "\"" + token + "\"";
    };
})(Entry.PyAstGenerator.prototype);<commit_msg>Apply Lang<commit_after>/*
 *
 */
"use strict";

goog.provide("Entry.PyAstGenerator");

Entry.PyAstGenerator = function() {

};

(function(p){
    p.generate = function(code) {
    	var filbertParse = filbert.parse;
        var locations = true;
        var ranges = true;
        var options = { locations: locations, ranges: ranges };
        try {
            var astTree = filbertParse(code, options);
            return astTree;
        }
        catch (error) {
            var msgTokens = error.message.split('\'');
            var title = Entry.TextCodingError.TITLE_SYNTAX;
            console.log("msgTokens", msgTokens);

            var message, subject;
            if (error.expectedType && error.tokType) {
                if (error.tokType === "eof" || error.tokType === "newline")
                    message = Lang.TextCoding.message_conv_is_expect1 +
                        this.getTokenLang(error.expectedType) + Lang.TextCoding.message_conv_is_expect2;
                else
                    message = Lang.TextCoding.message_conv_instead.replace(
                        "%1", this.getTokenLang(error.tokType)
                    ).replace(
                        "%2", this.getTokenLang(error.expectedType));
                    subject = Entry.TextCodingError.SUBJECT_SYNTAX_TOKEN;
            } else if (error.tokType) {
                if (error.tokType === "eof" || error.tokType === "newline")
                    message = Entry.TextCodingError.MESSAGE_SYNTAX_UNEXPECTED_TOKEN;
                else
                    message = Lang.TextCoding.message_conv_is_wrong1 + this.getTokenLang(error.tokType) +
                        Lang.TextCoding.message_conv_is_wrong1;
                subject = Entry.TextCodingError.SUBJECT_SYNTAX_TOKEN;
            } else if (msgTokens[0].trim() == "Unexpected token") {
                message = Entry.TextCodingError.MESSAGE_SYNTAX_UNEXPECTED_TOKEN;
                subject = Entry.TextCodingError.SUBJECT_SYNTAX_TOKEN;
            } else if (msgTokens[0].trim() == "Unexpected character") {
                message = Entry.TextCodingError.MESSAGE_SYNTAX_UNEXPECTED_CHARACTER;
                subject = Entry.TextCodingError.SUBJECT_SYNTAX_CHARACTER;
            } else if(msgTokens[0].trim() == "Reserved variable word") {
                message = Entry.TextCodingError.MESSAGE_SYNTAX_RESERVED_TOKEN;
                subject = Entry.TextCodingError.SUBJECT_CONV_VARIABLE;
            } else if(msgTokens[0].trim() == "Reserved list word") {
                message = Entry.TextCodingError.MESSAGE_SYNTAX_RESERVED_TOKEN_LIST;
                subject = Entry.TextCodingError.SUBJECT_CONV_LIST;
            } else if(msgTokens[0].trim() == "Unexpected indent") {
                message = Entry.TextCodingError.MESSAGE_SYNTAX_UNEXPECTED_CHARACTER;
                subject = Entry.TextCodingError.SUBJECT_SYNTAX_INDENT;
            } else {
                message = Entry.TextCodingError.MESSAGE_SYNTAX_DEFAULT;
                subject = Entry.TextCodingError.SUBJECT_SYNTAX_DEFAULT;
            }

            if(msgTokens[1])
                var keyword = msgTokens[1];

            error.title = Lang.TextCoding[title] || title;
            error.message = Lang.TextCoding[message] || message;
            error.keyword = keyword || "";
            error.subject = Lang.TextCoding[subject] || subject;

            throw error;
        }
    };

    p.getTokenLang = function(token) {
        if (Array.isArray(token)) {
            var tokens = token.map(this._getTokenLang);
            var lastToken = tokens.pop();
            return tokens.join(", ") + Lang.TextCoding.message_conv_or + lastToken;
        }
        else
            return this._getTokenLang(token);
    };

    p._getTokenLang = function(token) {
        return Lang.TextCoding[token] || "\"" + token + "\"";
    };
})(Entry.PyAstGenerator.prototype);<|endoftext|>


<commit_before>angular.module('myApp.directives', [

]).

directive('uaPassValidate', function() { // http://bit.ly/1cwp3h0
	return {
		restrict: 'A', // restrict to an attribute
		require: 'ngModel', // must have ng-model attribute
		link: function(scope, elem, attr, ctrl) {
			ctrl.$parsers.push(function( value ) {
				var lowerAlph = !!(value || 'a').match(/[a-z]/); // pass if empty
				var upperAlph = !!(value || 'A').match(/[A-Z]/);
				var hasNumber = !!(value || '0').match(/[0-9]/);
				var metLength = !!(value || 'abcdef').match(/.{6,}/);
				var specialCh = !!(value || '!').match(/[^a-zA-Z0-9]/);
				var valid = lowerAlph && upperAlph && hasNumber && metLength && specialCh;

				ctrl.$setValidity('lowerAlph', lowerAlph);
				ctrl.$setValidity('upperAlph', upperAlph);
				ctrl.$setValidity('hasNumber', hasNumber);
				ctrl.$setValidity('metLength', metLength);
				ctrl.$setValidity('specialCh', specialCh);
				ctrl.$setValidity('passValid', valid);

				return (valid && value) ? value : undefined; // but don't return object
			});
		}
	};
}).

directive('uaBlank', function() {
	return {
		restrict: 'A',
		require: 'ngModel',
		link: function(scope, elem, attr, ctrl) {
			ctrl.$parsers.push(function(value) {
				return value ? value : undefined;
			});
		}
	};
}).

directive('uaPhone', function() {
	var formatPhone = function (tel) {
		if (!tel) return undefined;
		var value = tel.toString().trim().replace(/[^0-9]/g, ''), country, city, number;

		switch (value.length) {
			case 10: // +1PPP####### -> C (PPP) ###-####
				country = 1;
				city = value.slice(0, 3);
				number = value.slice(3);
				break;

			case 11: // +CPPP####### -> CCC (PP) ###-####
				country = value[0];
				city = value.slice(1, 4);
				number = value.slice(4);
				break;

			case 12: // +CCCPP####### -> CCC (PP) ###-####
				country = value.slice(0, 3);
				city = value.slice(3, 5);
				number = value.slice(5);
				break;

			default:
				return value;
		}
		if (country == 1) country = "";
		number = number.slice(0, 3) + '-' + number.slice(3);
		return (country + " (" + city + ") " + number).trim();
	};

	return {
		restrict: 'A',
		require: '?ngModel',
		link: function($scope, elem, attr, ctrl) {
			ctrl.$parsers.unshift(function (tel) {
				tel = formatPhone(tel);
				elem.val(tel);
				return tel;
			});
		}
	};
}).

directive('notify', ['$timeout', function($timeout) { // extending from ui.bootstrap.alert
	return {
		restrict:'EA',
		replace: true,
		template: '
'+
			'	<alert type="message.type" close="clearMessage()">' +
			'		{{message.pre}} {{message.msg}}' +
			'	</alert>'+
			'
',
		scope: {
			'message': '='
		},
		link: function($scope) {
			var timer;

			$scope.clearMessage = function() {
				$scope.message = false;
			};
			$scope.$watch('message', function(val) {
				$timeout.cancel(timer);
				$scope.messages = [val];
				if (val) timer = $timeout($scope.clearMessage, (val.delay || 15)*1000);
			});
		}
	};
}]).

directive('uaMagicFormatter', ['$filter', function($filter) {
	var formatters = {
		currency: function(val) {
			var decimal = val.split('.')[1];
			decimal = (decimal === undefined) ? "" : ("." + decimal.substr(0,2)); // decimal formatting
			val = parseInt(val.replace(/[^\d\.]/g,'')); // convert to number
			val = $filter('currency')(val, '$'); // format directly
			val = val.substring(0, val.length-3); // remove decimals
			return val + decimal;
		}
	};
	return {
		restrict: 'A',
		require: '?ngModel',
		link: function(scope, element, attrs, ctrl) {
			ctrl.$parsers.unshift(function(val) {
				val = formatters[ attrs.uaMagicFormatter ]( val );
				return element.val( val ).val();
			});
		}
	};
}]);<commit_msg>allowing HTML in alert<commit_after>angular.module('myApp.directives', [

]).

directive('uaPassValidate', function() { // http://bit.ly/1cwp3h0
	return {
		restrict: 'A', // restrict to an attribute
		require: 'ngModel', // must have ng-model attribute
		link: function(scope, elem, attr, ctrl) {
			ctrl.$parsers.push(function( value ) {
				var lowerAlph = !!(value || 'a').match(/[a-z]/); // pass if empty
				var upperAlph = !!(value || 'A').match(/[A-Z]/);
				var hasNumber = !!(value || '0').match(/[0-9]/);
				var metLength = !!(value || 'abcdef').match(/.{6,}/);
				var specialCh = !!(value || '!').match(/[^a-zA-Z0-9]/);
				var valid = lowerAlph && upperAlph && hasNumber && metLength && specialCh;

				ctrl.$setValidity('lowerAlph', lowerAlph);
				ctrl.$setValidity('upperAlph', upperAlph);
				ctrl.$setValidity('hasNumber', hasNumber);
				ctrl.$setValidity('metLength', metLength);
				ctrl.$setValidity('specialCh', specialCh);
				ctrl.$setValidity('passValid', valid);

				return (valid && value) ? value : undefined; // but don't return object
			});
		}
	};
}).

directive('uaBlank', function() {
	return {
		restrict: 'A',
		require: 'ngModel',
		link: function(scope, elem, attr, ctrl) {
			ctrl.$parsers.push(function(value) {
				return value ? value : undefined;
			});
		}
	};
}).

directive('uaPhone', function() {
	var formatPhone = function (tel) {
		if (!tel) return undefined;
		var value = tel.toString().trim().replace(/[^0-9]/g, ''), country, city, number;

		switch (value.length) {
			case 10: // +1PPP####### -> C (PPP) ###-####
				country = 1;
				city = value.slice(0, 3);
				number = value.slice(3);
				break;

			case 11: // +CPPP####### -> CCC (PP) ###-####
				country = value[0];
				city = value.slice(1, 4);
				number = value.slice(4);
				break;

			case 12: // +CCCPP####### -> CCC (PP) ###-####
				country = value.slice(0, 3);
				city = value.slice(3, 5);
				number = value.slice(5);
				break;

			default:
				return value;
		}
		if (country == 1) country = "";
		number = number.slice(0, 3) + '-' + number.slice(3);
		return (country + " (" + city + ") " + number).trim();
	};

	return {
		restrict: 'A',
		require: '?ngModel',
		link: function($scope, elem, attr, ctrl) {
			ctrl.$parsers.unshift(function (tel) {
				tel = formatPhone(tel);
				elem.val(tel);
				return tel;
			});
		}
	};
}).

directive('notify', ['$timeout', '$sce', function($timeout, $sce) { // extending from ui.bootstrap.alert
	return {
		restrict:'EA',
		replace: true,
		template: '
'+
			'	<alert type="message.type" close="clearMessage()" class="alert-block">' +
			'
{{message.pre}}
' +
			'		' +
			'	</alert>'+
			'
',
		scope: {
			'message': '='
		},
		link: function($scope) {
			var timer;
			$scope.clearMessage = function() {
				$scope.message = false;
			};
			$scope.$watch('message', function(val) {
				$timeout.cancel(timer);
				$scope.cleanHTML =  $sce.trustAsHtml(val.msg);
				if (val) timer = $timeout($scope.clearMessage, (val.delay || 15)*1000);
			});
		}
	};
}]).

directive('uaMagicFormatter', ['$filter', function($filter) {
	var formatters = {
		currency: function(val) {
			var decimal = val.split('.')[1];
			decimal = (decimal === undefined) ? "" : ("." + decimal.substr(0,2)); // decimal formatting
			val = parseInt(val.replace(/[^\d\.]/g,'')); // convert to number
			val = $filter('currency')(val, '$'); // format directly
			val = val.substring(0, val.length-3); // remove decimals
			return val + decimal;
		}
	};
	return {
		restrict: 'A',
		require: '?ngModel',
		link: function(scope, element, attrs, ctrl) {
			ctrl.$parsers.unshift(function(val) {
				val = formatters[ attrs.uaMagicFormatter ]( val );
				return element.val( val ).val();
			});
		}
	};
}]);<|endoftext|>


<commit_before>/**
 * Needs jquery.
 * Can be required with commonjs or require.js
 */

(function() {

    var conf = {};
    var sessionRefreshTimeout = undefined;

    function myAjax(method,url,creds,data) {

            var headers = getAuthHeaders(creds);
            var opts = {
                /*
                crossDomain: true,
                xhrFields: { withCredentials: true },
                */
                type : method,
                headers : headers,
                url:url
            };

            if (data !== undefined) {

                headers['Content-Type'] = 'application/json';
                opts.processData = false;
                opts.data = data;

            }

            return $.ajax(opts);

    }

    function getUrl (suffix) { return conf.urlBase + suffix; }

    function getAuthHeaders (creds) {

        if (creds && creds.user && creds.pass) {

            return {
                'Authorization':
                'Basic ' + btoa(creds.user + ':' + creds.pass)
            };

        } else if (creds && creds.cookie) {

            // For testing purposes, sending a custom cookie is supported
            // This does not work on standard browsers

            return { 'Cookie': creds.cookie };

        } else if (creds && creds.authorization) {

            // For testing purposes, sending a custom authorization
            // header is supported.

            return {'Authorization': creds.authorization};

        } else {

            return {};

        }

    }

    function clearSessionRefresh(data) {

        if (sessionRefreshTimeout) {
            clearTimeout(sessionRefreshTimeout);
            sessionRefreshTimeout = undefined;
        }

    }

    function setSessionRefresh(data) {

        sessionRefreshTimeout = setTimeout(refreshSession,data.refresh);

    }

    function refreshSession(data) {

        return myAjax('GET',getUrl('session'))
            .done(setSessionRefresh);

    }

    var libcatconf = {

        getAuthHeaders : getAuthHeaders,

        /** return an array of user and domain nodeIds */
        getUsersAndDomains : function (options) {

            if (options === undefined) options = {};

            return myAjax('GET',getUrl('node'),options.creds);

        },

        getUsers : function (options) {

            if (options === undefined) options = {};

            return myAjax('GET',getUrl('node?users=1'),options.creds);

        },

        getDomainMembers : function (domain,options) {

            if (options === undefined) options = {};

            var url = getUrl('node?in-domain=' + encodeURIComponent(domain))

            return myAjax('GET',url,options.creds);

        },

        getDomains : function (options) {

            if (options === undefined) options = {};

            return myAjax('GET',getUrl('node?domains=1'),options.creds);

        },

        putNode : function (node,options) {

            if (options === undefined) options = {};

            var query = options.singleLevel ? '?single-level=1' :'';
            var nodeId = options.nodeId || node.metadata.nodeId;

            return myAjax('PUT',getUrl('node/'+nodeId+query),options.creds,
                JSON.stringify(node));

        },

        deleteNode : function (nodeId,options) {

            if (options === undefined) options = {};

            return myAjax('DELETE',getUrl('node/'+nodeId),options.creds);

        },

        getNode : function (nodeId,options) {

            if (options === undefined) options = {};

            var query = options.singleLevel ? '?single-level=1' : '';

            return myAjax('GET',getUrl('node/'+nodeId+query),options.creds);

        },

        getMyNode : function (options) {

            if (options === undefined) options = {};

            var nodeId = libcatconf.getUserName(options.creds);
            var def = $.Deferred();

            if (nodeId) {

                return libcatconf.getNode(nodeId,options);

            } else {

                myAjax('GET',getUrl('session'),options.creds)
                    .done(gotMySession)
                    .fail(failGetMyNode);
                return def;

            }

            function gotMySession (data) {

                nodeId = data.user;
                return libcatconf.getNode(nodeId,options).
                    done(gotMyNode).
                    fail(failGetMyNode);

            }

            function gotMyNode (data) { def.resolve(data); }
            function failGetMyNode (err) { def.reject(err); }

        },

        login : function (creds) {

            return myAjax('POST',getUrl('session'),creds)
                .done(setSessionRefresh);

        },

        logout : function (creds) {

            clearSessionRefresh();

            return myAjax('DELETE',getUrl('session'),creds)

        },

        isSpecialProperty : function (key) {

            return (key == 'metadata')

        },

        configure : function (newConf) {

            conf = newConf;

        },

        getUserName : function (creds) {

            return creds ? creds.user : undefined;

        },

    };

    if ((typeof module !== 'undefined') && (module.exports)) {

        // this is node.js

        $ = require('jquery');
        btoa = require('btoa');

        module.exports = libcatconf;

    } else if (typeof define == "function") {

        // this is require.js

        define([],libcatconf);

    } else {

        // this is just a plain html script-tag.

        window.libcatconf = libcatconf;

    }

})()

<commit_msg>support catconf cors<commit_after>/**
 * Needs jquery.
 * Can be required with commonjs or require.js
 */

(function() {

    var conf = {};
    var sessionRefreshTimeout = undefined;

    function myAjax(method,url,creds,data) {

            var headers = getAuthHeaders(creds);
            var opts = {
                crossDomain: true,
                xhrFields: { withCredentials: true },
                type : method,
                headers : headers,
                url:url
            };

            if (data !== undefined) {

                headers['Content-Type'] = 'application/json';
                opts.processData = false;
                opts.data = data;

            }

            return $.ajax(opts);

    }

    function getUrl (suffix) { return conf.urlBase + suffix; }

    function getAuthHeaders (creds) {

        if (creds && creds.user && creds.pass) {

            return {
                'Authorization':
                'Basic ' + btoa(creds.user + ':' + creds.pass)
            };

        } else if (creds && creds.cookie) {

            // For testing purposes, sending a custom cookie is supported
            // This does not work on standard browsers

            return { 'Cookie': creds.cookie };

        } else if (creds && creds.authorization) {

            // For testing purposes, sending a custom authorization
            // header is supported.

            return {'Authorization': creds.authorization};

        } else {

            return {};

        }

    }

    function clearSessionRefresh(data) {

        if (sessionRefreshTimeout) {
            clearTimeout(sessionRefreshTimeout);
            sessionRefreshTimeout = undefined;
        }

    }

    function setSessionRefresh(data) {

        sessionRefreshTimeout = setTimeout(refreshSession,data.refresh);

    }

    function refreshSession(data) {

        return myAjax('GET',getUrl('session'))
            .done(setSessionRefresh);

    }

    var libcatconf = {

        getAuthHeaders : getAuthHeaders,

        /** return an array of user and domain nodeIds */
        getUsersAndDomains : function (options) {

            if (options === undefined) options = {};

            return myAjax('GET',getUrl('node'),options.creds);

        },

        getUsers : function (options) {

            if (options === undefined) options = {};

            return myAjax('GET',getUrl('node?users=1'),options.creds);

        },

        getDomainMembers : function (domain,options) {

            if (options === undefined) options = {};

            var url = getUrl('node?in-domain=' + encodeURIComponent(domain))

            return myAjax('GET',url,options.creds);

        },

        getDomains : function (options) {

            if (options === undefined) options = {};

            return myAjax('GET',getUrl('node?domains=1'),options.creds);

        },

        putNode : function (node,options) {

            if (options === undefined) options = {};

            var query = options.singleLevel ? '?single-level=1' :'';
            var nodeId = options.nodeId || node.metadata.nodeId;

            return myAjax('PUT',getUrl('node/'+nodeId+query),options.creds,
                JSON.stringify(node));

        },

        deleteNode : function (nodeId,options) {

            if (options === undefined) options = {};

            return myAjax('DELETE',getUrl('node/'+nodeId),options.creds);

        },

        getNode : function (nodeId,options) {

            if (options === undefined) options = {};

            var query = options.singleLevel ? '?single-level=1' : '';

            return myAjax('GET',getUrl('node/'+nodeId+query),options.creds);

        },

        getMyNode : function (options) {

            if (options === undefined) options = {};

            var nodeId = libcatconf.getUserName(options.creds);
            var def = $.Deferred();

            if (nodeId) {

                return libcatconf.getNode(nodeId,options);

            } else {

                myAjax('GET',getUrl('session'),options.creds)
                    .done(gotMySession)
                    .fail(failGetMyNode);
                return def;

            }

            function gotMySession (data) {

                nodeId = data.user;
                return libcatconf.getNode(nodeId,options).
                    done(gotMyNode).
                    fail(failGetMyNode);

            }

            function gotMyNode (data) { def.resolve(data); }
            function failGetMyNode (err) { def.reject(err); }

        },

        login : function (creds) {

            return myAjax('POST',getUrl('session'),creds)
                .done(setSessionRefresh);

        },

        logout : function (creds) {

            clearSessionRefresh();

            return myAjax('DELETE',getUrl('session'),creds)

        },

        isSpecialProperty : function (key) {

            return (key == 'metadata')

        },

        configure : function (newConf) {

            conf = newConf;

        },

        getUserName : function (creds) {

            return creds ? creds.user : undefined;

        },

    };

    if ((typeof module !== 'undefined') && (module.exports)) {

        // this is node.js

        $ = require('jquery');
        btoa = require('btoa');

        module.exports = libcatconf;

    } else if (typeof define == "function") {

        // this is require.js

        define([],libcatconf);

    } else {

        // this is just a plain html script-tag.

        window.libcatconf = libcatconf;

    }

})()

<|endoftext|>


<commit_before>'use strict';

(function() {
  angular.module('hutmap', ['hutmap.services', 'hutmap.directives',
    'hutmap.filters', 'hutmap.controllers', 'AngularGM', 'ngResource',
    'ui.bootstrap']).

  config(
    ['$routeProvider', '$locationProvider', 'PlacesProvider',
    function($routeProvider, $locationProvider, PlacesProvider) {

    $routeProvider.
      when('/', {
        templateUrl: '/partials/home.html',
        activetab: 'home',
      }).
      when('/map/', {
        templateUrl: '/partials/map.html',
        activetab: 'map',
        reloadOnSearch: false,
      }).
      when('/about/', {
        templateUrl: '/partials/about.html',
        activetab: 'about',
      });

    $locationProvider.html5Mode(true);

    // suggest bounds for our search results
    PlacesProvider.bounds(new google.maps.LatLngBounds(
        new google.maps.LatLng(30, -130),
        new google.maps.LatLng(65, -80)));
  }]).

  constant('hutmapMapId', 'map_canvas').

  value('mapOptions', {
    zoom : 3,
    center : new google.maps.LatLng(46.87916, -120),
    mapTypeId : google.maps.MapTypeId.TERRAIN,
    streetViewControl: false,
    panControlOptions: {
      position: google.maps.ControlPosition.LEFT_CENTER
    },
    zoomControlOptions: {
      position: google.maps.ControlPosition.LEFT_CENTER
    },

  }).

  value('markerOptions', {
    huts: {
      icon: '/static/img/marker_gray_small.png',
      shape: {
        coord: [6, 0, 2, 2, 0, 6, 6, 13, 12, 6, 10, 2, 6, 0],
        type: 'poly'
      },
      zIndex: 0
    },
    filteredHuts: {
      icon: '/static/img/marker_red_small.png',
      shape: {
        coord: [6, 0, 2, 2, 0, 6, 6, 13, 12, 6, 10, 2, 6, 0],
        type: 'poly'
      },
      zIndex: 1
    },
    selected: {
      icon: '/static/img/marker_yellow_small.png',
      zIndex: 2
    }
  }).

  run(['hutmapMapId', 'angulargmContainer', function(hutmapMapId, angulargmContainer) {
    var gmapPromise = angulargmContainer.getMapPromise(hutmapMapId);

    /**
     * Add new map types to our Google Map.
     * Add drag zoom control.
     */
    gmapPromise.then(function(gmap) {
      var getTile = {};

      /**
       * Function for retrieving MSR USGS topo tiles.
       *
       * @param {google.maps.Point} point The tile coordinate.
       * @param {number} zoom The zoom level of the map.
       * @returns {string} The URL of the needed tile.
       */
      getTile.MSR_TOPO = function(point, zoom) {
        var projection = gmap.getProjection();
        var h = Math.pow(2, zoom);
        var swPnt = new google.maps.Point(point.x * 256 / h, (point.y + 1) * 256 / h);
        var nePnt = new google.maps.Point((point.x + 1) * 256 / h, (point.y) * 256 / h);
        var sw = projection.fromPointToLatLng(swPnt);
        var ne = projection.fromPointToLatLng(nePnt);
        var bbox = [sw.lng(), sw.lat(), ne.lng(), ne.lat()];
        var url = "http://msrmaps.com/ogcmap.ashx?version=1.1.1&request=GetMap&Layers=drg&Styles=default&SRS=EPSG:4326&BBOX=" +
          bbox.join(',') + "&width=256&height=256&format=image/jpeg";
        return url;
      };

      /**
       * Retrieves ArcGis USA topo tiles.
       */
      getTile.ARC_GIS_USA = function(point, zoom) {
        var c = 1 << zoom,
        column = (point.x % c);
        if (column < 0) { column += c }
        var url = "http://services.arcgisonline.com/ArcGIS/rest/services/USA_Topo_Maps/MapServer/tile/";
        return url + (parseInt(zoom)) + "/" + point.y + "/" + column
      };

      /**
       * Retrieves ArcGis World topo tiles.
       */
      getTile.ARC_GIS_WORLD = function(point, zoom) {
        var c = 1 << zoom,
        column = (point.x % c);
        if (column < 0) { column += c }
        var url = "http://services.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/tile/";
        return url + (parseInt(zoom)) + "/" + point.y + "/" + column
      };

      var mapTypes = {
        MSR_TOPO: new google.maps.ImageMapType({
          name: "MSR USGS",
          alt: "USGS topos from Microsoft Research",
          minZoom: 1,
          maxZoom: 15,
          tileSize: new google.maps.Size(256, 256),
          isPng: false,
          getTileUrl: getTile.MSR_TOPO
        }),

        ARC_GIS_USA: new google.maps.ImageMapType({
          name: "ArcGIS USA",
          alt: "ArcGIS USA Topos",
          minZoom: 1,
          maxZoom: 15,
          tileSize: new google.maps.Size(256, 256),
          isPng: true,
          getTileUrl: getTile.ARC_GIS_USA
        }),

        ARC_GIS_WORLD: new google.maps.ImageMapType({
          name: "ArcGIS World",
          alt: "ArcGIS World Topos",
          minZoom: 1,
          maxZoom: 15,
          tileSize: new google.maps.Size(256, 256),
          isPng: true,
          getTileUrl: getTile.ARC_GIS_WORLD
        })
      };

      angular.forEach(mapTypes, function(mapType, key) {
        gmap.mapTypes.set(mapType.name, mapType);
      });

      gmap.setOptions({
        mapTypeControlOptions: {
          mapTypeIds: [google.maps.MapTypeId.ROADMAP,
                       google.maps.MapTypeId.SATELLITE,
                       google.maps.MapTypeId.HYBRID,
                       google.maps.MapTypeId.TERRAIN,
                       mapTypes.MSR_TOPO.name,
                       mapTypes.ARC_GIS_USA.name,
                       mapTypes.ARC_GIS_WORLD.name]
        }
      });

      gmap.enableKeyDragZoom({
        key: 'alt',
        visualEnabled: true,
        visualPosition: google.maps.ControlPosition.LEFT_CENTER
      });
    });
  }]);

})();
<commit_msg>Set ArcGIS World as default map type.<commit_after>'use strict';

(function() {
  angular.module('hutmap', ['hutmap.services', 'hutmap.directives',
    'hutmap.filters', 'hutmap.controllers', 'AngularGM', 'ngResource',
    'ui.bootstrap']).

  config(
    ['$routeProvider', '$locationProvider', 'PlacesProvider',
    function($routeProvider, $locationProvider, PlacesProvider) {

    $routeProvider.
      when('/', {
        templateUrl: '/partials/home.html',
        activetab: 'home',
      }).
      when('/map/', {
        templateUrl: '/partials/map.html',
        activetab: 'map',
        reloadOnSearch: false,
      }).
      when('/about/', {
        templateUrl: '/partials/about.html',
        activetab: 'about',
      });

    $locationProvider.html5Mode(true);

    // suggest bounds for our search results
    PlacesProvider.bounds(new google.maps.LatLngBounds(
        new google.maps.LatLng(30, -130),
        new google.maps.LatLng(65, -80)));
  }]).

  constant('hutmapMapId', 'map_canvas').

  value('mapOptions', {
    zoom : 3,
    center : new google.maps.LatLng(46.87916, -120),
    mapTypeId : google.maps.MapTypeId.TERRAIN, // overriden in the run block below
    streetViewControl: false,
    panControlOptions: {
      position: google.maps.ControlPosition.LEFT_CENTER
    },
    zoomControlOptions: {
      position: google.maps.ControlPosition.LEFT_CENTER
    },

  }).

  value('markerOptions', {
    huts: {
      icon: '/static/img/marker_gray_small.png',
      shape: {
        coord: [6, 0, 2, 2, 0, 6, 6, 13, 12, 6, 10, 2, 6, 0],
        type: 'poly'
      },
      zIndex: 0
    },
    filteredHuts: {
      icon: '/static/img/marker_red_small.png',
      shape: {
        coord: [6, 0, 2, 2, 0, 6, 6, 13, 12, 6, 10, 2, 6, 0],
        type: 'poly'
      },
      zIndex: 1
    },
    selected: {
      icon: '/static/img/marker_yellow_small.png',
      zIndex: 2
    }
  }).

  run(['hutmapMapId', 'angulargmContainer', function(hutmapMapId, angulargmContainer) {
    var gmapPromise = angulargmContainer.getMapPromise(hutmapMapId);

    /**
     * Add new map types to our Google Map.
     * Add drag zoom control.
     */
    gmapPromise.then(function(gmap) {
      var getTile = {};

      /**
       * Function for retrieving MSR USGS topo tiles.
       *
       * @param {google.maps.Point} point The tile coordinate.
       * @param {number} zoom The zoom level of the map.
       * @returns {string} The URL of the needed tile.
       */
      getTile.MSR_TOPO = function(point, zoom) {
        var projection = gmap.getProjection();
        var h = Math.pow(2, zoom);
        var swPnt = new google.maps.Point(point.x * 256 / h, (point.y + 1) * 256 / h);
        var nePnt = new google.maps.Point((point.x + 1) * 256 / h, (point.y) * 256 / h);
        var sw = projection.fromPointToLatLng(swPnt);
        var ne = projection.fromPointToLatLng(nePnt);
        var bbox = [sw.lng(), sw.lat(), ne.lng(), ne.lat()];
        var url = "http://msrmaps.com/ogcmap.ashx?version=1.1.1&request=GetMap&Layers=drg&Styles=default&SRS=EPSG:4326&BBOX=" +
          bbox.join(',') + "&width=256&height=256&format=image/jpeg";
        return url;
      };

      /**
       * Retrieves ArcGis USA topo tiles.
       */
      getTile.ARC_GIS_USA = function(point, zoom) {
        var c = 1 << zoom,
        column = (point.x % c);
        if (column < 0) { column += c }
        var url = "http://services.arcgisonline.com/ArcGIS/rest/services/USA_Topo_Maps/MapServer/tile/";
        return url + (parseInt(zoom)) + "/" + point.y + "/" + column
      };

      /**
       * Retrieves ArcGis World topo tiles.
       */
      getTile.ARC_GIS_WORLD = function(point, zoom) {
        var c = 1 << zoom,
        column = (point.x % c);
        if (column < 0) { column += c }
        var url = "http://services.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/tile/";
        return url + (parseInt(zoom)) + "/" + point.y + "/" + column
      };

      var mapTypes = {
        MSR_TOPO: new google.maps.ImageMapType({
          name: "MSR USGS",
          alt: "USGS topos from Microsoft Research",
          minZoom: 1,
          maxZoom: 15,
          tileSize: new google.maps.Size(256, 256),
          isPng: false,
          getTileUrl: getTile.MSR_TOPO
        }),

        ARC_GIS_USA: new google.maps.ImageMapType({
          name: "ArcGIS USA",
          alt: "ArcGIS USA Topos",
          minZoom: 1,
          maxZoom: 15,
          tileSize: new google.maps.Size(256, 256),
          isPng: true,
          getTileUrl: getTile.ARC_GIS_USA
        }),

        ARC_GIS_WORLD: new google.maps.ImageMapType({
          name: "ArcGIS World",
          alt: "ArcGIS World Topos",
          minZoom: 1,
          maxZoom: 15,
          tileSize: new google.maps.Size(256, 256),
          isPng: true,
          getTileUrl: getTile.ARC_GIS_WORLD
        })
      };

      angular.forEach(mapTypes, function(mapType, key) {
        gmap.mapTypes.set(mapType.name, mapType);
      });

      gmap.setOptions({
        mapTypeControlOptions: {
          mapTypeIds: [google.maps.MapTypeId.ROADMAP,
                       google.maps.MapTypeId.SATELLITE,
                       google.maps.MapTypeId.HYBRID,
                       google.maps.MapTypeId.TERRAIN,
                       mapTypes.MSR_TOPO.name,
                       mapTypes.ARC_GIS_USA.name,
                       mapTypes.ARC_GIS_WORLD.name]
        }
      });

      gmap.setMapTypeId(mapTypes.ARC_GIS_WORLD.name);

      gmap.enableKeyDragZoom({
        key: 'alt',
        visualEnabled: true,
        visualPosition: google.maps.ControlPosition.LEFT_CENTER
      });
    });
  }]);

})();
<|endoftext|>


<commit_before>/**
 * struct.js - chainable ArrayBuffer DataView wrapper
 *
 * @author Meiguro / http://meiguro.com/
 * @license MIT
 */

var capitalize = function(str) {
  return str.charAt(0).toUpperCase() + str.substr(1);
};

var struct = function(def) {
  this._littleEndian = true;
  this._offset = 0;
  this._cursor = 0;
  this._makeAccessors(def);
  this._view = new DataView(new ArrayBuffer(this._size));
  this._def = def;
};

struct.types = {
  int8: { size: 1 },
  uint8: { size: 1 },
  int16: { size: 2 },
  uint16: { size: 2 },
  int32: { size: 4 },
  uint32: { size: 4 },
  int64: { size: 8 },
  uint64: { size: 8 },
  float32: { size: 2 },
  float64: { size: 4 },
  cstring: { size: 1, dynamic: true },
  data: { size: 0, dynamic: true },
};

var makeDataViewAccessor = function(type, typeName) {
  var getName = 'get' + capitalize(typeName);
  var setName = 'set' + capitalize(typeName);
  type.get = function(offset, little) {
    this._advance = type.size;
    return this._view[getName](offset, little);
  };
  type.set = function(offset, value, little) {
    this._advance = type.size;
    this._view[setName](offset, value, little);
  };
};

for (var k in struct.types) {
  var type = struct.types[k];
  makeDataViewAccessor(type, k);
}

struct.types.bool = struct.types.uint8;

struct.types.cstring.get = function(offset) {
  var chars = [];
  var buffer = this._view;
  for (var i = offset, ii = buffer.byteLength, j = 0; i < ii && buffer.getUint8(i) !== 0; ++i, ++j) {
    chars[j] = String.fromCharCode(buffer.getUint8(i));
  }
  this._advance = chars.length + 1;
  return chars.join('');
};

struct.types.cstring.set = function(offset, value) {
  this._grow(offset + value.length + 1);
  var i = offset;
  var buffer = this._view;
  for (var j = 0, jj = value.length; j < jj && value[i] !== '\0'; ++i, ++j) {
    buffer.setUint8(i, value.charCodeAt(j));
  }
  buffer.setUint8(i, 0);
  this._advance = value.length + 1;
};

struct.types.data.get = function(offset) {
  var length = this._value;
  this._cursor = offset;
  var buffer = this._view;
  var copy = new DataView(new ArrayBuffer(length));
  for (var i = 0; i < length; ++i) {
    copy.setUint8(i, buffer.getUint8(i + offset));
  }
  this._advance = length;
  return copy;
};

struct.types.data.set = function(offset, value) {
  var length = value.byteLength || value.length;
  this._cursor = offset;
  this._grow(offset + length);
  var buffer = this._view;
  if (value instanceof ArrayBuffer) {
    value = new DataView(value);
  }
  for (var i = 0; i < length; ++i) {
    buffer.setUint8(i + offset, value instanceof DataView ? value.getUint8(i) : value[i]);
  }
  this._advance = length;
};

struct.prototype._grow = function(target) {
  var buffer = this._view;
  var size = buffer.byteLength;
  if (target <= size) { return; }
  while (size < target) { size *= 2; }
  var copy = new DataView(new ArrayBuffer(size));
  for (var i = 0; i < buffer.byteLength; ++i) {
    copy.setUint8(i, buffer.getUint8(i));
  }
  this._view = copy;
};

struct.prototype._prevField = function(field) {
  field = field || this._access;
  var fieldIndex = this._fields.indexOf(field);
  return this._fields[fieldIndex - 1];
};

struct.prototype._makeAccessor = function(field) {
  this[field.name] = function(value) {
    var type = field.type;
    if (field.dynamic) {
      var prevField = this._prevField(field);
      if (prevField === undefined) {
        this._cursor = 0;
      } else if (this._access === field) {
        this._cursor -= this._advance;
      } else if (this._access !== prevField) {
        throw new Error('dynamic field requires sequential access');
      }
    } else {
      this._cursor = this._offset + field.index;
    }
    this._access = field;
    var result = this;
    if (arguments.length === 0) {
      result = type.get.call(this, this._cursor, this._littleEndian);
      this._value = result;
    } else {
      if (field.transform) {
        value = field.transform(value, field);
      }
      type.set.call(this, this._cursor, value, this._littleEndian);
      this._value = value;
    }
    this._cursor += this._advance;
    return result;
  };
  return this;
};

struct.prototype._makeMetaAccessor = function(name, transform) {
  this[name] = function(value, field) {
    transform.call(this, value, field);
    return this;
  };
};

struct.prototype._makeAccessors = function(def, index, fields, prefix) {
  index = index || 0;
  this._fields = ( fields = fields || [] );
  var prevField = fields[fields.length];
  for (var i = 0, ii = def.length; i < ii; ++i) {
    var member = def[i];
    var type = member[0];
    if (typeof type === 'string') {
      type = struct.types[type];
    }
    var name = member[1];
    if (prefix) {
      name = prefix + capitalize(name);
    }
    var transform = member[2];
    if (type instanceof struct) {
      if (transform) {
        this._makeMetaAccessor(name, transform);
      }
      this._makeAccessors(type._def, index, fields, name);
      index = this._size;
      continue;
    }
    var field = {
      index: index,
      type: type,
      name: name,
      transform: transform,
      dynamic: type.dynamic || prevField && prevField.dynamic,
    };
    this._makeAccessor(field);
    fields.push(field);
    index += type.size;
    prevField = field;
  }
  this._size = index;
  return this;
};

struct.prototype.prop = function(def) {
  var fields = this._fields;
  var i = 0, ii = fields.length, name;
  if (arguments.length === 0) {
    var obj = {};
    for (; i < ii; ++i) {
      name = fields[i].name;
      obj[name] = this[name]();
    }
    return obj;
  }
  for (; i < ii; ++i) {
    name = fields[i].name;
    if (name in def) {
      this[name](def[name]);
    }
  }
  return this;
};

struct.prototype.view = function(view) {
  if (arguments.length === 0) {
    return this._view;
  }
  if (view instanceof ArrayBuffer) {
    view = new DataView(view);
  }
  this._view = view;
  return this;
};

struct.prototype.offset = function(offset) {
  if (arguments.length === 0) {
    return this._offset;
  }
  this._offset = offset;
  return this;
};

module.exports = struct;

<commit_msg>Add struct.js uint64 support<commit_after>/**
 * struct.js - chainable ArrayBuffer DataView wrapper
 *
 * @author Meiguro / http://meiguro.com/
 * @license MIT
 */

var capitalize = function(str) {
  return str.charAt(0).toUpperCase() + str.substr(1);
};

var struct = function(def) {
  this._littleEndian = true;
  this._offset = 0;
  this._cursor = 0;
  this._makeAccessors(def);
  this._view = new DataView(new ArrayBuffer(this._size));
  this._def = def;
};

struct.types = {
  int8: { size: 1 },
  uint8: { size: 1 },
  int16: { size: 2 },
  uint16: { size: 2 },
  int32: { size: 4 },
  uint32: { size: 4 },
  int64: { size: 8 },
  uint64: { size: 8 },
  float32: { size: 2 },
  float64: { size: 4 },
  cstring: { size: 1, dynamic: true },
  data: { size: 0, dynamic: true },
};

var makeDataViewAccessor = function(type, typeName) {
  var getName = 'get' + capitalize(typeName);
  var setName = 'set' + capitalize(typeName);
  type.get = function(offset, little) {
    this._advance = type.size;
    return this._view[getName](offset, little);
  };
  type.set = function(offset, value, little) {
    this._advance = type.size;
    this._view[setName](offset, value, little);
  };
};

for (var k in struct.types) {
  var type = struct.types[k];
  makeDataViewAccessor(type, k);
}

struct.types.bool = struct.types.uint8;

struct.types.uint64.get = function(offset, little) {
  var buffer = this._view;
  var a = buffer.getUint32(offset, little);
  var b = buffer.getUint32(offset + 4, little);
  this._advance = 8;
  return ((little ? b : a) << 32) + (little ? a : b);
};

struct.types.uint64.set = function(offset, value, little) {
  var a = value & 0xFFFFFFFF;
  var b = (value >> 32) & 0xFFFFFFFF;
  var buffer = this._view;
  buffer.setUint32(offset, little ? a : b, little);
  buffer.setUint32(offset + 4, little ? b : a, little);
  this._advance = 8;
};

struct.types.cstring.get = function(offset) {
  var chars = [];
  var buffer = this._view;
  for (var i = offset, ii = buffer.byteLength, j = 0; i < ii && buffer.getUint8(i) !== 0; ++i, ++j) {
    chars[j] = String.fromCharCode(buffer.getUint8(i));
  }
  this._advance = chars.length + 1;
  return chars.join('');
};

struct.types.cstring.set = function(offset, value) {
  this._grow(offset + value.length + 1);
  var i = offset;
  var buffer = this._view;
  for (var j = 0, jj = value.length; j < jj && value[i] !== '\0'; ++i, ++j) {
    buffer.setUint8(i, value.charCodeAt(j));
  }
  buffer.setUint8(i, 0);
  this._advance = value.length + 1;
};

struct.types.data.get = function(offset) {
  var length = this._value;
  this._cursor = offset;
  var buffer = this._view;
  var copy = new DataView(new ArrayBuffer(length));
  for (var i = 0; i < length; ++i) {
    copy.setUint8(i, buffer.getUint8(i + offset));
  }
  this._advance = length;
  return copy;
};

struct.types.data.set = function(offset, value) {
  var length = value.byteLength || value.length;
  this._cursor = offset;
  this._grow(offset + length);
  var buffer = this._view;
  if (value instanceof ArrayBuffer) {
    value = new DataView(value);
  }
  for (var i = 0; i < length; ++i) {
    buffer.setUint8(i + offset, value instanceof DataView ? value.getUint8(i) : value[i]);
  }
  this._advance = length;
};

struct.prototype._grow = function(target) {
  var buffer = this._view;
  var size = buffer.byteLength;
  if (target <= size) { return; }
  while (size < target) { size *= 2; }
  var copy = new DataView(new ArrayBuffer(size));
  for (var i = 0; i < buffer.byteLength; ++i) {
    copy.setUint8(i, buffer.getUint8(i));
  }
  this._view = copy;
};

struct.prototype._prevField = function(field) {
  field = field || this._access;
  var fieldIndex = this._fields.indexOf(field);
  return this._fields[fieldIndex - 1];
};

struct.prototype._makeAccessor = function(field) {
  this[field.name] = function(value) {
    var type = field.type;
    if (field.dynamic) {
      var prevField = this._prevField(field);
      if (prevField === undefined) {
        this._cursor = 0;
      } else if (this._access === field) {
        this._cursor -= this._advance;
      } else if (this._access !== prevField) {
        throw new Error('dynamic field requires sequential access');
      }
    } else {
      this._cursor = field.index;
    }
    this._access = field;
    var result = this;
    if (arguments.length === 0) {
      result = type.get.call(this, this._offset + this._cursor, this._littleEndian);
      this._value = result;
    } else {
      if (field.transform) {
        value = field.transform(value, field);
      }
      type.set.call(this, this._offset + this._cursor, value, this._littleEndian);
      this._value = value;
    }
    this._cursor += this._advance;
    return result;
  };
  return this;
};

struct.prototype._makeMetaAccessor = function(name, transform) {
  this[name] = function(value, field) {
    transform.call(this, value, field);
    return this;
  };
};

struct.prototype._makeAccessors = function(def, index, fields, prefix) {
  index = index || 0;
  this._fields = ( fields = fields || [] );
  var prevField = fields[fields.length];
  for (var i = 0, ii = def.length; i < ii; ++i) {
    var member = def[i];
    var type = member[0];
    if (typeof type === 'string') {
      type = struct.types[type];
    }
    var name = member[1];
    if (prefix) {
      name = prefix + capitalize(name);
    }
    var transform = member[2];
    if (type instanceof struct) {
      if (transform) {
        this._makeMetaAccessor(name, transform);
      }
      this._makeAccessors(type._def, index, fields, name);
      index = this._size;
      continue;
    }
    var field = {
      index: index,
      type: type,
      name: name,
      transform: transform,
      dynamic: type.dynamic || prevField && prevField.dynamic,
    };
    this._makeAccessor(field);
    fields.push(field);
    index += type.size;
    prevField = field;
  }
  this._size = index;
  return this;
};

struct.prototype.prop = function(def) {
  var fields = this._fields;
  var i = 0, ii = fields.length, name;
  if (arguments.length === 0) {
    var obj = {};
    for (; i < ii; ++i) {
      name = fields[i].name;
      obj[name] = this[name]();
    }
    return obj;
  }
  for (; i < ii; ++i) {
    name = fields[i].name;
    if (name in def) {
      this[name](def[name]);
    }
  }
  return this;
};

struct.prototype.view = function(view) {
  if (arguments.length === 0) {
    return this._view;
  }
  if (view instanceof ArrayBuffer) {
    view = new DataView(view);
  }
  this._view = view;
  return this;
};

struct.prototype.offset = function(offset) {
  if (arguments.length === 0) {
    return this._offset;
  }
  this._offset = offset;
  return this;
};

module.exports = struct;

<|endoftext|>