<commit_before>var Class    = require('js-class'),
    _        = require('underscore'),
    elements = require('evo-elements'),
    Config   = elements.Config,
    Logger   = elements.Logger,
    Neuron   = require('./Neuron');

var Program = Class({
    constructor: function (name, opts) {
        opts || (opts = {});
        this.name = name;
        var conf = Config.conf(_.extend({ reloadSignal: true }, opts.conf || {}));
        this.options = conf.opts[name] || {};
        this.logger = new Logger(name);
        (this.neuron = new Neuron(_.extend({ name: name }, opts.neuron || {})))
            .on('error', this.onError.bind(this))
            .on('state', this.onState.bind(this))
            .on('close', this.onClose.bind(this))
            .on('connect', this.onConnect.bind(this))
            .on('disconnect', this.onDisconnect.bind(this))
            .on('message', this.onMessage.bind(this));
        conf.on('reload', this._reload.bind(this));
    },

    /** @function
     * @description Simplified version of dispatching requests
     */
    dispatch: function (event, opts) {
        var prefix = (opts && opts.prefix) || 'neuron:';
        var self = this;
        this.neuron.dispatch(event, function (req) {
            var handler = self[prefix + event];
            if (handler) {
                if (opts && opts.schema) {
                    req.accept(opts.schema, function (data) {
                        handler.call(self, req, data);
                    });
                } else {
                    handler.call(self, req);
                }
            }
        });
        return this;
    },

    /** @function
     * @description Start the program
     */
    run: function () {
        this.neuron.start();
    },

    /** @function
     * @description Reload configurations
     *
     * Override this to perform the actual logic
     */
    reload: function (options) {
        this.options = options;
    },

    /** @function
     * @description Event when receptor/axon/dendrites error
     *
     * @param {Error} err       The error
     * @param {object} extra    Extra information
     *          - receptor: undefined
     *          - axon: { src: 'a', id: branchName }
     *          - dendrite: { src: 'd', id: dendriteId }
     */
    onError: function (err, extra) {
        // by default, the error should be raised
        throw err;
    },

    /** @function
     * @description Event when axon connectivity changes
     *
     * @param {String} state    Current connectivity
     *          - connecting    connecting a branch
     *          - connected     branch connected
     *          - disconnected  branch disconnected
     * @param {String} branch   Branch name
     */
    onState: function (state, branch) {
        // do nothing
    },

    /** @function
     * @description Event when receptor closed
     */
    onClose: function () {
        // do nothing
    },

    /** @function
     * @description Event when a dendrite is connected
     *
     * @param {String} id       Dendrite Id
     */
    onConnect: function (id) {
        // do nothing
    },

    /** @function
     * @description Event when a dendrite is disconnected
     *
     * @param {String} id       Dendrite Id
     */
    onDisconnect: function (id) {
        // do nothing
    },

    /** @function
     * @description Event when a message received
     *
     * @param {object} msg      Message
     * @param {object} info     Message source info
     *          - from Axon: { src: 'a', id: branchName }
     *          - from Dendrite: { src: 'd', id: dendriteId }
     */
    onMessage: function (msg, info) {
        // do nothing
    },

    _reload: function () {
        var options = Config.conf().opts[this.name];
        if (typeof(options) == 'object') {
            this.reload(options);
        }
    }
});

module.exports = Program;
<commit_msg>fix default onError behavior<commit_after>var Class    = require('js-class'),
    _        = require('underscore'),
    elements = require('evo-elements'),
    Config   = elements.Config,
    Logger   = elements.Logger,
    Neuron   = require('./Neuron');

var Program = Class({
    constructor: function (name, opts) {
        opts || (opts = {});
        this.name = name;
        var conf = Config.conf(_.extend({ reloadSignal: true }, opts.conf || {}));
        this.options = conf.opts[name] || {};
        this.logger = new Logger(name);
        (this.neuron = new Neuron(_.extend({ name: name }, opts.neuron || {})))
            .on('error', this.onError.bind(this))
            .on('state', this.onState.bind(this))
            .on('close', this.onClose.bind(this))
            .on('connect', this.onConnect.bind(this))
            .on('disconnect', this.onDisconnect.bind(this))
            .on('message', this.onMessage.bind(this));
        conf.on('reload', this._reload.bind(this));
    },

    /** @function
     * @description Simplified version of dispatching requests
     */
    dispatch: function (event, opts) {
        var prefix = (opts && opts.prefix) || 'neuron:';
        var self = this;
        this.neuron.dispatch(event, function (req) {
            var handler = self[prefix + event];
            if (handler) {
                if (opts && opts.schema) {
                    req.accept(opts.schema, function (data) {
                        handler.call(self, req, data);
                    });
                } else {
                    handler.call(self, req);
                }
            }
        });
        return this;
    },

    /** @function
     * @description Start the program
     */
    run: function () {
        this.neuron.start();
    },

    /** @function
     * @description Reload configurations
     *
     * Override this to perform the actual logic
     */
    reload: function (options) {
        this.options = options;
    },

    /** @function
     * @description Event when receptor/axon/dendrites error
     *
     * @param {Error} err       The error
     * @param {object} extra    Extra information
     *          - receptor: undefined
     *          - axon: { src: 'a', id: branchName }
     *          - dendrite: { src: 'd', id: dendriteId }
     */
    onError: function (err, extra) {
        // by default, the error is logged
        if (extra) {
            this.logger.error('%s:%s %s', extra.src, extra.id, err.message);
        } else {
            this.logger.error('Receptor %s', err.message);
        }
    },

    /** @function
     * @description Event when axon connectivity changes
     *
     * @param {String} state    Current connectivity
     *          - connecting    connecting a branch
     *          - connected     branch connected
     *          - disconnected  branch disconnected
     * @param {String} branch   Branch name
     */
    onState: function (state, branch) {
        // do nothing
    },

    /** @function
     * @description Event when receptor closed
     */
    onClose: function () {
        // do nothing
    },

    /** @function
     * @description Event when a dendrite is connected
     *
     * @param {String} id       Dendrite Id
     */
    onConnect: function (id) {
        // do nothing
    },

    /** @function
     * @description Event when a dendrite is disconnected
     *
     * @param {String} id       Dendrite Id
     */
    onDisconnect: function (id) {
        // do nothing
    },

    /** @function
     * @description Event when a message received
     *
     * @param {object} msg      Message
     * @param {object} info     Message source info
     *          - from Axon: { src: 'a', id: branchName }
     *          - from Dendrite: { src: 'd', id: dendriteId }
     */
    onMessage: function (msg, info) {
        // do nothing
    },

    _reload: function () {
        var options = Config.conf().opts[this.name];
        if (typeof(options) == 'object') {
            this.reload(options);
        }
    }
});

module.exports = Program;
<|endoftext|>


<commit_before>

var KEYWORDS = ["x", "y", "cx", "cy", "bg", "size", "col", "frame", "w", "h", "rect", "clear", "for", "c"];
var MATH_PROPS = ["E", "LN2", "LN10", "LOG2E", "LOG10E", "PI", "PI2", "SQRT1_2", "SQRT2"];
var MATHS = ["abs", "acos", "asin", "atan", "atan2",
           "ceil", "cos", "exp", "floor", "imul", "log", "max", "min", "pow", "random", "round", "sin", "sqrt", "tan"];
var CTX_FUNCS = Object.getOwnPropertyNames(CanvasRenderingContext2D.prototype);

PI2 = Math.PI2 = Math.PI*2.0;

var Centi = function(name){
    this.name = name ? name : "ct";

    this.canvas = null;
    this.ctx = null;

    this.x=0;
    this.y=0;
    //
    this.c = 0;
    this.w = 720;
    this.h = 360;
    this.cx = this.w/2;
    this.cy = this.h/2;
    //

    this.bgcolor = {r:0, g:0, b:0};

    this.bFill = true;

    this.drawMethod = '';

    this.toGifFunc = null;

};

Centi.prototype.init = function(canvas){
    this.canvas = canvas;

    if ( canvas.getContext ) {
        this.ctx = canvas.getContext("2d");
        this.clear();
        return true;
    } else {
        return false;
    }
};

Centi.prototype.parse = function(tw){

    tw = tw.replace(/\s/g, "");
    tw = tw.replace(/\b/g, "");
    tw = tw.replace(/(\))([A-Za-z0-9_\}])/g, ");$2");
    tw = tw.replace(/(for\()([A-Za-z_\-\.\(\)]+)(\,)([A-Za-z0-9_\-\.\(\)]+)(\,)([A-Za-z0-9_\-\.\(\)\*\+\/]+)(\))/g, "for($2=$4;$2<$6;$2++)");
    // for ( var i=0; i<MATHS.length; i++ ) {
    //     var math_word = "" + MATHS[i] + "\\(";
    //     tw = tw.replace(new RegExp(math_word, "g"), "Math." + MATHS[i] + "(");
    // }
    // for ( var i=0; i<MATH_PROPS.length; i++ ) {
    //     tw = tw.replace(new RegExp(MATH_PROPS[i], "g"), "Math." + MATH_PROPS[i]);
    // }
//    for ( var i=0; i<CTX_FUNCS.length; i++ ) {
//        var math_word = "" + CTX_FUNCS[i] + "\\(";
//        tw = tw.replace(new RegExp(math_word, "g"), "ctx." + CTX_FUNCS[i] + "(");
//    }
    var frameReg = /frame[A-Za-z0-9_\%\&\:\(\)\{\}\;\=\+\-\<\>\*\.\,\/\[\]]+/i;
    var setupMethod = tw.replace(frameReg, "");
    var frameMethod = frameReg.test(tw) ? tw.match(frameReg)[0] : "frame(){}";
    frameMethod = frameMethod.slice(frameMethod.indexOf("{")+1, frameMethod.lastIndexOf("}"));

    var forReg = new RegExp(this.name+".for\\(", "g");
    var ifReg = new RegExp(this.name+".if\\(", "g");
    var numbersReg = new RegExp("(" + this.name + ")\.([0-9\.]+)", "g");
    //var valueReg = /(^[A-Za-z_][A-Za-z0-9_]+)([\%\&\:\(\)\{\}\;\=\+\-\<\>\*\/\[\]\,])/g;
    var valueReg2 = /([A-Za-z0-9_]+)([\%\&\:\(\)\{\}\;\=\+\-\<\>\*\/\[\]\,\^])/g;
    setupMethod = setupMethod.replace(valueReg2, this.name + "."+"$1"+"$2");
    //setupMethod = setupMethod.replace(valueReg, this.name + "."+"$1"+"$2");
    //setupMethod = setupMethod.replace(new RegExp(this.name + "." + this.name, "g"), this.name);
    setupMethod = setupMethod.replace(numbersReg, "$2");
    setupMethod = setupMethod.replace(forReg, "for(");
    setupMethod = setupMethod.replace(ifReg, "if(");
    for ( var i=0; i<MATHS.length; i++ ) {
        var math_word = this.name + "." + MATHS[i] + "\\(";
        setupMethod = setupMethod.replace(new RegExp(math_word, "g"), "Math." + MATHS[i] + "(");
    }
    for ( var i=0; i<MATH_PROPS.length; i++ ) {
        setupMethod = setupMethod.replace(new RegExp(this.name + "." + MATH_PROPS[i], "g"), "Math." + MATH_PROPS[i]);
    }
    //console.log(setupMethod);

    frameMethod = frameMethod.replace(valueReg2, this.name + "."+"$1"+"$2");
    //frameMethod = frameMethod.replace(valueReg, this.name + "."+"$1"+"$2");
    //frameMethod = frameMethod.replace(new RegExp(this.name + "." + this.name, "g"), this.name);
    frameMethod = frameMethod.replace(numbersReg, "$2");
    frameMethod = frameMethod.replace(forReg, "for(");
    frameMethod = frameMethod.replace(ifReg, "if(");
    for ( var i=0; i<MATHS.length; i++ ) {
        var math_word = this.name + "." + MATHS[i] + "\\(";
        frameMethod = frameMethod.replace(new RegExp(math_word, "g"), "Math." + MATHS[i] + "(");
    }
    for ( var i=0; i<MATH_PROPS.length; i++ ) {
        frameMethod = frameMethod.replace(new RegExp(this.name + "." + MATH_PROPS[i], "g"), "Math." + MATH_PROPS[i]);
    }
    //console.log(frameMethod);

    this.drawMethod = frameMethod;
    //console.log(setupMethod);
    //console.log(drawMethod);
    this.bg(0);
    evalInContext(setupMethod, this);
    return true;

};

