<commit_before>(function() {
    "use strict";

    var fn = timbre.fn;

    function SynthDefNode(_args) {
        timbre.Object.call(this, _args);
        fn.fixAR(this);

        var _ = this._;

        _.poly     = 4;
        _.genList  = [];
        _.genDict  = {};
        _.synthdef = null;
        _.isEnded  = true;

        _.remGen = remGen.bind(this);
    }
    fn.extend(SynthDefNode);

    var $ = SynthDefNode.prototype;

    Object.defineProperties($, {
        def: {
            set: function(value) {
                if (typeof value === "function") {
                    this._.synthdef = value;
                }
            },
            get: function() {
                return this._.synthdef;
            }
        },
        poly: {
            set: function(value) {
                if (typeof value === "number") {
                    if (0 < value && value <= 64) {
                        this._.poly = value;
                    }
                }
            },
            get: function() {
                return this._.poly;
            }
        }
    });

    var doneAction = function(opts) {
        remGen.call(this, opts.gen);
    };

    var remGen = function(gen) {
        var _ = this._;
        var i = _.genList.indexOf(gen);
        if (i !== -1) {
            _.genList.splice(i, 1);
        }
        _.genDict[gen.noteNum] = null;
    };

    var noteOn = function(noteNum, freq, velocity, _opts) {
        velocity |= 0;
        if (velocity <= 0) {
            this.noteOff(this, noteNum);
        } else if (velocity > 127) {
            velocity = 127;
        }
        var _ = this._;
        var list = _.genList, dict = _.genDict;
        var gen = dict[noteNum];
        if (gen) {
            _.remGen(gen);
        }

        var opts = {
            freq    : freq,
            noteNum : noteNum,
            velocity: velocity
        };
        if (_opts) {
            for (var key in _opts) {
                opts[key] = _opts[key];
            }
        }
        opts.doneAction = doneAction.bind(this, opts);

        gen = this._.synthdef.call(this, opts);

        if (gen instanceof timbre.Object) {
            gen.noteNum = noteNum;
            list.push(gen);
            dict[noteNum] = opts.gen = gen;

            _.isEnded = false;

            if (list.length >= _.poly) {
                _.remGen(list[0]);
            }
        }
    };

    var midicps = (function() {
        var table = new Float32Array(128);
        for (var i = 0; i < 128; ++i) {
            table[i] = 440 * Math.pow(2, (i - 69) * 1 / 12);
        }
        return table;
    })();

    var cpsmidi = function(cps) {
        if (cps > 0) {
            return Math.log(cps * 1 / 440) * Math.LOG2E * 12 + 69;
        } else {
            return 0;
        }
    };

    $.noteOn = function(noteNum, velocity, _opts) {
        var freq = midicps[noteNum] || (440 * Math.pow(2, (noteNum - 69) / 12));
        noteOn.call(this, (noteNum + 0.5)|0, freq, velocity, _opts);
        return this;
    };

    $.noteOff = function(noteNum) {
        var gen = this._.genDict[noteNum];
        if (gen && gen.release) {
            gen.release();
        }
        return this;
    };

    $.noteOnWithFreq = function(freq, velocity, _opts) {
        var noteNum = cpsmidi(freq);
        noteOn.call(this, (noteNum + 0.5)|0, freq, velocity, _opts);
        return this;
    };

    $.noteOffWithFreq = function(freq) {
        var noteNum = cpsmidi(freq);
        return this.noteOff((noteNum + 0.5)|0);
    };

    $.allNoteOff = function() {
        var list = this._.genList;
        for (var i = 0, imax = list.length; i < imax; ++i) {
            if (list[i].release) {
                list[i].release();
            }
        }
    };

    $.allSoundOff = function() {
        var _ = this._;
        var list = _.genList;
        var dict = _.genDict;
        while (list.length) {
            delete dict[list.shift().noteNum];
        }
    };

    $.process = function(tickID) {
        var cell = this.cell;
        var _ = this._;

        if (this.tickID !== tickID) {
            this.tickID = tickID;

            fn.inputSignalAR(this);

            // process
            if (!_.isEnded) {
                var list;
                var i, imax;
                var j, jmax = cell.length;
                var tmp;

                list = _.genList;
                for (i = 0, imax = list.length; i < imax; ++i) {
                    tmp = list[i].process(tickID);
                    for (j = jmax; j--; ) {
                        cell[j] += tmp[j];
                    }
                }
                if (imax === 0) {
                    fn.nextTick(fn.onended.bind(null, this));
                }
            }

            fn.outputSignalAR(this);
        }

        return cell;
    };

    fn.register("SynthDef", SynthDefNode);

    var env_desc = {
        set: function(value) {
            if (typeof value === "object" && value.constructor === Object) {
                if (typeof value.type === "string") {
                    this._.env = value;
                }
            }
        },
        get: function() {
            return this._.env;
        }
    };

    fn.register("OscGen", (function() {

        var wave_desc = {
            set: function(value) {
                if (typeof value === "string") {
                    this._.wave = value;
                }
            },
            get: function() {
                return this._.wave;
            }
        };

        var synthdef = function(opts) {
            var _ = this._;
            var synth, env, envtype;

            env = _.env || {};
            envtype = env.type || "perc";

            synth = timbre("osc", {wave:_.wave, freq:opts.freq, mul:opts.velocity/128});
            synth = timbre(envtype, env, synth).on("ended", opts.doneAction).bang();

            return synth;
        };

        return function(_args) {
            var instance = new SynthDefNode(_args);

            instance._.wave = "sin";

            Object.defineProperties(instance, {
                env: env_desc, wave: wave_desc
            });

            instance.def = synthdef;

            return instance;
        };
    })());

    fn.register("PluckGen", (function() {

        var synthdef = function(opts) {
            var _ = this._;
            var synth, env, envtype;

            env = _.env || {};
            envtype = env.type || "perc";

            synth = timbre("pluck", {freq:opts.freq, mul:opts.velocity/128}).bang();
            synth = timbre(envtype, env, synth).on("ended", opts.doneAction).bang();

            return synth;
        };

        return function(_args) {
            var instance = new SynthDefNode(_args);

            Object.defineProperties(instance, {
                env: env_desc
            });

            instance.def = synthdef;

            return instance;
        };
    })());

})();
<commit_msg>fix T("env").clone()<commit_after>(function() {
    "use strict";

    var fn = timbre.fn;

    function SynthDefNode(_args) {
        timbre.Object.call(this, _args);
        fn.fixAR(this);

        var _ = this._;

        _.poly     = 4;
        _.genList  = [];
        _.genDict  = {};
        _.synthdef = null;
        _.isEnded  = true;

        _.remGen = remGen.bind(this);
    }
    fn.extend(SynthDefNode);

    var $ = SynthDefNode.prototype;

    Object.defineProperties($, {
        def: {
            set: function(value) {
                if (typeof value === "function") {
                    this._.synthdef = value;
                }
            },
            get: function() {
                return this._.synthdef;
            }
        },
        poly: {
            set: function(value) {
                if (typeof value === "number") {
                    if (0 < value && value <= 64) {
                        this._.poly = value;
                    }
                }
            },
            get: function() {
                return this._.poly;
            }
        }
    });

    var doneAction = function(opts) {
        remGen.call(this, opts.gen);
    };

    var remGen = function(gen) {
        var _ = this._;
        var i = _.genList.indexOf(gen);
        if (i !== -1) {
            _.genList.splice(i, 1);
        }
        _.genDict[gen.noteNum] = null;
    };

    var noteOn = function(noteNum, freq, velocity, _opts) {
        velocity |= 0;
        if (velocity <= 0) {
            this.noteOff(this, noteNum);
        } else if (velocity > 127) {
            velocity = 127;
        }
        var _ = this._;
        var list = _.genList, dict = _.genDict;
        var gen = dict[noteNum];
        if (gen) {
            _.remGen(gen);
        }

        var opts = {
            freq    : freq,
            noteNum : noteNum,
            velocity: velocity
        };
        if (_opts) {
            for (var key in _opts) {
                opts[key] = _opts[key];
            }
        }
        opts.doneAction = doneAction.bind(this, opts);

        gen = this._.synthdef.call(this, opts);

        if (gen instanceof timbre.Object) {
            gen.noteNum = noteNum;
            list.push(gen);
            dict[noteNum] = opts.gen = gen;

            _.isEnded = false;

            if (list.length >= _.poly) {
                _.remGen(list[0]);
            }
        }
    };

    var midicps = (function() {
        var table = new Float32Array(128);
        for (var i = 0; i < 128; ++i) {
            table[i] = 440 * Math.pow(2, (i - 69) * 1 / 12);
        }
        return table;
    })();

    var cpsmidi = function(cps) {
        if (cps > 0) {
            return Math.log(cps * 1 / 440) * Math.LOG2E * 12 + 69;
        } else {
            return 0;
        }
    };

    $.noteOn = function(noteNum, velocity, _opts) {
        var freq = midicps[noteNum] || (440 * Math.pow(2, (noteNum - 69) / 12));
        noteOn.call(this, (noteNum + 0.5)|0, freq, velocity, _opts);
        return this;
    };

    $.noteOff = function(noteNum) {
        var gen = this._.genDict[noteNum];
        if (gen && gen.release) {
            gen.release();
        }
        return this;
    };

    $.noteOnWithFreq = function(freq, velocity, _opts) {
        var noteNum = cpsmidi(freq);
        noteOn.call(this, (noteNum + 0.5)|0, freq, velocity, _opts);
        return this;
    };

    $.noteOffWithFreq = function(freq) {
        var noteNum = cpsmidi(freq);
        return this.noteOff((noteNum + 0.5)|0);
    };

    $.allNoteOff = function() {
        var list = this._.genList;
        for (var i = 0, imax = list.length; i < imax; ++i) {
            if (list[i].release) {
                list[i].release();
            }
        }
    };

    $.allSoundOff = function() {
        var _ = this._;
        var list = _.genList;
        var dict = _.genDict;
        while (list.length) {
            delete dict[list.shift().noteNum];
        }
    };

    $.process = function(tickID) {
        var cell = this.cell;
        var _ = this._;

        if (this.tickID !== tickID) {
            this.tickID = tickID;

            fn.inputSignalAR(this);

            // process
            if (!_.isEnded) {
                var list;
                var i, imax;
                var j, jmax = cell.length;
                var tmp;

                list = _.genList;
                for (i = 0, imax = list.length; i < imax; ++i) {
                    tmp = list[i].process(tickID);
                    for (j = jmax; j--; ) {
                        cell[j] += tmp[j];
                    }
                }
                if (imax === 0) {
                    fn.nextTick(fn.onended.bind(null, this));
                }
            }

            fn.outputSignalAR(this);
        }

        return cell;
    };

    fn.register("SynthDef", SynthDefNode);

    var env_desc = {
        set: function(value) {
            if (typeof value === "object" && value.constructor === Object) {
                if (typeof value.type === "string") {
                    this._.env = value;
                }
            } else if (value instanceof timbre.Object) {
                this._.env = value;
            }
        },
        get: function() {
            return this._.env;
        }
    };

    fn.register("OscGen", (function() {

        var wave_desc = {
            set: function(value) {
                if (typeof value === "string") {
                    this._.wave = value;
                }
            },
            get: function() {
                return this._.wave;
            }
        };

        var synthdef = function(opts) {
            var _ = this._;
            var synth, env, envtype;

            env = _.env || {};
            envtype = env.type || "perc";

            synth = timbre("osc", {wave:_.wave, freq:opts.freq, mul:opts.velocity/128});
            if (env instanceof timbre.Object) {
                if (typeof env.clone === "function") {
                    synth = env.clone().append(synth);
                }
            } else {
                synth = timbre(envtype, env, synth);
            }
            synth.on("ended", opts.doneAction).bang();

            return synth;
        };

        return function(_args) {
            var instance = new SynthDefNode(_args);

            instance._.wave = "sin";

            Object.defineProperties(instance, {
                env: env_desc, wave: wave_desc
            });

            instance.def = synthdef;

            return instance;
        };
    })());

    fn.register("PluckGen", (function() {

        var synthdef = function(opts) {
            var _ = this._;
            var synth, env, envtype;

            env = _.env || {};
            envtype = env.type || "perc";

            synth = timbre("pluck", {freq:opts.freq, mul:opts.velocity/128}).bang();
            if (env instanceof timbre.Object) {
                if (typeof env.clone === "function") {
                    synth = env.clone().append(synth);
                }
            } else {
                synth = timbre(envtype, env, synth);
            }
            synth.on("ended", opts.doneAction).bang();

            return synth;
        };

        return function(_args) {
            var instance = new SynthDefNode(_args);

            Object.defineProperties(instance, {
                env: env_desc
            });

            instance.def = synthdef;

            return instance;
        };
    })());

})();
<|endoftext|>


