<commit_before>var WIDTH = window.innerWidth;
var HEIGHT = window.innerHeight;
var GRIDSIZE = 25;
var PI=Math.PI, cos=Math.cos, sin=Math.sin, abs=Math.abs, rad=Snap.rad;

var selected; //"selected"

// Utilities

function randint(max){
    return Math.floor(Math.random() * max);
}

function randcolor(){
    return Snap.hsl(randint(360), 50, 50);
}

function choice(list){
    return list[randint(list.length)];
}

// properly delete from a list
function deleteItem(list, item) {
    var idx = list.indexOf(item);
    if (idx > -1) {
        list.splice(idx, 1);
    }
    return item;
}

function getGroup(id){
    return [].slice.call(Snap.selectAll('path')).filter(function(e){
        return e.attr('group') === id;
    });

}

function rotatePoint(ox, oy, px, py, angle){
    // translate to be around origin
    var x = px - ox;
    var y = py - oy;
    // rotate
    var s = sin(angle);
    var c = cos(angle);
    var px = x * c - y * s;
    var py = x * s + y * c;
    // translate back
    return [px + ox, py + oy];
}

function randomId() {
    // Based on Paul Irish's random hex color:http://www.paulirish.com/2009/random-hex-color-code-snippets/
    // Theoretically could return non-unique values, not going to let that keep me up at night
    return 'k' + Math.floor(Math.random() * 16777215).toString(16); // 'k' because ids have to start with a letter
}

Snap.plugin(function (Snap, Element, Paper, global, Fragment) {
    var prevdx, prevdy;
    function onDrag(dx, dy, x, y, evt){
        if(evt.shiftKey){
            this.moveTo(Math.round((x-window.innerWidth/2)/25)*25, Math.round((y-window.innerHeight/2)/25)*25);
        }else{
            this.move(dx - prevdx, dy - prevdy);
        }
        prevdx = dx;
        prevdy = dy;
    }

    function onDragStart(x, y, evt){
        prevdx = prevdy = 0;
        if (evt.metaKey){
            this.insertBefore(this.clone().setup());
        }
    }

    function onDragEnd(evt){
        this.snapToGrid();
        this.joinGroup(randcolor());
        selected = this;
    }

    var pathFns = {

        asterisk: function(e){
            var cx=e.num('cx'), cy=e.num('cy'), r=e.num('r'), num=e.num('num'), rot=e.rad('rot');
            var path = [];
            var theta = PI * 2 / num;
            for (var i = 0; i < num; i++){
                path.push('M', cx, cy, cos(theta * i + rot) * r + cx, sin(theta * i + rot) * r + cy);
            }
            return path.join(' ');
        },
        polygon: function(e){
            var cx=e.num('cx'), cy=e.num('cy'), r=e.num('r'), num=e.num('num'), rot=e.rad('rot');
            var path = ['M'];
            var theta = PI * 2 / num;
            for (var i = 0; i < num; i++){
                path.push(cos(theta * i + rot) * r + cx, sin(theta * i + rot) * r + cy);
            }
            path.push('Z');
            return path.join(' ');
        },
        star: function(e){
            var cx=e.num('cx'), cy=e.num('cy'), r=e.num('r'), num=e.num('num'), rot=e.rad('rot');
            // num should be odd and 5 or greater
            var skip = (num - 1) / 2;
            var theta = PI * 2 / num * skip;
            var path = ['M'];
            for (var i = 0; i < num; i++){
                path.push(cos(theta * i + rot) * r + cx, sin(theta * i + rot) * r + cy);
            }
            path.push('Z');
            return path.join(' ');
        },
        spiral: function(e){
            var cx=e.num('cx'), cy=e.num('cy'), r=e.num('r'), num=e.num('num'), len=e.num('len'), rot=e.rad('rot');
            var theta = PI * 2 / num;
            var flipH = e.bool('flipH') ? -1 : +1, flipV = e.bool('flipV') ? -1 : +1;
            var dR = r / (num * len);
            var path = ['M'];
            for (var i = 0; i < (num * len); i++){
                path.push(cos(theta * i + rot) * (dR * i) * flipH + cx,
                          sin(theta * i + rot) * (dR * i) * flipV + cy);
            }
            return path.join(' ');
        },
        line: function(e){
            var x1=e.num('cx'), y1=e.num('cy'), x2=e.num('x2')+x1, y2=e.num('y2')+y1;
            var cx = (x1+x2)/2, cy=(y1+y2)/2, rot=e.rad('rot');
            var p1 = rotatePoint(cx, cy, x1, y1, rot);
            var p2 = rotatePoint(cx, cy, x2, y2, rot);
            return ['M', p1[0], p1[1], p2[0], p2[1]].join(' ');
        },
        coffin: function(cx, cy, r){
        },
        crescent: function(cx, cy, r){
        },
        trigram: function(cx, cy, r, h){
        },
        leaf: function(cx, cy, r){
        },
        heart: function(cx, cy, r){
        }
    }

    // New path handlers

    Paper.prototype.asterisk = function(cx, cy, r, num){
        return this.path()
            .attr('r', r).attr('num', num).attr('type', 'asterisk')
            .moveTo(cx, cy).setup();
    };

    Paper.prototype.rpolygon = function(cx, cy, r, num){
        return this.path()
            .attr('r', r).attr('num', num).attr('type', 'polygon')
            .moveTo(cx, cy).setup();
    };

    Paper.prototype.star = function(cx, cy, r, num){
        return this.path()
            .attr('r', r).attr('num', num).attr('type', 'star')
            .moveTo(cx, cy).setup();
    };

    Paper.prototype.spiral = function(cx, cy, r, num, len){
        return this.path()
            .attr('r', r).attr('num', num).attr('len', len).attr('type', 'spiral')
            .moveTo(cx, cy).setup();
    };

    Paper.prototype.line = function(cx, cy, x2, y2){
        return this.path()
            .attr('x2', x2).attr('y2', y2).attr('type', 'line')
            .moveTo(cx, cy).setup();
    };

    // Element extensions

    Element.prototype.setup = function(){
        return this.drag(onDrag, onDragStart, onDragEnd);
    };

    Element.prototype.num = function(name){
        return Number(this.attr(name));
    };

    Element.prototype.rad = function(name){
        return rad(this.num(name));
    };

    Element.prototype.bool = function(name, val){
        if (typeof(val) === 'undefined'){
            return this.attr(name) === 'true';
        }else{
            if (val){
                this.attr(name, 'true');
            }else{
                this.node.removeAttribute(name);
            }
        }
        return this;
    };

    Element.prototype.ease = function(name){
        return mina[this.attr(name)] || mina.easeinout; // get easing
    };

    Element.prototype.update = function(){
        return this.attr('d', pathFns[this.attr('type')](this));
    }

    Element.prototype.moveTo = function(cx, cy){
        return this.attr('cx', cx).attr('cy', cy).update();
    };

    Element.prototype.move = function(dx, dy){
        return this.attr('cx', this.num('cx') + dx).attr('cy', this.num('cy') + dy).update();
    };

    Element.prototype.rotateTo = function(deg){
        return this.attr('rot', deg).update();
    };

    Element.prototype.rotate = function(deg){
        return this.attr('rot', this.num('rot') + deg).update();
    };

    Element.prototype.flipH = function(){
        if (this.node.hasAttribute('flipH')){
            this.node.removeAttribute('flipH');
        }else{
            this.attr('flipH', true);
        }
        return this.update();
    };

    Element.prototype.flipV = function(){
        if (this.node.hasAttribute('flipV')){
            this.node.removeAttribute('flipV');
        }else{
            this.attr('flipV', true);
        }
        return this.update();
    };

    Element.prototype.snapToGrid = function(){
        var x = this.num('cx'), y = this.num('cy');
        x = Math.round(x/GRIDSIZE)*GRIDSIZE
        y = Math.round(y/GRIDSIZE)*GRIDSIZE
        /*var dX = x % GRIDSIZE;
        if (dX < GRIDSIZE / 2){
            x -= dX;
        }else{
            x += GRIDSIZE - dX;
        }
        var dY = y % GRIDSIZE;
        if (dY < GRIDSIZE / 2){
            y -= dY;
        }else{
            y += GRIDSIZE - dY;
        }*/
        this.moveTo(x,y);
    };

    Element.prototype.pulse = function(){
        var dur=this.num('dur') || 1000, color=this.attr('color') || '#00F';
        var easing=this.ease('ease');
        this.animate({stroke: color, strokeWidth: 7}, dur, easing, this.unPulse)
    };

    Element.prototype.unPulse = function(){
        var dur=this.num('dur') || 1000, color='#000';
        var easing=this.ease('ease');
        this.animate({stroke: color, strokeWidth: 5}, dur, easing, this.endPulse);
    };

    Element.prototype.endPulse = function(){
    };

    function distance(x1, y1, x2, y2){
        var val = Math.sqrt(Math.pow(x2-x1, 2) + Math.pow(y2-y1, 2));
        return val;
    }

    Element.prototype.intersects = function(e){
        var selfType = this.attr('type');
        var otherType = e.attr('type');
        if (selfType === 'line' && otherType === 'line'){
            return !! Snap.path.intersection(this, e).length;
        }else if (selfType === 'line'){
            var x1=this.num('cx'), x2=this.num('x2')+x1, y1=this.num('cy'), y2=this.num('y2')+y1;
            var ex=e.num('cx'), ey=e.num('cy');
            return ((distance(x1, y1, ex, ey) < 30) ||
                    (distance(x2, y2, ex, ey) < 30));
        }else if (otherType === 'line'){
            var x1=e.num('cx'), x2=e.num('x2')+x1, y1=e.num('cy'), y2=e.num('y2')+y1;
            var tx=this.num('cx'), ty=this.num('cy');
            return ((distance(x1, y1, tx, ty) < 30) ||
                    (distance(x2, y2, tx, ty) < 30));
        }else{
            return (distance(this.num('cx'), this.num('cy'), e.num('cx'), e.num('cy')) < 40);
        }
    };

    Element.prototype.joinGroup = function(color){
        var self = this;
        self.attr('stroke', color);
        self.attr('group', '');
        var group = null;
        var connected = [].slice.call(Snap.selectAll('path')).filter(function(e){
            if (self === e){
                return false;
            }
            return self.intersects(e);
        });
        connected.forEach(function(e){
            if (!group){
                if (e.attr('group')){
                    group = e.attr('group');
                    self.attr('group', group);
                    color = e.attr('stroke');
                    self.attr('stroke', color);
                }else{
                    group = randomId();
                    self.attr('group', group);
                    e.attr('group', group);
                    e.attr('stroke', color);
                }
            }else{
                if (e.attr('group') === group){
                    // do nothing
                }else if (!e.attr('group')){
                    e.attr('group', group);
                    e.attr('stroke', color);
                }else{
                    // adopt group
                    getGroup(e.attr('group')).forEach(function(e){
                        e.attr('group', group);
                        e.attr('stroke', color);
                    });

                }
            }
        });
    };

});

var ATTRS = {
    fill: 'transparent',
    stroke: '#000',
    strokeWidth: 5,
    color: '#00F', // for animation
}
<commit_msg>fixing animation<commit_after>var WIDTH = window.innerWidth;
var HEIGHT = window.innerHeight;
var GRIDSIZE = 25;
var PI=Math.PI, cos=Math.cos, sin=Math.sin, abs=Math.abs, rad=Snap.rad;

var selected; //"selected"

// Utilities

function randint(max){
    return Math.floor(Math.random() * max);
}

function randcolor(){
    return Snap.hsl(randint(360), 50, 50);
}

function choice(list){
    return list[randint(list.length)];
}

// properly delete from a list
function deleteItem(list, item) {
    var idx = list.indexOf(item);
    if (idx > -1) {
        list.splice(idx, 1);
    }
    return item;
}

function getGroup(id){
    return [].slice.call(Snap.selectAll('path')).filter(function(e){
        return e.attr('group') === id;
    });

}