Centi.prototype.update = function(){
    evalInContext(this.drawMethod, this);
    this.c++;
    if ( this.toGifFunc != null ) this.toGifFunc(this.ctx);
};

//centi funcs

Centi.prototype.bg = function(){
    var len = arguments.length;
    if ( len == 1 ) {
        this.bgcolor.r = parseInt(arguments[0]);
        this.bgcolor.g = parseInt(arguments[0]);
        this.bgcolor.b = parseInt(arguments[0]);
    } else if ( len == 3 ) {
        this.bgcolor.r = parseInt(arguments[0]);
        this.bgcolor.g = parseInt(arguments[1]);
        this.bgcolor.b = parseInt(arguments[2]);
    }
    this.clear();
};

Centi.prototype.lg = function(){
    console.log(arguments);
};

Centi.prototype.sz = function(_w, _h){ this.size(_w, _h); };
Centi.prototype.size = function(_w, _h){
    this.w = parseInt(_w);
    this.h = parseInt(_h);
    this.canvas.width = this.w;
    this.canvas.height = this.h;
    this.cx = this.w/2;
    this.cy = this.h/2;
};

Centi.prototype.clr = function(){ this.clear(); };
Centi.prototype.clear = function(){
    this.ctx.fillStyle = "rgb("+this.bgcolor.r+","+this.bgcolor.g+","+this.bgcolor.b+")";
    this.ctx.fillRect(0,0,this.w, this.h);
};

// Randomize

Centi.prototype.rnd = function(){
    var len = arguments.length;
    if ( len == 1 ) {
        return Math.random()*arguments[0];
    } else if ( len == 2 ) {
        return Math.random()*(arguments[1] - arguments[0]) + arguments[0];
    } else {
        return Math.random();
    }
};
Centi.prototype.rand = function(){
    var len = arguments.length;
    if ( len == 1 ) {
        return Math.random()*arguments[0];
    } else if ( len == 2 ) {
        return Math.random()*(arguments[1] - arguments[0]) + arguments[0];
    } else {
        return Math.random();
    }
};

Centi.prototype.nz = function() {
    var len = arguments.length;
    if ( len == 1 ) {
        return perlin.perlin2(arguments[0], 0);
    } else if ( len == 2 ) {
        return perlin.perlin2(arguments[0], arguments[1]);
    } else if ( len == 3 ) {
        return perlin.perlin3(arguments[0], arguments[1], arguments[2]);
    }
    return 0;
};
Centi.prototype.noise = function(){
    var len = arguments.length;
    if ( len == 1 ) {
        return perlin.perlin2(arguments[0], 0);
    } else if ( len == 2 ) {
        return perlin.perlin2(arguments[0], arguments[1]);
    } else if ( len == 3 ) {
        return perlin.perlin3(arguments[0], arguments[1], arguments[2]);
    }
    return 0;
};

// draw

Centi.prototype.rect = function(_x, _y, _w, _h){
    if ( this.bFill ) this.ctx.fillRect(_x, _y, _w, _h);
    else this.ctx.strokeRect(_x, _y, _w, _h);
};

Centi.prototype.ln = function(_x1, _y1, _x2, _y2){ this.line(_x1, _y1, _x2, _y2); };
Centi.prototype.line = function(_x1, _y1, _x2, _y2){
    this.ctx.beginPath();
    this.ctx.moveTo(_x1, _y1);
    this.ctx.lineTo(_x2, _y2);
    this.ctx.stroke();
};

Centi.prototype.moveTo = function(_x1, _y1){
    this.ctx.moveTo(_x1, _y1);
};

Centi.prototype.lineTo = function(_x1, _y1){
    this.ctx.lineTo(_x1, _y1);
};

Centi.prototype.oval = function(_x, _y, _rad) {
    this.ctx.beginPath();
    this.ctx.arc(_x, _y, _rad, 0, Math.PI * 2, true);
    if ( this.bFill ) this.ctx.fill();
    else this.ctx.stroke()
};

Centi.prototype.beginShape = function(){
    this.ctx.beginPath();
};

Centi.prototype.endShape = function(){
    if ( this.bFill ) this.ctx.fill();
    else this.ctx.stroke();
};

Centi.prototype.drawMe = function(){
    var len = arguments.length;
    if ( len == 2 ) {
        this.ctx.drawImage(this.canvas, arguments[0], arguments[1]);
    } else if ( len == 4 ) {
        this.ctx.drawImage(this.canvas, arguments[0], arguments[1], arguments[2], arguments[3]);
    } else if ( len == 8 ) {
        this.ctx.drawImage(this.canvas, arguments[0], arguments[1], arguments[2], arguments[3], arguments[4], arguments[5], arguments[6], arguments[7]);
    }
};

// transform

Centi.prototype.push = function(){
    this.ctx.save();
};

Centi.prototype.pop = function(){
    this.ctx.restore();
};

Centi.prototype.rotate = function(_rota){
    this.ctx.rotate(_rota);
};

Centi.prototype.scale = function(_x, _y){
    this.ctx.scale(_x, _y);
};

Centi.prototype.translate = function(_x, _y){
    this.ctx.translate(_x, _y);
};

// util

Centi.prototype.col = function(){
    var len = arguments.length;
    var s = "rgb(0,0,0)";
    if ( len == 1 ) {
        s = "rgb(" + parseInt(arguments[0]) + "," + parseInt(arguments[0]) + "," + parseInt(arguments[0]) + ")";
    } else if ( len == 2 ) {
        s = "rgba(" + parseInt(arguments[0]) + "," + parseInt(arguments[0]) + "," + parseInt(arguments[0]) + "," + parseInt(arguments[1])/255.0 + ")";
    } else if ( len == 3 ) {
        s = "rgb(" + parseInt(arguments[0]) + "," + parseInt(arguments[1]) + "," + parseInt(arguments[2]) + ")";
    } else if ( len == 4 ) {
        s = "rgba(" + parseInt(arguments[0]) + "," + parseInt(arguments[1]) + "," + parseInt(arguments[2]) + "," + parseInt(arguments[3])/255.0 + ")";
    }
    this.ctx.fillStyle = s;
    this.ctx.strokeStyle = s;
};

Centi.prototype.fill = function(){
    this.bFill = true;
};

Centi.prototype.strk = function(){ this.stroke(); };
Centi.prototype.stroke = function(){
    this.bFill = false;
};

Centi.prototype.interp = function(a, b, rate){
    return b + (a-b)*rate;
};

Centi.prototype.sortNum = function(_arr){
    _arr.sort(
        function(a,b){
            if( a < b ) return -1;
            if( a > b ) return 1;
            return 0;
        }
    );
}

Centi.prototype.reverse = function(_arr){
    _arr.reverse();
}

Centi.prototype.vec2 = function(_x, _y){
    return new Centi.Vec2(_x, _y);
};
Centi.Vec2 = function(_x, _y){
    this.x = _x;
    this.y = _y;
};;

// centi funcs

Centi.prototype.reset = function(){
    this.c = 0;
    this.bFill = true;
};

var CT_FUNCS = Object.getOwnPropertyNames(Centi.prototype);

<commit_msg>added lineWidth<commit_after>

var KEYWORDS = ["x", "y", "cx", "cy", "bg", "size", "col", "frame", "w", "h", "rect", "clear", "for", "c"];
var MATH_PROPS = ["E", "LN2", "LN10", "LOG2E", "LOG10E", "PI", "PI2", "SQRT1_2", "SQRT2"];
var MATHS = ["abs", "acos", "asin", "atan", "atan2",
           "ceil", "cos", "exp", "floor", "imul", "log", "max", "min", "pow", "random", "round", "sin", "sqrt", "tan"];
var CTX_FUNCS = Object.getOwnPropertyNames(CanvasRenderingContext2D.prototype);

PI2 = Math.PI2 = Math.PI*2.0;

var Centi = function(name){
    this.name = name ? name : "ct";

    this.canvas = null;
    this.ctx = null;

    this.x=0;
    this.y=0;
    //
    this.c = 0;
    this.w = 720;
    this.h = 360;
    this.cx = this.w/2;
    this.cy = this.h/2;
    //

    this.bgcolor = {r:0, g:0, b:0};

    this.bFill = true;

    this.drawMethod = '';

    this.toGifFunc = null;

};

Centi.prototype.init = function(canvas){
    this.canvas = canvas;

    if ( canvas.getContext ) {
        this.ctx = canvas.getContext("2d");
        this.clear();
        return true;
    } else {
        return false;
    }
};

Centi.prototype.parse = function(tw){

    tw = tw.replace(/\s/g, "");
    tw = tw.replace(/\b/g, "");
    tw = tw.replace(/(\))([A-Za-z0-9_\}])/g, ");$2");
    tw = tw.replace(/(for\()([A-Za-z_\-\.\(\)]+)(\,)([A-Za-z0-9_\-\.\(\)]+)(\,)([A-Za-z0-9_\-\.\(\)\*\+\/]+)(\))/g, "for($2=$4;$2<$6;$2++)");
    // for ( var i=0; i<MATHS.length; i++ ) {
    //     var math_word = "" + MATHS[i] + "\\(";
    //     tw = tw.replace(new RegExp(math_word, "g"), "Math." + MATHS[i] + "(");
    // }
    // for ( var i=0; i<MATH_PROPS.length; i++ ) {
    //     tw = tw.replace(new RegExp(MATH_PROPS[i], "g"), "Math." + MATH_PROPS[i]);
    // }
//    for ( var i=0; i<CTX_FUNCS.length; i++ ) {
//        var math_word = "" + CTX_FUNCS[i] + "\\(";
//        tw = tw.replace(new RegExp(math_word, "g"), "ctx." + CTX_FUNCS[i] + "(");
//    }
    var frameReg = /frame[A-Za-z0-9_\%\&\:\(\)\{\}\;\=\+\-\<\>\*\.\,\/\[\]]+/i;
    var setupMethod = tw.replace(frameReg, "");
    var frameMethod = frameReg.test(tw) ? tw.match(frameReg)[0] : "frame(){}";
    frameMethod = frameMethod.slice(frameMethod.indexOf("{")+1, frameMethod.lastIndexOf("}"));

    var forReg = new RegExp(this.name+".for\\(", "g");
    var ifReg = new RegExp(this.name+".if\\(", "g");
    var numbersReg = new RegExp("(" + this.name + ")\.([0-9\.]+)", "g");
    //var valueReg = /(^[A-Za-z_][A-Za-z0-9_]+)([\%\&\:\(\)\{\}\;\=\+\-\<\>\*\/\[\]\,])/g;
    var valueReg2 = /([A-Za-z0-9_]+)([\%\&\:\(\)\{\}\;\=\+\-\<\>\*\/\[\]\,\^])/g;
    setupMethod = setupMethod.replace(valueReg2, this.name + "."+"$1"+"$2");
    //setupMethod = setupMethod.replace(valueReg, this.name + "."+"$1"+"$2");
    //setupMethod = setupMethod.replace(new RegExp(this.name + "." + this.name, "g"), this.name);
    setupMethod = setupMethod.replace(numbersReg, "$2");
    setupMethod = setupMethod.replace(forReg, "for(");
    setupMethod = setupMethod.replace(ifReg, "if(");
    for ( var i=0; i<MATHS.length; i++ ) {
        var math_word = this.name + "." + MATHS[i] + "\\(";
        setupMethod = setupMethod.replace(new RegExp(math_word, "g"), "Math." + MATHS[i] + "(");
    }
    for ( var i=0; i<MATH_PROPS.length; i++ ) {
        setupMethod = setupMethod.replace(new RegExp(this.name + "." + MATH_PROPS[i], "g"), "Math." + MATH_PROPS[i]);
    }
    //console.log(setupMethod);

    frameMethod = frameMethod.replace(valueReg2, this.name + "."+"$1"+"$2");
    //frameMethod = frameMethod.replace(valueReg, this.name + "."+"$1"+"$2");
    //frameMethod = frameMethod.replace(new RegExp(this.name + "." + this.name, "g"), this.name);
    frameMethod = frameMethod.replace(numbersReg, "$2");
    frameMethod = frameMethod.replace(forReg, "for(");
    frameMethod = frameMethod.replace(ifReg, "if(");
    for ( var i=0; i<MATHS.length; i++ ) {
        var math_word = this.name + "." + MATHS[i] + "\\(";
        frameMethod = frameMethod.replace(new RegExp(math_word, "g"), "Math." + MATHS[i] + "(");
    }
    for ( var i=0; i<MATH_PROPS.length; i++ ) {
        frameMethod = frameMethod.replace(new RegExp(this.name + "." + MATH_PROPS[i], "g"), "Math." + MATH_PROPS[i]);
    }
    //console.log(frameMethod);

    this.drawMethod = frameMethod;
    //console.log(setupMethod);
    //console.log(drawMethod);
    this.bg(0);
    evalInContext(setupMethod, this);
    return true;

};