<commit_before>// jquery.livesearch.js
// Version 1.2
// documentation: http://bililite.com/blog/2013/03/07/new-jquery-plugin-livesearch/
// depends on jQuery, bililiteRange.s, bililiteRange.util.js

// Copyright (c) 2013 Daniel Wachsstock
// MIT license:
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:

// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
(function($, undefined){

$.fn.livesearch = function(back, filter){
	var text = this;
	// need separate ranges for each one of text!
	var rngs = text.map(function() {return bililiteRange(this).bounds('selection')}).get();

	filter = filter || function (string){
		try{
			return new RegExp(string);
		}catch(e){
			return /(?:)/; // blank regexp
		}
	}

	return function(evt){
		var text = bililiteRange(this).all();
		if (evt.type != 'blur' && evt.type != 'focusout'){
			rngs.forEach(function(rng){
				rng = rng.clone().find(filter(text), undefined, back);
				highlight(rng);
				$(rng.element()).trigger('livesearch', [text, rng.match]);
			});
		}else{
			rngs.forEach(function(rng){
				var el = $(rng.element());
				deletehighlight(rng);
				rng.find(filter(text), undefined, back);
				el.trigger('livesearchdone', [text, rng.match]);
				var scroll = el.data('livesearch.scroll');
				if (scroll){
					// this will only be approximate if there's no word wrap on the text area.
					el.prop('scrollTop', scroll.top);
				}
				el.one('focus', function() {rng.select()});
			});
		}
	}
}

function highlight (rng){
	// display the range in an overlying element (using $.fn.texthighight is too flaky)
	var el = $(rng.element());
	var display = el.data('livesearch.display');
	if (!display){
		// create display element
		display = $('<pre>').addClass('livesearch').css({
			overflow: 'auto',
			whiteSpace: 'pre-wrap',
			position: 'absolute',
			fontFamily: el.css('fontFamily'),
			fontSize: el.css('fontSize')
		}).appendTo('body');
	}
	// set size and location and font
	display.offset(el.offset()).width(el.outerWidth()).height(el.outerHeight());
	display.empty();
	var text = rng.all();
	var b = rng.bounds();
	display.append(document.createTextNode(text.slice(0, b[0])));
	var highlighter = $('<span>').text(text.slice(b[0],b[1])).appendTo(display);
	display.append(document.createTextNode(text.slice(b[1])));
	var top = highlighter.position().top + display.prop('scrollTop');
	// scroll the parent div to put the highlighted area 1/3 of the way down
	// we always use word wrapping, so it's always visible horizontally
	display.stop(true).animate({scrollTop: top - display.height()/3});
	$.data(this, 'livesearch.scroll', {
		top : display.prop('scrollTop')
	});

	// remember this element
	el.data('livesearch.display', display);
}

function deletehighlight(rng){
	console.log('deleting');
	var display = $.data(rng._el, 'livesearch.display');
	if (display){
		display.remove();
		$.removeData(rng._el, 'livesearch.display');
	}
}

})(jQuery);<commit_msg>add livesearch to vi<commit_after>// jquery.livesearch.js
// Version 1.2
// documentation: http://bililite.com/blog/2013/03/07/new-jquery-plugin-livesearch/
// depends on jQuery, bililiteRange.s, bililiteRange.util.js

// Copyright (c) 2013 Daniel Wachsstock
// MIT license:
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:

// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
(function($, undefined){

$.fn.livesearch = function(back, filter){
	var text = this;
	// need separate ranges for each one of text!
	var rngs = text.map(function() {return bililiteRange(this).bounds('selection')}).get();

	filter = filter || function (string){
		try{
			return new RegExp(string);
		}catch(e){
			return /(?:)/; // blank regexp
		}
	}

	return function(evt){
		var text = bililiteRange(this).all();
		if (evt.type != 'blur' && evt.type != 'focusout'){
			rngs.forEach(function(rng){
				rng = rng.clone().find(filter(text), undefined, back);
				highlight(rng);
				$(rng.element()).trigger('livesearch', [text, rng.match]);
			});
		}else{
			rngs.forEach(function(rng){
				var el = $(rng.element());
				deletehighlight(rng);
				rng.find(filter(text), undefined, back);
				el.trigger('livesearchdone', [text, rng.match]);
				var scroll = el.data('livesearch.scroll');
				if (scroll){
					// this will only be approximate if there's no word wrap on the text area.
					el.prop('scrollTop', scroll.top);
				}
				el.one('focus', function() {rng.select()});
			});
		}
	}
}

function highlight (rng){
	// display the range in an overlying element (using $.fn.texthighight is too flaky)
	var el = $(rng.element());
	var display = el.data('livesearch.display');
	if (!display){
		// create display element
		display = $('<pre>').addClass('livesearch').css({
			overflow: 'auto',
			whiteSpace: 'pre-wrap',
			position: 'absolute',
			fontFamily: el.css('fontFamily'),
			fontSize: el.css('fontSize')
		}).appendTo('body');
	}
	// set size and location and font
	display.offset(el.offset()).width(el.outerWidth()).height(el.outerHeight());
	display.empty();
	var text = rng.all();
	var b = rng.bounds();
	display.append(document.createTextNode(text.slice(0, b[0])));
	var highlighter = $('<span>').text(text.slice(b[0],b[1])).appendTo(display);
	display.append(document.createTextNode(text.slice(b[1])));
	var top = highlighter.position().top + display.prop('scrollTop');
	// scroll the parent div to put the highlighted area 1/3 of the way down
	// we always use word wrapping, so it's always visible horizontally
	display.stop(true).animate({scrollTop: top - display.height()/3});
	$.data(this, 'livesearch.scroll', {
		top : display.prop('scrollTop')
	});

	// remember this element
	el.data('livesearch.display', display);
}

function deletehighlight(rng){
	var display = $.data(rng._el, 'livesearch.display');
	if (display){
		display.remove();
		$.removeData(rng._el, 'livesearch.display');
	}
}

})(jQuery);<|endoftext|>


<commit_before>var canvas;
var container;
var gl;

function setMinTime() {
    return $.ajax({type: 'GET', url: 'times.php?search=' + search, async: false});
}

function setDataList() {
    $.ajax("dataList.php", {async: 'false'}).success(function(j) {
        var options = '<option value="default">Pick database...</option>';
        data = jQuery.parseJSON(j);
        for (var i = 0; i < data.length; i++) {
            options += '<option value="' + data[i] + '">' + data[i] + '</option>';
        }

        $("#language").html(options);
    });
}