function rotatePoint(ox, oy, px, py, angle){
    // translate to be around origin
    var x = px - ox;
    var y = py - oy;
    // rotate
    var s = sin(angle);
    var c = cos(angle);
    var px = x * c - y * s;
    var py = x * s + y * c;
    // translate back
    return [px + ox, py + oy];
}

function randomId() {
    // Based on Paul Irish's random hex color:http://www.paulirish.com/2009/random-hex-color-code-snippets/
    // Theoretically could return non-unique values, not going to let that keep me up at night
    return 'k' + Math.floor(Math.random() * 16777215).toString(16); // 'k' because ids have to start with a letter
}

Snap.plugin(function (Snap, Element, Paper, global, Fragment) {
    var prevdx, prevdy;
    function onDrag(dx, dy, x, y, evt){
        if(evt.shiftKey){
            this.moveTo(Math.round((x-window.innerWidth/2)/25)*25, Math.round((y-window.innerHeight/2)/25)*25);
        }else{
            this.move(dx - prevdx, dy - prevdy);
        }
        prevdx = dx;
        prevdy = dy;
    }

    function onDragStart(x, y, evt){
        prevdx = prevdy = 0;
        if (evt.metaKey){
            this.insertBefore(this.clone().setup());
        }
    }

    function onDragEnd(evt){
        this.snapToGrid();
        this.joinGroup(randcolor());
        selected = this;
    }

    var pathFns = {

        asterisk: function(e){
            var cx=e.num('cx'), cy=e.num('cy'), r=e.num('r'), num=e.num('num'), rot=e.rad('rot');
            var path = [];
            var theta = PI * 2 / num;
            for (var i = 0; i < num; i++){
                path.push('M', cx, cy,
                          cos(theta * i + rot) * r + cx,
                          sin(theta * i + rot) * r + cy);
            }
            return path.join(' ');
        },
        polygon: function(e){
            var cx=e.num('cx'), cy=e.num('cy'), r=e.num('r'), num=e.num('num'), rot=e.rad('rot');
            var path = ['M'];
            var theta = PI * 2 / num;
            for (var i = 0; i < num; i++){
                path.push(cos(theta * i + rot) * r + cx, sin(theta * i + rot) * r + cy);
            }
            path.push('Z');
            return path.join(' ');
        },
        star: function(e){
            var cx=e.num('cx'), cy=e.num('cy'), r=e.num('r'), num=e.num('num'), rot=e.rad('rot');
            // num should be odd and 5 or greater
            var skip = (num - 1) / 2;
            var theta = PI * 2 / num * skip;
            var path = ['M'];
            for (var i = 0; i < num; i++){
                path.push(cos(theta * i + rot) * r + cx, sin(theta * i + rot) * r + cy);
            }
            path.push('Z');
            return path.join(' ');
        },
        spiral: function(e){
            var cx=e.num('cx'), cy=e.num('cy'), r=e.num('r'), num=e.num('num'), len=e.num('len'), rot=e.rad('rot');
            var theta = PI * 2 / num;
            var flipH = e.bool('flipH') ? -1 : +1, flipV = e.bool('flipV') ? -1 : +1;
            var dR = r / (num * len);
            var path = ['M'];
            for (var i = 0; i < (num * len); i++){
                path.push(cos(theta * i + rot) * (dR * i) * flipH + cx,
                          sin(theta * i + rot) * (dR * i) * flipV + cy);
            }
            return path.join(' ');
        },
        line: function(e){
            var x1=e.num('cx'), y1=e.num('cy'), x2=e.num('x2')+x1, y2=e.num('y2')+y1;
            var cx = (x1+x2)/2, cy=(y1+y2)/2, rot=e.rad('rot');
            var p1 = rotatePoint(cx, cy, x1, y1, rot);
            var p2 = rotatePoint(cx, cy, x2, y2, rot);
            return ['M', p1[0], p1[1], p2[0], p2[1]].join(' ');
        },
        coffin: function(cx, cy, r){
        },
        crescent: function(cx, cy, r){
        },
        trigram: function(cx, cy, r, h){
        },
        leaf: function(cx, cy, r){
        },
        heart: function(cx, cy, r){
        }
    }

    // New path handlers

    Paper.prototype.asterisk = function(cx, cy, r, num){
        return this.path()
            .attr('r', r).attr('num', num).attr('type', 'asterisk')
            .moveTo(cx, cy).setup();
    };

    Paper.prototype.rpolygon = function(cx, cy, r, num){
        return this.path()
            .attr('r', r).attr('num', num).attr('type', 'polygon')
            .moveTo(cx, cy).setup();
    };

    Paper.prototype.star = function(cx, cy, r, num){
        return this.path()
            .attr('r', r).attr('num', num).attr('type', 'star')
            .moveTo(cx, cy).setup();
    };

    Paper.prototype.spiral = function(cx, cy, r, num, len){
        return this.path()
            .attr('r', r).attr('num', num).attr('len', len).attr('type', 'spiral')
            .moveTo(cx, cy).setup();
    };

    Paper.prototype.line = function(cx, cy, x2, y2){
        return this.path()
            .attr('x2', x2).attr('y2', y2).attr('type', 'line')
            .moveTo(cx, cy).setup();
    };

    // Element extensions

    Element.prototype.setup = function(){
        return this.drag(onDrag, onDragStart, onDragEnd);
    };

    Element.prototype.num = function(name){
        return Number(this.attr(name));
    };

    Element.prototype.rad = function(name){
        return rad(this.num(name));
    };

    Element.prototype.bool = function(name, val){
        if (typeof(val) === 'undefined'){
            return this.attr(name) === 'true';
        }else{
            if (val){
                this.attr(name, 'true');
            }else{
                this.node.removeAttribute(name);
            }
        }
        return this;
    };

    Element.prototype.ease = function(name){
        return mina[this.attr(name)] || mina.easeinout; // get easing
    };

    Element.prototype.update = function(b){
        if(b){
            return this.animate({d: pathFns[this.attr('type')](this)}, 100, this.ease(), this.update)
        }
        return this.attr('d', pathFns[this.attr('type')](this));
    }

    Element.prototype.moveTo = function(cx, cy){
        return this.attr('cx', cx).attr('cy', cy).update();
    };

    Element.prototype.move = function(dx, dy){
        return this.attr('cx', this.num('cx') + dx).attr('cy', this.num('cy') + dy).update();
    };

    Element.prototype.rotateTo = function(deg){
        return this.attr('rot', deg).update();
    };

    Element.prototype.rotate = function(deg){
        return this.attr('rot', this.num('rot') + deg).update();
    };

    Element.prototype.flipH = function(){
        if (this.node.hasAttribute('flipH')){
            this.node.removeAttribute('flipH');
        }else{
            this.attr('flipH', true);
        }
        return this.update();
    };

    Element.prototype.flipV = function(){
        if (this.node.hasAttribute('flipV')){
            this.node.removeAttribute('flipV');
        }else{
            this.attr('flipV', true);
        }
        return this.update();
    };

    Element.prototype.snapToGrid = function(){
        var x = this.num('cx'), y = this.num('cy');
        x = Math.round(x/GRIDSIZE)*GRIDSIZE
        y = Math.round(y/GRIDSIZE)*GRIDSIZE
        /*var dX = x % GRIDSIZE;
        if (dX < GRIDSIZE / 2){
            x -= dX;
        }else{
            x += GRIDSIZE - dX;
        }
        var dY = y % GRIDSIZE;
        if (dY < GRIDSIZE / 2){
            y -= dY;
        }else{
            y += GRIDSIZE - dY;
        }*/
        this.moveTo(x,y);
    };

    Element.prototype.pulse = function(){
        var dur=this.num('dur') || 1000, color=this.attr('color') || '#00F';
        var easing=this.ease('ease');
        this.animate({stroke: color, strokeWidth: 7}, dur, easing, this.unPulse)
    };

    Element.prototype.unPulse = function(){
        var dur=this.num('dur') || 1000, color='#000';
        var easing=this.ease('ease');
        this.animate({stroke: color, strokeWidth: 5}, dur, easing, this.endPulse);
    };

    Element.prototype.endPulse = function(){
    };

    function distance(x1, y1, x2, y2){
        var val = Math.sqrt(Math.pow(x2-x1, 2) + Math.pow(y2-y1, 2));
        return val;
    }

    Element.prototype.intersects = function(e){
        var selfType = this.attr('type');
        var otherType = e.attr('type');
        if (selfType === 'line' && otherType === 'line'){
            return !! Snap.path.intersection(this, e).length;
        }else if (selfType === 'line'){
            var x1=this.num('cx'), x2=this.num('x2')+x1, y1=this.num('cy'), y2=this.num('y2')+y1;
            var ex=e.num('cx'), ey=e.num('cy');
            return ((distance(x1, y1, ex, ey) < 30) ||
                    (distance(x2, y2, ex, ey) < 30));
        }else if (otherType === 'line'){
            var x1=e.num('cx'), x2=e.num('x2')+x1, y1=e.num('cy'), y2=e.num('y2')+y1;
            var tx=this.num('cx'), ty=this.num('cy');
            return ((distance(x1, y1, tx, ty) < 30) ||
                    (distance(x2, y2, tx, ty) < 30));
        }else{
            return (distance(this.num('cx'), this.num('cy'), e.num('cx'), e.num('cy')) < 40);
        }
    };

    Element.prototype.joinGroup = function(color){
        var self = this;
        self.attr('stroke', color);
        self.attr('group', '');
        var group = null;
        var connected = [].slice.call(Snap.selectAll('path')).filter(function(e){
            if (self === e){
                return false;
            }
            return self.intersects(e);
        });
        connected.forEach(function(e){
            if (!group){
                if (e.attr('group')){
                    group = e.attr('group');
                    self.attr('group', group);
                    color = e.attr('stroke');
                    self.attr('stroke', color);
                }else{
                    group = randomId();
                    self.attr('group', group);
                    e.attr('group', group);
                    e.attr('stroke', color);
                }
            }else{
                if (e.attr('group') === group){
                    // do nothing
                }else if (!e.attr('group')){
                    e.attr('group', group);
                    e.attr('stroke', color);
                }else{
                    // adopt group
                    getGroup(e.attr('group')).forEach(function(e){
                        e.attr('group', group);
                        e.attr('stroke', color);
                    });

                }
            }
        });
    };

});

var ATTRS = {
    fill: 'transparent',
    stroke: '#000',
    strokeWidth: 5,
    color: '#00F', // for animation
}
<|endoftext|>


<commit_before>/**
 * app.js
 */

$.ajaxSetup({
    async: false
});

var jvmMode = "-server";
var space = " ";
var gcCollectorAlgorithm = "";

var jdkVersion = "";
var minHeapSize = "";
var maxHeapSize = "";
var defaultPermSize = "";
var maxPermSize = "";

var defaultMetaspace = "";
var maxMetaspace = "";

var tooltipMap = {};

var hashCodeAlgo = '';

var jvmOptsChkBox = {};

var inputBindAttrs = 'DOMAttrModified textInput input change keypress paste focus'

var debugOpts = {};
var performanceOpts = {};

var g1gcOpts = {};

var g1gcInputBoxMap = {};
/**
 * Populate Tooltip from the tooltip.json file.
 */
function populateTooltip() {
    $.getJSON('data/tooltip.json', function (data) {
        $.each(data.tooltips, function (key, val) {
            tooltipMap['tooltip-' + val.id] = val.tooltip;
        });
    });

    /* $("i").each(function () {
     var id = this.id;
     console.log(id);
     $("#" + id).tooltip({
     "title": function () {
     return "" + tooltipMap[id] + "";
     }
     });
     });*/
}