Centi.prototype.update = function(){
    evalInContext(this.drawMethod, this);
    this.c++;
    if ( this.toGifFunc != null ) this.toGifFunc(this.ctx);
};

//centi funcs

Centi.prototype.bg = function(){
    var len = arguments.length;
    if ( len == 1 ) {
        this.bgcolor.r = parseInt(arguments[0]);
        this.bgcolor.g = parseInt(arguments[0]);
        this.bgcolor.b = parseInt(arguments[0]);
    } else if ( len == 3 ) {
        this.bgcolor.r = parseInt(arguments[0]);
        this.bgcolor.g = parseInt(arguments[1]);
        this.bgcolor.b = parseInt(arguments[2]);
    }
    this.clear();
};

Centi.prototype.lg = function(){
    console.log(arguments);
};

Centi.prototype.sz = function(_w, _h){ this.size(_w, _h); };
Centi.prototype.size = function(_w, _h){
    this.w = parseInt(_w);
    this.h = parseInt(_h);
    this.canvas.width = this.w;
    this.canvas.height = this.h;
    this.cx = this.w/2;
    this.cy = this.h/2;
};

Centi.prototype.clr = function(){ this.clear(); };
Centi.prototype.clear = function(){
    this.ctx.fillStyle = "rgb("+this.bgcolor.r+","+this.bgcolor.g+","+this.bgcolor.b+")";
    this.ctx.fillRect(0,0,this.w, this.h);
};

// Randomize

Centi.prototype.rnd = function(){
    var len = arguments.length;
    if ( len == 1 ) {
        return Math.random()*arguments[0];
    } else if ( len == 2 ) {
        return Math.random()*(arguments[1] - arguments[0]) + arguments[0];
    } else {
        return Math.random();
    }
};
Centi.prototype.rand = function(){
    var len = arguments.length;
    if ( len == 1 ) {
        return Math.random()*arguments[0];
    } else if ( len == 2 ) {
        return Math.random()*(arguments[1] - arguments[0]) + arguments[0];
    } else {
        return Math.random();
    }
};

Centi.prototype.nz = function() {
    var len = arguments.length;
    if ( len == 1 ) {
        return perlin.perlin2(arguments[0], 0);
    } else if ( len == 2 ) {
        return perlin.perlin2(arguments[0], arguments[1]);
    } else if ( len == 3 ) {
        return perlin.perlin3(arguments[0], arguments[1], arguments[2]);
    }
    return 0;
};
Centi.prototype.noise = function(){
    var len = arguments.length;
    if ( len == 1 ) {
        return perlin.perlin2(arguments[0], 0);
    } else if ( len == 2 ) {
        return perlin.perlin2(arguments[0], arguments[1]);
    } else if ( len == 3 ) {
        return perlin.perlin3(arguments[0], arguments[1], arguments[2]);
    }
    return 0;
};

// draw

Centi.prototype.rect = function(_x, _y, _w, _h){
    if ( this.bFill ) this.ctx.fillRect(_x, _y, _w, _h);
    else this.ctx.strokeRect(_x, _y, _w, _h);
};

Centi.prototype.ln = function(_x1, _y1, _x2, _y2){ this.line(_x1, _y1, _x2, _y2); };
Centi.prototype.line = function(_x1, _y1, _x2, _y2){
    this.ctx.beginPath();
    this.ctx.moveTo(_x1, _y1);
    this.ctx.lineTo(_x2, _y2);
    this.ctx.stroke();
};

Centi.prototype.lw = function(_w){ this.lineWidth(_w); };
Centi.prototype.lineWidth = function(_w){
    this.ctx.lineWidth = _w;
};

Centi.prototype.moveTo = function(_x1, _y1){
    this.ctx.moveTo(_x1, _y1);
};

Centi.prototype.lineTo = function(_x1, _y1){
    this.ctx.lineTo(_x1, _y1);
};

Centi.prototype.oval = function(_x, _y, _rad) {
    this.ctx.beginPath();
    this.ctx.arc(_x, _y, _rad, 0, Math.PI * 2, true);
    if ( this.bFill ) this.ctx.fill();
    else this.ctx.stroke()
};

Centi.prototype.beginShape = function(){
    this.ctx.beginPath();
};

Centi.prototype.endShape = function(){
    if ( this.bFill ) this.ctx.fill();
    else this.ctx.stroke();
};

Centi.prototype.drawMe = function(){
    var len = arguments.length;
    if ( len == 2 ) {
        this.ctx.drawImage(this.canvas, arguments[0], arguments[1]);
    } else if ( len == 4 ) {
        this.ctx.drawImage(this.canvas, arguments[0], arguments[1], arguments[2], arguments[3]);
    } else if ( len == 8 ) {
        this.ctx.drawImage(this.canvas, arguments[0], arguments[1], arguments[2], arguments[3], arguments[4], arguments[5], arguments[6], arguments[7]);
    }
};

// transform

Centi.prototype.push = function(){
    this.ctx.save();
};

Centi.prototype.pop = function(){
    this.ctx.restore();
};

Centi.prototype.rotate = function(_rota){
    this.ctx.rotate(_rota);
};

Centi.prototype.scale = function(_x, _y){
    this.ctx.scale(_x, _y);
};

Centi.prototype.translate = function(_x, _y){
    this.ctx.translate(_x, _y);
};

// util

Centi.prototype.col = function(){
    var len = arguments.length;
    var s = "rgb(0,0,0)";
    if ( len == 1 ) {
        s = "rgb(" + parseInt(arguments[0]) + "," + parseInt(arguments[0]) + "," + parseInt(arguments[0]) + ")";
    } else if ( len == 2 ) {
        s = "rgba(" + parseInt(arguments[0]) + "," + parseInt(arguments[0]) + "," + parseInt(arguments[0]) + "," + parseInt(arguments[1])/255.0 + ")";
    } else if ( len == 3 ) {
        s = "rgb(" + parseInt(arguments[0]) + "," + parseInt(arguments[1]) + "," + parseInt(arguments[2]) + ")";
    } else if ( len == 4 ) {
        s = "rgba(" + parseInt(arguments[0]) + "," + parseInt(arguments[1]) + "," + parseInt(arguments[2]) + "," + parseInt(arguments[3])/255.0 + ")";
    }
    this.ctx.fillStyle = s;
    this.ctx.strokeStyle = s;
};

Centi.prototype.fill = function(){
    this.bFill = true;
};

Centi.prototype.strk = function(){ this.stroke(); };
Centi.prototype.stroke = function(){
    this.bFill = false;
};

Centi.prototype.interp = function(a, b, rate){
    return b + (a-b)*rate;
};

Centi.prototype.sortNum = function(_arr){
    _arr.sort(
        function(a,b){
            if( a < b ) return -1;
            if( a > b ) return 1;
            return 0;
        }
    );
}

Centi.prototype.reverse = function(_arr){
    _arr.reverse();
}

Centi.prototype.vec2 = function(_x, _y){
    return new Centi.Vec2(_x, _y);
};
Centi.Vec2 = function(_x, _y){
    this.x = _x;
    this.y = _y;
};;

// centi funcs

Centi.prototype.reset = function(){
    this.c = 0;
    this.bFill = true;
};

var CT_FUNCS = Object.getOwnPropertyNames(Centi.prototype);

<|endoftext|>


<commit_before>'use strict';

function click_button(clicked_button_id){
    if(core_menu_open){
        return;
    }

    core_audio_start({
      'id': 'boop',
    });

    randomize_buttons(clicked_button_id);
}

function decisecond(){
    time = (core_storage_data['game-mode'] === 1
      && core_storage_data['max'] > 0)
      ? (Number.parseFloat(time) - .1).toFixed(1)
      : (Number.parseFloat(time) + .1).toFixed(1);

    document.getElementById('time').innerHTML = time;

    // If in max-time mode and time is less than or equal to 0 and max-time isn't 0...
    if(core_storage_data['game-mode'] === 1
      && time <= 0
      && core_storage_data['max'] > 0){
        stop();

    // ...else if in max-points mode and score is not greater than max-points and max-points is not equal to 0.
    }else if(core_storage_data['game-mode'] === 0
      && core_storage_data['max'] !== 0
      && score >= core_storage_data['max']){
        stop();
    }
}

function randomize_buttons(clicked_button_id){
    if(game_running){
        // Stop game if clicking on a negative button ends the game and clicked on a negative button.
        if(document.getElementById('negative-onclick').value == 1
          && document.getElementById(clicked_button_id).value.lastIndexOf('-', 0) === 0){
            stop();
            return;
        }
    }

    // Increase or decrease time based on settings value for clicked button.
    score = score
      + (document.getElementById(clicked_button_id).value.lastIndexOf('+', 0) === 0
        ? core_storage_data['positive-points']
        : core_storage_data['negative-points']);
    document.getElementById('score').innerHTML = score;

    // Reset buttons to disabled, value=-, and black backgrounds if game has not ended with this click.
    let game_ended = !(core_storage_data['game-mode'] === 1
      || core_storage_data['max'] === 0
      || score < core_storage_data['max']);

    let loop_counter = grid_dimensions_squared - 1;
    do{
        let element = document.getElementById(loop_counter);
        element.disabled = true;

        if(game_ended){
            continue;
        }

        element.style.background = '#2a2a2a';
        element.value = ' ';
    }while(loop_counter--);

    if(game_ended){
        return;
    }

    let space_taken = 0;

    // Randomize locations of and setup positive buttons that currently exist.
    if(core_storage_data['positive-frequency'] > 0){
        loop_counter = core_storage_data['positive-frequency'] > grid_dimensions_squared - 1
          ? grid_dimensions_squared - 1
          : core_storage_data['positive-frequency'] - 1;
        space_taken = loop_counter + 1;
        do{
            let button = '';
            do{
                button = core_random_integer({
                  'max': grid_dimensions_squared,
                });
            }while(!document.getElementById(button).disabled);

            let element = document.getElementById(button);
            element.style.background = core_storage_data['color-positive'];
            element.disabled = false;
            element.value = core_storage_data['positive-points'] > 0
              ? '+'
              : '-';
        }while(loop_counter--);
    }

    // If there are no positive buttons or space for negative buttons is available.
    if(core_storage_data['positive-frequency'] == 0
      || (core_storage_data['grid-dimensions'] > 1
        && grid_dimensions_squared - space_taken > 0)
    ){
        // Create and randomize enough negative buttons to fill available space or just number of negative buttons.
        loop_counter = core_storage_data['negative-frequency'] > grid_dimensions_squared - space_taken - 1
          ? grid_dimensions_squared - space_taken - 1
          : core_storage_data['negative-frequency'] - 1;
        if(loop_counter >= 0){
            do{
                let button = '';
                do{
                    button = core_random_integer({
                      'max': grid_dimensions_squared,
                    });
                }while(!document.getElementById(button).disabled);

                let element = document.getElementById(button);
                element.style.background = core_storage_data['color-negative'];
                element.disabled = false;
                element.value = core_storage_data['negative-points'] > 0
                  ? '+'
                  : '-';
            }while(loop_counter--);
        }
    }
}