//
//    function reload(){
//            var container = document.getElementById("container");
//            var content = container.innerHTML;
//            container.innerHTML= content;
//        }

function outputUpdate(speednum) {
    document.querySelector('#speednum').value = vol;
}

function initGlobe() {
    document.body.style.backgroundImage = 'none'; // remove loading
    container = document.getElementById('container');
    globe = new DAT.Globe(container);
    globe.addData([], {format: 'magnitude', animated: false});
    globe.createPoints();
    globe.animate();

    animate = function() {
        requestAnimationFrame(animate);
    };

    animate();
}

function setGlobeData() {
    setInterval(function() {
        interval = 5000;
        time = time + interval;
        dataResp = $.ajax({
            type: 'GET',
            url: 'data.php?offset=' + time + '&search=' + search + '&interval=' + interval,
            async: false
        });
        dataObj = dataResp.responseText;
        data = jQuery.parseJSON(dataObj);
        window.data = data;
        if (data.length > 0) {
            for (i = 0; i < data.length; i += 1) {
                globe.addData(data[i], {format: 'magnitude', animated: false});
            }
            globe.createPoints();
            globe.animate();
        }
    }, 2000);
}

//
//dataSource.bind("sync", function(e) {
//  $('container').data("container").dataSource.read();
//});
//
function addGlobeData(search, colour) {
    dataResp = $.ajax({
        type: 'GET',
        url: 'search.php?search=' + search + '&colour=' + colour,
        async: false
    });
    dataObj = dataResp.responseText;
    data = jQuery.parseJSON(dataObj);
    window.data = data;
    if (data && data.length > 0) {
        globe.addData(data, {format: 'magnitude', animated: false});
        globe.createPoints();
        globe.animate();
    }
    else {
        alert("too many");
    }
}<commit_msg>fixed the check for data<commit_after>var canvas;
var container;
var gl;

function setMinTime() {
    return $.ajax({type: 'GET', url: 'times.php?search=' + search, async: false});
}

function setDataList() {
    $.ajax("dataList.php", {async: 'false'}).success(function(j) {
        var options = '<option value="default">Pick database...</option>';
        data = jQuery.parseJSON(j);
        for (var i = 0; i < data.length; i++) {
            options += '<option value="' + data[i] + '">' + data[i] + '</option>';
        }

        $("#language").html(options);
    });
}

//
//    function reload(){
//            var container = document.getElementById("container");
//            var content = container.innerHTML;
//            container.innerHTML= content;
//        }

function outputUpdate(speednum) {
    document.querySelector('#speednum').value = vol;
}

function initGlobe() {
    document.body.style.backgroundImage = 'none'; // remove loading
    container = document.getElementById('container');
    globe = new DAT.Globe(container);
    globe.addData([], {format: 'magnitude', animated: false});
    globe.createPoints();
    globe.animate();

    animate = function() {
        requestAnimationFrame(animate);
    };

    animate();
}

function setGlobeData() {
    setInterval(function() {
        interval = 5000;
        time = time + interval;
        dataResp = $.ajax({
            type: 'GET',
            url: 'data.php?offset=' + time + '&search=' + search + '&interval=' + interval,
            async: false
        });
        dataObj = dataResp.responseText;
        data = jQuery.parseJSON(dataObj);
        window.data = data;
        if (data.length > 0) {
            for (i = 0; i < data.length; i += 1) {
                globe.addData(data[i], {format: 'magnitude', animated: false});
            }
            globe.createPoints();
            globe.animate();
        }
    }, 2000);
}

//
//dataSource.bind("sync", function(e) {
//  $('container').data("container").dataSource.read();
//});
//
function addGlobeData(search, colour) {
    dataResp = $.ajax({
        type: 'GET',
        url: 'search.php?search=' + search + '&colour=' + colour,
        async: false
    });
    dataObj = dataResp.responseText;
    if (dataObj) {
        data = jQuery.parseJSON(dataObj);
        window.data = data;
        if (dataObj && data.length > 0) {
            globe.addData(data, {format: 'magnitude', animated: false});
            globe.createPoints();
            globe.animate();
        }
        else {
            alert("No Results");
        }
    } else {
        alert("Please wait 10 mins and try again");
    }
}<|endoftext|>