function populateDebuggingOptions() {
    $.getJSON('data/debuggingOpts.json', function (data) {
        $.each(data.debugging, function (key, val) {
            // Parse the JSON and store the id and jvm Option Value in a map
            debugOpts['' + val.id + ''] = val.value;
            var tmp = generateCheckbox(val.id, val.text, val.tooltip);
            $('#debugging').append(tmp);
        });
    });
}

function populatePerformanceOptions() {
    $.getJSON('data/performanceOpts.json', function (data) {
        $.each(data.performance, function (key, val) {
            // Parse the JSON and store the id and jvm Option Value in a map
            performanceOpts['' + val.id + ''] = val.value;
            var tmp = generateCheckbox(val.id, val.text, val.tooltip);
            $('#performance').append(tmp);
        });
    });
}

function populateG1GCExtraFlags() {
    $.getJSON('data/g1gcOpts.json', function (data) {
        var g1gcHtml = '';
        $.each(data.g1gcOpts, function (key, val) {
            // Parse the JSON and store the id and jvm Option Value in a map
            g1gcOpts['' + val.id + ''] = val.value;
            var tmp = generateInputbox(val.id, val.text, val.tooltip);
            g1gcHtml += tmp;
        });

        $('#g1ExtraFlags').append('
Garbage First (G1) Garbage Collection Options
 '
            + '
'
            + g1gcHtml
            + '
');

    });
}

function generateCheckbox(id, text, tooltip) {
    var tmp = '
' +
        '        ' + text + '  ' +
        '
' +
        '         <input id="' + id + '" type="checkbox" value=""> ' +
        '
' +
        '
';

    return tmp;
}

function generateInputbox(id, text, tooltip) {

    var tmp = '
' +
        '  ' + text + ' ' +
        '
' +
        '    <input class="form-control" id="' + id + '" type="text" value="">' +
        '
' +
        '
';

    return tmp;
}

/**
 * Function to invoke on document ready.
 */
$(document).ready(function () {

    populateDebuggingOptions();
    populatePerformanceOptions();

    populateG1GCExtraFlags();

    populateTooltip();
    resetJVMOptions();

    $("[data-toggle=tooltip]").tooltip();

    // Initial value for jdkVersion
    jdkVersion = $("input:radio[name='jdkVersionRadioGroup']:checked").val();

    $("input[name='jdkVersionRadioGroup']").click(function () {
        jdkVersion = $("input:radio[name='jdkVersionRadioGroup']:checked").val();

        if (jdkVersion == 'jdkVersion8') {
            $("#metaSpace").removeClass('hidden');
            $("#permSize").addClass('hidden');

        } else {
            $("#metaSpace").addClass('hidden');
            $("#permSize").removeClass('hidden');

        }

    });

    $('[id^=g1gc-]').bind(inputBindAttrs, function () {
           addKeyValueToMap($(this).attr('id'), $(this).val(), g1gcInputBoxMap);
           validateAndRefreshJVMOptions();
    });

});

$('form').on('change', ':checkbox', function () {
    validateAndRefreshJVMOptions();
});

/**
 * GC Algorithm Selector
 */
$('#gcCollector').on('change', function () {

    var gcAlgo = this.value;

    if (gcAlgo == 'g1') {
        gcCollectorAlgorithm = '-XX:+UseG1GC';
        $("#g1ExtraFlags").removeClass('hidden');
    } else if (gcAlgo == 'cms') {
        gcCollectorAlgorithm = '-XX:+UseConcMarkSweepGC';
        $("#g1ExtraFlags").addClass('hidden');
    } else if (gcAlgo == 'parallel') {
        gcCollectorAlgorithm = '-XX:+UseParNewGC -XX:+UseConcMarkSweepGC';
        $("#g1ExtraFlags").addClass('hidden');
    } else {
        gcCollectorAlgorithm = '';
    }

});

/**
 * GC Algorithm Selector
 */
$('#hashcodeSelect').on('change', function () {
    if (!isEmpty(this.value)) {
        hashCodeAlgo = '';
    } else {
        hashCodeAlgo = '-XX:hashCode=' + this.value;

    }
});

/**
 * Reset Form Options
 */
function resetJVMOptions() {
    // Hide the G1 extra option panel
    $("#g1ExtraFlags").addClass('hidden');
    $("#metaSpace").addClass('hidden');
    $("#permSize").removeClass('hidden');

    $("#printGCDetails").text("unchecked");
    $("#enableGCLogRotation").text("unchecked");
}

/**
 * HeapSize
 */
$('#minHeapSize').bind(inputBindAttrs, function () {
    updateMemoryInputFields('minHeapSize', $(this).val(), '-Xms');

});

$('#maxHeapSize').bind(inputBindAttrs, function () {
    updateMemoryInputFields('maxHeapSize', $(this).val(), '-Xmx');
});

$('#defaultPermSize').bind(inputBindAttrs, function () {
    updateMemoryInputFields('defaultPermSize', $(this).val(), '-XX:PermSize=');

});

$('#maxPermSize').bind(inputBindAttrs, function () {
    updateMemoryInputFields('maxPermSize', $(this).val(), '-XX:MaxPermSize=');
});

$('#defaultMetaSpace').bind(inputBindAttrs, function () {
    updateMemoryInputFields('defaultMetaspace', $(this).val(), '-XX:MetaspaceSize=');
});

$('#maxMetaSpace').bind(inputBindAttrs, function () {
    updateMemoryInputFields('maxMetaspace', $(this).val(), '-XX:MaxMetaspaceSize=');
});

// G1 GC Flags

function getSizeUnitValue(sizeUnitId) {
    var sizeUnit = '';
    if (sizeUnitId != null) {
        sizeUnit = $('#' + sizeUnitId).val();
    }

    return sizeUnit;
}

function updateMemoryInputFields(varName, varValue, prefix) {
    if (isEmpty(varValue)) {
        var tmpValue = prefix + varValue;
        this[varName] = tmpValue;
    } else {
        this[varName] = '';
    }

    validateAndRefreshJVMOptions();
}

function addKeyValueToMap(key, value, map) {
    if (!(key in map)) {
        // Value doesn't exist
        map['' + key + ''] = value;

    } else {
        map['' + key + ''] = value;
    }

}

function isEmpty(data) {
    return $.trim(data) != '';
}

/**
 * Global Change Listener
 */
$("form :input").change(function () {
    validateAndRefreshJVMOptions();
});

function updateCheckboxValues(map) {
    for (var key in map) {
        if (map.hasOwnProperty(key)) {
            validateCheckboxInput(key, map[key]);
        }
    }

}

function validateAndRefreshJVMOptions() {

    // Debugging
    updateCheckboxValues(debugOpts);

    //Performance
    updateCheckboxValues(performanceOpts);

    refreshJVMFlagRef();
}

function getIdVal(data) {
    return $("#" + data).attr('value');
}

function validateCheckboxInput(chkboxId, jvmFlag) {
    if ($("#" + chkboxId).is(':checked')) {

        jvmOptsChkBox['' + chkboxId + ''] = jvmFlag;
        this[chkboxId] = jvmFlag;
    } else {
        jvmOptsChkBox['' + chkboxId + ''] = '';
        this[chkboxId] = '';
    }
}

function getG1ExtraFlags() {
    var tmp = '';
    for (var key in g1gcOpts) {
        if (g1gcOpts.hasOwnProperty(key)) {
            var g1gcOptionValue = g1gcOpts[key];

            if (g1gcInputBoxMap[key]) {

                var extraOptValue = g1gcInputBoxMap[key] || '';

            if (!extraOptValue.trim()) {
                // String is empty; don't do anything
            } else {
                tmp += space + g1gcOptionValue + extraOptValue;

            }
            }

        }
    }

    return tmp;

}

/**
 * Refresh the JVM Options Summary textbox
 */
function refreshJVMFlagRef() {
    $("#jvmFlagResult").text('');

    // Set the JVM Mode
    addTextToJVMSummary(jvmMode);

    // Heap Size
    addMemoryOptsToJVMSummary(minHeapSize, getSizeUnitValue('heapSizeSelect'));
    addMemoryOptsToJVMSummary(maxHeapSize, getSizeUnitValue('heapSizeSelect'));

    if (jdkVersion == 'jdkVersion8') {
        // Metaspace
        addMemoryOptsToJVMSummary(defaultMetaspace, getSizeUnitValue('metaSpaceSelect'));
        addMemoryOptsToJVMSummary(maxMetaspace, getSizeUnitValue('metaSpaceSelect'));
    } else {
        // Perm Size
        addMemoryOptsToJVMSummary(defaultPermSize, getSizeUnitValue('permSizeSelect'));
        addMemoryOptsToJVMSummary(maxPermSize, getSizeUnitValue('permSizeSelect'));
    }

    // GC Collector Algorithm
    addTextToJVMSummary(gcCollectorAlgorithm);

    // Use G1 Extra Flags only if the collector algorithm is G1GC
    if (gcCollectorAlgorithm == '-XX:+UseG1GC') {

        addTextToJVMSummary( getG1ExtraFlags());

    }

    // hashcode Algo
    addTextToJVMSummary(hashCodeAlgo);

    // Iterate through performanceOpts
    for (var key in jvmOptsChkBox) {
        if (jvmOptsChkBox.hasOwnProperty(key)) {
            addTextToJVMSummary(jvmOptsChkBox[key]);
        }
    }

}

function addTextToJVMSummary(val) {

    if (!val.trim()) {
        // String is empty; don't do anything
    } else {
        $("#jvmFlagResult").append(val);
        $("#jvmFlagResult").append(space);
    }
}

function addMemoryOptsToJVMSummary(val, sizeSelect) {

    if (!val.trim()) {
        // String is empty; don't do anything
    } else {
        $("#jvmFlagResult").append(val + sizeSelect);
        $("#jvmFlagResult").append(space);
    }
}
<commit_msg>Update app.js<commit_after>/**
 * app.js
 */

$.ajaxSetup({
    async: false
});

var jvmMode = "-server";
var space = " ";
var gcCollectorAlgorithm = "";

var jdkVersion = "";
var minHeapSize = "";
var maxHeapSize = "";
var defaultPermSize = "";
var maxPermSize = "";

var defaultMetaspace = "";
var maxMetaspace = "";

var tooltipMap = {};

var hashCodeAlgo = '';

var jvmOptsChkBox = {};

var inputBindAttrs = 'DOMAttrModified textInput input change keypress paste focus'

var debugOpts = {};
var performanceOpts = {};

var g1gcOpts = {};

var g1gcInputBoxMap = {};
/**
 * Populate Tooltip from the tooltip.json file.
 */
function populateTooltip() {
    $.getJSON('http://sachin-handiekar.github.io/jvmconfig/data/tooltip.json', function (data) {
        $.each(data.tooltips, function (key, val) {
            tooltipMap['tooltip-' + val.id] = val.tooltip;
        });
    });

    /* $("i").each(function () {
     var id = this.id;
     console.log(id);
     $("#" + id).tooltip({
     "title": function () {
     return "" + tooltipMap[id] + "";
     }
     });
     });*/
}

function populateDebuggingOptions() {
    $.getJSON('http://sachin-handiekar.github.io/jvmconfig/data/debuggingOpts.json', function (data) {
        $.each(data.debugging, function (key, val) {
            // Parse the JSON and store the id and jvm Option Value in a map
            debugOpts['' + val.id + ''] = val.value;
            var tmp = generateCheckbox(val.id, val.text, val.tooltip);
            $('#debugging').append(tmp);
        });
    });
}

function populatePerformanceOptions() {
    $.getJSON('http://sachin-handiekar.github.io/jvmconfig/data/performanceOpts.json', function (data) {
        $.each(data.performance, function (key, val) {
            // Parse the JSON and store the id and jvm Option Value in a map
            performanceOpts['' + val.id + ''] = val.value;
            var tmp = generateCheckbox(val.id, val.text, val.tooltip);
            $('#performance').append(tmp);
        });
    });
}

function populateG1GCExtraFlags() {
    $.getJSON('http://sachin-handiekar.github.io/jvmconfig/data/g1gcOpts.json', function (data) {
        var g1gcHtml = '';
        $.each(data.g1gcOpts, function (key, val) {
            // Parse the JSON and store the id and jvm Option Value in a map
            g1gcOpts['' + val.id + ''] = val.value;
            var tmp = generateInputbox(val.id, val.text, val.tooltip);
            g1gcHtml += tmp;
        });

        $('#g1ExtraFlags').append('
Garbage First (G1) Garbage Collection Options
 '
            + '
'
            + g1gcHtml
            + '
');

    });
}

function generateCheckbox(id, text, tooltip) {
    var tmp = '
' +
        '        ' + text + '  ' +
        '
' +
        '         <input id="' + id + '" type="checkbox" value=""> ' +
        '
' +
        '
';

    return tmp;
}

function generateInputbox(id, text, tooltip) {

    var tmp = '
' +
        '  ' + text + ' ' +
        '
' +
        '    <input class="form-control" id="' + id + '" type="text" value="">' +
        '
' +
        '
';

    return tmp;
}

/**
 * Function to invoke on document ready.
 */
$(document).ready(function () {

    populateDebuggingOptions();
    populatePerformanceOptions();

    populateG1GCExtraFlags();

    populateTooltip();
    resetJVMOptions();

    $("[data-toggle=tooltip]").tooltip();

    // Initial value for jdkVersion
    jdkVersion = $("input:radio[name='jdkVersionRadioGroup']:checked").val();

    $("input[name='jdkVersionRadioGroup']").click(function () {
        jdkVersion = $("input:radio[name='jdkVersionRadioGroup']:checked").val();

        if (jdkVersion == 'jdkVersion8') {
            $("#metaSpace").removeClass('hidden');
            $("#permSize").addClass('hidden');

        } else {
            $("#metaSpace").addClass('hidden');
            $("#permSize").removeClass('hidden');

        }

    });

    $('[id^=g1gc-]').bind(inputBindAttrs, function () {
           addKeyValueToMap($(this).attr('id'), $(this).val(), g1gcInputBoxMap);
           validateAndRefreshJVMOptions();
    });

    $.ajaxSetup({
    async: true
});

});

$('form').on('change', ':checkbox', function () {
    validateAndRefreshJVMOptions();
});

/**
 * GC Algorithm Selector
 */
$('#gcCollector').on('change', function () {

    var gcAlgo = this.value;

    if (gcAlgo == 'g1') {
        gcCollectorAlgorithm = '-XX:+UseG1GC';
        $("#g1ExtraFlags").removeClass('hidden');
    } else if (gcAlgo == 'cms') {
        gcCollectorAlgorithm = '-XX:+UseConcMarkSweepGC';
        $("#g1ExtraFlags").addClass('hidden');
    } else if (gcAlgo == 'parallel') {
        gcCollectorAlgorithm = '-XX:+UseParNewGC -XX:+UseConcMarkSweepGC';
        $("#g1ExtraFlags").addClass('hidden');
    } else {
        gcCollectorAlgorithm = '';
    }

});

/**
 * GC Algorithm Selector
 */
$('#hashcodeSelect').on('change', function () {
    if (!isEmpty(this.value)) {
        hashCodeAlgo = '';
    } else {
        hashCodeAlgo = '-XX:hashCode=' + this.value;

    }
});

/**
 * Reset Form Options
 */
function resetJVMOptions() {
    // Hide the G1 extra option panel
    $("#g1ExtraFlags").addClass('hidden');
    $("#metaSpace").addClass('hidden');
    $("#permSize").removeClass('hidden');

    $("#printGCDetails").text("unchecked");
    $("#enableGCLogRotation").text("unchecked");
}

/**
 * HeapSize
 */
$('#minHeapSize').bind(inputBindAttrs, function () {
    updateMemoryInputFields('minHeapSize', $(this).val(), '-Xms');

});

$('#maxHeapSize').bind(inputBindAttrs, function () {
    updateMemoryInputFields('maxHeapSize', $(this).val(), '-Xmx');
});

$('#defaultPermSize').bind(inputBindAttrs, function () {
    updateMemoryInputFields('defaultPermSize', $(this).val(), '-XX:PermSize=');

});

$('#maxPermSize').bind(inputBindAttrs, function () {
    updateMemoryInputFields('maxPermSize', $(this).val(), '-XX:MaxPermSize=');
});

$('#defaultMetaSpace').bind(inputBindAttrs, function () {
    updateMemoryInputFields('defaultMetaspace', $(this).val(), '-XX:MetaspaceSize=');
});

$('#maxMetaSpace').bind(inputBindAttrs, function () {
    updateMemoryInputFields('maxMetaspace', $(this).val(), '-XX:MaxMetaspaceSize=');
});

// G1 GC Flags

function getSizeUnitValue(sizeUnitId) {
    var sizeUnit = '';
    if (sizeUnitId != null) {
        sizeUnit = $('#' + sizeUnitId).val();
    }

    return sizeUnit;
}

function updateMemoryInputFields(varName, varValue, prefix) {
    if (isEmpty(varValue)) {
        var tmpValue = prefix + varValue;
        this[varName] = tmpValue;
    } else {
        this[varName] = '';
    }

    validateAndRefreshJVMOptions();
}

function addKeyValueToMap(key, value, map) {
    if (!(key in map)) {
        // Value doesn't exist
        map['' + key + ''] = value;

    } else {
        map['' + key + ''] = value;
    }

}

function isEmpty(data) {
    return $.trim(data) != '';
}

/**
 * Global Change Listener
 */
$("form :input").change(function () {
    validateAndRefreshJVMOptions();
});

function updateCheckboxValues(map) {
    for (var key in map) {
        if (map.hasOwnProperty(key)) {
            validateCheckboxInput(key, map[key]);
        }
    }

}

function validateAndRefreshJVMOptions() {

    // Debugging
    updateCheckboxValues(debugOpts);

    //Performance
    updateCheckboxValues(performanceOpts);

    refreshJVMFlagRef();
}

function getIdVal(data) {
    return $("#" + data).attr('value');
}

function validateCheckboxInput(chkboxId, jvmFlag) {
    if ($("#" + chkboxId).is(':checked')) {

        jvmOptsChkBox['' + chkboxId + ''] = jvmFlag;
        this[chkboxId] = jvmFlag;
    } else {
        jvmOptsChkBox['' + chkboxId + ''] = '';
        this[chkboxId] = '';
    }
}

function getG1ExtraFlags() {
    var tmp = '';
    for (var key in g1gcOpts) {
        if (g1gcOpts.hasOwnProperty(key)) {
            var g1gcOptionValue = g1gcOpts[key];

            if (g1gcInputBoxMap[key]) {

                var extraOptValue = g1gcInputBoxMap[key] || '';

            if (!extraOptValue.trim()) {
                // String is empty; don't do anything
            } else {
                tmp += space + g1gcOptionValue + extraOptValue;

            }
            }

        }
    }

    return tmp;

}

/**
 * Refresh the JVM Options Summary textbox
 */
function refreshJVMFlagRef() {
    $("#jvmFlagResult").text('');

    // Set the JVM Mode
    addTextToJVMSummary(jvmMode);

    // Heap Size
    addMemoryOptsToJVMSummary(minHeapSize, getSizeUnitValue('heapSizeSelect'));
    addMemoryOptsToJVMSummary(maxHeapSize, getSizeUnitValue('heapSizeSelect'));

    if (jdkVersion == 'jdkVersion8') {
        // Metaspace
        addMemoryOptsToJVMSummary(defaultMetaspace, getSizeUnitValue('metaSpaceSelect'));
        addMemoryOptsToJVMSummary(maxMetaspace, getSizeUnitValue('metaSpaceSelect'));
    } else {
        // Perm Size
        addMemoryOptsToJVMSummary(defaultPermSize, getSizeUnitValue('permSizeSelect'));
        addMemoryOptsToJVMSummary(maxPermSize, getSizeUnitValue('permSizeSelect'));
    }

    // GC Collector Algorithm
    addTextToJVMSummary(gcCollectorAlgorithm);

    // Use G1 Extra Flags only if the collector algorithm is G1GC
    if (gcCollectorAlgorithm == '-XX:+UseG1GC') {

        addTextToJVMSummary( getG1ExtraFlags());

    }

    // hashcode Algo
    addTextToJVMSummary(hashCodeAlgo);

    // Iterate through performanceOpts
    for (var key in jvmOptsChkBox) {
        if (jvmOptsChkBox.hasOwnProperty(key)) {
            addTextToJVMSummary(jvmOptsChkBox[key]);
        }
    }

}

function addTextToJVMSummary(val) {

    if (!val.trim()) {
        // String is empty; don't do anything
    } else {
        $("#jvmFlagResult").append(val);
        $("#jvmFlagResult").append(space);
    }
}

function addMemoryOptsToJVMSummary(val, sizeSelect) {

    if (!val.trim()) {
        // String is empty; don't do anything
    } else {
        $("#jvmFlagResult").append(val + sizeSelect);
        $("#jvmFlagResult").append(space);
    }
}
<|endoftext|>


<commit_before>'use strict';

angular.module('chronontology', [
    'ui.bootstrap',
    'ui.scroll.jqlite',
    'ui.scroll',
    'ngRoute',
    'ngResource',
    'ui.scroll.jqlite',
    'ui.scroll',
    'idai.templates',
    'idai.components',
    'chronontology.services',
    'chronontology.directives',
    'chronontology.controllers',
    'chronontology.filters',
    'chronontology.components'
])
    .config(['$routeProvider', '$locationProvider', '$compileProvider', '$httpProvider',
        function ($routeProvider, $locationProvider, $compileProvider, $httpProvider) {

            $locationProvider.html5Mode(true);

            $httpProvider.defaults.cache = true;
            $routeProvider
                .when('/', {templateUrl: 'partials/homepage.html'})
                .when('/search', {templateUrl: 'partials/search.html'})
                .when('/period/:id', {templateUrl: 'partials/period.html'})
                .when('/thesaurus/:provenance', {templateUrl: 'partials/thesaurus.html'})
                .when('/about', {templateUrl: 'partials/about.html'})
                .when('/contact', {templateUrl: 'partials/contact.html'})

	}
]).constant('chronontologySettings', {
	baseUri: "http://chronontology.dainst.org",
    geowidgetURL: "http://chronontology.i3mainz.hs-mainz.de/spatialapi/geowidget",
	internalRelations: [
		"isSenseOf", "hasSense",
		"isPartOf", "hasPart",
		"isListedIn", "lists",
		"follows", "isFollowedBy",
		"sameAs",
		"isSimilarTo"
	],
	gazetteerRelations: [
		"isNamedAfter",
		"hasCoreArea",
		"spatiallyPartOfRegion"
	],
    validTypes: [
        'period'
    ],
    validSubtypes: [
        'alle Bedeutungen', 'kulturell', 'pottery style', 'politisch', 'Chronological subdivision',
        'Geological Epoch', 'Geological Period', 'Geological Era', 'material culture'
    ],
    validProvenances: [
        'chronontology', 'Arachne', 'aat'
    ]
}).constant('componentsSettings', {
    transl8Uri: 'https://arachne.dainst.org/transl8/translation/jsonp?application=chronontology_frontend&application=shared&lang={LANG}&callback=JSON_CALLBACK',
    // searchUri: 'https://arachne.dainst.org/data/suggest?q=',
    mailTo: 'idai.chronontology@dainst.org'
}).run(['$rootScope', function($rootScope) {

}]);
<commit_msg>add Allen relations<commit_after>'use strict';

angular.module('chronontology', [
    'ui.bootstrap',
    'ui.scroll.jqlite',
    'ui.scroll',
    'ngRoute',
    'ngResource',
    'ui.scroll.jqlite',
    'ui.scroll',
    'idai.templates',
    'idai.components',
    'chronontology.services',
    'chronontology.directives',
    'chronontology.controllers',
    'chronontology.filters',
    'chronontology.components'
])
    .config(['$routeProvider', '$locationProvider', '$compileProvider', '$httpProvider',
        function ($routeProvider, $locationProvider, $compileProvider, $httpProvider) {

            $locationProvider.html5Mode(true);

            $httpProvider.defaults.cache = true;
            $routeProvider
                .when('/', {templateUrl: 'partials/homepage.html'})
                .when('/search', {templateUrl: 'partials/search.html'})
                .when('/period/:id', {templateUrl: 'partials/period.html'})
                .when('/thesaurus/:provenance', {templateUrl: 'partials/thesaurus.html'})
                .when('/about', {templateUrl: 'partials/about.html'})
                .when('/contact', {templateUrl: 'partials/contact.html'})

	}
]).constant('chronontologySettings', {
	baseUri: "http://chronontology.dainst.org",
    geowidgetURL: "http://chronontology.i3mainz.hs-mainz.de/spatialapi/geowidget",
	internalRelations: [
		"isSenseOf", "hasSense",
		"isPartOf", "hasPart",
		"isListedIn", "lists",
		"follows", "isFollowedBy",
		"sameAs",
		"isSimilarTo"
	],
	allenRelations: [
		"includes", "occursDuring",
		"meetsInTimeWith", "isMetInTimeBy",
		"occursBefore", "occursAfter",
		"isEqualInTimeTo",
		"starts", "isStartedBy",
		"finishes", "isFinishedBy",
		"overlapsInTimeWith", "isOverlappedInTimeBy"
	],
	gazetteerRelations: [
		"isNamedAfter",
		"hasCoreArea",
		"spatiallyPartOfRegion"
	],
    validTypes: [
        'period'
    ],
    validSubtypes: [
        'alle Bedeutungen', 'kulturell', 'pottery style', 'politisch', 'Chronological subdivision',
        'Geological Epoch', 'Geological Period', 'Geological Era', 'material culture'
    ],
    validProvenances: [
        'chronontology', 'Arachne', 'aat'
    ]
}).constant('componentsSettings', {
    transl8Uri: 'https://arachne.dainst.org/transl8/translation/jsonp?application=chronontology_frontend&application=shared&lang={LANG}&callback=JSON_CALLBACK',
    // searchUri: 'https://arachne.dainst.org/data/suggest?q=',
    mailTo: 'idai.chronontology@dainst.org'
}).run(['$rootScope', function($rootScope) {

}]);
<|endoftext|>


<commit_before>ko.bindingHandlers['codeMirror'] = {
  init: function(element, valueAccessor, allBindings) {
    var value = valueAccessor();
    var mainCode = CodeMirror.fromTextArea(
      element,
      {
        mode: "markdown",
        lineNumbers: true
      }
    );
    mainCode.on('change', function (cm) {
      value(cm.getValue());
    });

    value.mainCode = mainCode;

    ko.bindingHandlers['value'].init(element, valueAccessor, allBindings);
  },
  update: function(element, valueAccessor, allBindings){
    var value = valueAccessor();
    if (value() != value.mainCode.getValue()) {
      value.mainCode.setValue(value());
    }
    ko.bindingHandlers['value'].update(element, valueAccessor, allBindings)
  }
};

ko.extenders['timestamp'] = function(target, option) {
  target.created = ko.observable(new Date());
  target.updated = ko.observable(new Date());

  target.subscribe(function() {
    target.updated(new Date());
  });
  return target
};

ko.extenders['sortedBy'] = function(target, option) {
  var observableGetter, postSorted, order;

  if (option.observableGetter) {
    observableGetter = option.observableGetter;
  } else {
    observableGetter = function(value) { return value };
  }
  if (option.postSorted) {
    postSorted = option.postSorted;
  } else {
    postSorted = function() {};
  }
  if (option.order) {
    order = option.order;
  } else {
    order = 'asc'
  }

  target._isSorting = false;  // Not to call recursive.

  // Subscribe added elements to apply subscriber for sorting.
  target.subscribe(function(changes) {
    changes.forEach(function(change) {
      if (change.status === 'added') {
        // Subscriber for sorting.
        observableGetter(change.value).subscribe(function() {
          if (!target._isSorting) {  // Not to call recursive.

            // Get the current array value and try to sort.
            var originalArray = target();
            var sorted = originalArray.concat().sort(function(left, right) {
              if (observableGetter(left)() == observableGetter(right)){
                return 0
              }
              if (order === 'asc') {
                return observableGetter(left)() < observableGetter(right)() ? -1 : 1
              } else {
                return observableGetter(left)() > observableGetter(right)() ? -1 : 1
              }
            });

            // If the sorted value is as same as original, won't change the observable.
            var shouldBeSorted = false;
            sorted.forEach(function(sortedElement, idx) {
              if (sortedElement !== originalArray[idx]) {
                shouldBeSorted = true;
              }
            });
            if (shouldBeSorted) {
              target._isSorting = true;
              target(sorted);
              postSorted();
              target._isSorting = false;
            }
          }
        })
      }
    });
  }, null, 'arrayChange');
  return target
};

var Memo = function() {
  var self = this;

  self.text = ko.observable("").extend({timestamp: ""});
  self.title = ko.pureComputed(function() {
    // FIXME: Take title from CodeMirror.title
    var title = self.text().split('\n')[0];
    if (!title.trim()) {
      return '(no title)'
    }
    return title
  });
};

var OtterViewModel = function() {
  var self = this;
  self.memos = ko.observableArray().
    extend({persist: 'otterMemos'}).
    extend({sortedBy: {observableGetter: function(memo) {return memo.text.updated},
                       postSorted: function() {self.chosenMemoIdx(0)},
                       order: 'desc'}});
  self.numMemos = ko.computed(function() {
    return self.memos().length
  });
  self.chosenMemoIdx = ko.observable();
  self.chosenMemo = ko.pureComputed(function() {
    return self.memos()[self.chosenMemoIdx()]
  });
  self.isShownDeleteConfirm = ko.observable(false);

  self.chooseMemo = function(memo) {
    self.chosenMemoIdx(self.memos.indexOf(memo));
    return true
  };
  self.addMemo = function() {
    self.memos.unshift(new Memo());
    return true
  };
  self.deleteMemo = function() {
    self.memos.remove(self.chosenMemo());
    var idx = self.chosenMemoIdx();
    var last_idx = self.numMemos() - 1;

    if (idx >= last_idx) {
      self.chosenMemoIdx(last_idx);
    }
    if (self.numMemos() == 0) {
      self.memos.removeAll();
      self.memos([new Memo()]);
      self.chosenMemoIdx(0);
    }
    self.isShownDeleteConfirm(false);
  };

  self.showDeleteConfirm = function() {
    self.isShownDeleteConfirm(true);
  };
  self.hideDeleteConfirm = function() {
    self.isShownDeleteConfirm(false);
  };

  self.memos([new Memo()]);
  self.chosenMemoIdx(0);
};

window.addEventListener("load", function() {
  ko.applyBindings(new OtterViewModel());
});
<commit_msg>Fixed not to flush memo pad when the memos automatically sorted<commit_after>ko.bindingHandlers['codeMirror'] = {
  init: function(element, valueAccessor, allBindings) {
    var value = valueAccessor();
    var mainCode = CodeMirror.fromTextArea(
      element,
      {
        mode: "markdown",
        lineNumbers: true
      }
    );
    mainCode.on('change', function (cm) {
      value(cm.getValue());
    });

    value.mainCode = mainCode;

    ko.bindingHandlers['value'].init(element, valueAccessor, allBindings);
  },
  update: function(element, valueAccessor, allBindings){
    var value = valueAccessor();
    if (value() != value.mainCode.getValue()) {
      value.mainCode.setValue(value());
    }
    ko.bindingHandlers['value'].update(element, valueAccessor, allBindings)
  }
};

ko.extenders['timestamp'] = function(target, option) {
  target.created = ko.observable(new Date());
  target.updated = ko.observable(new Date());

  target.subscribe(function() {
    target.updated(new Date());
  });
  return target
};

ko.extenders['sortedBy'] = function(target, option) {
  var observableGetter, postSorted, order;

  if (option.observableGetter) {
    observableGetter = option.observableGetter;
  } else {
    observableGetter = function(value) { return value };
  }
  if (option.postSorted) {
    postSorted = option.postSorted;
  } else {
    postSorted = function() {};
  }
  if (option.order) {
    order = option.order;
  } else {
    order = 'asc'
  }

  target._isSorting = false;  // Not to call recursive.

  // Subscribe added elements to apply subscriber for sorting.
  target.subscribe(function(changes) {
    changes.forEach(function(change) {
      if (change.status === 'added') {
        // Subscriber for sorting.
        observableGetter(change.value).subscribe(function() {
          if (!target._isSorting) {  // Not to call recursive.

            // Get the current array value and try to sort.
            var originalArray = target();
            var sorted = originalArray.concat().sort(function(left, right) {
              if (observableGetter(left)() == observableGetter(right)){
                return 0
              }
              if (order === 'asc') {
                return observableGetter(left)() < observableGetter(right)() ? -1 : 1
              } else {
                return observableGetter(left)() > observableGetter(right)() ? -1 : 1
              }
            });

            // If the sorted value is as same as original, won't change the observable.
            var shouldBeSorted = false;
            sorted.forEach(function(sortedElement, idx) {
              if (sortedElement !== originalArray[idx]) {
                shouldBeSorted = true;
              }
            });
            if (shouldBeSorted) {
              target._isSorting = true;
              target(sorted);
              postSorted();
              target._isSorting = false;
            }
          }
        })
      }
    });
  }, null, 'arrayChange');
  return target
};

var Memo = function() {
  var self = this;

  self.text = ko.observable("").extend({timestamp: ""});
  self.title = ko.pureComputed(function() {
    // FIXME: Take title from CodeMirror.title
    var title = self.text().split('\n')[0];
    if (!title.trim()) {
      return '(no title)'
    }
    return title
  });
};

var OtterViewModel = function() {
  var self = this;
  self.memos = ko.observableArray().
    extend({persist: 'otterMemos'}).
    extend({sortedBy: {observableGetter: function(memo) {return memo.text.updated},
                       order: 'desc'}});
  self.numMemos = ko.computed(function() {
    return self.memos().length
  });
  // Use observable directly instead of computed,
  // not to flush the memo pad when the memos automatically sorted.
  // Actually this can be implemented by ko.computed with self.memos and self.chosenMemoIdx.
  self.chosenMemo = ko.observable();
  self.isShownDeleteConfirm = ko.observable(false);

  self.chooseMemo = function(memo) {
    self.chosenMemo(memo);
    return true
  };
  self.addMemo = function() {
    var memo = new Memo();
    self.memos.unshift(memo);
    self.chosenMemo(memo);
    return true
  };
  self.deleteMemo = function() {
    //     +-- idx
    //     |
    // [a, b, c, d]
    //        |
    //        +-----last_idx
    var idx = self.memos.indexOf(self.chosenMemo());
    var last_idx = self.numMemos() - 2;

    self.memos.remove(self.chosenMemo());

    if (idx > last_idx) {
      self.chosenMemo(self.memos()[last_idx]);
    } else {
      self.chosenMemo(self.memos()[idx])
    }
    if (self.numMemos() == 0) {
      self.memos.removeAll();
      self.memos([new Memo()]);
      self.chosenMemo(self.memos()[0]);
    }
    self.isShownDeleteConfirm(false);
  };

  self.showDeleteConfirm = function() {
    self.isShownDeleteConfirm(true);
  };
  self.hideDeleteConfirm = function() {
    self.isShownDeleteConfirm(false);
  };

  self.memos([new Memo()]);
  self.chosenMemo(self.memos()[0])
};

window.addEventListener("load", function() {
  ko.applyBindings(new OtterViewModel());
});
<|endoftext|>


<commit_before>$(document).ready(function() {

    /*
     * Data Tables
     */

    // Setup - add a text input to filtesearch footers
    $('#table-maplist tfoot th.filtersearch').each( function () {
        var title = $(this).text();
        $(this).html( '<input type="text" placeholder="filter '+title+'" />' );
    } );

    // Setup - add a dropdown to dropdownsearch footers
    $('#table-maplist tfoot th.dropdownsearch').each( function () {
        var title = $(this).text();
        $(this).html( '<select><option value=""></option><option value="yes">' + title + '</option><option value="no">no ' + title + '</option></select>' );
    } );

    var table = $('#table-maplist').DataTable( {
        "ajax": "data/maps.json",
        "lengthMenu": [[50, 100, 250, 500, 1000], [50, 100, 250, 500, 1000]],
        "pageLength": 250,
        "colReorder": true,
        "stateSave": true,
        "fixedHeader": {
            "header": true,
            "headerOffset": $('#main-nav').height()
        },
        "processing": true,
        "deferRender": true,
        "language": {
            "search": "",
            "lengthMenu": "_MENU_",
            "processing": '
Processing a large file, this might take a second

'
        },
        "buttons": [
            {
                "extend": "csvHtml5",
                "text": '',
            },
            {
                "extend": "colvis",
                "postfixButtons": [ 'colvisRestore' ],
                "text": ''
            }
        ],
        "dom": "<'#table-controls'lfB>" +
                "<'row'<'col-sm-12'tr>>" +
                "<'row'<'col-sm-5'i><'col-sm-7'p>>",
        "columns": [
            { "data": "pk3" },
            { "data": "bsp[
 ]" },
            { "data": "filesize" },
            { "data": "filesize" },
            { "data": "shasum" },
            { "data": "mapshot" },
            { "data": "title" },
            { "data": "author" },
            { "data": "gametypes[, ]" },
            { "data": "map[, ]" },
            { "data": "radar[, ]" },
            { "data": "waypoints[, ]" },
            { "data": "license" },
            { "data": "date" }
        ],
        "columnDefs": [
            {   // pk3
                "targets": 0,
                "render": function ( data, type, full, meta ) {
                    var pk3 = data;
                    if (type === 'display' && data.length > 40) {
                        data = ''+data.substr( 0, 38 )+'...';
                    }
                    return '' + data + '';
                }
            },
            {   // bsp
                "targets": 1,
                "render": function ( data, type, full, meta ) {
                    if (data != false && data.length > 0) {
            			if (data.length > 40 && data.indexOf('
') == -1) {
                            data = ''+data.substr( 0, 38 )+'...';
        		    	}
        		    }
                    return data;
                }
            },
            {   // filesize
                "targets": 2,
                "orderData": 3,
                "render": function ( data, type, full, meta ) {
                    return(bytesToSize(data));
                }
            },
            {   // filesize (bytes)
                "targets": 3,
                "visible": false,
                "searchable": false
            },
            {   // shasum
                "targets": 4,
                "visible": false,
            },
            {   // mapshot file
                "targets": 5,
                "render": function ( data, type, full, meta ) {
                    var string = "";
                    if (data.length > 0) {
                        data.forEach(function(value, index, array) {
                            string += '';
                        });
                    }
                    return string;
                }
            },
            {   // title
                "targets": 6,
                "render": function ( data, type, full, meta ) {
                    return (data != false) ? data : "";
                }
            },
            {   // author
                "targets": 7,
                "render": function ( data, type, full, meta ) {
                    return (data != false) ? data : "";
                }
            },
            {   // map file
                "targets": 9,
                "render": function ( data, type, full, meta ) {
                    return (data != false) ? "yes" : "no";
                }
            },
            {   // radar file
                "targets": 10,
                "render": function ( data, type, full, meta ) {
                    return (data != false) ? "yes" : "no";
                }
            },
            {   // waypoints file
                "targets": 11,
                "render": function ( data, type, full, meta ) {
                    return (data != false) ? "yes" : "no";
                }
            },
            {   // license file
                "targets": 12,
                "render": function ( data, type, full, meta ) {
                    return (data != false) ? "yes" : "no";
                }
            },
            {
                // date
                "targets": 13,
                "render": function ( data, type, full, meta ) {
                    d = new Date(0);
                    d.setUTCSeconds(data);
                    return d.toISOString().slice(0,10);
                }
            }
        ],
        "initComplete": function( settings, json ) {
            // clear filters on page load
            $("tfoot input").val('').trigger('change');
            $("tfoot select").val('').trigger('change');
            // Hacky way to put the controls in the navbar
            $("#table-controls .btn").addClass("btn-sm");
            $("#table-maplist_length").addClass("pull-right");
            $("#table-maplist_filter").addClass("pull-right");
            $("#table-controls").detach().appendTo('#nav-table-controls');
            $("#table-controls").show();
        },
        "preDrawCallback": function( settings ) {
            $("#table-controls").hide();
        },
        "drawCallback": function( settings ) {
            $('[data-toggle="popover"]').popover('destroy');
            initPopovers();
        }
    } );

    // Reorder callback
    table.on( 'column-reorder', function ( e, settings, details ) {
        initPopovers();
    });

    // Popover image previews
    function initPopovers() {
        $('a[rel=popover]').popover({
            html: true,
            trigger: 'hover',
            content: function () {
                return '';
            }
        });
    }

    // Apply filtersearch and dropdownsearch
    table.columns().every( function () {
        var that = this;

        $( 'input', this.footer() ).on( 'keyup change', function () {
            if ( that.search() !== this.value ) {
                that
                    .search( this.value )
                    .draw();
            }
        } );

        $( 'select', this.footer() ).on( 'change', function () {
            if ( that.search() !== this.value ) {
                that
                    .search( this.value )
                    .draw();
            }
        } );

    } );

    /*
     * Charts
     */

    var chartsDrawn = false;
    var allCharts = [];

    function drawCharts(data) {
            $("#charts").show();

            // Pie
            allCharts[0] = c3.generate(data.mapinfos);
            allCharts[1] = c3.generate(data.mapshots);
            allCharts[2] = c3.generate(data.maps);
            allCharts[3] = c3.generate(data.radars);
            allCharts[4] = c3.generate(data.waypoints);
            allCharts[5] = c3.generate(data.licenses);

            // Scatter
            var filesizes = {
                tooltip: {
                    format: {
                        title: function (x) { return; },
                        name: function (name, ratio, id, index) { return "map count"; },
                        value: function (value, ratio, id, index) { return value; }
                    }
                }
            };

            $.extend(filesizes, data.filesizes);
            allCharts[6] = c3.generate(filesizes);

            // Line
            allCharts[7] = c3.generate(data.mapsbyyear);

            $("#loading-charts").hide();
    }

    function hideCharts() {
        allCharts.forEach(function(value, index, array) {
            value.hide();
        });
    }

    function showCharts() {
        $("#loading-charts").hide();
        $("#charts").show();
        allCharts.forEach(function(value, index, array) {
            value.show();
        });
    }

    // Need to hide datatables when changing tabs for fixedHeader
    var visible = true;
    var tableContainer = $(table.table().container());

    // Bootstrap tab shown event
    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {

        // decide whether to show the table or not
        if (visible) { // hide table
            $("#nav-table-controls").hide();
            tableContainer.css('display', 'none');
        } else { // show table
            $("#nav-table-controls").show();
            tableContainer.css('display', 'block');
            hideCharts();
        }

        table.fixedHeader.adjust();

        visible = ! visible;

        $("#charts").hide();
        $("#loading-charts").show();

        if (!chartsDrawn) {
            $.get('data/charts.json', function(data) {
                drawCharts(data);
                chartsDrawn = true;
            });
        } else {
            showCharts();
        }

    });

} );

function bytesToSize(bytes) {
   var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
   if (bytes == 0) return '0 Byte';
   var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
   return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
};

<commit_msg>typo and fixed a regression with table-controls<commit_after>$(document).ready(function() {

    /*
     * Data Tables
     */

    // Setup - add a text input to filtesearch footers
    $('#table-maplist tfoot th.filtersearch').each( function () {
        var title = $(this).text();
        $(this).html( '<input type="text" placeholder="filter '+title+'" />' );
    } );

    // Setup - add a dropdown to dropdownsearch footers
    $('#table-maplist tfoot th.dropdownsearch').each( function () {
        var title = $(this).text();
        $(this).html( '<select><option value=""></option><option value="yes">' + title + '</option><option value="no">no ' + title + '</option></select>' );
    } );

    var table = $('#table-maplist').DataTable( {
        "ajax": "data/maps.json",
        "lengthMenu": [[50, 100, 250, 500, 1000], [50, 100, 250, 500, 1000]],
        "pageLength": 250,
        "colReorder": true,
        "stateSave": true,
        "fixedHeader": {
            "header": true,
            "headerOffset": $('#main-nav').height()
        },
        "processing": true,
        "deferRender": true,
        "language": {
            "search": "",
            "lengthMenu": "_MENU_",
            "processing": '
Processing a large file, this might take a second

'
        },
        "buttons": [
            {
                "extend": "csvHtml5",
                "text": '',
            },
            {
                "extend": "colvis",
                "postfixButtons": [ 'colvisRestore' ],
                "text": ''
            }
        ],
        "dom": "<'#table-controls'lfB>" +
                "<'row'<'col-sm-12'tr>>" +
                "<'row'<'col-sm-5'i><'col-sm-7'p>>",
        "columns": [
            { "data": "pk3" },
            { "data": "bsp[
 ]" },
            { "data": "filesize" },
            { "data": "filesize" },
            { "data": "shasum" },
            { "data": "mapshot" },
            { "data": "title" },
            { "data": "author" },
            { "data": "gametypes[, ]" },
            { "data": "map[, ]" },
            { "data": "radar[, ]" },
            { "data": "waypoints[, ]" },
            { "data": "license" },
            { "data": "date" }
        ],
        "columnDefs": [
            {   // pk3
                "targets": 0,
                "render": function ( data, type, full, meta ) {
                    var pk3 = data;
                    if (type === 'display' && data.length > 40) {
                        data = ''+data.substr( 0, 38 )+'...';
                    }
                    return '' + data + '';
                }
            },
            {   // bsp
                "targets": 1,
                "render": function ( data, type, full, meta ) {
                    if (data != false && data.length > 0) {
            			if (data.length > 40 && data.indexOf('
') == -1) {
                            data = ''+data.substr( 0, 38 )+'...';
        		    	}
        		    }
                    return data;
                }
            },
            {   // filesize
                "targets": 2,
                "orderData": 3,
                "render": function ( data, type, full, meta ) {
                    return(bytesToSize(data));
                }
            },
            {   // filesize (bytes)
                "targets": 3,
                "visible": false,
                "searchable": false
            },
            {   // shasum
                "targets": 4,
                "visible": false,
            },
            {   // mapshot file
                "targets": 5,
                "render": function ( data, type, full, meta ) {
                    var string = "";
                    if (data.length > 0) {
                        data.forEach(function(value, index, array) {
                            string += '';
                        });
                    }
                    return string;
                }
            },
            {   // title
                "targets": 6,
                "render": function ( data, type, full, meta ) {
                    return (data != false) ? data : "";
                }
            },
            {   // author
                "targets": 7,
                "render": function ( data, type, full, meta ) {
                    return (data != false) ? data : "";
                }
            },
            {   // map file
                "targets": 9,
                "render": function ( data, type, full, meta ) {
                    return (data != false) ? "yes" : "no";
                }
            },
            {   // radar file
                "targets": 10,
                "render": function ( data, type, full, meta ) {
                    return (data != false) ? "yes" : "no";
                }
            },
            {   // waypoints file
                "targets": 11,
                "render": function ( data, type, full, meta ) {
                    return (data != false) ? "yes" : "no";
                }
            },
            {   // license file
                "targets": 12,
                "render": function ( data, type, full, meta ) {
                    return (data != false) ? "yes" : "no";
                }
            },
            {
                // date
                "targets": 13,
                "render": function ( data, type, full, meta ) {
                    d = new Date(0);
                    d.setUTCSeconds(data);
                    return d.toISOString().slice(0,10);
                }
            }
        ],
        "initComplete": function( settings, json ) {
            // clear filters on page load
            $("tfoot input").val('').trigger('change');
            $("tfoot select").val('').trigger('change');
            // Hacky way to put the controls in the navbar
            $("#table-controls .btn").addClass("btn-sm");
            $("#table-maplist_length").addClass("pull-right");
            $("#table-maplist_filter").addClass("pull-right");
            $("#table-controls").detach().appendTo('#nav-table-controls');
            $("#table-controls").show();
        },
        "preDrawCallback": function( settings ) {
            $("#table-controls").hide();
        },
        "drawCallback": function( settings ) {
            $("#table-controls").show();
            $('[data-toggle="popover"]').popover('destroy');
            initPopovers();
        }
    } );

    // Reorder callback
    table.on( 'column-reorder', function ( e, settings, details ) {
        initPopovers();
    });

    // Popover image previews
    function initPopovers() {
        $('a[rel=popover]').popover({
            html: true,
            trigger: 'hover',
            content: function () {
                return '';
            }
        });
    }

    // Apply filtersearch and dropdownsearch
    table.columns().every( function () {
        var that = this;

        $( 'input', this.footer() ).on( 'keyup change', function () {
            if ( that.search() !== this.value ) {
                that
                    .search( this.value )
                    .draw();
            }
        } );

        $( 'select', this.footer() ).on( 'change', function () {
            if ( that.search() !== this.value ) {
                that
                    .search( this.value )
                    .draw();
            }
        } );

    } );

    /*
     * Charts
     */

    var chartsDrawn = false;
    var allCharts = [];

    function drawCharts(data) {
            $("#charts").show();

            // Pie
            allCharts[0] = c3.generate(data.mapinfos);
            allCharts[1] = c3.generate(data.mapshots);
            allCharts[2] = c3.generate(data.maps);
            allCharts[3] = c3.generate(data.radars);
            allCharts[4] = c3.generate(data.waypoints);
            allCharts[5] = c3.generate(data.licenses);

            // Bar Chart
            var filesizes = {
                tooltip: {
                    format: {
                        title: function (x) { return; },
                        name: function (name, ratio, id, index) { return "map count"; },
                        value: function (value, ratio, id, index) { return value; }
                    }
                }
            };

            $.extend(filesizes, data.filesizes);
            allCharts[6] = c3.generate(filesizes);

            // Line
            allCharts[7] = c3.generate(data.mapsbyyear);

            $("#loading-charts").hide();
    }

    function hideCharts() {
        allCharts.forEach(function(value, index, array) {
            value.hide();
        });
    }

    function showCharts() {
        $("#loading-charts").hide();
        $("#charts").show();
        allCharts.forEach(function(value, index, array) {
            value.show();
        });
    }

    // Need to hide datatables when changing tabs for fixedHeader
    var visible = true;
    var tableContainer = $(table.table().container());

    // Bootstrap tab shown event
    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {

        // decide whether to show the table or not
        if (visible) { // hide table
            $("#nav-table-controls").hide();
            tableContainer.css('display', 'none');
        } else { // show table
            $("#nav-table-controls").show();
            tableContainer.css('display', 'block');
            hideCharts();
        }

        table.fixedHeader.adjust();

        visible = ! visible;

        $("#charts").hide();
        $("#loading-charts").show();

        if (!chartsDrawn) {
            $.get('data/charts.json', function(data) {
                drawCharts(data);
                chartsDrawn = true;
            });
        } else {
            showCharts();
        }

    });

} );

function bytesToSize(bytes) {
   var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
   if (bytes == 0) return '0 Byte';
   var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
   return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
};

<|endoftext|>


<commit_before>// Enemies our player must avoid
var Enemy = function() {
  // Variables applied to each of our instances go here,
  // we've provided one for you to get started

  // The image/sprite for our enemies, this uses
  // a helper we've provided to easily load images
  this.sprite = 'images/enemy-bug.png';
  this.x = Enemy.prototype.startX();
  this.y = Enemy.prototype.startY();
  this.speed = Enemy.prototype.speed();
};

// Generate a start position for each enemy, slightly less than width of canvas
// which is 505.
Enemy.prototype.startX = function() {
  return Math.random() * 450;
};

// Appropriate start position are at 56 + n83, where n == 0, 1, or 2.
// Random value from array courtesy of:
// http://stackoverflow.com/questions/4550505/getting-random-value-from-an-array
Enemy.prototype.startY = function() {
  var options = [0, 1, 2];
  var result = 56 + 83 * options[Math.floor(Math.random() * options.length)];
  return result;
};

// Update the enemy's position, required method for game
// Parameter: dt, a time delta between ticks
Enemy.prototype.update = function( dt ) {
  // You should multiply any movement by the dt parameter
  // which will ensure the game runs at the same speed for
  // all computers.
  this.x = this.x + this.speed;
  if (this.x > 600) {
    this.x = -150;
    this.y = Enemy.prototype.startY();
    this.speed = Enemy.prototype.speed();
  }
};

// Generate a random, appropriate speed for each bug
Enemy.prototype.speed = function (){
  return 1.25 + (Math.random() * 5);
};

// Draw the enemy on the screen, required method for game
Enemy.prototype.render = function() {
  ctx.drawImage( Resources.get( this.sprite ), this.x, this.y );
};

// Now write your own player class
// This class requires an update(), render() and
// a handleInput() method.
var Player = function() {
  this.sprite = 'images/char-boy.png';
  this.x = 300;
  this.y = 388;
};

Player.prototype.update = function( dt ) {

};

Player.prototype.render = function() {
  ctx.drawImage( Resources.get( this.sprite ), this.x, this.y );
};

Player.prototype.handleInput = function() {

};

// Now instantiate your objects.
// Place all enemy objects in an array called allEnemies
// Place the player object in a variable called player
var allEnemies = [];
var player = new Player();

//Pick number of enemies
var enemyCount = function( count ) {
  for ( var i = 0; i < count; i++ ) {
    allEnemies.push( new Enemy() );
  }
};

enemyCount( 3 );

// This listens for key presses and sends the keys to your
// Player.handleInput() method. You don't need to modify this.
document.addEventListener( 'keyup', function( e ) {
  var allowedKeys = {
    37: 'left',
    38: 'up',
    39: 'right',
    40: 'down'
  };

  player.handleInput( allowedKeys[ e.keyCode ] );
} );
<commit_msg>Feat: Basic move controls<commit_after>// Enemies our player must avoid
var Enemy = function() {
  // Variables applied to each of our instances go here,
  // we've provided one for you to get started

  // The image/sprite for our enemies, this uses
  // a helper we've provided to easily load images
  this.sprite = 'images/enemy-bug.png';
  this.x = Enemy.prototype.startX();
  this.y = Enemy.prototype.startY();
  this.speed = Enemy.prototype.speed();
};

// Generate a start position for each enemy, slightly less than width of canvas
// which is 505.
Enemy.prototype.startX = function() {
  return Math.random() * 450;
};

// Appropriate start position are at 56 + n83, where n == 0, 1, or 2.
// Random value from array courtesy of:
// http://stackoverflow.com/questions/4550505/getting-random-value-from-an-array
Enemy.prototype.startY = function() {
  var options = [0, 1, 2];
  var result = 56 + 83 * options[Math.floor(Math.random() * options.length)];
  return result;
};

// Update the enemy's position, required method for game
// Parameter: dt, a time delta between ticks
Enemy.prototype.update = function( dt ) {
  // You should multiply any movement by the dt parameter
  // which will ensure the game runs at the same speed for
  // all computers.
  this.x = this.x + this.speed;
  if (this.x > 600) {
    this.x = -150;
    this.y = Enemy.prototype.startY();
    this.speed = Enemy.prototype.speed();
  }
};

// Generate a random, appropriate speed for each bug
Enemy.prototype.speed = function (){
  return 1.25 + (Math.random() * 5);
};

// Draw the enemy on the screen, required method for game
Enemy.prototype.render = function() {
  ctx.drawImage( Resources.get( this.sprite ), this.x, this.y );
};

// Now write your own player class
// This class requires an update(), render() and
// a handleInput() method.
var Player = function() {
  this.sprite = 'images/char-boy.png';
  this.x = 300;
  this.y = 388;
};

Player.prototype.update = function( dt ) {

};

Player.prototype.render = function() {
  ctx.drawImage( Resources.get( this.sprite ), this.x, this.y );
};

Player.prototype.handleInput = function(input) {
  if (input === 'left'){
    this.x = this.x - 101;
  }
  else if (input === 'up'){
    this.y = this.y - 83;
  }
  else if (input === 'right'){
    this.x = this.x + 101;
  }
  else if (input === 'down'){
    this.y = this.y + 83;
  }
};

// Now instantiate your objects.
// Place all enemy objects in an array called allEnemies
// Place the player object in a variable called player
var allEnemies = [];
var player = new Player();

//Pick number of enemies
var enemyCount = function( count ) {
  for ( var i = 0; i < count; i++ ) {
    allEnemies.push( new Enemy() );
  }
};

enemyCount( 3 );

// This listens for key presses and sends the keys to your
// Player.handleInput() method. You don't need to modify this.
document.addEventListener( 'keyup', function( e ) {
  var allowedKeys = {
    37: 'left',
    38: 'up',
    39: 'right',
    40: 'down'
  };

  player.handleInput( allowedKeys[ e.keyCode ] );
} );
<|endoftext|>


<commit_before>function bindEvent(element, type, handler) {
  if(element.addEventListener) {
    element.addEventListener(type, handler, false);
  } else {
    element.attachEvent('on'+type, handler);
  }
}

bindEvent(document.getElementById("play"), 'click', function(){
  document.getElementById("audio").play();
});

window.onload = function(){
  if (navigator.mozApps){
    html = " | Install on Mozilla Marketplace"
    document.getElementById("install").innerHTML = html

    bindEvent(document.getElementById("mozilla_app"), 'click', function(){
      var request = navigator.mozApps.install("http://instantohthehumanity.com/app.webapp");
      request.onsuccess = function() {
        alert("App installed");
      };
      request.onerror = function() {
        alert(this.error.name);
      };
    });
  }
};
<commit_msg>Fixes manifest url<commit_after>function bindEvent(element, type, handler) {
  if(element.addEventListener) {
    element.addEventListener(type, handler, false);
  } else {
    element.attachEvent('on'+type, handler);
  }
}

bindEvent(document.getElementById("play"), 'click', function(){
  document.getElementById("audio").play();
});

window.onload = function(){
  if (navigator.mozApps){
    html = " | Install on Mozilla Marketplace"
    document.getElementById("install").innerHTML = html

    bindEvent(document.getElementById("mozilla_app"), 'click', function(){
      var request = navigator.mozApps.install("http://instantohthehumanity.com/manifest.webapp");
      request.onsuccess = function() {
        alert("App installed");
      };
      request.onerror = function() {
        alert(this.error.name);
      };
    });
  }
};
<|endoftext|>


<commit_before>'use strict';

var app = angular.module('nm-sandbox', ['ngRoute']);

app.provider('sbRoutes', function() {

  this.routes = [
    {
      name: 'add',
      title: 'Create',
      templateUrl: 'add-page'
    }, {
      name: 'members',
      title: 'Members',
      templateUrl: 'members-page'
    }, {
      name: 'about',
      title: 'About',
      templateUrl: 'about-page'
    }, {
      name: 'contact',
      title: 'Contact',
      templateUrl: 'contact-page'
    }
  ];

  var _this = this;

  this.$get = function() {
    return _this.routes;
  };
});

app.config(['$routeProvider', '$locationProvider', 'sbRoutesProvider',

	function($routeProvider, $locationProvider, sbPagesProvider){

		sbPagesProvider.routes.map(function(page){
			$routeProvider.when('/' + page.name, { templateUrl: page.templateUrl });
		});

		$routeProvider.otherwise({
			redirectTo: '/add'
		});

		$locationProvider.html5Mode(true);
	}
]);

app.controller('menuController', ['$route', 'sbRoutes', '$scope', function($route, sbRoutes, $scope){
  $scope.sbRoutes = sbRoutes;
  $scope.$route = $route;
}]);

app.controller('addController', ['$scope', 'Members', function($scope, Members){

  $scope.newMember = {};

  $scope.addMember = function(){
    Members.create($scope.newMember);
    $scope.newMember = {};
  };
}]);

app.controller('membersController', ['$scope', 'Members', function($scope, Members){
  $scope.members = Members.get();

  $scope.deleteMember = function(index){
    Members.delete(index);
  }

}]);

app.service('Members', [function(){
  var members = [{
    firstName: 'Nicolas',
    lastName: 'Moise',
    phoneNumber: '514-245-6074'
  }];

  this.create = function(member){
    members.push(member);
  };

  this.get = function(){
    return members;
  };

	this.delete = function(index){
		members.splice(index, 1);
	}
}]);
<commit_msg>cleanup<commit_after>'use strict';

var app = angular.module('nm-sandbox', ['ngRoute']);

app.provider('sbRoutes', function() {

  this.routes = [
    {
      name: 'add',
      title: 'Create',
      templateUrl: 'add-page'
    }, {
      name: 'members',
      title: 'Members',
      templateUrl: 'members-page'
    }, {
      name: 'about',
      title: 'About',
      templateUrl: 'about-page'
    }, {
      name: 'contact',
      title: 'Contact',
      templateUrl: 'contact-page'
    }
  ];

  var _this = this;

  this.$get = function() {
    return _this.routes;
  };
});

app.config(['$routeProvider', '$locationProvider', 'sbRoutesProvider',
  function($routeProvider, $locationProvider, sbPagesProvider){
    sbPagesProvider.routes.map(function(page){
      $routeProvider.when('/' + page.name, { templateUrl: page.templateUrl });
    });

    $routeProvider.otherwise({
      redirectTo: '/add'
    });

    $locationProvider.html5Mode(true);
  }
]);

app.controller('menuController', ['$route', 'sbRoutes', '$scope', function($route, sbRoutes, $scope){
  $scope.sbRoutes = sbRoutes;
  $scope.$route = $route;
}]);

app.controller('addController', ['$scope', 'Members', function($scope, Members){

  $scope.newMember = {};

  $scope.addMember = function(){
    Members.create($scope.newMember);
    $scope.newMember = {};
  };
}]);

app.controller('membersController', ['$scope', 'Members', function($scope, Members){
  $scope.members = Members.get();

  $scope.deleteMember = function(index){
    Members.delete(index);
  }

}]);

app.service('Members', [function(){
  var members = [{
    firstName: 'Nicolas',
    lastName: 'Moise',
    phoneNumber: '514-245-6074'
  }];

  this.create = function(member){
    members.push(member);
  };

  this.get = function(){
    return members;
  };

  this.delete = function(index){
    members.splice(index, 1);
  }
}]);
<|endoftext|>


<commit_before>$(function () {
  var roads = L.geoJson(null, {
    style: function (feature) {
      return {
        color: ['#ca0020', '#f4a582', '#92c5de', '#0571b0'][Math.floor(Math.random() * 4)],
        weight: 3,
        opacity: 1
      }
    }
  }),
  map = L.map('map', {
    center: [39.952473, -75.164106],
    zoom: 10,
    layers: [
      L.tileLayer('http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png', {
      	attribution: '© CartoDB',
      	subdomains: 'abcd',
      	minZoom: 0,
      	maxZoom: 18
      })
    ]
  }),
  topPane = map._createPane('leaflet-top-pane', map.getPanes().overlayPane),
  topLayer = L.tileLayer('http://openmapsurfer.uni-hd.de/tiles/adminb/x={x}&y={y}&z={z}', {
  	minZoom: 0,
  	maxZoom: 19,
  	attribution: 'Imagery from GIScience Research Group @ University of Heidelberg — Map data © OpenStreetMap'
  }).setZIndex(20).addTo(map)

  $.getJSON('data/local_roads.geojson', function (data) {
      roads.addData(data)
      map.fitBounds(roads.getBounds())
  })

  topPane.appendChild(topLayer.getContainer())

  $(document).on('click', '[data-toggle="offcanvas"]', function () {
    $('.row-offcanvas').toggleClass('active')
  })
})
<commit_msg>Update app.js<commit_after>$(function () {
  var map = L.map('map', {
    center: [39.952473, -75.164106],
    zoom: 10,
    layers: [
      L.tileLayer('http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png', {
      	attribution: '© CartoDB',
      	subdomains: 'abcd',
      	minZoom: 0,
      	maxZoom: 18
      })
    ]
  }),
  roads = L.geoJson(null, {
    style: function (feature) {
      return {
        color: ['#ca0020', '#f4a582', '#92c5de', '#0571b0'][Math.floor(Math.random() * 4)],
        weight: 3,
        opacity: 1
      }
    }
  }).addTo(map),
  topPane = map._createPane('leaflet-top-pane', map.getPanes().overlayPane),
  topLayer = L.tileLayer('http://openmapsurfer.uni-hd.de/tiles/adminb/x={x}&y={y}&z={z}', {
  	minZoom: 0,
  	maxZoom: 19,
  	attribution: 'Imagery from GIScience Research Group @ University of Heidelberg — Map data © OpenStreetMap'
  }).setZIndex(20).addTo(map)

  $.getJSON('data/local_roads.geojson', function (data) {
      roads.addData(data)
      map.fitBounds(roads.getBounds())
  })

  topPane.appendChild(topLayer.getContainer())

  $(document).on('click', '[data-toggle="offcanvas"]', function () {
    $('.row-offcanvas').toggleClass('active')
  })
})
<|endoftext|>


<commit_before>
$(document).ready(function ($) {
    console.log('App loading...');
    Idea = Backbone.Model.extend({
        idAttribute: "_id",
        defaults: function () {
            return {
                title: "none set",
                url: '/ideas',
            };
        },
        initialize: function () {
            if (!this.get("title")) {
                this.set({
                    "title": this.defaults().title
                });
            }
            this.set({
                "url": this.defaults().url
            });
        }
    });

    InputView = Backbone.View.extend({
        initialize: function () {
            _.bindAll(this, 'render');
            this.template = _.template($('#idea-create').html());
        },
        events: {
            "keypress .inputBox"  : "newIdea",
        },
        newIdea: function(e) {
            if (e.keyCode == 13) {
                Idea.create({title: $('.inputBox').val()});
                $('.inputBox').val('');
                }
        },
        render: function () {
            $(this.el).html(this.template);
            return this;
        }
    });

    IdeaView = Backbone.View.extend({
        tagName: 'li',
        initialize: function () {
            //Javascript is dumb...
            _.bindAll(this, 'render', 'remove');
            // implemented so that it will refresh when the model changes...
            this.model.bind('change', this.render);
            this.model.bind('destroy', this.remove);
            this.template = _.template($('#idea-template').html());
        },
        events:{
            'click .destroy' : 'clear',
            'click .title'   : 'edit'
        },
        clear: function(){
            console.log('Destroyed');
            this.model.destroy();
        },

        edit: function(){
            console.log('PENDING: This will edit the item in the future.');
            //this.$el.find('.title').text(';-O')

        },
        render: function () {
            var renderedContent = this.template(this.model.toJSON());
            $(this.el).html(renderedContent);
            //Return 'this' so that method chaining is possible
            return this;
        }
    });

    Ideas = Backbone.Collection.extend({
        model: Idea,
        url: '/ideas'
    });

    IdeasView = Backbone.View.extend({
        initialize: function () {
            _.bindAll(this, 'render');
            this.template = _.template($('#ideas-template').html());
            this.collection.bind('reset', this.render);
        },
        render: function () {
            var $ideas, collection;
            $(this.el).html(this.template);
            //using this.$() scopes it to the particular DOM element
            $ideas = this.$('.ideas');
            this.collection.each(function (idea) {
                var ideaItem = new IdeaView({
                    model: idea,
                    collection: collection
                });
                $ideas.append(ideaItem.render().el);
            });
            return this;
        }
    });

    UnpopularIdeas = Backbone.Router.extend({
        routes: {
            '': 'home'
        },
        initialize: function () {
            ideas = new Ideas;
            ideas.fetch();
            this.stream = new IdeasView({
                collection: ideas
            });
            this.inputBox = new InputView;
        },
        home: function () {
            $('#container').append(this.inputBox.render().el);
            $('#container').append(this.stream.render().el);
        }
    });

    window.App = new UnpopularIdeas;
    Backbone.history.start();

});<commit_msg>whoops! Left out .save()<commit_after>
$(document).ready(function ($) {
    console.log('App loading...');
    Idea = Backbone.Model.extend({
        idAttribute: "_id",
        defaults: function () {
            return {
                title: "none set",
                url: '/ideas',
            };
        },
        initialize: function () {
            if (!this.get("title")) {
                this.set({
                    "title": this.defaults().title
                });
            }
            this.set({
                "url": this.defaults().url
            });
        }
    });

    InputView = Backbone.View.extend({
        initialize: function () {
            _.bindAll(this, 'render');
            this.template = _.template($('#idea-create').html());
        },
        events: {
            "keypress .inputBox"  : "newIdea",
        },
        newIdea: function(e) {
            if (e.keyCode == 13) {
                var newIdea = new Idea({title: $('.inputBox').val()});
                newIdea.save();
                $('.inputBox').val('');
                }
        },
        render: function () {
            $(this.el).html(this.template);
            return this;
        }
    });

    IdeaView = Backbone.View.extend({
        tagName: 'li',
        initialize: function () {
            //Javascript is dumb...
            _.bindAll(this, 'render', 'remove');
            // implemented so that it will refresh when the model changes...
            this.model.bind('change', this.render);
            this.model.bind('destroy', this.remove);
            this.template = _.template($('#idea-template').html());
        },
        events:{
            'click .destroy' : 'clear',
            'click .title'   : 'edit'
        },
        clear: function(){
            console.log('Destroyed');
            this.model.destroy();
        },

        edit: function(){
            console.log('PENDING: This will edit the item in the future.');
            //this.$el.find('.title').text(';-O')

        },
        render: function () {
            var renderedContent = this.template(this.model.toJSON());
            $(this.el).html(renderedContent);
            //Return 'this' so that method chaining is possible
            return this;
        }
    });

    Ideas = Backbone.Collection.extend({
        model: Idea,
        url: '/ideas'
    });

    IdeasView = Backbone.View.extend({
        initialize: function () {
            _.bindAll(this, 'render');
            this.template = _.template($('#ideas-template').html());
            this.collection.bind('reset', this.render);
        },
        render: function () {
            var $ideas, collection;
            $(this.el).html(this.template);
            //using this.$() scopes it to the particular DOM element
            $ideas = this.$('.ideas');
            this.collection.each(function (idea) {
                var ideaItem = new IdeaView({
                    model: idea,
                    collection: collection
                });
                $ideas.append(ideaItem.render().el);
            });
            return this;
        }
    });

    UnpopularIdeas = Backbone.Router.extend({
        routes: {
            '': 'home'
        },
        initialize: function () {
            ideas = new Ideas;
            ideas.fetch();
            this.stream = new IdeasView({
                collection: ideas
            });
            this.inputBox = new InputView;
        },
        home: function () {
            $('#container').append(this.inputBox.render().el);
            $('#container').append(this.stream.render().el);
        }
    });

    window.App = new UnpopularIdeas;
    Backbone.history.start();

});<|endoftext|>