function start(){
    grid_dimensions_squared = Math.max(
      core_storage_data['grid-dimensions'] * core_storage_data['grid-dimensions'],
      1
    );

    // Create game-div buttons.
    let output = '';
    for(let loop_counter = 0; loop_counter < grid_dimensions_squared; loop_counter++){
        if(loop_counter % core_storage_data['grid-dimensions'] === 0
          && loop_counter !== 0){
            output += '
';
        }

        output += '<input class=gridbuttonclickable disabled id=' + loop_counter
          + ' onclick=click_button(' + loop_counter
          + ') type=button value=" ">';
    }
    document.getElementById('game-div').innerHTML = output + '
';

    let loop_counter = grid_dimensions_squared - 1;
    do{
        document.getElementById(loop_counter).style.background = '#2a2a2a';
    }while(loop_counter--);

    // Reset game buttons.
    loop_counter = grid_dimensions_squared - 1;
    do{
        let element = document.getElementById(loop_counter);
        element.disabled = true;
        element.style.background = '#2a2a2a';
        element.value = ' ';
    }while(loop_counter--);

    document.getElementById('score-max').innerHTML = '';
    document.getElementById('time-max').innerHTML = '';

    // Generate positive and negative buttons.
    randomize_buttons(
      core_random_integer({
        'max': grid_dimensions_squared,
      })
    );

    score = 0;
    time = 0;

    document.getElementById('score').innerHTML = score;
    document.getElementById('time').innerHTML = 0;

    // Setup max-time or max-points displays.
    if(core_storage_data['game-mode'] === 1){
        time = core_storage_data['max'] >= 0
          ? (core_storage_data['max'] === ''
            ? 0
            : core_storage_data['max']
          )
          : 30;
        if(core_storage_data['max'] > 0){
            document.getElementById('time-max').innerHTML = ' / ' + core_storage_data['max'];
        }

    }else if(core_storage_data['max'] > 0){
        document.getElementById('score-max').innerHTML = ' / ' + core_storage_data['max'];
    }

    game_running = true;
    core_interval_modify({
      'id': 'interval',
      'interval': 100,
      'todo': decisecond,
    });
}

function stop(){
    core_interval_pause_all();
    game_running = false;

    // Disable buttons to prevent further clicks.
    let loop_counter = grid_dimensions_squared - 1;
    do{
        document.getElementById(loop_counter).disabled = true;
    }while(loop_counter--);
}
<commit_msg>prevented timer from decreasing after game ends<commit_after>'use strict';

function click_button(clicked_button_id){
    if(core_menu_open){
        return;
    }

    core_audio_start({
      'id': 'boop',
    });

    randomize_buttons(clicked_button_id);
}

function decisecond(){
    if(!game_running){
        return;
    }

    time = (core_storage_data['game-mode'] === 1
      && core_storage_data['max'] > 0)
      ? (Number.parseFloat(time) - .1).toFixed(1)
      : (Number.parseFloat(time) + .1).toFixed(1);

    document.getElementById('time').innerHTML = time;

    // If in max-time mode and time is less than or equal to 0 and max-time isn't 0...
    if(core_storage_data['game-mode'] === 1
      && time <= 0
      && core_storage_data['max'] > 0){
        stop();

    // ...else if in max-points mode and score is not greater than max-points and max-points is not equal to 0.
    }else if(core_storage_data['game-mode'] === 0
      && core_storage_data['max'] !== 0
      && score >= core_storage_data['max']){
        stop();
    }
}

function randomize_buttons(clicked_button_id){
    if(game_running){
        // Stop game if clicking on a negative button ends the game and clicked on a negative button.
        if(document.getElementById('negative-onclick').value == 1
          && document.getElementById(clicked_button_id).value.lastIndexOf('-', 0) === 0){
            stop();
            return;
        }
    }

    // Increase or decrease time based on settings value for clicked button.
    score = score
      + (document.getElementById(clicked_button_id).value.lastIndexOf('+', 0) === 0
        ? core_storage_data['positive-points']
        : core_storage_data['negative-points']);
    document.getElementById('score').innerHTML = score;

    // Reset buttons to disabled, value=-, and black backgrounds if game has not ended with this click.
    let game_ended = !(core_storage_data['game-mode'] === 1
      || core_storage_data['max'] === 0
      || score < core_storage_data['max']);

    let loop_counter = grid_dimensions_squared - 1;
    do{
        let element = document.getElementById(loop_counter);
        element.disabled = true;

        if(game_ended){
            continue;
        }

        element.style.background = '#2a2a2a';
        element.value = ' ';
    }while(loop_counter--);

    if(game_ended){
        return;
    }

    let space_taken = 0;

    // Randomize locations of and setup positive buttons that currently exist.
    if(core_storage_data['positive-frequency'] > 0){
        loop_counter = core_storage_data['positive-frequency'] > grid_dimensions_squared - 1
          ? grid_dimensions_squared - 1
          : core_storage_data['positive-frequency'] - 1;
        space_taken = loop_counter + 1;
        do{
            let button = '';
            do{
                button = core_random_integer({
                  'max': grid_dimensions_squared,
                });
            }while(!document.getElementById(button).disabled);

            let element = document.getElementById(button);
            element.style.background = core_storage_data['color-positive'];
            element.disabled = false;
            element.value = core_storage_data['positive-points'] > 0
              ? '+'
              : '-';
        }while(loop_counter--);
    }

    // If there are no positive buttons or space for negative buttons is available.
    if(core_storage_data['positive-frequency'] == 0
      || (core_storage_data['grid-dimensions'] > 1
        && grid_dimensions_squared - space_taken > 0)
    ){
        // Create and randomize enough negative buttons to fill available space or just number of negative buttons.
        loop_counter = core_storage_data['negative-frequency'] > grid_dimensions_squared - space_taken - 1
          ? grid_dimensions_squared - space_taken - 1
          : core_storage_data['negative-frequency'] - 1;
        if(loop_counter >= 0){
            do{
                let button = '';
                do{
                    button = core_random_integer({
                      'max': grid_dimensions_squared,
                    });
                }while(!document.getElementById(button).disabled);

                let element = document.getElementById(button);
                element.style.background = core_storage_data['color-negative'];
                element.disabled = false;
                element.value = core_storage_data['negative-points'] > 0
                  ? '+'
                  : '-';
            }while(loop_counter--);
        }
    }
}

function start(){
    grid_dimensions_squared = Math.max(
      core_storage_data['grid-dimensions'] * core_storage_data['grid-dimensions'],
      1
    );

    // Create game-div buttons.
    let output = '';
    for(let loop_counter = 0; loop_counter < grid_dimensions_squared; loop_counter++){
        if(loop_counter % core_storage_data['grid-dimensions'] === 0
          && loop_counter !== 0){
            output += '
';
        }

        output += '<input class=gridbuttonclickable disabled id=' + loop_counter
          + ' onclick=click_button(' + loop_counter
          + ') type=button value=" ">';
    }
    document.getElementById('game-div').innerHTML = output + '
';

    let loop_counter = grid_dimensions_squared - 1;
    do{
        document.getElementById(loop_counter).style.background = '#2a2a2a';
    }while(loop_counter--);

    // Reset game buttons.
    loop_counter = grid_dimensions_squared - 1;
    do{
        let element = document.getElementById(loop_counter);
        element.disabled = true;
        element.style.background = '#2a2a2a';
        element.value = ' ';
    }while(loop_counter--);

    document.getElementById('score-max').innerHTML = '';
    document.getElementById('time-max').innerHTML = '';

    // Generate positive and negative buttons.
    randomize_buttons(
      core_random_integer({
        'max': grid_dimensions_squared,
      })
    );

    score = 0;
    time = 0;

    document.getElementById('score').innerHTML = score;
    document.getElementById('time').innerHTML = 0;

    // Setup max-time or max-points displays.
    if(core_storage_data['game-mode'] === 1){
        time = core_storage_data['max'] >= 0
          ? (core_storage_data['max'] === ''
            ? 0
            : core_storage_data['max']
          )
          : 30;
        if(core_storage_data['max'] > 0){
            document.getElementById('time-max').innerHTML = ' / ' + core_storage_data['max'];
        }

    }else if(core_storage_data['max'] > 0){
        document.getElementById('score-max').innerHTML = ' / ' + core_storage_data['max'];
    }

    game_running = true;
    core_interval_modify({
      'id': 'interval',
      'interval': 100,
      'todo': decisecond,
    });
}

function stop(){
    core_interval_pause_all();
    game_running = false;

    // Disable buttons to prevent further clicks.
    let loop_counter = grid_dimensions_squared - 1;
    do{
        document.getElementById(loop_counter).disabled = true;
    }while(loop_counter--);
}
<|endoftext|>