<commit_before>function show_commits(project) {
  project = project.replace(/\s+/g, '');
  var url = "../Jsons/"+project+".json";
  $.getJSON(url, function(json) {
    $('#page-wrapper').html('');
    $('#page-wrapper').append('

Commits - '+project+'

');
    $('#page-wrapper').append('

 Ismael Alvarez (IsmaelAlvarez)
Total: 1

message: Solucionado problema con gradle/maven
time: 2016-04-27 19:05:00
url: https://github.com/IsmaelAlvarez/logisim/commit/0953d5355dca7044b651c1f246314842af7d1674

')
  })
}

function general_view(project) {
  project = project.replace(/\s+/g, '');
  var url = "../Jsons/"+project+".json";
  $.getJSON(url, function(json) {
    $('#page-wrapper').html('');
    $('#page-wrapper').append('

Review - '+project+'

');
    $('#page-wrapper').append('

');
    var datas = [];
    for (var i in json) {
      var d = {user: json[i].user, commits: json[i].commits.length, issues: json[i].issues.length, comments: json[i].comments.length};
      data.push(d);
    }
    Morris.Bar({
      element: 'bar',
      data: datas,
      xkey: 'user',
      ykeys: ['commits', 'issues', 'comments'],
      labels: ['Commits', 'Issues', 'Comentarios'],
      stacked: true,
      resize:true
    });
  });
}
<commit_msg>graphs shows real data<commit_after>function show_commits(project) {
  project = project.replace(/\s+/g, '');
  var url = "../Jsons/"+project+".json";
  $.getJSON(url, function(json) {
    $('#page-wrapper').html('');
    $('#page-wrapper').append('

Commits - '+project+'

');
    $('#page-wrapper').append('

 Ismael Alvarez (IsmaelAlvarez)
Total: 1

message: Solucionado problema con gradle/maven
time: 2016-04-27 19:05:00
url: https://github.com/IsmaelAlvarez/logisim/commit/0953d5355dca7044b651c1f246314842af7d1674

')
  })
}

function general_view(project) {
  project = project.replace(/\s+/g, '');
  var url = "../Jsons/"+project+".json";
  $.getJSON(url, function(json) {
    $('#page-wrapper').html('');
    $('#page-wrapper').append('

Review - '+project+'

');
    $('#page-wrapper').append('

');
    var datas = [];
    for (var i in json) {
      var d = {user: json[i].user, commits: json[i].commits.length, issues: json[i].issues.length, comments: json[i].comments.length};
      datas.push(d);
    }
    Morris.Bar({
      element: 'bar',
      data: datas,
      xkey: 'user',
      ykeys: ['commits', 'issues', 'comments'],
      labels: ['Commits', 'Issues', 'Comentarios'],
      stacked: true,
      resize:true
    });
  });
}
<|endoftext|>


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

/* global Cookies:true */

'use strict';

var setupUse = require('./use.js');
var nextHour = require('./demo.js').nextHour;
var scrollToElement = require('./demo.js').scrollToElement;
var getAndParseCookieName = require('./demo.js').getAndParseCookieName;

// var currentPage = require('./demo.js').currentPage;

$(document).ready(function() {
  $('._training--example').click(function() {
    var currentExample = $(this);

    $('.showing div._examples--class__selected button').click();
    // clear all user classifier info
    $('.classifier').attr('data-hasfile', '0');

    var kind = $(this).data('kind');

    if ($('._examples[data-kind=' + kind + ']').hasClass('showing')) {
      $('.showing').removeClass('showing');
      $('._container--bundle-form').removeClass('active');
      $('._training--example').map(function(index, item) {
        $(item).css('opacity', '1.0');
        $(item).find('img').css('box-shadow', '0px 0px 0px 0px transparent');
        $(item).find('._training--use-your-own').css('box-shadow', '0px 0px 0px 0px transparent');
      });
    } else {
      $('._training--example').map(function(index, item) {
        if (!$(item).is(currentExample)) {
          $(item).css('opacity', '0.5');
          $(item).find('img').css('box-shadow', '0px 0px 0px 0px transparent');
          $(item).find('._training--use-your-own').css('box-shadow', '0px 0px 0px 0px transparent');
        } else {
          $(item).css('opacity', '1.0');
          $(item).find('img').css('box-shadow', '0px 0px 0px 3px #336588');
          $(item).find('._training--use-your-own').css('box-shadow', '0px 0px 0px 3px #336588');
        }
      });
      $('.showing').removeClass('showing');
      $('._examples[data-kind=' + kind + ']').removeClass('removed');
      $('._container--bundle-form input[type=submit]').addClass('disabled');
      $('._container--bundle-form input[type=submit]').prop('disabled', true);
      setTimeout(function() {
        $('.showing').addClass('removed');
        $('._examples[data-kind=' + kind + ']').addClass('showing');
        $('.train--row').addClass('showing');
        if (lookupName(kind)) {
          $('input.base--input._examples--input-name').val('Name of classifier: ' + lookupName(kind));
          $('input.base--input._examples--input-name').prop('readonly', true);
          $('input.base--input._examples--input-name').addClass('bundle');
        } else {
          $('input.base--input._examples--input-name').val('');
          $('input.base--input._examples--input-name').prop('readonly', false);
          $('input.base--input._examples--input-name').removeClass('bundle');
        }
        $('._container--bundle-form').addClass('active');
      }, 100);

      setTimeout(function() {
        scrollToElement($('._examples.showing'));
      }, 100);

      if ($(this).css('opacity') === '0.5') {
        $testSection.hide();
      }
    }
  });

  function warningMessagesVisability() {
    if ($('.classifier[data-hasfile=1]').length > 1) {
      $('.upload_message').hide();
      return true;
    } else {
      $('.upload_message').show();
      return false;
    }
  }

  function enableTrainClassifier() {
    var enable = $('.showing ._examples--class__selected._positive').length > 2;
    enable = enable || ($('.showing ._examples--class__selected._positive').length > 0 && $('.showing ._examples--class__selected._negative').length === 1 );
    enable = enable || warningMessagesVisability();

    // the name has to be filled out, too
    if (enable && $('.base--input._examples--input-name').val().length) {
      $('.train--train-button.base--button').removeClass('disabled');
      $('.train--train-button.base--button').prop('disabled', false);
    } else {
      $('.train--train-button.base--button').addClass('disabled');
      $('.train--train-button.base--button').prop('disabled', true);
    }
  }

  $('button[type=reset]').click(function() {
    if ($('.showing div._examples--class__selected button').length > 0) {
      $('.showing div._examples--class__selected button').click();
    } else {
      $('form.upload')[0].reset();
      if (!$('input.base--input._examples--input-name').prop('readonly')) {
        $('input.base--input._examples--input-name').val('');
        $('input.base--input._examples--input-name').prop('readonly', false);
      }
    }
    $testSection.hide();
    enableTrainClassifier();
  });

  $('._examples--class button').click(function() {
    if ($(this).parent().hasClass('_examples--class__selected')) {
      $(this).data('selected', 0);
      $(this).html('Select');
    } else {
      $(this).data('selected', 1);
      $(this).html('Deselect');
    }
    $(this).parent().toggleClass('_examples--class__selected');

    enableTrainClassifier();

    if ($.map($('._examples--class[data-kind=' + $(this).parent().data('kind') + '] button'), function(item) { return $(item).text(); }).reduce(function(k, v) { return k || v === 'Select'; }, false)) {
      $('a.select_all').text('Select All');
    }

    return false;
  });

  $('._examples--class img').click(function() {
    var contactSheet = $('._examples--contact-sheet[data-kind=' + $(this).data('kind') + ']');
    if ( $(this).css('box-shadow') === 'rgb(51, 101, 136) 0px 0px 0px 3px' && contactSheet.css('display') === 'flex') {
      contactSheet.hide();
    } else {
      $('._examples--class img').css('box-shadow', '0px 0px 0px 0px transparent');
      $(this).css('box-shadow', '0px 0px 0px 3px #336588');
      $(this).data('name');
      $('._examples--contact-sheet[data-kind=' + $(this).data('kind') + '] img').attr('src', '/images/bundles/' + $(this).data('kind') + '/' + $(this).data('name') + '-contact.jpg');
      contactSheet.css('display', 'flex');

      setTimeout(function() {
        scrollToElement(contactSheet);
      }, 100);
    }
  });

  $('._examples--contact-sheet img').click(function() {
    $(this).attr('src', '');
    $(this).parent().css('display', 'none');

    scrollToElement($('._examples.showing'));
  });

  $('a.select_all').click(function() {
    var currentText = $(this).text();
    if ($('.showing div._examples--class:not(._examples--class__selected)').length > 0) {
      $('.showing div._examples--class:not(._examples--class__selected) button').click();
    } else {
      $('.showing div._examples--class__selected button').click();
    }
    $(this).text(currentText === 'Select All' ? 'Deselect All' : 'Select All');
  });

  $('.classifier .text').on('click', function(e) {
    e.preventDefault();
    $(this).parent().find('input[type=file]').click();
  });

  $('.classifier input[type=file]').on('change', function(e) {
    var nameInput = $(e.target).parent().find('input[type=text]');
    if ($(e.target).length > 0 && ($(e.target)[0].files && $(e.target)[0].files.length > 0)) {
      if ($(e.target)[0].files[0].size > (5 * 1024 * 1024)) {
        // eslint-disable-next-line no-alert
        alert('This file exceeds the maximum size of 5 MB. Please choose another file');
      }
      var baseFileName = $(e.target)[0].files[0].name;
      nameInput.val(baseFileName.split('.')[0]);
      $(e.target).parent().attr('data-hasfile', 1);
      $(e.target).parent().find('.text-label').hide();
      $(e.target).parent().find('.text-zip-image').css('display', 'block');
      $(e.target).parent().find('.clear_link').show();
    }
  });

  $('.classifier a.clear_link').on('click', function(e) {
    e.preventDefault();
    $(e.target).parent().find('input').val('');
    $(e.target).parent().attr('data-hasfile', '0');
    $(e.target).parent().find('.text').find('.text-label').show();
    $(e.target).parent().find('.text').find('.text-zip-image').hide();
    $(e.target).parent().find('.clear_link').hide();
    enableTrainClassifier();
  });

  $('input[type=text].base--input._examples--input-name').on('input', function() {
    $('form.upload input[type=hidden][name=classifiername]').val($(this).val());
    enableTrainClassifier();
  });

  $('form.upload.training_dropzone').on('change', function() {
    enableTrainClassifier();
  });

  $('._examples--user-input').on('drop', function(e) {
    e.preventDefault();
  });

  var $loading = $('.train--loading');
  var $error = $('.train--error');
  var $errorMsg = $('.train--error-message');
  var $trainButton = $('.train--train-button');
  var $testSection = $('.test--section');

  function resetPage() {
    $loading.hide();
    $error.hide();
    $('.test--output.test--output-row').hide();
  }

  function showTrainingError(err) {
    $loading.hide();
    $error.show();
    var message = 'Error creating the classifier';
    if (err.responseJSON) {
      message = err.responseJSON.error;
    }
    $errorMsg.html(message);
  }

  function lookupName(token) {
    return {
      moleskine: 'Moleskine Types',
      dogs: 'Dog Breeds',
      insurance: 'Insurance Claims',
      omniearth: 'Satellite Imagery'
    }[token];
  }

  function lookupClassiferRealNameMap() {
    var classifierNameMapping = {};
    classifierNameMapping.dogs = {};
    classifierNameMapping.dogs.goldenretriever = 'Golden Retriever';
    classifierNameMapping.dogs.husky = 'Husky';
    classifierNameMapping.dogs.dalmatian = 'Dalmatian';
    classifierNameMapping.dogs.beagle = 'Beagle';
    classifierNameMapping.insurance = {};
    classifierNameMapping.insurance.brokenwinshield = 'Broken Windshield';
    classifierNameMapping.insurance.flattire = 'Flat Tire';
    classifierNameMapping.insurance.motorcycleaccident = 'Motorcycle Accident';
    classifierNameMapping.insurance.vandalism = 'Vandalism';
    classifierNameMapping.moleskine = {};
    classifierNameMapping.moleskine.journaling = 'Journaling';
    classifierNameMapping.moleskine.landscape = 'Landscape';
    classifierNameMapping.moleskine.notebook = 'Notebook';
    classifierNameMapping.moleskine.portrait = 'Portrait';
    classifierNameMapping.omniearth = {};
    classifierNameMapping.omniearth.baseball = 'Baseball';
    classifierNameMapping.omniearth.cars = 'Cars';
    classifierNameMapping.omniearth.golf = 'Golf';
    classifierNameMapping.omniearth.tennis = 'Tennis';
    return classifierNameMapping;
  }

  function getExamplesData() {
    return $('.showing div._examples--class__selected')
        .map(function(idx, item) {
          return {
            name: $(item).data('name'),
            realname: $(item).data('realname'),
            kind: $(item).data('kind')
          };
        })
        .toArray().reduce(function(k, v) {
          k.bundles.push(v.name);
          if (v.realname) {
            k.names.push(v.realname);
          }
          k.kind = v.kind;
          return k;
        }, {bundles: [], names: []});
  }

  function flashTrainedClassifer() {
    $('.train--trained-successfully').addClass('showing');
    setTimeout(function() {
      $('.train--trained-successfully').removeClass('showing');
    }, 3000);
  }

  function uploadBundledClass() {
    var data = getExamplesData();
    data.name = lookupName(data.kind);
    submitClassifier({
      data: JSON.stringify(data),
      bundle: data,
      contentType: 'application/json; charset=utf-8'
    });
  }

  function uploadUserClass() {
    var formElement = document.querySelector('form#user_upload');
    var form = new FormData(formElement);
    var bundle = { names: [$('.base--input._examples--input-name').val()], kind: 'user' };
    submitClassifier({
      data: form,
      bundle: bundle
    });
  }

  function submitClassifier(params) {
    $.ajax({
      type: 'POST',
      url: '/api/classifiers',
      data: params.data,
      contentType: params.contentType || false,
      processData: false,
      dataType: 'json',
      success: function(classifier) {
        setTimeout(function() {
          checkClassifier(classifier.classifier_id, function done() {
            Cookies.set('bundle', params.bundle, { expires: nextHour()});
            Cookies.set('classNameMap', lookupClassiferRealNameMap(), { expires: nextHour()});
            Cookies.set('classifier', classifier, { expires: nextHour()});
            resetPage();
            flashTrainedClassifer();
            scrollToElement($('.train--trained-successfully'), 65);
            $('.test--section').show();
            $('.test--classifier').text($('input.base--input._examples--input-name').val());
            showTestPanel(classifier);
          });
        }, 5000);
      },
      error: showTrainingError
    });
  }

  $trainButton.click(function() {
    $loading.show();
    $error.hide();
    $testSection.hide();

    scrollToElement($loading);

    if ($('.showing').data('kind') === 'user') {
      uploadUserClass();
    } else {
      uploadBundledClass();
    }
  });

  var classifierCheckPollInterval = 5000;
  var totalWaitingTime = 0;
  function checkClassifier(classifierId, done) {
    totalWaitingTime += classifierCheckPollInterval;
    $.get('/api/classifiers/' + classifierId)
    .success(function(data) {
      if (data.status === 'ready') {
        done(data);
      } else if (data.status === 'failed') {
        showTrainingError();
      } else {
        setTimeout(checkClassifier, classifierCheckPollInterval, classifierId, done);
      }
    })
    .fail(showTrainingError);
  }

  setupUse({ panel: 'use' });
  setupUse({ panel: 'test' });

  function showTestPanel(classifier) {
    // TODO: send classifier-id
    $('#test_classifier_id').val(classifier.classifier_id);
    $('.base--h2.test--classifier').text(classifier.name);
    $testSection.show();
  }

  var classifier = getAndParseCookieName('classifier');
  if (classifier) {
    showTestPanel(classifier);
  }
});
<commit_msg>Use random is removed for user trained<commit_after>/**
 * Copyright 2015 IBM Corp. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/* global Cookies:true */

'use strict';

var setupUse = require('./use.js');
var nextHour = require('./demo.js').nextHour;
var scrollToElement = require('./demo.js').scrollToElement;
var getAndParseCookieName = require('./demo.js').getAndParseCookieName;

// var currentPage = require('./demo.js').currentPage;

$(document).ready(function() {
  $('._training--example').click(function() {
    var currentExample = $(this);

    $('.showing div._examples--class__selected button').click();
    // clear all user classifier info
    $('.classifier').attr('data-hasfile', '0');

    var kind = $(this).data('kind');

    if ($('._examples[data-kind=' + kind + ']').hasClass('showing')) {
      $('.showing').removeClass('showing');
      $('._container--bundle-form').removeClass('active');
      $('._training--example').map(function(index, item) {
        $(item).css('opacity', '1.0');
        $(item).find('img').css('box-shadow', '0px 0px 0px 0px transparent');
        $(item).find('._training--use-your-own').css('box-shadow', '0px 0px 0px 0px transparent');
      });
    } else {
      $('._training--example').map(function(index, item) {
        if (!$(item).is(currentExample)) {
          $(item).css('opacity', '0.5');
          $(item).find('img').css('box-shadow', '0px 0px 0px 0px transparent');
          $(item).find('._training--use-your-own').css('box-shadow', '0px 0px 0px 0px transparent');
        } else {
          $(item).css('opacity', '1.0');
          $(item).find('img').css('box-shadow', '0px 0px 0px 3px #336588');
          $(item).find('._training--use-your-own').css('box-shadow', '0px 0px 0px 3px #336588');
        }
      });
      $('.showing').removeClass('showing');
      $('._examples[data-kind=' + kind + ']').removeClass('removed');
      $('._container--bundle-form input[type=submit]').addClass('disabled');
      $('._container--bundle-form input[type=submit]').prop('disabled', true);
      setTimeout(function() {
        $('.showing').addClass('removed');
        $('._examples[data-kind=' + kind + ']').addClass('showing');
        $('.train--row').addClass('showing');
        if (lookupName(kind)) {
          $('input.base--input._examples--input-name').val('Name of classifier: ' + lookupName(kind));
          $('input.base--input._examples--input-name').prop('readonly', true);
          $('input.base--input._examples--input-name').addClass('bundle');
        } else {
          $('input.base--input._examples--input-name').val('');
          $('input.base--input._examples--input-name').prop('readonly', false);
          $('input.base--input._examples--input-name').removeClass('bundle');
        }
        $('._container--bundle-form').addClass('active');
      }, 100);

      setTimeout(function() {
        scrollToElement($('._examples.showing'));
      }, 100);

      if ($(this).css('opacity') === '0.5') {
        $testSection.hide();
      }
    }
  });

  function warningMessagesVisability() {
    if ($('.classifier[data-hasfile=1]').length > 1) {
      $('.upload_message').hide();
      return true;
    } else {
      $('.upload_message').show();
      return false;
    }
  }

  function enableTrainClassifier() {
    var enable = $('.showing ._examples--class__selected._positive').length > 2;
    enable = enable || ($('.showing ._examples--class__selected._positive').length > 0 && $('.showing ._examples--class__selected._negative').length === 1 );
    enable = enable || warningMessagesVisability();

    // the name has to be filled out, too
    if (enable && $('.base--input._examples--input-name').val().length) {
      $('.train--train-button.base--button').removeClass('disabled');
      $('.train--train-button.base--button').prop('disabled', false);
    } else {
      $('.train--train-button.base--button').addClass('disabled');
      $('.train--train-button.base--button').prop('disabled', true);
    }
  }

  $('button[type=reset]').click(function() {
    if ($('.showing div._examples--class__selected button').length > 0) {
      $('.showing div._examples--class__selected button').click();
    } else {
      $('form.upload')[0].reset();
      if (!$('input.base--input._examples--input-name').prop('readonly')) {
        $('input.base--input._examples--input-name').val('');
        $('input.base--input._examples--input-name').prop('readonly', false);
      }
    }
    $testSection.hide();
    enableTrainClassifier();
  });

  $('._examples--class button').click(function() {
    if ($(this).parent().hasClass('_examples--class__selected')) {
      $(this).data('selected', 0);
      $(this).html('Select');
    } else {
      $(this).data('selected', 1);
      $(this).html('Deselect');
    }
    $(this).parent().toggleClass('_examples--class__selected');

    enableTrainClassifier();

    if ($.map($('._examples--class[data-kind=' + $(this).parent().data('kind') + '] button'), function(item) { return $(item).text(); }).reduce(function(k, v) { return k || v === 'Select'; }, false)) {
      $('a.select_all').text('Select All');
    }

    return false;
  });

  $('._examples--class img').click(function() {
    var contactSheet = $('._examples--contact-sheet[data-kind=' + $(this).data('kind') + ']');
    if ( $(this).css('box-shadow') === 'rgb(51, 101, 136) 0px 0px 0px 3px' && contactSheet.css('display') === 'flex') {
      contactSheet.hide();
    } else {
      $('._examples--class img').css('box-shadow', '0px 0px 0px 0px transparent');
      $(this).css('box-shadow', '0px 0px 0px 3px #336588');
      $(this).data('name');
      $('._examples--contact-sheet[data-kind=' + $(this).data('kind') + '] img').attr('src', '/images/bundles/' + $(this).data('kind') + '/' + $(this).data('name') + '-contact.jpg');
      contactSheet.css('display', 'flex');

      setTimeout(function() {
        scrollToElement(contactSheet);
      }, 100);
    }
  });

  $('._examples--contact-sheet img').click(function() {
    $(this).attr('src', '');
    $(this).parent().css('display', 'none');

    scrollToElement($('._examples.showing'));
  });

  $('a.select_all').click(function() {
    var currentText = $(this).text();
    if ($('.showing div._examples--class:not(._examples--class__selected)').length > 0) {
      $('.showing div._examples--class:not(._examples--class__selected) button').click();
    } else {
      $('.showing div._examples--class__selected button').click();
    }
    $(this).text(currentText === 'Select All' ? 'Deselect All' : 'Select All');
  });

  $('.classifier .text').on('click', function(e) {
    e.preventDefault();
    $(this).parent().find('input[type=file]').click();
  });

  $('.classifier input[type=file]').on('change', function(e) {
    var nameInput = $(e.target).parent().find('input[type=text]');
    if ($(e.target).length > 0 && ($(e.target)[0].files && $(e.target)[0].files.length > 0)) {
      if ($(e.target)[0].files[0].size > (5 * 1024 * 1024)) {
        // eslint-disable-next-line no-alert
        alert('This file exceeds the maximum size of 5 MB. Please choose another file');
      }
      var baseFileName = $(e.target)[0].files[0].name;
      nameInput.val(baseFileName.split('.')[0]);
      $(e.target).parent().attr('data-hasfile', 1);
      $(e.target).parent().find('.text-label').hide();
      $(e.target).parent().find('.text-zip-image').css('display', 'block');
      $(e.target).parent().find('.clear_link').show();
    }
  });

  $('.classifier a.clear_link').on('click', function(e) {
    e.preventDefault();
    $(e.target).parent().find('input').val('');
    $(e.target).parent().attr('data-hasfile', '0');
    $(e.target).parent().find('.text').find('.text-label').show();
    $(e.target).parent().find('.text').find('.text-zip-image').hide();
    $(e.target).parent().find('.clear_link').hide();
    enableTrainClassifier();
  });

  $('input[type=text].base--input._examples--input-name').on('input', function() {
    $('form.upload input[type=hidden][name=classifiername]').val($(this).val());
    enableTrainClassifier();
  });

  $('form.upload.training_dropzone').on('change', function() {
    enableTrainClassifier();
  });

  $('._examples--user-input').on('drop', function(e) {
    e.preventDefault();
  });

  var $loading = $('.train--loading');
  var $error = $('.train--error');
  var $errorMsg = $('.train--error-message');
  var $trainButton = $('.train--train-button');
  var $testSection = $('.test--section');

  function resetPage() {
    $loading.hide();
    $error.hide();
    $('.test--output.test--output-row').hide();
  }

  function showTrainingError(err) {
    $loading.hide();
    $error.show();
    var message = 'Error creating the classifier';
    if (err.responseJSON) {
      message = err.responseJSON.error;
    }
    $errorMsg.html(message);
  }

  function lookupName(token) {
    return {
      moleskine: 'Moleskine Types',
      dogs: 'Dog Breeds',
      insurance: 'Insurance Claims',
      omniearth: 'Satellite Imagery'
    }[token];
  }

  function lookupClassiferRealNameMap() {
    var classifierNameMapping = {};
    classifierNameMapping.dogs = {};
    classifierNameMapping.dogs.goldenretriever = 'Golden Retriever';
    classifierNameMapping.dogs.husky = 'Husky';
    classifierNameMapping.dogs.dalmatian = 'Dalmatian';
    classifierNameMapping.dogs.beagle = 'Beagle';
    classifierNameMapping.insurance = {};
    classifierNameMapping.insurance.brokenwinshield = 'Broken Windshield';
    classifierNameMapping.insurance.flattire = 'Flat Tire';
    classifierNameMapping.insurance.motorcycleaccident = 'Motorcycle Accident';
    classifierNameMapping.insurance.vandalism = 'Vandalism';
    classifierNameMapping.moleskine = {};
    classifierNameMapping.moleskine.journaling = 'Journaling';
    classifierNameMapping.moleskine.landscape = 'Landscape';
    classifierNameMapping.moleskine.notebook = 'Notebook';
    classifierNameMapping.moleskine.portrait = 'Portrait';
    classifierNameMapping.omniearth = {};
    classifierNameMapping.omniearth.baseball = 'Baseball';
    classifierNameMapping.omniearth.cars = 'Cars';
    classifierNameMapping.omniearth.golf = 'Golf';
    classifierNameMapping.omniearth.tennis = 'Tennis';
    return classifierNameMapping;
  }

  function getExamplesData() {
    return $('.showing div._examples--class__selected')
        .map(function(idx, item) {
          return {
            name: $(item).data('name'),
            realname: $(item).data('realname'),
            kind: $(item).data('kind')
          };
        })
        .toArray().reduce(function(k, v) {
          k.bundles.push(v.name);
          if (v.realname) {
            k.names.push(v.realname);
          }
          k.kind = v.kind;
          return k;
        }, {bundles: [], names: []});
  }

  function flashTrainedClassifer() {
    $('.train--trained-successfully').addClass('showing');
    setTimeout(function() {
      $('.train--trained-successfully').removeClass('showing');
    }, 3000);
  }

  function uploadBundledClass() {
    var data = getExamplesData();
    data.name = lookupName(data.kind);
    submitClassifier({
      data: JSON.stringify(data),
      bundle: data,
      contentType: 'application/json; charset=utf-8'
    });
  }

  function uploadUserClass() {
    var formElement = document.querySelector('form#user_upload');
    var form = new FormData(formElement);
    var bundle = { names: [$('.base--input._examples--input-name').val()], kind: 'user' };
    submitClassifier({
      data: form,
      bundle: bundle
    });
  }

  function submitClassifier(params) {
    $.ajax({
      type: 'POST',
      url: '/api/classifiers',
      data: params.data,
      contentType: params.contentType || false,
      processData: false,
      dataType: 'json',
      success: function(classifier) {
        setTimeout(function() {
          checkClassifier(classifier.classifier_id, function done() {
            Cookies.set('bundle', params.bundle, { expires: nextHour()});
            Cookies.set('classNameMap', lookupClassiferRealNameMap(), { expires: nextHour()});
            Cookies.set('classifier', classifier, { expires: nextHour()});
            resetPage();
            flashTrainedClassifer();
            scrollToElement($('.train--trained-successfully'), 65);
            $('.test--section').show();
            if (params.bundle.kind === 'user') {
              $('a.base--a.test--random-test-image').hide();
              $('input[type=text].test--url-input.base--input').attr('placeholder', 'Paste an image URL');
            } else {
              $('a.base--a.test--random-test-image').show();
              $('input[type=text].test--url-input.base--input').attr('placeholder', 'Or paste an image URL');
            }
            $('.test--classifier').text($('input.base--input._examples--input-name').val());
            showTestPanel(classifier);
          });
        }, 5000);
      },
      error: showTrainingError
    });
  }

  $trainButton.click(function() {
    $loading.show();
    $error.hide();
    $testSection.hide();

    scrollToElement($loading);

    if ($('.showing').data('kind') === 'user') {
      uploadUserClass();
    } else {
      uploadBundledClass();
    }
  });

  var classifierCheckPollInterval = 5000;
  var totalWaitingTime = 0;
  function checkClassifier(classifierId, done) {
    totalWaitingTime += classifierCheckPollInterval;
    $.get('/api/classifiers/' + classifierId)
    .success(function(data) {
      if (data.status === 'ready') {
        done(data);
      } else if (data.status === 'failed') {
        showTrainingError();
      } else {
        setTimeout(checkClassifier, classifierCheckPollInterval, classifierId, done);
      }
    })
    .fail(showTrainingError);
  }

  setupUse({ panel: 'use' });
  setupUse({ panel: 'test' });

  function showTestPanel(classifier) {
    // TODO: send classifier-id
    $('#test_classifier_id').val(classifier.classifier_id);
    $('.base--h2.test--classifier').text(classifier.name);
    $testSection.show();
  }

  var classifier = getAndParseCookieName('classifier');
  if (classifier) {
    showTestPanel(classifier);
  }
});
<|endoftext|>


<commit_before>/**
 * jquery.oscillator.1.0.js
 * A super simple jQuery extension that oscillates integer values between a max and min.
 * This plugin requires jQuery!
 *
 * Copyright (c) 2013 Caleb K Matthiesen <c@calebkm.com>
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use, copy,
 * modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 *
 * Example usage - oscillating body opacity:
 *
 * var myOscillator = new $.oscillator({ min: 0, max: 100, speed: 50 }, function(){
 *   $('body').css({ opacity: myOscillator.value/100 });
 * });
 *
 *
 *  See below for default options.
 *
 */

;(function($){
  $.oscillator = function(options, func){
    // oscillator
    var oscillator = this;

	  // defaults
	  this.defaults = {
		  min:   1,    // minimum value & starting value
		  max:   100,  // maximum value
		  speed: 1000, // increment speed
		  dir:   'up'  // initial increment direction: 'up' or 'down'
		};

		// merge options
		this.options = $.extend({}, this.defaults, options);

		// oscillator value and direction
		this.dir   = this.options.dir;
		this.value = this.options.min;

		// start interval
		var interval = setInterval(oscillate, oscillator.options.speed);

		// oscillation function
		function oscillate(){
			if (oscillator.dir == 'up'){
			  // increment value
			  oscillator.value++;
			  // if at max value, flip direction
			  if (oscillator.value >= oscillator.options.max){
			    oscillator.dir = 'down';
			  }
			} else {
			  // decrement value
				oscillator.value--;
				// if at min value, flip direction
				if (oscillator.value <= oscillator.options.min){
				  oscillator.dir = 'up';
				}
			};
			// call function, if given
			if (typeof func == 'function') func();
		};
	};
})(jQuery);<commit_msg>Removed ugly white space<commit_after>/**
 * jquery.oscillator.1.0.js
 * A super simple jQuery extension that oscillates integer values between a max and min.
 * This plugin requires jQuery!
 *
 * Copyright (c) 2013 Caleb K Matthiesen <c@calebkm.com>
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use, copy,
 * modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 *
 * Example usage - oscillating body opacity:
 *
 * var myOscillator = new $.oscillator({ min: 0, max: 100, speed: 50 }, function(){
 *   $('body').css({ opacity: myOscillator.value/100 });
 * });
 *
 *
 *  See below for default options.
 *
 */

;(function($){
  $.oscillator = function(options, func){
    // oscillator
    var oscillator = this;

    // defaults
    this.defaults = {
      min:   1,    // minimum value & starting value
      max:   100,  // maximum value
      speed: 1000, // increment speed
      dir:   'up'  // initial increment direction: 'up' or 'down'
    };

    // merge options
    this.options = $.extend({}, this.defaults, options);

    // oscillator value and direction
    this.dir   = this.options.dir;
    this.value = this.options.min;

    // start interval
    var interval = setInterval(oscillate, oscillator.options.speed);

    // oscillation function
    function oscillate(){
      if (oscillator.dir == 'up'){
        // increment value
        oscillator.value++;
        // if at max value, flip direction
        if (oscillator.value >= oscillator.options.max){
          oscillator.dir = 'down';
        }
      } else {
        // decrement value
        oscillator.value--;
        // if at min value, flip direction
        if (oscillator.value <= oscillator.options.min){
          oscillator.dir = 'up';
        }
      };
      // call function, if given
      if (typeof func == 'function') func();
    };
  };
})(jQuery);<|endoftext|>


<commit_before>/*jslint browser: true, nomen: true, todo: true */
(function ($, window, document) {
    'use strict';

    var P, Parallaxin, px, pct;

    px = function (n) { return {value: n, px: true}; };
    pct = function (n) { return {value: n, pct: true}; };

    P = Parallaxin = function () {};
    Parallaxin.instances = [];

    Parallaxin.prototype = {
        optionAttributePrefix: 'data-parallaxin-',

        defaultOptions: {
            // The container element. Defaults to the parent of the selected element.
            container: null,

            // Should the element move vertically?
            vertical: true,

            // Should the element move horizontally?
            horizontal: false,

            // Does the container change sizes?
            responsive: false,

            // Contrain the range of motion within the container. Can be a
            // string or array, specified in the order "top", "right", "bottom",
            // "left." If less than four values are provided, they will be
            // expanded like with CSS. For example, the following are all
            // equivalent: `0`, `'0'`, `'0 0'`, `'0 0 0 0'` `[0]`, `[0, 0]`,
            // `[0, 0, 0, 0]`. Percentage values are also allowed.
            insets: 0
        },

        initialize: function ($el, options) {
            this.$el = $el;
            this.options = $.extend(this.defaultOptions, this.getHtmlOptions(), options);
            if (this.options.container) {
                this.$container = $(this.options.container);
            } else {
                this.$container = this.$el.parent();
            }
            this._insets = this.parseInsets(this.options.insets);

            if (!P.$win) {
                P.$win = $(window);
            }
            if (!P._hasScrollHandler) {
                P._hasScrollHandler = true;
                P.$win.on('scroll', P.onScroll);
            }
            if (!P._hasResizeHandler && this.options.responsive) {
                P._hasResizeHandler = true;
                P.$win.on('resize', P.onWindowResize);
            }

            P.instances.push(this);
            this.update(false);
            return this;
        },

        destroy: function () {
            var index = P.instances.indexOf(this);
            P.instances.splice(index, 1);
            return this;
        },

        // Update the position of the element.
        update: function (r) {
            var
                recalculate = r !== false,
                recalculateContainerSize = recalculate,
                recalculateSize = recalculate,
                // TODO: Performance could be improved if there could be an option for setting this to false and a way to do it manually. (Gotta figure out a good name for the option.)
                recalculateContainerPosition = true,
                bounds = this._bounds,
                size = this._size,
                containerSize = this._containerSize,
                containerPosition = this._containerPosition,
                scrollPosition = P.getScrollPosition(),
                windowSize = P.getWindowSize(),
                css = {};

            if (recalculateContainerSize || !containerSize) {
                containerSize = this._containerSize = this.calculateElSize(this.$container);
                bounds = this._bounds = this.calculateBounds(this._insets, containerSize);
            }

            if (recalculateSize || !size) {
                size = this._size = this.calculateElSize(this.$el);
            }

            if (recalculateContainerPosition || !containerPosition) {
                // Unlike sizes, jQUery calculates both vertical and horizontal
                // positions with one measurement, so we can't do them
                // separately.
                containerPosition = this._containerPosition = this.$container.offset();
            }

            if (this.options.horizontal) {
                css.left = this.updatePosition(bounds.L, bounds.R,
                    containerPosition.left, containerSize.width, size.width,
                    scrollPosition.left, windowSize.width);
            }
            if (this.options.vertical) {
                css.top = this.updatePosition(bounds.T, bounds.B,
                    containerPosition.top, containerSize.height, size.height,
                    scrollPosition.top, windowSize.height);
            }

            if (css.left !== undefined || css.top !== undefined) {
                this.$el.css(css);
            }
        },

        updatePosition: function (boundsMin, boundsMax, containerPosition, containerSize, elSize, scrollPosition, windowSize) {
            // When the container is at the top of the viewport (min scrollTop),
            // $el should be aligned to its top. When the container is at the
            // bottom of the viewport (max scrollTop), $el should be aligned to
            // the bottom.
            var min, max, pct, targetMin, targetMax, pos;

            if (containerPosition + containerSize < scrollPosition) {
                // Container is above viewport.
                return undefined;
            }
            if (containerPosition > scrollPosition + windowSize) {
                // Container is below viewport.
                return undefined;
            }

            if (elSize <= windowSize) {
                max = containerPosition;
                min = containerPosition + containerSize - windowSize;
                targetMin = boundsMax - elSize;
                targetMax = boundsMin;
            } else {
                min = containerPosition - windowSize;
                max = containerPosition + containerSize;
                targetMin = boundsMin - elSize;
                targetMax = boundsMax;
            }

            pct = (scrollPosition - min) / (max - min);
            pos = targetMin + pct * (targetMax - targetMin);
            return pos;
        },

        calculateElSize: function ($el) {
            var size = {};
            if (this.options.horizontal) {
                size.width = $el.outerWidth();
            }
            if (this.options.vertical) {
                size.height = $el.outerHeight();
            }
            return size;
        },

        calculateBound: function (inset, size, fromOpposite) {
            if (inset.pct) {
                return this.calculateBound(px(inset.value * size), size, fromOpposite);
            }
            if (fromOpposite) {
                return size - inset.value;
            }
            return inset.value;
        },

        // Convert parsed insets into actual pixel positions based on the size
        // of the container.
        calculateBounds: function (insets, containerSize) {
            var bounds = {};
            if (this.options.horizontal) {
                bounds.R = this.calculateBound(insets.R, containerSize.width);
                bounds.L = this.calculateBound(insets.L, containerSize.width, true);
            }
            if (this.options.vertical) {
                bounds.T = this.calculateBound(insets.T, containerSize.height);
                bounds.B = this.calculateBound(insets.B, containerSize.height, true);
            }
            return bounds;
        },

        parseInset: function (val) {
            switch ($.type(val)) {
            case 'number':
                return px(val);
            case 'string':
                if (val.indexOf('%') > -1) {
                    return pct(parseFloat(val) / 100);
                }
                return px(parseInt(val, 10));
            }
        },

        // Parse inset options into numbers and units corresponding to each
        // side.
        parseInsets: function (val) {
            var parsed, a, v, h, t, r, b, l;

            switch ($.type(val)) {
            case 'number':
                return {T: px(val), R: px(val), B: px(val), L: px(val)};
            case 'array':
                switch (val.length) {
                case 1:
                    a = this.parseInset(val[0]);
                    return {T: a, R: a, B: a, L: a};
                case 2:
                    v = this.parseInset(val[0]);
                    h = this.parseInset(val[1]);
                    return {T: v, R: h, B: v, L: h};
                case 4:
                    t = this.parseInset(val[0]);
                    r = this.parseInset(val[1]);
                    b = this.parseInset(val[2]);
                    l = this.parseInset(val[4]);
                    return {T: t, R: r, B: b, L: l};
                }
                break;
            case 'string':
                return this.parseInsets(val.replace(/^\s+|\s+$/, '').split(/\s+/));
            }
        },

        getHtmlOptions: function () {
            var self = this,
                opts = {};
            $.each(this.$el[0].attributes, function (i, attr) {
                if (attr.name.indexOf(self.optionAttributePrefix) !== -1) {
                    opts[attr.name.substr(self.optionAttributePrefix.length)] = attr.value;
                }
            });
            return opts;
        }
    };

    Parallaxin.getScrollPosition = function (recalculate) {
        if (recalculate || !P._scrollPosition) {
            P._scrollPosition = {
                top: P.$win.scrollTop(),
                left: P.$win.scrollLeft()
            };
        }
        return P._scrollPosition;
    };

    Parallaxin.getWindowSize = function (recalculate) {
        if (recalculate || !P._windowSize) {
            P._windowSize = {
                width: P.$win.width(),
                height: P.$win.height()
            };
        }
        return P._windowSize;
    };

    Parallaxin.onScroll = function () {
        var i, instance,
            oldPos = P._scrollPosition,
            pos = P.getScrollPosition(true),
            topChanged = !oldPos || oldPos.top !== pos.top,
            leftChanged = !oldPos || oldPos.top !== pos.top;
        for (i = P.instances.length - 1; i >= 0; i -= 1) {
            instance = P.instances[i];
            if ((topChanged && instance.options.vertical) || (leftChanged && instance.options.horizontal)) {
                instance.update(false);
            }
        }
    };

    Parallaxin.onWindowResize = function () {
        var i, instance;
        P.getWindowSize(true);
        for (i = P.instances.length - 1; i >= 0; i -= 1) {
            instance = P.instances[i];
            if (instance.options.responsive) {
                instance.update();
            }
        }
    };

    $.extend($.fn, {
        parallaxin: function (optionsOrMethod) {
            var returnValue = this,
                args = arguments;
            this.each(function (i, el) {
                var $el = $(el),
                    plugin = $el.data('parallaxin'),
                    method = typeof optionsOrMethod === 'string' ? optionsOrMethod : null,
                    options = method === null ? optionsOrMethod || {} : {};

                if (!plugin) {
                    if (method) {
                        $.error('You can\'t call the parallaxin method "' + method
                                + '" without first initializing the plugin by calling '
                                + 'parallaxin() on the jQuery object.');
                    } else {
                        plugin = new Parallaxin().initialize($el, options);
                        $el.data('parallaxin', plugin);
                    }
                } else if (method) {
                    if (typeof plugin[method] !== 'function') {
                        $.error('Method "' + method + '" does not exist on jQuery.parallaxin');
                    } else {
                        // NOTE: If you call a method that returns a value, you will only get the result from the last item in the collection.
                        returnValue = plugin[method].apply(plugin, Array.prototype.slice.call(args, 1));
                    }
                }
            });
            return returnValue;
        }
    });
}(this.jQuery, window, document));
<commit_msg>Add "fixed" and "hideOnExit" options<commit_after>/*jslint browser: true, nomen: true, todo: true */
(function ($, window, document) {
    'use strict';

    var P, Parallaxin, px, pct;

    px = function (n) { return {value: n, px: true}; };
    pct = function (n) { return {value: n, pct: true}; };

    P = Parallaxin = function () {};
    Parallaxin.instances = [];

    Parallaxin.prototype = {
        optionAttributePrefix: 'data-parallaxin-',

        defaultOptions: {
            // The container element. Defaults to the parent of the selected element.
            container: null,

            // Should the element move vertically?
            vertical: true,

            // Should the element move horizontally?
            horizontal: false,

            // Does the container change sizes?
            responsive: false,

            // Should the element use fixed positioning? The default value
            // depends on whether the element is styles as "position: fixed"
            // at the time the plugin is initialized, so normally you shouldn't
            // need to set this option; just set "position: fixed" in your
            // stylesheet.
            //
            // Using fixed positioning means the element is positioned relative
            // to the document instead of its parent and can result in a much
            // smoother parallax effect.
            fixed: null,

            // Should the element be hidden when its container leaves the
            // viewport? This helps to eliminate z-index issues when using fixed
            // positioning and multiple parallaxin elements.
            hideOnExit: true,

            // Contrain the range of motion within the container. Can be a
            // string or array, specified in the order "top", "right", "bottom",
            // "left." If less than four values are provided, they will be
            // expanded like with CSS. For example, the following are all
            // equivalent: `0`, `'0'`, `'0 0'`, `'0 0 0 0'` `[0]`, `[0, 0]`,
            // `[0, 0, 0, 0]`. Percentage values are also allowed.
            insets: 0
        },

        initialize: function ($el, options) {
            var isFixed;

            this.$el = $el;
            this.options = $.extend(this.defaultOptions, this.getHtmlOptions(), options);
            if (this.options.container) {
                this.$container = $(this.options.container);
            } else {
                this.$container = this.$el.parent();
            }
            this._insets = this.parseInsets(this.options.insets);

            isFixed = $el.css('position') === 'fixed';
            if (this.options.fixed === null || this.options.fixed === undefined) {
                this.options.fixed = isFixed;
            }
            if (this.options.fixed && !isFixed) {
                this.$el.css('position', 'fixed');
            }

            if (!P.$win) {
                P.$win = $(window);
            }
            if (!P._hasScrollHandler) {
                P._hasScrollHandler = true;
                P.$win.on('scroll', P.onScroll);
            }
            if (!P._hasResizeHandler && this.options.responsive) {
                P._hasResizeHandler = true;
                P.$win.on('resize', P.onWindowResize);
            }

            P.instances.push(this);
            this.update(false);
            return this;
        },

        destroy: function () {
            var index = P.instances.indexOf(this);
            P.instances.splice(index, 1);
            return this;
        },

        // Update the position of the element.
        update: function (r) {
            var
                shouldHide,
                recalculate = r !== false,
                recalculateContainerSize = recalculate,
                recalculateSize = recalculate,
                // TODO: Performance could be improved if there could be an option for setting this to false and a way to do it manually. (Gotta figure out a good name for the option.)
                recalculateContainerPosition = true,
                bounds = this._bounds,
                size = this._size,
                containerSize = this._containerSize,
                containerPosition = this._containerPosition,
                scrollPosition = P.getScrollPosition(),
                windowSize = P.getWindowSize(),
                css = {};

            if (recalculateContainerSize || !containerSize) {
                containerSize = this._containerSize = this.calculateElSize(this.$container);
                bounds = this._bounds = this.calculateBounds(this._insets, containerSize);
            }

            if (recalculateSize || !size) {
                size = this._size = this.calculateElSize(this.$el, this._isHidden);
            }

            if (recalculateContainerPosition || !containerPosition) {
                // Unlike sizes, jQUery calculates both vertical and horizontal
                // positions with one measurement, so we can't do them
                // separately.
                containerPosition = this._containerPosition = this.$container.offset();
            }

            if (this.options.horizontal) {
                css.left = this.updatePosition(bounds.L, bounds.R,
                    containerPosition.left, containerSize.width, size.width,
                    scrollPosition.left, windowSize.width);
            }
            if (this.options.vertical) {
                css.top = this.updatePosition(bounds.T, bounds.B,
                    containerPosition.top, containerSize.height, size.height,
                    scrollPosition.top, windowSize.height);
            }

            if (this.options.hideOnExit) {
                shouldHide = (!this.options.horizontal || css.left === undefined) &&
                    (!this.options.vertical || css.top === undefined);
                if (shouldHide !== !!this._isHidden) {
                    this.$el[shouldHide ? 'hide' : 'show']();
                    this._isHidden = shouldHide;
                }
            }

            if (css.left !== undefined || css.top !== undefined) {
                this.$el.css(css);
            }
        },

        updatePosition: function (boundsMin, boundsMax, containerPosition, containerSize, elSize, scrollPosition, windowSize) {
            // When the container is at the top of the viewport (min scrollTop),
            // $el should be aligned to its top. When the container is at the
            // bottom of the viewport (max scrollTop), $el should be aligned to
            // the bottom.
            var min, max, pct, targetMin, targetMax, pos;

            if (containerPosition + containerSize < scrollPosition) {
                // Container is above viewport.
                return undefined;
            }
            if (containerPosition > scrollPosition + windowSize) {
                // Container is below viewport.
                return undefined;
            }

            if (elSize <= windowSize) {
                max = containerPosition;
                min = containerPosition + containerSize - windowSize;
                targetMin = boundsMax - elSize;
                targetMax = boundsMin;
            } else {
                min = containerPosition - windowSize;
                max = containerPosition + containerSize;
                targetMin = boundsMin - elSize;
                targetMax = boundsMax;
            }

            pct = (scrollPosition - min) / (max - min);
            pos = targetMin + pct * (targetMax - targetMin);

            if (this.options.fixed) {
                // Make the positioin relative to the document instead of the
                // container.
                pos += containerPosition - scrollPosition;
            }

            return pos;
        },

        calculateElSize: function ($el, isHidden) {
            var size = {};
            if (isHidden) {
                $el.show();
            }
            if (this.options.horizontal) {
                size.width = $el.outerWidth();
            }
            if (this.options.vertical) {
                size.height = $el.outerHeight();
            }
            if (isHidden) {
                $el.hide();
            }
            return size;
        },

        calculateBound: function (inset, size, fromOpposite) {
            if (inset.pct) {
                return this.calculateBound(px(inset.value * size), size, fromOpposite);
            }
            if (fromOpposite) {
                return size - inset.value;
            }
            return inset.value;
        },

        // Convert parsed insets into actual pixel positions based on the size
        // of the container.
        calculateBounds: function (insets, containerSize) {
            var bounds = {};
            if (this.options.horizontal) {
                bounds.R = this.calculateBound(insets.R, containerSize.width);
                bounds.L = this.calculateBound(insets.L, containerSize.width, true);
            }
            if (this.options.vertical) {
                bounds.T = this.calculateBound(insets.T, containerSize.height);
                bounds.B = this.calculateBound(insets.B, containerSize.height, true);
            }
            return bounds;
        },

        parseInset: function (val) {
            switch ($.type(val)) {
            case 'number':
                return px(val);
            case 'string':
                if (val.indexOf('%') > -1) {
                    return pct(parseFloat(val) / 100);
                }
                return px(parseInt(val, 10));
            }
        },

        // Parse inset options into numbers and units corresponding to each
        // side.
        parseInsets: function (val) {
            var parsed, a, v, h, t, r, b, l;

            switch ($.type(val)) {
            case 'number':
                return {T: px(val), R: px(val), B: px(val), L: px(val)};
            case 'array':
                switch (val.length) {
                case 1:
                    a = this.parseInset(val[0]);
                    return {T: a, R: a, B: a, L: a};
                case 2:
                    v = this.parseInset(val[0]);
                    h = this.parseInset(val[1]);
                    return {T: v, R: h, B: v, L: h};
                case 4:
                    t = this.parseInset(val[0]);
                    r = this.parseInset(val[1]);
                    b = this.parseInset(val[2]);
                    l = this.parseInset(val[4]);
                    return {T: t, R: r, B: b, L: l};
                }
                break;
            case 'string':
                return this.parseInsets(val.replace(/^\s+|\s+$/, '').split(/\s+/));
            }
        },

        getHtmlOptions: function () {
            var self = this,
                opts = {};
            $.each(this.$el[0].attributes, function (i, attr) {
                if (attr.name.indexOf(self.optionAttributePrefix) !== -1) {
                    opts[attr.name.substr(self.optionAttributePrefix.length)] = attr.value;
                }
            });
            return opts;
        }
    };

    Parallaxin.getScrollPosition = function (recalculate) {
        if (recalculate || !P._scrollPosition) {
            P._scrollPosition = {
                top: P.$win.scrollTop(),
                left: P.$win.scrollLeft()
            };
        }
        return P._scrollPosition;
    };

    Parallaxin.getWindowSize = function (recalculate) {
        if (recalculate || !P._windowSize) {
            P._windowSize = {
                width: P.$win.width(),
                height: P.$win.height()
            };
        }
        return P._windowSize;
    };

    Parallaxin.onScroll = function () {
        var i, instance,
            oldPos = P._scrollPosition,
            pos = P.getScrollPosition(true),
            topChanged = !oldPos || oldPos.top !== pos.top,
            leftChanged = !oldPos || oldPos.top !== pos.top;
        for (i = P.instances.length - 1; i >= 0; i -= 1) {
            instance = P.instances[i];
            if ((topChanged && instance.options.vertical) || (leftChanged && instance.options.horizontal)) {
                instance.update(false);
            }
        }
    };

    Parallaxin.onWindowResize = function () {
        var i, instance;
        P.getWindowSize(true);
        for (i = P.instances.length - 1; i >= 0; i -= 1) {
            instance = P.instances[i];
            if (instance.options.responsive) {
                instance.update();
            }
        }
    };

    $.extend($.fn, {
        parallaxin: function (optionsOrMethod) {
            var returnValue = this,
                args = arguments;
            this.each(function (i, el) {
                var $el = $(el),
                    plugin = $el.data('parallaxin'),
                    method = typeof optionsOrMethod === 'string' ? optionsOrMethod : null,
                    options = method === null ? optionsOrMethod || {} : {};

                if (!plugin) {
                    if (method) {
                        $.error('You can\'t call the parallaxin method "' + method
                                + '" without first initializing the plugin by calling '
                                + 'parallaxin() on the jQuery object.');
                    } else {
                        plugin = new Parallaxin().initialize($el, options);
                        $el.data('parallaxin', plugin);
                    }
                } else if (method) {
                    if (typeof plugin[method] !== 'function') {
                        $.error('Method "' + method + '" does not exist on jQuery.parallaxin');
                    } else {
                        // NOTE: If you call a method that returns a value, you will only get the result from the last item in the collection.
                        returnValue = plugin[method].apply(plugin, Array.prototype.slice.call(args, 1));
                    }
                }
            });
            return returnValue;
        }
    });
}(this.jQuery, window, document));
<|endoftext|>