<commit_before>function flatten(tf, $$$mptypes) {
  if (tf.$unflattened$)return tf.$unflattened$;
  if (tf.jsc$)tf=tf.jsc$;
  var mm=getrtmm$$(tf);
  var t0,iadic,argx;
  if (mm && mm.ps) {
    if (mm.ps.length===1) {
      t0=mm.ps[0].$t;
      if (!(t0.t===Sequential || t0.t===Sequence)) {
        t0=detpl$(mm.ps[0].$t);
      }
      iadic=variadicness(t0);
      argx = t0.t==='T' ? t0.l.length : 1;
    } else {
      throw new TypeError("Invalid argument to flatten: " +tf);
    }
  } else {
    throw new TypeError("Missing metamodel for " + tf);
  }
  var rf;
  if (t0.t==='T') {
    //Tuple
    if (iadic) {
      rf=function fftv(){
        var t = [];
        for (var i=0;i<argx-1;i++) {
          t.push(arguments[i]);
        }
        var seqarg=arguments[argx-1];
        if (seqarg===undefined || seqarg.length===0) {
          seqarg=empty();
        } else if (seqarg !== null && !is$(seqarg,{t:Sequence})) {
          seqarg=ArraySequence(seqarg,{Element$ArraySequence:seqarg._elemTarg()});
        }
        if (argx===1&&t.length==0)return tf(seqarg);
        return tf(tpl$(t,seqarg));
      }
    } else {
      rf=function fft1(){
        var t=[];
        if (arguments.length===1 && is$(arguments[0],t0)) {
          //Spread tuple
          return tf(arguments[0]);
        } else if (arguments.length===1 && argx===1 && is$(arguments[0],{t:Sequential,a:{Element$Sequential:t0.l[0]}})) {
          //This definitely stinks
          return tf(arguments[0]);
        } else {
          for (var i=0;i<argx;i++) {
            t.push(arguments[i]);
          }
        }
        return tf(tpl$(t));
      }
    }
    rf.$crtmm$={$t:mm.$t,ps:[]};
    for(var i=0;i<t0.l.length;i++){
      rf.$crtmm$.ps.push({$t:t0.l[i],mt:'prm',nm:'flat'+i});
      if (t0.l[i].seq)rf.$crtmm$.ps[i].$t.seq=t0.l[i].seq;
    }
  } else {
    //Single variadic argument
    rf=function ffs(s,$mpt){
      return tf(s?tpl$(s):empty(),$mpt);
    };
    rf.$crtmm$={$t:mm.$t,ps:[{$t:{t:t0.t},nm:'flat#0',seq:iadic}]};
    if (t0.a)rf.$crtmm$.ps[0].$t.a=t0.a;
    if (extendsType(t0,{t:Empty}))rf.$crtmm$.ps=[];
  }
  rf.$$targs$$={Return$Callable:$$$mptypes.Return$flatten,Arguments$Callable:$$$mptypes.Args$flatten};
  rf.$flattened$=tf;
  return rf;
}
<commit_msg>fix ceylon/ceylon-js#618<commit_after>function flatten(tf, $$$mptypes) {
  if (tf.$unflattened$)return tf.$unflattened$;
  if (tf.jsc$)tf=tf.jsc$;
  var mm=getrtmm$$(tf);
  var t0,iadic,argx;
  if (mm && mm.ps) {
    if (mm.ps.length===1) {
      t0=mm.ps[0].$t;
      if (!(t0.t===Sequential || t0.t===Sequence)) {
        t0=detpl$(mm.ps[0].$t);
      }
      iadic=variadicness(t0);
      argx = t0.t==='T' ? t0.l.length : 1;
    } else {
      throw new TypeError("Invalid argument to flatten: " +tf);
    }
  } else {
    throw new TypeError("Missing metamodel for " + tf);
  }
  var rf;
  if (t0.t==='T') {
    //Tuple
    if (iadic) {
      rf=function fftv(){
        var t = [];
        for (var i=0;i<argx-1;i++) {
          t.push(arguments[i]);
        }
        var seqarg=arguments[argx-1];
        if (seqarg===undefined || seqarg.length===0) {
          seqarg=empty();
        } else if (seqarg !== null && !is$(seqarg,{t:Sequence})) {
          seqarg=ArraySequence(seqarg,{Element$ArraySequence:seqarg._elemTarg()});
        }
        if (argx===1&&t.length==0)return tf(seqarg);
        return tf(tpl$(t,seqarg));
      }
    } else {
      rf=function fft1(){
        var t=[];
        if (arguments.length===1 && is$(arguments[0],t0)) {
          //Spread tuple
          return tf(arguments[0]);
        } else if (arguments.length===1 && argx===1 && is$(arguments[0],{t:Sequential,a:{Element$Sequential:t0.l[0]}})) {
          //This definitely stinks
          return tf(arguments[0]);
        } else {
          for (var i=0;i<argx;i++) {
            t.push(arguments[i]);
          }
        }
        if (t.length===1 && t0.l && t0.l.length===1 && is$(t[0],{t:Sequential}) && (t0.l[0].t===Sequence||t0.l[0].t===Sequential||t0.l[0].t===Tuple||t0.l[0].t==='T')) {
          //special case: 1-arg with tuple against 1-param 1x tuple with 1 Sequential element
          return tf(t[0]);
        }
        return tf(tpl$(t));
      }
    }
    rf.$crtmm$={$t:mm.$t,ps:[]};
    for(var i=0;i<t0.l.length;i++){
      rf.$crtmm$.ps.push({$t:t0.l[i],mt:'prm',nm:'flat'+i});
      if (t0.l[i].seq)rf.$crtmm$.ps[i].$t.seq=t0.l[i].seq;
    }
  } else {
    //Single variadic argument
    rf=function ffs(s,$mpt){
      return tf(s?tpl$(s):empty(),$mpt);
    };
    rf.$crtmm$={$t:mm.$t,ps:[{$t:{t:t0.t},nm:'flat#0',seq:iadic}]};
    if (t0.a)rf.$crtmm$.ps[0].$t.a=t0.a;
    if (extendsType(t0,{t:Empty}))rf.$crtmm$.ps=[];
  }
  rf.$$targs$$={Return$Callable:$$$mptypes.Return$flatten,Arguments$Callable:$$$mptypes.Args$flatten};
  rf.$flattened$=tf;
  return rf;
}
<|endoftext|>


<commit_before>// implementation of object "process" in ceylon.language
function languageClass() {
    var lang = new languageClass.$$;
    Basic(lang);
    return lang;
}
languageClass.$$metamodel$$={$nm:'languageClass',$mt:'cls',$ps:[],$an:function(){return[shared()];},mod:$$METAMODEL$$,d:['ceylon.language','language']};
initTypeProto(languageClass, "ceylon.language::language", $init$Basic());
var lang$proto=languageClass.$$.prototype;
defineAttr(lang$proto, 'version', function() {
    return String$("1.0.0",3);
},undefined,{$t:{t:String$}, $cont:lang$proto, $an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','language','$at','version']});
defineAttr(lang$proto, 'majorVersion', function(){ return 1; },undefined,
  {$t:{t:Integer}, $cont:lang$proto, $an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','language','$at','majorVersion']});
defineAttr(lang$proto, 'minorVersion', function(){ return 0; },undefined,
  {$t:{t:Integer}, $cont:lang$proto, $an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','language','$at','minorVersion']});
defineAttr(lang$proto, 'releaseVersion', function(){ return 0; },undefined,
  {$t:{t:Integer}, $cont:lang$proto, $an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','language','$at','releaseVersion']});
defineAttr(lang$proto, 'versionName', function(){ return String$("Buckaroo Banzai",15); },undefined,
  {$t:{t:String$}, $cont:lang$proto, $an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','language','$at','versionName']});
defineAttr(lang$proto, 'majorVersionBinary', function(){ return 5; },undefined,
  {$t:{t:Integer}, $cont:lang$proto, $an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','language','$at','majorVersionBinary']});
defineAttr(lang$proto, 'minorVersionBinary', function(){ return 0; },undefined,
  {$t:{t:Integer}, $cont:lang$proto, $an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','language','$at','minorVersionBinary']});
var languageString = String$("language", 8);
defineAttr(lang$proto, 'string', function() {
    return languageString;
},undefined,{$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','Object','$at','string']});

var language$ = languageClass();
function getLanguage() { return language$; }
exports.getLanguage=getLanguage;

function processClass() {
    var proc = new processClass.$$;
    Basic(proc);
    return proc;
}
processClass.$$metamodel$$={$nm:'processClass',$mt:'cls',$ps:[],$an:function(){return[shared()];},mod:$$METAMODEL$$,d:['ceylon.language','process']};
initTypeProto(processClass, "ceylon.language::process", $init$Basic());
var process$proto = processClass.$$.prototype;

var argv = getEmpty();
var namedArgs = {};
if ((typeof process !== "undefined") && (process.argv !== undefined)) {
    // parse command line arguments
    if (process.argv.length > 1) {
        var args = process.argv.slice(1);
        for (var i=0; i<args.length; ++i) {
            var arg = args[i];
            if (arg.charAt(0) == '-') {
                var pos = 1;
                if (arg.charAt(1) == '-') { pos = 2; }
                arg = arg.substr(pos);
                pos = arg.indexOf('=');
                if (pos >= 0) {
                    namedArgs[arg.substr(0, pos)] = String$(arg.substr(pos+1));
                } else {
                    var value = args[i+1];
                    if ((value !== undefined) && (value.charAt(0) != '-')) {
                        namedArgs[arg] = String$(value);
                        ++i;
                    } else {
                        namedArgs[arg] = null;
                    }
                }
            }
            args[i] = String$(args[i]);
        }
        argv = ArraySequence(args, {Element:{t:String$}});
    }
} else if (typeof window !== "undefined") {
    // parse URL parameters
    var parts = window.location.search.substr(1).replace('+', ' ').split('&');
    if ((parts.length > 1) || ((parts.length > 0) && (parts[0].length > 0))) {
        var argStrings = new Array(parts.length);
        //can't do "for (i in parts)" anymore because of the added stuff to arrays
        var i;
        for (i=0; i<parts.length; i++) { argStrings[i] = String$(parts[i]); }
        argv = ArraySequence(argStrings, {Element:{t:String$}});

        for (i=0; i < parts.length; i++) {
            var part = parts[i];
            var pos = part.indexOf('=');
            if (pos >= 0) {
                var value = decodeURIComponent(part.substr(pos+1));
                namedArgs[part.substr(0, pos)] = String$(value);
            } else {
                namedArgs[part] = null;
            }
        }
    }
}
defineAttr(process$proto, 'arguments', function(){ return argv; },undefined,
  {$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','arguments']});
process$proto.namedArgumentPresent = function(name) {
    return (name in namedArgs);
}
process$proto.namedArgumentValue = function(name) {
    var value = namedArgs[name];
    return (value !== undefined) ? value : null;
}

var properties = {};
if (typeof navigator !== "undefined") {
    if (navigator.language !== undefined) {
        properties["user.language"] = String$(navigator.language);
    }
    if (navigator.platform !== undefined) {
        properties["os.name"] = String$(navigator.platform);
    }
    if (navigator.userLanguage||navigator.browserLanguage||navigator.language) {
        properties["user.locale"]=String$(navigator.userLanguage||navigator.browserLanguage||navigator.language);
    }
}
if (typeof process !== "undefined") {
    if (process.platform !== undefined) {
        properties["os.name"] = String$(process.platform);
    }
    if (process.arch !== undefined) {
        properties["os.arch"] = String$(process.arch);
    }
}
if (typeof document !== "undefined") {
    if (document.defaultCharset !== undefined) {
        properties["file.encoding"] = String$(document.defaultCharset);
    }
}

var linesep = String$('\n', 1);
var filesep = String$('/', 1);
var pathsep = String$(':', 1);
var osname = properties["os.name"];
if ((osname !== undefined) && (osname.search(/windows/i) >= 0)) {
    linesep = String$("\r\n", 2);
    filesep = String$('\\', 1);
    pathsep = String$(';', 1);
}
properties["line.separator"] = linesep;
properties["file.separator"] = filesep;
properties["path.separator"] = pathsep;

process$proto.propertyValue = function(name) {
    var value = properties[name];
    return (value !== undefined) ? value : null;
}

defineAttr(process$proto, 'newline', function(){ return linesep; },undefined,
  {$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','newline']});

if ((typeof process !== "undefined") && (process.stdout !== undefined)) {
    process$proto.write = function(string) {
        process.stdout.write(string.valueOf());
    }
    process$proto.writeLine = function(line) {
        this.write(line.valueOf());
        this.write(linesep.valueOf());
    }
} else if ((typeof console !== "undefined") && (console.log !== undefined)) {
    process$proto.writeLine = function(line) {
        console.log(line.valueOf());
    }
    process$proto.write = process$proto.writeLine;
} else {
    process$proto.write = function() {};
    process$proto.writeLine = function() {};
}

if ((typeof process !== "undefined") && (process.stderr !== undefined)) {
    process$proto.writeError = function(string) {
        process.stderr.write(string.valueOf());
    }
    process$proto.writeErrorLine = function(line) {
        this.writeError(line.valueOf());
        this.writeError(linesep.valueOf());
    }
} else if ((typeof console !== "undefined") && (console.error !== undefined)) {
    process$proto.writeErrorLine = function(line) {
        console.error(line.valueOf());
    }
    process$proto.writeError = process$proto.writeErrorLine;
} else {
    process$proto.writeError = process$proto.write;
    process$proto.writeErrorLine = process$proto.writeLine;
}

process$proto.flush = function(){}
process$proto.flushError=function(){}
process$proto.readLine = function() {
    return String$("", 0);//TODO
}

defineAttr(process$proto, 'milliseconds', function() {
    return Date.now();
},undefined,{$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','milliseconds']});
defineAttr(process$proto, 'nanoseconds', function() {
    return Date.now()*1000000;
},undefined,{$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','nanoseconds']});

if ((typeof process !== "undefined") && (process.exit !== undefined)) {
    process$proto.exit = function(code) {
        process.exit(code);
    }
} else {
    process$proto.exit = function() {}
}

var processString = String$("process", 7);
defineAttr(process$proto, 'string', function() {
    return processString;
},undefined,{$t:{t:String$},$cont:process$proto,$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','Object','$at','string']});
defineAttr(process$proto, 'vm', function() {
    if (typeof process !== "undefined" && process.execPath && process.execPath.match(/node(js)?(\.exe)?$/)) {
        return String$("node.js", 7);
    } else if (typeof window === 'object') {
        return String$("Browser", 7);
    }
    return String$("Unknown JavaScript environment", 30);
},undefined,{$t:{t:String$},$cont:process$proto,$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','vm']});
defineAttr(process$proto, 'vmVersion', function() {
    if (typeof process !== "undefined" && typeof process.version === 'string') {
        return String$(process.version);
    }
    return String$("Unknown");
},undefined,{$t:{t:String$},$cont:process$proto,$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','vmVersion']});
defineAttr(process$proto, 'os',function() {
    if (typeof process !== "undefined" && typeof process.platform === 'string') {
        return String$(process.platform);
    }
    return String$("Unknown");
},undefined,{$t:{t:String$},$cont:process$proto,$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','os']});
defineAttr(process$proto, 'osVersion', function() {
    return String$("Unknown");
},undefined,{$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','osVersion']});
defineAttr(process$proto, 'timezoneOffset', function(){
  return new Date().getTimezoneOffset()*60000;
},undefined,{$t:{t:Integer}, $cont:process$proto, $an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','timezoneOffset']});
defineAttr(process$proto, 'locale', function(){
  return properties["user.locale"] || String$("Unknown",7);
},undefined,{$t:{t:String$}, $cont:process$proto, $an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','locale']});

var process$ = processClass();
function getProcess() { return process$; }
exports.getProcess=getProcess;
<commit_msg>Fixed binary version number for the JS backend<commit_after>// implementation of object "process" in ceylon.language
function languageClass() {
    var lang = new languageClass.$$;
    Basic(lang);
    return lang;
}
languageClass.$$metamodel$$={$nm:'languageClass',$mt:'cls',$ps:[],$an:function(){return[shared()];},mod:$$METAMODEL$$,d:['ceylon.language','language']};
initTypeProto(languageClass, "ceylon.language::language", $init$Basic());
var lang$proto=languageClass.$$.prototype;
defineAttr(lang$proto, 'version', function() {
    return String$("1.0.0",3);
},undefined,{$t:{t:String$}, $cont:lang$proto, $an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','language','$at','version']});
defineAttr(lang$proto, 'majorVersion', function(){ return 1; },undefined,
  {$t:{t:Integer}, $cont:lang$proto, $an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','language','$at','majorVersion']});
defineAttr(lang$proto, 'minorVersion', function(){ return 0; },undefined,
  {$t:{t:Integer}, $cont:lang$proto, $an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','language','$at','minorVersion']});
defineAttr(lang$proto, 'releaseVersion', function(){ return 0; },undefined,
  {$t:{t:Integer}, $cont:lang$proto, $an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','language','$at','releaseVersion']});
defineAttr(lang$proto, 'versionName', function(){ return String$("Buckaroo Banzai",15); },undefined,
  {$t:{t:String$}, $cont:lang$proto, $an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','language','$at','versionName']});
defineAttr(lang$proto, 'majorVersionBinary', function(){ return 6; },undefined,
  {$t:{t:Integer}, $cont:lang$proto, $an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','language','$at','majorVersionBinary']});
defineAttr(lang$proto, 'minorVersionBinary', function(){ return 0; },undefined,
  {$t:{t:Integer}, $cont:lang$proto, $an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','language','$at','minorVersionBinary']});
var languageString = String$("language", 8);
defineAttr(lang$proto, 'string', function() {
    return languageString;
},undefined,{$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','Object','$at','string']});

var language$ = languageClass();
function getLanguage() { return language$; }
exports.getLanguage=getLanguage;

function processClass() {
    var proc = new processClass.$$;
    Basic(proc);
    return proc;
}
processClass.$$metamodel$$={$nm:'processClass',$mt:'cls',$ps:[],$an:function(){return[shared()];},mod:$$METAMODEL$$,d:['ceylon.language','process']};
initTypeProto(processClass, "ceylon.language::process", $init$Basic());
var process$proto = processClass.$$.prototype;

var argv = getEmpty();
var namedArgs = {};
if ((typeof process !== "undefined") && (process.argv !== undefined)) {
    // parse command line arguments
    if (process.argv.length > 1) {
        var args = process.argv.slice(1);
        for (var i=0; i<args.length; ++i) {
            var arg = args[i];
            if (arg.charAt(0) == '-') {
                var pos = 1;
                if (arg.charAt(1) == '-') { pos = 2; }
                arg = arg.substr(pos);
                pos = arg.indexOf('=');
                if (pos >= 0) {
                    namedArgs[arg.substr(0, pos)] = String$(arg.substr(pos+1));
                } else {
                    var value = args[i+1];
                    if ((value !== undefined) && (value.charAt(0) != '-')) {
                        namedArgs[arg] = String$(value);
                        ++i;
                    } else {
                        namedArgs[arg] = null;
                    }
                }
            }
            args[i] = String$(args[i]);
        }
        argv = ArraySequence(args, {Element:{t:String$}});
    }
} else if (typeof window !== "undefined") {
    // parse URL parameters
    var parts = window.location.search.substr(1).replace('+', ' ').split('&');
    if ((parts.length > 1) || ((parts.length > 0) && (parts[0].length > 0))) {
        var argStrings = new Array(parts.length);
        //can't do "for (i in parts)" anymore because of the added stuff to arrays
        var i;
        for (i=0; i<parts.length; i++) { argStrings[i] = String$(parts[i]); }
        argv = ArraySequence(argStrings, {Element:{t:String$}});

        for (i=0; i < parts.length; i++) {
            var part = parts[i];
            var pos = part.indexOf('=');
            if (pos >= 0) {
                var value = decodeURIComponent(part.substr(pos+1));
                namedArgs[part.substr(0, pos)] = String$(value);
            } else {
                namedArgs[part] = null;
            }
        }
    }
}
defineAttr(process$proto, 'arguments', function(){ return argv; },undefined,
  {$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','arguments']});
process$proto.namedArgumentPresent = function(name) {
    return (name in namedArgs);
}
process$proto.namedArgumentValue = function(name) {
    var value = namedArgs[name];
    return (value !== undefined) ? value : null;
}

var properties = {};
if (typeof navigator !== "undefined") {
    if (navigator.language !== undefined) {
        properties["user.language"] = String$(navigator.language);
    }
    if (navigator.platform !== undefined) {
        properties["os.name"] = String$(navigator.platform);
    }
    if (navigator.userLanguage||navigator.browserLanguage||navigator.language) {
        properties["user.locale"]=String$(navigator.userLanguage||navigator.browserLanguage||navigator.language);
    }
}
if (typeof process !== "undefined") {
    if (process.platform !== undefined) {
        properties["os.name"] = String$(process.platform);
    }
    if (process.arch !== undefined) {
        properties["os.arch"] = String$(process.arch);
    }
}
if (typeof document !== "undefined") {
    if (document.defaultCharset !== undefined) {
        properties["file.encoding"] = String$(document.defaultCharset);
    }
}

var linesep = String$('\n', 1);
var filesep = String$('/', 1);
var pathsep = String$(':', 1);
var osname = properties["os.name"];
if ((osname !== undefined) && (osname.search(/windows/i) >= 0)) {
    linesep = String$("\r\n", 2);
    filesep = String$('\\', 1);
    pathsep = String$(';', 1);
}
properties["line.separator"] = linesep;
properties["file.separator"] = filesep;
properties["path.separator"] = pathsep;

process$proto.propertyValue = function(name) {
    var value = properties[name];
    return (value !== undefined) ? value : null;
}

defineAttr(process$proto, 'newline', function(){ return linesep; },undefined,
  {$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','newline']});

if ((typeof process !== "undefined") && (process.stdout !== undefined)) {
    process$proto.write = function(string) {
        process.stdout.write(string.valueOf());
    }
    process$proto.writeLine = function(line) {
        this.write(line.valueOf());
        this.write(linesep.valueOf());
    }
} else if ((typeof console !== "undefined") && (console.log !== undefined)) {
    process$proto.writeLine = function(line) {
        console.log(line.valueOf());
    }
    process$proto.write = process$proto.writeLine;
} else {
    process$proto.write = function() {};
    process$proto.writeLine = function() {};
}

if ((typeof process !== "undefined") && (process.stderr !== undefined)) {
    process$proto.writeError = function(string) {
        process.stderr.write(string.valueOf());
    }
    process$proto.writeErrorLine = function(line) {
        this.writeError(line.valueOf());
        this.writeError(linesep.valueOf());
    }
} else if ((typeof console !== "undefined") && (console.error !== undefined)) {
    process$proto.writeErrorLine = function(line) {
        console.error(line.valueOf());
    }
    process$proto.writeError = process$proto.writeErrorLine;
} else {
    process$proto.writeError = process$proto.write;
    process$proto.writeErrorLine = process$proto.writeLine;
}

process$proto.flush = function(){}
process$proto.flushError=function(){}
process$proto.readLine = function() {
    return String$("", 0);//TODO
}

defineAttr(process$proto, 'milliseconds', function() {
    return Date.now();
},undefined,{$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','milliseconds']});
defineAttr(process$proto, 'nanoseconds', function() {
    return Date.now()*1000000;
},undefined,{$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','nanoseconds']});

if ((typeof process !== "undefined") && (process.exit !== undefined)) {
    process$proto.exit = function(code) {
        process.exit(code);
    }
} else {
    process$proto.exit = function() {}
}

var processString = String$("process", 7);
defineAttr(process$proto, 'string', function() {
    return processString;
},undefined,{$t:{t:String$},$cont:process$proto,$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','Object','$at','string']});
defineAttr(process$proto, 'vm', function() {
    if (typeof process !== "undefined" && process.execPath && process.execPath.match(/node(js)?(\.exe)?$/)) {
        return String$("node.js", 7);
    } else if (typeof window === 'object') {
        return String$("Browser", 7);
    }
    return String$("Unknown JavaScript environment", 30);
},undefined,{$t:{t:String$},$cont:process$proto,$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','vm']});
defineAttr(process$proto, 'vmVersion', function() {
    if (typeof process !== "undefined" && typeof process.version === 'string') {
        return String$(process.version);
    }
    return String$("Unknown");
},undefined,{$t:{t:String$},$cont:process$proto,$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','vmVersion']});
defineAttr(process$proto, 'os',function() {
    if (typeof process !== "undefined" && typeof process.platform === 'string') {
        return String$(process.platform);
    }
    return String$("Unknown");
},undefined,{$t:{t:String$},$cont:process$proto,$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','os']});
defineAttr(process$proto, 'osVersion', function() {
    return String$("Unknown");
},undefined,{$an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','osVersion']});
defineAttr(process$proto, 'timezoneOffset', function(){
  return new Date().getTimezoneOffset()*60000;
},undefined,{$t:{t:Integer}, $cont:process$proto, $an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','timezoneOffset']});
defineAttr(process$proto, 'locale', function(){
  return properties["user.locale"] || String$("Unknown",7);
},undefined,{$t:{t:String$}, $cont:process$proto, $an:function(){return[shared(),actual()]},mod:$$METAMODEL$$,d:['ceylon.language','process','$at','locale']});

var process$ = processClass();
function getProcess() { return process$; }
exports.getProcess=getProcess;
<|endoftext|>


<commit_before>/*
 * sshowjs
 * mjhoy | 2011
 *
 * ermm, beta...
 *
 */

(function ($, undefined) {

  // Helper function. Returns the indexes `k` items away from
  // index `n` for an array of length `len`. Useful for
  // getting nearby images in the slideshow to pre-load.
  var index_neighbors = function (n, k, len) {
    if (n >= len) return undefined;
    var arr = [],
        i, x, r, offset;
    for (i = 0, x = k * 2; i <= x; i += 1) {
      offset = (i - k) + n;
      if (offset < 0) {
        r = len + offset;
      } else if (offset >= len) {
        r = offset - len;
      } else {
        r = offset;
      }
      if ((r >= 0) && (r < len) && (arr.indexOf(r) < 0)) {
        arr.push(r);
      }
      if (arr.length === len) {
        break;
      }
    }
    return arr;
  }

  // The classes we will use in constructing new elements.
  var domClass = {
    sshow      : 'sshow',
    wrapper    : 'sshow_wrapper',
    stage      : 'sshow_stage',
    status     : 'sshow_status',
    navigation : 'sshow_navigation',
    location   : 'sshow_location',
    nextLink   : 'sshow_nextLink',
    prevLink   : 'sshow_prevLink'
  };

  // Same as `domClass` but with the dot in front, for CSS selectors.
  var sel = (function () {
    var obj = {};
    $.each(domClass, function (k, v) {
      obj[k] = '.' + v;
    });
    return obj;
  })();

  // The default DOM set up of status and next/prev indicators.
  var statusSetup = function (sshow, el) {
    var status     = $("
"),
        navigation = $("
"),
        next       = $("Next"),
        location   = $(""),
        prev       = $("Prev");
    // status
    // `- navigation
    //    |- next
    //    |- location
    //    `- prev
    status.prepend(navigation.prepend(location));
    navigation.prepend(next).append(prev);
    $(sel.wrapper, el).prepend(status);
  };

  var handlerSetup = function (sshow, el) {
    $(sel.nextLink, el).click(function() { sshow.next(); });
    $(sel.prevLink, el).click(function() { sshow.prev(); });
  };

  // Default options for the sshow function.
  var defaultOptions = {
    statusSetup: statusSetup,
    handlerSetup: handlerSetup
  };

  Sshow = function () {
  };

  $.extend(Sshow.prototype, {

    init : function (el, opts) {
      var options, wrapper, stage;

      el = $(el).addClass(domClass.sshow);
      this.el = el;
      options = $.extend(defaultOptions, (opts || {}));

      // The overall wrapper.
      wrapper = $("

");
      stage   = $("

");

      wrapper.prepend(stage);
      el.prepend(wrapper);

      // Call "status" setup -- meant for DOM insertion of status elements.
      if ($.isFunction(options.statusSetup)) options.statusSetup(this, el);
      // Call "handler" setup -- meant to attach handlers to DOM events.
      if ($.isFunction(options.handlerSetup)) options.handlerSetup(this, el);
      return this;
    },

    set : function (index) {
      var el = this.el,
          currentIndex = this.currentIndex,
          // Are we showing the current image?
          same = (currentIndex === index);

      this.loadImage(index);
      return this;
    },

    load : function (index) {

    },

    next : function () {
      console.log('next!');
    },

    prev : function () {
      console.log('prev!');
    }

  });

  // The main sshow function.
  $.fn.sshow = function (opts) {
    return this.each(function () {
      $(this).data('sshow', new Sshow().init(this, opts));
    });
  };

})(jQuery);
<commit_msg>initialize instance variables we will use<commit_after>/*
 * sshowjs
 * mjhoy | 2011
 *
 * ermm, beta...
 *
 */

(function ($, undefined) {

  // Helper function. Returns the indexes `k` items away from
  // index `n` for an array of length `len`. Useful for
  // getting nearby images in the slideshow to pre-load.
  var index_neighbors = function (n, k, len) {
    if (n >= len) return undefined;
    var arr = [],
        i, x, r, offset;
    for (i = 0, x = k * 2; i <= x; i += 1) {
      offset = (i - k) + n;
      if (offset < 0) {
        r = len + offset;
      } else if (offset >= len) {
        r = offset - len;
      } else {
        r = offset;
      }
      if ((r >= 0) && (r < len) && (arr.indexOf(r) < 0)) {
        arr.push(r);
      }
      if (arr.length === len) {
        break;
      }
    }
    return arr;
  }

  // The classes we will use in constructing new elements.
  var domClass = {
    sshow      : 'sshow',
    wrapper    : 'sshow_wrapper',
    stage      : 'sshow_stage',
    status     : 'sshow_status',
    navigation : 'sshow_navigation',
    location   : 'sshow_location',
    nextLink   : 'sshow_nextLink',
    prevLink   : 'sshow_prevLink'
  };

  // Same as `domClass` but with the dot in front, for CSS selectors.
  var sel = (function () {
    var obj = {};
    $.each(domClass, function (k, v) {
      obj[k] = '.' + v;
    });
    return obj;
  })();

  // The default DOM set up of status and next/prev indicators.
  var statusSetup = function (sshow, el) {
    var status     = $("
"),
        navigation = $("
"),
        next       = $("Next"),
        location   = $(""),
        prev       = $("Prev");
    // status
    // `- navigation
    //    |- next
    //    |- location
    //    `- prev
    status.prepend(navigation.prepend(location));
    navigation.prepend(next).append(prev);
    $(sel.wrapper, el).prepend(status);
  };

  var handlerSetup = function (sshow, el) {
    $(sel.nextLink, el).click(function() { sshow.next(); });
    $(sel.prevLink, el).click(function() { sshow.prev(); });
  };

  // Default options for the sshow function.
  var defaultOptions = {
    statusSetup: statusSetup,
    handlerSetup: handlerSetup
  };

  Sshow = function () {
    // Options are provided to the `init` method.
    this.options = {};

    // The `el` variable contains the jQuery-wrapped DOM element.
    this.el = undefined;

    // Current index displaying.
    this.currentIndex = 0;

    // Array of URLs to the full-sized (non-thumbnail) images.
    this.fulls  = [];

    // Array of URLs to thumbnail images.
    this.thumbs = [];

    // References the original elements if they are anchors to
    // full-sized images.
    this.originalElements = [];
  };

  $.extend(Sshow.prototype, {

    init : function (el, opts) {
      var options, wrapper, stage;

      el = $(el).addClass(domClass.sshow);
      this.el = el;
      options = this.options = $.extend(defaultOptions, (opts || {}));

      // The overall wrapper.
      wrapper = $("

");
      stage   = $("

");

      wrapper.prepend(stage);
      el.prepend(wrapper);

      // Call "status" setup -- meant for DOM insertion of status elements.
      if ($.isFunction(options.statusSetup)) options.statusSetup(this, el);
      // Call "handler" setup -- meant to attach handlers to DOM events.
      if ($.isFunction(options.handlerSetup)) options.handlerSetup(this, el);
      return this;
    },

    set : function (index) {
      var el = this.el,
          currentIndex = this.currentIndex,
          // Are we showing the current image?
          same = (currentIndex === index);

      this.loadImage(index);
      return this;
    },

    load : function (index) {

    },

    next : function () {
      console.log('next!');
    },

    prev : function () {
      console.log('prev!');
    }

  });

  // The main sshow function.
  $.fn.sshow = function (opts) {
    return this.each(function () {
      $(this).data('sshow', new Sshow().init(this, opts));
    });
  };

})(jQuery);
<|endoftext|>


<commit_before>function Game(string){
	this.string = string;
};

Game.prototype.populateBoard = function(){
	var string = this.string;
	var cells = $(".grid-cell");
	cells.each(function(index){
		if (string[index] != 0){
			$(cells[index]).text(string[index]);
		};
	});
};

Game.prototype.addRandomNumber = function(){
	var possibilities = [2,2,2,4,2,2,2,2]
	randomGeneratedNumber = possibilities[Math.floor(Math.random() * possibilities.length)];
	var gameArray = this.string.split("");
	var emptyCells = []
	gameArray.forEach(function(cell, index){
		if(cell === "0" ){
			emptyCells.push(index);
		}
	});
	var indexOfEmptyCell = emptyCells[Math.floor(Math.random() * emptyCells.length)];
	gameArray[indexOfEmptyCell] = randomGeneratedNumber.toString();
	this.string = gameArray.join('');
	console.log(this.string);
};

Game.prototype.move = function(direction){
	var string = this.string;
	var one = string.substring(0, 4).split("")
	var two = string.substring(4, 8).split("")
	var three = string.substring(8, 12).split("")
	var four = string.substring(12, 16).split("")
	var newArray = [one,two, three, four]
	if (direction === "up") {
		var upArray = transpose(newArray);
		upArray.forEach(function(section){
			var filteredSection = turnToInteger(removeZeros(section));
			if (filteredSection.length === 4) {
				if ((filteredSection[0] === filteredSection[1]) && (filteredSection[2] === filteredSection[3])) {
					filteredSection[0] = filteredSection[0] + filteredSection[1]
					filteredSection[1] = 0
					filteredSection[2] = filteredSection[2] + filteredSection[3]
					filteredSection[3] = 0
				} else if (filteredSection[0] === filteredSection[1]) {
					filteredSection[0] = filteredSection[0] + filteredSection[1]
					filteredSection[1] = filteredSection[2]
					filteredSection[2] = filteredSection[3]
					filteredSection[3] = 0
				} else if (filteredSection[1] === filteredSection[2]) {
					filteredSection[1] = filteredSection[1] + filteredSection[2]
				} else if (filteredSection[2] === filteredSection[3]) {
					filteredSection[2] = filteredSection[2] + filteredSection[3]
				};
			};
		});
	};
};

<commit_msg>complete iteration logic for updating up button<commit_after>function Game(string){
	this.string = string;
};

Game.prototype.populateBoard = function(){
	var string = this.string;
	var cells = $(".grid-cell");
	cells.each(function(index){
		if (string[index] != 0){
			$(cells[index]).text(string[index]);
		};
	});
};

Game.prototype.addRandomNumber = function(){
	var possibilities = [2,2,2,4,2,2,2,2,2,2]
	randomGeneratedNumber = possibilities[Math.floor(Math.random() * possibilities.length)];
	var gameArray = this.string.split("");
	var emptyCells = []
	gameArray.forEach(function(cell, index){
		if(cell === "0" ){
			emptyCells.push(index);
		}
	});
	var indexOfEmptyCell = emptyCells[Math.floor(Math.random() * emptyCells.length)];
	gameArray[indexOfEmptyCell] = randomGeneratedNumber.toString();
	this.string = gameArray.join('');
	console.log(this.string);
};

Game.prototype.move = function(direction){
	var string = this.string;
	var one = string.substring(0, 4).split("")
	var two = string.substring(4, 8).split("")
	var three = string.substring(8, 12).split("")
	var four = string.substring(12, 16).split("")
	var newArray = [one,two, three, four]
	if (direction === "up") {
		var upArray = transpose(newArray);
		upArray.forEach(function(section){
			var filteredSection = turnToInteger(removeZeros(section));
			if (filteredSection.length === 4) {
				if ((filteredSection[0] === filteredSection[1]) && (filteredSection[2] === filteredSection[3])) {
					filteredSection[0] = filteredSection[0] + filteredSection[1]
					filteredSection[1] = filteredSection[2] + filteredSection[3]
					filteredSection[2] = 0
					filteredSection[3] = 0
				} else if (filteredSection[0] === filteredSection[1] && filteredSection[2] != filteredSection[3]) {
						filteredSection[0] = filteredSection[0] + filteredSection[1]
						filteredSection[1] = filteredSection[2]
						filteredSection[2] = filteredSection[3]
						filteredSection[3] = 0
				} else if (filteredSection[0] != filteredSection[1] && filteredSection[2] === filteredSection[3]) {
						filteredSection[2] = filteredSection[2] + filteredSection[3]
						filteredSection[3] = 0
				} else if (filteredSection[1] === filteredSection[2]) {
						filteredSection[1] = filteredSection[1] + filteredSection[2]
						filteredSection[2] = filteredSection[3]
						filteredSection[3] = 0
				}
			} else if (filteredSection.length === 3) {
					if (filteredSection[0] === filteredSection[1]) {
						filteredSection[0] = filteredSection[0] + filteredSection[1]
						filteredSection[1] = filteredSection[2]
					} else if (filteredSection[1] === filteredSection[2]) {
							filteredSection[1] = filteredSection[1] + filteredSection[2]
							filteredSection[2] = 0
					}
			} else if (filteredSection.length === 2) {
				if (filteredSection[0] === filteredSection[1]) {
						filteredSection[0] = filteredSection[0] + filteredSection[1]
						filteredSection[1] = 0
				};
			};
		});
	};
};

<|endoftext|>


<commit_before>window.addEventListener("load", Init_Game, false);

var WIDTH = 800, HEIGHT = 480,
    canvas, context, keyDict,
    bullet_array, bullet_image, zombie_array, player,
    mouse_x, mouse_y, mouse_down;

function Init_Game() {
    canvas = document.getElementById("game_canvas");
    context = canvas.getContext("2d");

    mouse_down = false;

    keyDict = {"W": false, "S": false, "A": false, "D": false};

    bullet_array = [];
    bullet_image = new Image();
    bullet_image.src = "images/bullet.png";

    zombie_array=new Array(100);
    var zombie;
    for (var i=0;i<10;++i)
    {
        for (var j=0;j<10;++j)
        {
            zombie=new Character(i * 100, j * 100, 0, 0, 50, 50, 1/(i+j) + .1,
                                 "images/zombie.png");
            zombie_array[i*10+j]=zombie;
        }
    }
    player=new Character(100, 300, 0, 0, 50, 50, 3, "images/player.png");
    player.direction = "south";

    window.addEventListener("keydown",doKeyDown,true);
    window.addEventListener("keyup",doKeyUp,true);
    window.addEventListener("mousedown", doMouseDown, false);
    window.addEventListener("mouseup", doMouseUp, false);
    window.addEventListener("mousemove", doMouseMove, false);

    setInterval("Draw()", 10);
    setInterval("Update()", 10);
}

function Update()
{
    // setting player.drawx/drawy changes direction player image is facing
    if(keyDict["W"])
    {
        if (player.y - player.speed > 0){
            player.y -= player.speed ;
        }
        player.drawx=0;
        player.drawy=50;
    }
    else if(keyDict["S"])
    {
        if (player.y + player.height + player.speed < HEIGHT){
            player.y += player.speed ;
        }
        player.drawx=0;
        player.drawy=0;
    }
    else if(keyDict["A"])
    {
        if (player.x - player.speed > 0){
            player.x -= player.speed ;
        }
        player.drawx=0;
        player.drawy=100;
    }
    else if(keyDict["D"])
    {
        if (player.x + player.width + player.speed < WIDTH){
            player.x += player.speed ;
        }
        player.drawx=0;
        player.drawy=150;
    }
    if (mouse_down)
    {
        var bullet = new Bullet(player.x + player.width / 2,
                                player.y + player.height / 2,
                                mouse_x, mouse_y, 5, 5, 5, "images/bullet.png");
        bullet_array.push(bullet);
    }
    for (var i=0; i < zombie_array.length; ++i)
    {
        zombie_array[i].Update();
    }
    for (var i=0; i < bullet_array.length; ++i)
    {
        bullet_array[i].Update();
        var bullet_alive = true;
        // check for zombie intersections
        for (var j=0; j < zombie_array.length; ++j)
        {
            if(Intersects(bullet_array[i],zombie_array[j]))
            {
                // remove the zombie
                zombie_array[j].x=-60;
                zombie_array[j].speed=0;
                // remove the bullet
                bullet_array.splice(i, 1);
                bullet_alive = false;
                break;
            }
        }
        if (!bullet_alive) continue;
        // check if the bullet has gone out of bounds
        if ((bullet_array[i].x < 0) || (bullet_array[i].x > WIDTH) ||
            (bullet_array[i].y < 0) || (bullet_array[i].y > HEIGHT))
        {
            // remove the bullet
            bullet_array.splice(i, 1);
        }
    }
}

function Draw() {
    context.clearRect(0, 0, WIDTH, HEIGHT);

    player.Draw();
    for (var i=0;i < zombie_array.length; ++i)
    {
        zombie_array[i].Draw();
    }
    for (var i=0;i < bullet_array.length; ++i)
    {
        bullet_array[i].Draw();
    }
}

function Intersects(first,second)
{
    if((first.x<second.x+second.width) && (first.x+first.width>second.x)
        && (first.y<second.y+second.height) && (first.y+first.height>second.y))
    {
        return true;
    }
    else
    {
        return false;
    }
}

function doKeyDown(evt) {
    keyDict[getKeyValue(evt)] = true;
}

function doKeyUp(evt) {
    keyDict[getKeyValue(evt)] = false;
}

// Extract the string corresponding to the key pressed.
function getKeyValue(keyEvent) {
    var keyCode;
    // IE support
    if (event.which == undefined) {
        keyCode = keyEvent.keyCode;
    }
    // everyone else
    else {
        keyCode = keyEvent.which;
    }
    return String.fromCharCode(keyCode);
}

// mouse button just went down
function doMouseDown(mouseEvent) {
    mouse_down = true;
}

// mouse button just went up
function doMouseUp(mouseEvent) {
    mouse_down = false;
}

// mouse changed position
function doMouseMove(mouseEvent) {
    var mouse_pos = getCursorPosition(mouseEvent);
    mouse_x = mouse_pos[0];
    mouse_y = mouse_pos[1];
}

// Code pulled straight from Dive Into HTML5 (Halma)
// Unsure which browsers don't support pageX/pageY.
function getCursorPosition(mouseEvent) {
    var x, y;
    if (mouseEvent.pageX != undefined && mouseEvent.pageY != undefined) {
        x = mouseEvent.pageX;
        y = mouseEvent.pageY;
    }
    else {
        x = mouseEvent.clientX + document.body.scrollLeft
                + document.documentElement.scrollLeft;
        y = mouseEvent.clientY + document.body.scrollTop
                + document.documentElement.scrollTop;
    }
    x -= canvas.offsetLeft;
    y -= canvas.offsetTop;
    return [x, y];
}
<commit_msg>added canvas compatibility check, changed zombie_array to be dynamic<commit_after>window.addEventListener("load", Init_Game, false);

var WIDTH = 800, HEIGHT = 480,
    canvas, context, keyDict,
    bullet_array, bullet_image, zombie_array, player,
    mouse_x, mouse_y, mouse_down;

function Init_Game() {
    if (!document.createElement('canvas').getContext) {
        alert("This browser doesn't support canvas!");
        return;
    }
    canvas = document.getElementById("game_canvas");
    context = canvas.getContext("2d");

    mouse_down = false;

    // keys accepted as input need to be here to initialize them before they
    // get checked
    keyDict = {"W": false, "S": false, "A": false, "D": false};

    bullet_array = [];
    bullet_image = new Image();
    bullet_image.src = "images/bullet.png";

    zombie_array = [];
    var zombie;
    for (var i=0;i<10;++i)
    {
        for (var j=0;j<10;++j)
        {
            zombie=new Character(i * 100, j * 100, 0, 0, 50, 50, 1/(i+j) + .1,
                                 "images/zombie.png");
            zombie_array.push(zombie);
        }
    }
    player=new Character(100, 300, 0, 0, 50, 50, 3, "images/player.png");
    player.direction = "south";

    window.addEventListener("keydown",doKeyDown,true);
    window.addEventListener("keyup",doKeyUp,true);
    window.addEventListener("mousedown", doMouseDown, false);
    window.addEventListener("mouseup", doMouseUp, false);
    window.addEventListener("mousemove", doMouseMove, false);

    setInterval("Draw()", 10);
    setInterval("Update()", 10);
}

function Update()
{
    // setting player.drawx/drawy changes direction player image is facing
    if(keyDict["W"])
    {
        if (player.y - player.speed > 0){
            player.y -= player.speed ;
        }
        player.drawx=0;
        player.drawy=50;
    }
    else if(keyDict["S"])
    {
        if (player.y + player.height + player.speed < HEIGHT){
            player.y += player.speed ;
        }
        player.drawx=0;
        player.drawy=0;
    }
    else if(keyDict["A"])
    {
        if (player.x - player.speed > 0){
            player.x -= player.speed ;
        }
        player.drawx=0;
        player.drawy=100;
    }
    else if(keyDict["D"])
    {
        if (player.x + player.width + player.speed < WIDTH){
            player.x += player.speed ;
        }
        player.drawx=0;
        player.drawy=150;
    }
    if (mouse_down)
    {
        var bullet = new Bullet(player.x + player.width / 2,
                                player.y + player.height / 2,
                                mouse_x, mouse_y, 5, 5, 5, "images/bullet.png");
        bullet_array.push(bullet);
    }
    for (var i=0; i < zombie_array.length; ++i)
    {
        zombie_array[i].Update();
    }
    for (var i=0; i < bullet_array.length; ++i)
    {
        bullet_array[i].Update();
        var bullet_alive = true;
        // check for zombie intersections
        for (var j=0; j < zombie_array.length; ++j)
        {
            if(Intersects(bullet_array[i],zombie_array[j]))
            {
                // remove the zombie
                zombie_array[j].x=-60;
                zombie_array[j].speed=0;
                // remove the bullet
                bullet_array.splice(i, 1);
                bullet_alive = false;
                break;
            }
        }
        if (!bullet_alive) continue;
        // check if the bullet has gone out of bounds
        if ((bullet_array[i].x < 0) || (bullet_array[i].x > WIDTH) ||
            (bullet_array[i].y < 0) || (bullet_array[i].y > HEIGHT))
        {
            // remove the bullet
            bullet_array.splice(i, 1);
        }
    }
}

function Draw() {
    context.clearRect(0, 0, WIDTH, HEIGHT);

    player.Draw();
    for (var i=0;i < zombie_array.length; ++i)
    {
        zombie_array[i].Draw();
    }
    for (var i=0;i < bullet_array.length; ++i)
    {
        bullet_array[i].Draw();
    }
}

function Intersects(first,second)
{
    if((first.x<second.x+second.width) && (first.x+first.width>second.x)
        && (first.y<second.y+second.height) && (first.y+first.height>second.y))
    {
        return true;
    }
    else
    {
        return false;
    }
}

function doKeyDown(evt) {
    keyDict[getKeyValue(evt).toUpperCase()] = true;
}

function doKeyUp(evt) {
    keyDict[getKeyValue(evt).toUpperCase()] = false;
}

// Extract the string corresponding to the key pressed.
function getKeyValue(keyEvent) {
    var keyCode;
    // IE support
    if (event.which == undefined) {
        keyCode = keyEvent.keyCode;
    }
    // everyone else
    else {
        keyCode = keyEvent.which;
    }
    return String.fromCharCode(keyCode);
}

// mouse button just went down
function doMouseDown(mouseEvent) {
    mouse_down = true;
}

// mouse button just went up
function doMouseUp(mouseEvent) {
    mouse_down = false;
}

// mouse changed position
function doMouseMove(mouseEvent) {
    var mouse_pos = getCursorPosition(mouseEvent);
    mouse_x = mouse_pos[0];
    mouse_y = mouse_pos[1];
}

// Code pulled straight from Dive Into HTML5 (Halma)
// Unsure which browsers don't support pageX/pageY.
function getCursorPosition(mouseEvent) {
    var x, y;
    if (mouseEvent.pageX != undefined && mouseEvent.pageY != undefined) {
        x = mouseEvent.pageX;
        y = mouseEvent.pageY;
    }
    else {
        x = mouseEvent.clientX + document.body.scrollLeft
                + document.documentElement.scrollLeft;
        y = mouseEvent.clientY + document.body.scrollTop
                + document.documentElement.scrollTop;
    }
    x -= canvas.offsetLeft;
    y -= canvas.offsetTop;
    return [x, y];
}
<|endoftext|>