<commit_before>var Face = {
    init: function() {
        this._initPopup();
        this._initControls();
    },

    _popup: null,
    _sound: null,

    _initPopup: function() {
        this._popup = $('.popup-gallery').magnificPopup({
            delegate: '.mfp-image',
            type: 'image',

            tLoading: 'Loading image #%curr%...',
            mainClass: 'mfp-album-popup',

            gallery: {
                arrowMarkup: '',
                enabled: true,
                navigateByImgClick: true,
                preload: [0, 2],
            },

            image: {
                cursor: null,
                tError: 'The image #%curr% could not be loaded.',

                titleSrc: $.proxy(function (item) {
                    var slideshow = this._popup.data('slideshow');
                    var icon = slideshow ? "pause" : "play";
                    var el = item.data.el;
                    return '
'+
                        el.attr('data-face-details') +
                        '
'
                }, this),

                markup: '
'+
                            '

'+
                            '
'+
                                '

'+
                            '
'+
                            '
'+
                                '

'+
                                '

'+
                            '
'+
                        '
'
            },
            closeBtnInside: true,
            callbacks: {
                updateStatus: $.proxy(function () {
                    this._initImage();
                }, this),
                close: $.proxy(function () {
                    this._popup.removeData('slideshow');
		                history.pushState(null, null, $(".popup-gallery").data("url"));
                }, this),
		            open: function() {
		                var mfp = $.magnificPopup.instance;
		                var proto = $.magnificPopup.proto;

		                // extend function that moves to next item
		                mfp.next = function() {

			                  // if index is not last, call parent method
			                  if(mfp.index < mfp.items.length - 1) {
			                      proto.next.call(mfp);
			                      history.pushState(null, null, $($(".mfp-image")[mfp.index]).data("url"));
			                  } else {
			                      // otherwise do whatever you want, e.g. hide "next" arrow
			                      proto.close();
			                  }
		                };

		                // same with prev method
		                mfp.prev = function() {
			                  if(mfp.index > 0) {
			                      proto.prev.call(mfp);
			                      history.pushState(null, null, $($(".mfp-image")[mfp.index]).data("url"));
			                  }
		                };
		            }
            }
        });
        $.magnificPopup.instance.updateItemHTML = function() {
            var $this = this;
            var items = [];
            $.each($this.items, function(ii, item) {
                items.push({
                    src: $($("a.mfp-image")[ii]).attr("data-original-image-src"),
                    el: $($(".mfp-image")[ii])
                });
            });
            $this.items = items;
            $.magnificPopup.proto.updateItemHTML.call($this);
        }
    },

    _updateSlideshowButtonIcon: function () {
        var slideshow = this._popup.data('slideshow');
        var slideshowButton = $('.btn-slideshow i');
        if(slideshow) {
            slideshowButton.addClass('fa fa-pause');
            slideshowButton.removeClass('fa fa-play');
        } else {
            slideshowButton.addClass('fa fa-play');
            slideshowButton.removeClass('fa fa-pause');

        }

    },

    _initControls: function() {
        $('.album-controls').click($.proxy(function () {
            this._popup.data('slideshow', 'true');
            this._popup.magnificPopup('open');
        }, this));
    },

    _initImage: function() {
        $('.btn-fullscreen').on('click', function() {
            $('.mfp-container').addClass('mfp-container-fullscreen');
            return false;
        });

        $('.btn-slideshow').on('click', $.proxy(function() {
            var slideshow = this._popup.data("slideshow");
            if(slideshow) {
                this._popup.removeData('slideshow');
            } else {
                this._popup.data('slideshow', 'true');
            }

            this._updateSlideshowButtonIcon();

            return false;
        }, this));

        $('.mfp-figure').on('click', function() {
            $('.mfp-container').removeClass('mfp-container-fullscreen');
        });

	      var mfp = $.magnificPopup.instance;
	      history.pushState(null, null, $($(".mfp-image")[mfp.index]).data("url"));
    }

}

$(function() {
    Face.init();

    $(window).on("popstate", function() {
	      $('a[data-url="' + location.pathname + '"]').click();
    });
});
<commit_msg>#60 [Vinod/Lokesh] Fixed scrollable issue for faces viewer<commit_after>var Face = {
    init: function () {
        this._initPopup();
        this._initControls();
    },

    _popup: null,
    _sound: null,

    _initPopup: function () {
        this._popup = $('.popup-gallery').magnificPopup({
            delegate: '.mfp-image',
            type: 'image',

            tLoading: 'Loading image #%curr%...',
            mainClass: 'mfp-album-popup',

            gallery: {
                arrowMarkup: '',
                enabled: true,
                navigateByImgClick: true,
                preload: [0, 2],
            },

            image: {
                cursor: null,
                tError: 'The image #%curr% could not be loaded.',

                titleSrc: $.proxy(function (item) {
                    var slideshow = this._popup.data('slideshow');
                    var icon = slideshow ? "pause" : "play";
                    var el = item.data.el;
                    return '
' +
                        el.attr('data-face-details') +
                        '
'
                }, this),

                markup: '
' +
                '

' +
                '
' +
                '

' +
                '
' +
                '
' +
                '

' +
                '

' +
                '
' +
                '
'
            },
            closeBtnInside: true,
            callbacks: {
                updateStatus: $.proxy(function () {
                    this._initImage();
                }, this),
                close: $.proxy(function () {
                    this._popup.removeData('slideshow');
                    history.pushState(null, null, $(".popup-gallery").data("url"));
                    console.log("closed");
                    $(document).attr("overflow", "auto");
                }, this),
                open: function () {
                    var mfp = $.magnificPopup.instance;
                    var proto = $.magnificPopup.proto;

                    // extend function that moves to next item
                    mfp.next = function () {

                        // if index is not last, call parent method
                        if (mfp.index < mfp.items.length - 1) {
                            proto.next.call(mfp);
                            history.pushState(null, null, $($(".mfp-image")[mfp.index]).data("url"));
                        } else {
                            // otherwise do whatever you want, e.g. hide "next" arrow
                            proto.close();
                        }
                    };

                    // same with prev method
                    mfp.prev = function () {
                        if (mfp.index > 0) {
                            proto.prev.call(mfp);
                            history.pushState(null, null, $($(".mfp-image")[mfp.index]).data("url"));
                        }
                    };
                    $(document).attr("overflow", "hidden");
                }
            }
        });
        $.magnificPopup.instance.updateItemHTML = function () {
            var $this = this;
            var items = [];
            $.each($this.items, function (ii, item) {
                items.push({
                    src: $($("a.mfp-image")[ii]).attr("data-original-image-src"),
                    el: $($(".mfp-image")[ii])
                });
            });
            $this.items = items;
            $.magnificPopup.proto.updateItemHTML.call($this);
        }
    },

    _updateSlideshowButtonIcon: function () {
        var slideshow = this._popup.data('slideshow');
        var slideshowButton = $('.btn-slideshow i');
        if (slideshow) {
            slideshowButton.addClass('fa fa-pause');
            slideshowButton.removeClass('fa fa-play');
        } else {
            slideshowButton.addClass('fa fa-play');
            slideshowButton.removeClass('fa fa-pause');

        }

    },

    _initControls: function () {
        $('.album-controls').click($.proxy(function () {
            this._popup.data('slideshow', 'true');
            this._popup.magnificPopup('open');
        }, this));
    },

    _initImage: function () {
        $('.btn-fullscreen').on('click', function () {
            $('.mfp-container').addClass('mfp-container-fullscreen');
            return false;
        });

        $('.btn-slideshow').on('click', $.proxy(function () {
            var slideshow = this._popup.data("slideshow");
            if (slideshow) {
                this._popup.removeData('slideshow');
            } else {
                this._popup.data('slideshow', 'true');
            }

            this._updateSlideshowButtonIcon();

            return false;
        }, this));

        $('.mfp-figure').on('click', function () {
            $('.mfp-container').removeClass('mfp-container-fullscreen');
        });

        var mfp = $.magnificPopup.instance;
        history.pushState(null, null, $($(".mfp-image")[mfp.index]).data("url"));
    }

}

$(function () {
    Face.init();

    $(window).on("popstate", function () {
        $('a[data-url="' + location.pathname + '"]').click();
    });
});
<|endoftext|>


<commit_before>/* di.whtnDice is an opensource project to study the legendary dice curse
 * of Wil Wheaton
 * and get to the bottom of bad juju. At the moment,
 * it's just a dice roller, but later
 * functions will include a rolls database that can track
 * any sinking feeling that the kind of
 * cheetos you're eating is influencing your rolls.
 * Also v.1.0 is aiming at 5th edition D&D rules
 * usage. Later versions will be more system agnostic.
 * This is intended for mobile release, but
 * for now, this is just the engine. Minus the actual engine.
 * Broad strokes to get the system
 * working. Much to be built! -Ian
 */

//the dice object
var di = {  nmbr:undefined,
    	    sids:undefined,
    	    rols:undefined,
    	    totl:undefined,
    	    whtn:undefined,
    	    insn:'Sanity Error!'
	    //todo: getters and setters
	};

//saved rolls go here so they can be accessed and analyzed
//(unitl a proper DB is made)
//currnet version forgets after the battery of console.log()s are made.
//Need a proper DB,
//but this is proof of concept. todo: db that can store previous rolls.
var rolDB = [];

//checks to make sure user input values make sense.
//auto corrects in certain cases.
function rollSanity(di) {
    //isInt borrowed from http://stackoverflow.com/questions/14636536
    function isInt(value) {
	var x;
	return isNaN(value)?!1:(x=parseFloat(value),(0|x)===x);
    }

    if (di.nmbr === undefined) {
	di.insn = 'The outcome of your undefined number of dice\n'+
		'with between zero and infinity number of sides each\n'+
		'rolls unobserved in a mixed state of quantum flux\n'+
		'forever both Percy and Wheaton, like that poor cat.\n'+
		'Thus it remains with the Tao that cannot be told.\n\n'+
		'Please define the number of dice and their sides\n'+
		'if you prefer your rolls collapsed, measurable and pure.';
    } else if (di.nmbr === 0) {
	di.insn = '    If zero dice are thrown in simulation,\n'+
		'Even if someone is there to observe the outcome -\n'+
		'    Do they still roll poorly for Wil Wheaton?';
    } else if (di.sids === undefined) {
	di.sids = di.nmbr;
	di.nmbr = 1;
	di.insn = undefined;
    } else if (di.sids === 0) {
	di.insn = 'Zero sides?! Is it even there?!';
    } else if (di.sids === 1) {
	di.insn = 'Ok, Escher-trippiness of a one-sided dice aside,\n'+
		'Exactly how did you not know the outcome of this roll?';
    } else if (!(isInt(di.nmbr)) || !(isInt(di.sids))) {
	di.insn = 'Please make sure you entered integers\n'+
	      'for the number of dice and how many sides they have'
    } else {
	di.insn = undefined;
    }
}

/*the physics engine
(to be built: a different abstract function than builtin Math.random().
It will access the device's accelerometer and add physics + chaos
to generate the roll.
it'll be totally sweet!*/
function physics(di) {

    var rolls = [];

    for (var i = 0; i < di.nmbr; i++) {
	    rolls.push(Math.ceil( Math.random() * di.sids ));
    }

    di.rols = rolls;

    var totally = rolls.reduce(function(a ,b) {
	return a + b;
    });

    di.totl = totally;
}

//timeStamp() acts as a serial number for the roll in rolDB.
function timeStamp() {
    var rollTime = new Date();
    return rollTime.getTime();
}

//passes roll results to rolDB.
function rolDBize(di, rolDB) {
    var rollEntry = [],

    rollEntry = [timeStamp(), di.nmbr, di.sids, di.rols, di.totl];

    rolDB.push(rollEntry);
}
/* Phasing out CLI display

//make it so every lowest possible roll that's rolled displays "Wheaton!"
    //instead of the number
//Not used unless in CLI
function whtnize(di) {
    if (di.totl === di.nmbr) {
	di.whtn = 'Wheaton!';
    } else if (di.totl < (0.33 * (di.nmbr * di.sids))){
	di.whtn = 'lesser Wheaton.';
    } else if (di.totl === (di.nmbr * di.sids)) {
	di.whtn = 'Percy!';
    } else if (di.totl > (0.66 * (di.nmbr * di.sids))) {
	di.whtn = 'lesser Percy.';
    } else {
	di.whtn = '';
    }
}

//returns a neat string that shows what you rolled, and the total.
//Not used unless in CLI
function rollOut(di) {
    return (di.nmbr + " d" + di.sids + ": " + di.rols.join(", ") +
	       " Total: " + di.totl + " " +  di.whtn);
}
*/

//the main simple dice roll manager
function dice(dNum, dSid) {
    di.nmbr = dNum;
    di.sids = dSid;

    rollSanity(di);
    if (di.insn) { return di.insn;
    } else {

	physics(di);
	di.nmbr = 'R';
	rolDBize(di, rolDB);
	//whtnize(di);
	//return rollOut(di); //for CLI
	return di.totl;
    }
}

/*Mixed dice rolls. There are 6 Standard dice in D&D.
d4, d6, d8, d10, d12, and d20. It would be quite unusual for all these
types of dice to be rolled at the same time, but just in case,
rollMix will be able to handle up to 6 different kinds of dice rolls. */
function rollTgethr(dNum1, dSid1, dNum2, dSid2, dNum3, dSid3,
		    dNum4, dSid4, dNum5, dSid5, dNum6, dSid6) {
    var allRolls = [],
	//allDice = [],
	allTotal = 0;
    //var allWhton = "", //for CLI
	//displayString; //for CLI
/*
    function countWils() { //for CLI
	var lowest = dNum1 + dNum2 + dNum3 + dNum4 + dNum5 + dNum6,
	    highest = dNum1 * dSid1;

	if (dNum2 && dSid2) { highest += dNum2 * dSid2 }
	if (dNum3 && dSid3) { highest += dNum3 * dSid3 }
	if (dNum4 && dSid4) { highest += dNum4 * dSid4 }
	if (dNum5 && dSid5) { highest += dNum5 * dSid5 }
	if (dNum6 && dSid6) { highest += dNum6 * dSid6 }

	if (allTotal === lowest) {
	    allWhton = "Wheaton!";
	}
	else if (allTotal < 0.33 * highest) {
	    allWhton = "Lesser Wheaton.";
	}
	else if (allTotal === highest) {
	    allWhton = "Percy!";
	}
	else if (allTotal > 0.66 * highest) {
	    allWhton = "Lesser Percy.";
	}
    }
*/
    function theRoll(dNum, dSid) {
	di.nmbr = dNum;
	di.sids = dSid;
	rollSanity(di)
	if (di.insn) {
	    return di.insn;
	} else {
	    physics(di);
	    di.nmbr = 'T';
	    rolDBize(di, rolDB);
   	    //allDice.push(dNum + " d" + dSid);
	    for (var i = 0; i < di.rols.length; i++) {
		allRolls.push(di.rols[i]);
	    }
	}
    }

    theRoll(dNum1, dSid1);

    if (dNum2) { theRoll(dNum2, dSid2); }
    if (dNum3) { theRoll(dNum3, dSid3); }
    if (dNum4) { theRoll(dNum4, dSid4); }
    if (dNum5) { theRoll(dNum5, dSid5); }
    if (dNum6) { theRoll(dNum6, dSid6); }

    allTotal = allRolls.reduce(function(a ,b) {
	return a + b;
    });

    //countWils(); //For CLI

    //displayString = (allDice.join(", ") + ": " + allRolls.join(", ") +
    //		     " Total: " + allTotal + " " + allWhton); //for CLI

    //return displayString; //for CLI, a lot of unused code in rollMix
    return allTotal;
}

//Special kinds of D&D rolls, Advantage, Disadvantage, Percent, Inspiration and mixed rolls.
function rollHigh(dNum, dSid) {
    di.nmbr = dNum;
    di.sids = dSid;
    physics(di);
    di.nmbr = 1;
    di.totl = Math.max.apply(null, di.rols);
    //whtnize(di);
    di.nmbr = 'H';
    rolDBize(di, rolDB);
    //return rollOut(di); //for CLI
    return di.totl;
}

function rollLow(dNum, dSid) {
    di.nmbr = dNum;
    di.sids = dSid;
    physics(di);
    di.nmbr = 1;
    di.totl = Math.min.apply(null, di.rols);
    //whtnize(di);
    di.nmbr = 'L';
    rolDBize(di, rolDB);
    //return rollOut(di); //for CLI
    return di.totl;
}

//each dNum is a digit in a base dSid number.
//or each dSid is a number raised to the power of dNum.
//2,10 is 100 - 4,10 is 10000 - 4,2 is 16 - 2,8 is 64 etc.
function rollDigit(dNum, dSid) {
    var rollTime = new Date();
    di.nmbr = dNum;
    di.sids = dSid;
    physics(di);

    di.totl = 0;
    di.rols.reverse();
    for (i=0; i<di.rols.length; i++) {
	if (i === di.rols.length) {
	    di.totl += (di.rols[i] % di.sids);
	} else {
	    di.totl += (di.rols[i] % di.sids) * Math.pow(di.sids,i);
	}
    }
    di.rols.reverse();
    di.sids = Math.pow(di.sids,di.nmbr);
    if (di.totl === 0) {di.totl = di.sids;}

    di.nmbr = 1;
    //whtnize(di);

    di.nmbr = "D";
    rolDBize(di, rolDB);
    //return rollOut(di); //for CLI
    return di.totl;
}

//Accesses the last most recent roll,
    //May need to access rolDB instead of di.totl when DB goes up.
//then add itself to that roll.
function rollExtra(dNum, dSid) {
    var lastRoll = di.totl;
	di.nmbr = dNum;
	di.sids = dSid;
	physics(di);
	//whtnize(di);
	di.totl += lastRoll;
	di.nmbr = 'X';
	rolDBize(di, rolDB);
	//return rollOut(di); //for CLI
	return di.totl;
}

//input for manual rolls (like if you're using real dice).
//changes public variables directly.
function rollManual(dNum, dSid, rollsArray) {
    //dNum is an unused arg!
    di.nmbr = 'M';
    di.sids = dSid;
    //rolls needs to be an array.
    di.rols = rollsArray;
    di.totl = rollsArray.reduce(function(a ,b) { return a + b; });
    rolDBize(di, rolDB);
    //whtnize(di);
    //return rollOut(di); //for CLI
    return di.totl
}

function roll( arg0, arg1, arg2, arg3, arg4, arg5, arg6,
	       arg7, arg8, arg9, argA, argB, argC) {
    if (arg0 === 'dice') {
	return dice(arg1, arg2);
    } else if (arg0 === 'together') {
	return rollTgethr(arg1, arg2, arg3, arg4, arg5, arg6,
		          arg7, arg8, arg9, argA, argB, argC);
    } else if (arg0 === 'high') {
	return rollHigh(arg1, arg2);
    } else if (arg0 === 'low') {
	return rollLow(arg1, arg2);
    } else if (arg0 === 'digit') {
	return rollDigit(arg1, arg2);
    } else if (arg0 === 'extra') {
	return rollExtra(arg1, arg2);
    } else if (arg0 === 'manual') {
	return rollManual(arg1, arg2, arg3);
    } else {
	return dice(arg0, arg1);
    }
}

//***manual testing***
	//dice()
//console.log(roll('dice',20));
console.log(roll('dice',1,20));
//console.log(roll(1,20));
//console.log(roll(20));
	//Insane rolls
//console.log(roll('somethingelse',20));
//console.log(roll(2,1));
//console.log(roll(0,20));
//console.log(roll(20,0));
//console.log(roll());
	//Assorted rolls
console.log(roll('extra',1,10));
//console.log(roll('dice',10,6));
console.log(roll('high',2,20));
console.log(roll('low',2,20));
console.log(roll('extra',1,10));
console.log(roll('manual',1,20,[20]));
//console.log(roll('extra',1,10));
console.log(roll('together',2,12,3,10));
	//digit-based rolls
console.log(roll('digit',2,10));
//console.log(roll('digit',4,10));
//console.log(roll('digit',4,2));
//console.log(roll('digit',2,8));
//console.log(roll('digit',2,12));
//console.log(roll('digit',2,16));
console.log(rolDB);
<commit_msg>clean code of old wheatonize/string functions<commit_after>/* di.whtnDice is an opensource project to study the legendary dice curse
 * of Wil Wheaton
 * and get to the bottom of bad juju. At the moment,
 * it's just a dice roller, but later
 * functions will include a rolls database that can track
 * any sinking feeling that the kind of
 * cheetos you're eating is influencing your rolls.
 * Also v.1.0 is aiming at 5th edition D&D rules
 * usage. Later versions will be more system agnostic.
 * This is intended for mobile release, but
 * for now, this is just the engine. Minus the actual engine.
 * Broad strokes to get the system
 * working. Much to be built! -Ian
 */

//the dice object
var di = {  nmbr:undefined,
    	    sids:undefined,
    	    rols:undefined,
    	    totl:undefined,
    	    whtn:undefined,
    	    insn:'Sanity Error!'
	    //todo: turn this into an object with getters and setters
	};

//saved rolls go here so they can be accessed and analyzed
//(unitl a proper DB is made)
//currnet version forgets after the battery of console.log()s are made.
//Need a proper DB,
//but this is proof of concept. todo: db that can store previous rolls.
var rolDB = [];

//checks to make sure user input values make sense.
//auto corrects in certain cases.
function rollSanity(di) {
    //isInt borrowed from http://stackoverflow.com/questions/14636536
    function isInt(value) {
	var x;
	return isNaN(value)?!1:(x=parseFloat(value),(0|x)===x);
    }

    if (di.nmbr === undefined) {
	di.insn = 'The outcome of your undefined number of dice\n'+
		'with between zero and infinity number of sides each\n'+
		'rolls unobserved in a mixed state of quantum flux\n'+
		'forever both Percy and Wheaton, like that poor cat.\n'+
		'Thus it remains with the Tao that cannot be told.\n\n'+
		'Please define the number of dice and their sides\n'+
		'if you prefer your rolls collapsed, measurable and pure.';
    } else if (di.nmbr === 0) {
	di.insn = '    If zero dice are thrown in simulation,\n'+
		'Even if someone is there to observe the outcome -\n'+
		'    Do they still roll poorly for Wil Wheaton?';
    } else if (di.sids === undefined) {
	di.sids = di.nmbr;
	di.nmbr = 1;
	di.insn = undefined;
    } else if (di.sids === 0) {
	di.insn = 'Zero sides?! Is it even there?!';
    } else if (di.sids === 1) {
	di.insn = 'Ok, Escher-trippiness of a one-sided dice aside,\n'+
		'Exactly how did you not know the outcome of this roll?';
    } else if (!(isInt(di.nmbr)) || !(isInt(di.sids))) {
	di.insn = 'Please make sure you entered integers\n'+
	      'for the number of dice and how many sides they have'
    } else {
	di.insn = undefined;
    }
}

/*the physics engine
(to be built: a different abstract function than builtin Math.random().
It will access the device's accelerometer and add physics + chaos
to generate the roll.
it'll be totally sweet!*/
function physics(di) {

    var rolls = [];

    for (var i = 0; i < di.nmbr; i++) {
	    rolls.push(Math.ceil( Math.random() * di.sids ));
    }

    di.rols = rolls;

    var totally = rolls.reduce(function(a ,b) {
	return a + b;
    });

    di.totl = totally;
}

//timeStamp() acts as a serial number for the roll in rolDB.
function timeStamp() {
    var rollTime = new Date();
    return rollTime.getTime();
}

//passes roll results to rolDB.
function rolDBize(di, rolDB) {
    var rollEntry = [],

    rollEntry = [timeStamp(), di.nmbr, di.sids, di.rols, di.totl];

    rolDB.push(rollEntry);
}

//the main simple dice roll manager
function dice(dNum, dSid) {
    di.nmbr = dNum;
    di.sids = dSid;

    rollSanity(di);
    if (di.insn) { return di.insn;
    } else {
	physics(di);
	di.nmbr = 'R';
	rolDBize(di, rolDB);
	return di.totl;
    }
}

/*Mixed dice rolls. There are 6 Standard dice in D&D.
d4, d6, d8, d10, d12, and d20. It would be quite unusual for all these
types of dice to be rolled at the same time, but just in case,
rollTgethr will be able to handle up to 6 different kinds of dice rolls. */
function rollTgethr(dNum1, dSid1, dNum2, dSid2, dNum3, dSid3,
		    dNum4, dSid4, dNum5, dSid5, dNum6, dSid6) {
    var allRolls = [],
	allTotal = 0;

    function theRoll(dNum, dSid) {
	di.nmbr = dNum;
	di.sids = dSid;
	rollSanity(di)
	if (di.insn) {
	    return di.insn;
	} else {
	    physics(di);
	    di.nmbr = 'T';
	    rolDBize(di, rolDB);
	    for (var i = 0; i < di.rols.length; i++) {
		allRolls.push(di.rols[i]);
	    }
	}
    }

    theRoll(dNum1, dSid1);

    if (dNum2) { theRoll(dNum2, dSid2); }
    if (dNum3) { theRoll(dNum3, dSid3); }
    if (dNum4) { theRoll(dNum4, dSid4); }
    if (dNum5) { theRoll(dNum5, dSid5); }
    if (dNum6) { theRoll(dNum6, dSid6); }

    allTotal = allRolls.reduce(function(a ,b) {
	return a + b;
    });

    return allTotal;
}

//Special kinds of D&D rolls, Advantage, Disadvantage, Percent, Inspiration and mixed rolls.
function rollHigh(dNum, dSid) {
    di.nmbr = dNum;
    di.sids = dSid;
    physics(di);
    di.nmbr = 1;
    di.totl = Math.max.apply(null, di.rols);
    di.nmbr = 'H';
    rolDBize(di, rolDB);
    return di.totl;
}

function rollLow(dNum, dSid) {
    di.nmbr = dNum;
    di.sids = dSid;
    physics(di);
    di.nmbr = 1;
    di.totl = Math.min.apply(null, di.rols);
    di.nmbr = 'L';
    rolDBize(di, rolDB);
    return di.totl;
}

//each dNum is a digit in a base dSid number.
//or each dSid is a number raised to the power of dNum.
//2,10 is 100 - 4,10 is 10000 - 4,2 is 16 - 2,8 is 64 etc.
function rollDigit(dNum, dSid) {
    var rollTime = new Date();
    di.nmbr = dNum;
    di.sids = dSid;
    physics(di);

    di.totl = 0;
    di.rols.reverse();
    for (i=0; i<di.rols.length; i++) {
	if (i === di.rols.length) {
	    di.totl += (di.rols[i] % di.sids);
	} else {
	    di.totl += (di.rols[i] % di.sids) * Math.pow(di.sids,i);
	}
    }
    di.rols.reverse();
    di.sids = Math.pow(di.sids,di.nmbr);
    if (di.totl === 0) {di.totl = di.sids;}

    di.nmbr = "D";
    rolDBize(di, rolDB);
    return di.totl;
}

//Accesses the last most recent roll,
    //May need to access rolDB instead of di.totl when DB goes up.
//then add itself to that roll.
function rollExtra(dNum, dSid) {
    var lastRoll = di.totl;
	di.nmbr = dNum;
	di.sids = dSid;
	physics(di);
	di.totl += lastRoll;
	di.nmbr = 'X';
	rolDBize(di, rolDB);
	return di.totl;
}

//input for manual rolls (like if you're using real dice).
//changes public variables directly.
function rollManual(dSid, rollsArray) {
    //dNum is an unused arg!
    di.nmbr = 'M';
    di.sids = dSid;
    //rolls needs to be an array.
    di.rols = rollsArray;
    di.totl = rollsArray.reduce(function(a ,b) { return a + b; });
    rolDBize(di, rolDB);
    return di.totl
}

function roll( arg0, arg1, arg2, arg3, arg4, arg5, arg6,
	       arg7, arg8, arg9, argA, argB, argC) {
    if (arg0 === 'dice') {
	return dice(arg1, arg2);
    } else if (arg0 === 'together') {
	return rollTgethr(arg1, arg2, arg3, arg4, arg5, arg6,
		          arg7, arg8, arg9, argA, argB, argC);
    } else if (arg0 === 'high') {
	return rollHigh(arg1, arg2);
    } else if (arg0 === 'low') {
	return rollLow(arg1, arg2);
    } else if (arg0 === 'digit') {
	return rollDigit(arg1, arg2);
    } else if (arg0 === 'extra') {
	return rollExtra(arg1, arg2);
    } else if (arg0 === 'manual') {
	return rollManual(arg1, arg2);
    } else {
	return dice(arg0, arg1);
    }
}

//***manual testing***
	//dice()
//console.log(roll('dice',20));
console.log(roll('dice',1,20));
//console.log(roll(1,20));
//console.log(roll(20));
	//Insane rolls
//console.log(roll('somethingelse',20));
//console.log(roll(2,1));
//console.log(roll(0,20));
//console.log(roll(20,0));
//console.log(roll());
	//Assorted rolls
console.log(roll('extra',1,10));
//console.log(roll('dice',10,6));
console.log(roll('high',2,20));
console.log(roll('low',2,20));
console.log(roll('extra',1,10));
console.log(roll('manual',20,[20]));
//console.log(roll('extra',1,10));
console.log(roll('together',2,12,3,10));
	//digit-based rolls
console.log(roll('digit',2,10));
//console.log(roll('digit',4,10));
//console.log(roll('digit',4,2));
//console.log(roll('digit',2,8));
//console.log(roll('digit',2,12));
//console.log(roll('digit',2,16));
console.log(rolDB);
<|endoftext|>


<commit_before>/*
 * Copyright 2016 Teppo Kurki <teppo.kurki@iki.fi>
 *
 * 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.
 */

debug = require('debug')('signalk-server:subscriptionmanager')

function SubscriptionManager(app) {
  this.streambundle = app.streambundle
  this.selfContext = app.selfContext
}

SubscriptionManager.prototype.subscribe = function(command, errorCallback, callback) {
  if (Array.isArray(command.subscribe)) {
    return command.subscribe.reduce((acc, subscribeRow) => {
      if (subscribeRow.path) {
        var filteredBus = this.streambundle.
          getBus(subscribeRow.path).
          filter(contextMatcher(this.selfContext, command))
        if (subscribeRow.minPeriod) {
          filteredBus = filteredBus.debounceImmediate(subscribeRow.minPeriod)
        }
        acc.push(filteredBus.map(toDelta).onValue(callback))
        return acc
      }
    }, [])
  }
}

function contextMatcher(selfContext, subscribeCommand) {
  debug("subscribeCommand:" + JSON.stringify(subscribeCommand))
  if (subscribeCommand.context) {
    return normalizedDeltaData =>
      normalizedDeltaData.context === subscribeCommand.context ||
      ((subscribeCommand.context === 'vessels.self' ||
          subscribeCommand.context === 'self') &&
        normalizedDeltaData.context === selfContext)
  }
  return x => true
}

function toDelta(normalizedDeltaData) {
  return {
    context: normalizedDeltaData.context,
    updates: [{
      source: normalizedDeltaData.source,
      '$source': normalizedDeltaData['$source'],
      values: [{
        path: normalizedDeltaData.path,
        value: normalizedDeltaData.value
      }]
    }]
  }
}

module.exports = SubscriptionManager;
<commit_msg>Fix return in case there is no path<commit_after>/*
 * Copyright 2016 Teppo Kurki <teppo.kurki@iki.fi>
 *
 * 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.
 */

debug = require('debug')('signalk-server:subscriptionmanager')

function SubscriptionManager(app) {
  this.streambundle = app.streambundle
  this.selfContext = app.selfContext
}

SubscriptionManager.prototype.subscribe = function(command, errorCallback, callback) {
  if (Array.isArray(command.subscribe)) {
    return command.subscribe.reduce((acc, subscribeRow) => {
      if (subscribeRow.path) {
        var filteredBus = this.streambundle.
          getBus(subscribeRow.path).
          filter(contextMatcher(this.selfContext, command))
        if (subscribeRow.minPeriod) {
          filteredBus = filteredBus.debounceImmediate(subscribeRow.minPeriod)
        }
        acc.push(filteredBus.map(toDelta).onValue(callback))
      }
      return acc
    }, [])
  }
}

function contextMatcher(selfContext, subscribeCommand) {
  debug("subscribeCommand:" + JSON.stringify(subscribeCommand))
  if (subscribeCommand.context) {
    return normalizedDeltaData =>
      normalizedDeltaData.context === subscribeCommand.context ||
      ((subscribeCommand.context === 'vessels.self' ||
          subscribeCommand.context === 'self') &&
        normalizedDeltaData.context === selfContext)
  }
  return x => true
}

function toDelta(normalizedDeltaData) {
  return {
    context: normalizedDeltaData.context,
    updates: [{
      source: normalizedDeltaData.source,
      '$source': normalizedDeltaData['$source'],
      values: [{
        path: normalizedDeltaData.path,
        value: normalizedDeltaData.value
      }]
    }]
  }
}

module.exports = SubscriptionManager;
<|endoftext|>


<commit_before>'use strict'

const _uniq = require('lodash/uniq')
const _capitalize = require('lodash/capitalize')
const _isFinite = require('lodash/isFinite')
const _isEmpty = require('lodash/isEmpty')
const { prepareAmount } = require('bfx-api-node-util')
const runExample = require('../util/run_example')

module.exports = runExample({
  name: 'rest-balances',
  rest: {
    env: true,
    transform: true
  },

  params: {
    hideZeroBalances: true,
    filterByType: false,
    filterByCurrency: false,
    valueCCY: 'USD'
  }
}, async ({ debug, debugTable, rest, params }) => {
  const {
    valueCCY, hideZeroBalances, filterByType, filterByCurrency
  } = params

  const symbolForWallet = w => `t${w.currency}${valueCCY}`

  debug('fetching balances')

  const allWallets = await rest.balances() // actual balance fetch
  const balances = allWallets.filter(w => !( // filter as requested
    (hideZeroBalances && +w.amount === 0) ||
    (!_isEmpty(filterByType) && (w.type.toLowerCase() !== filterByType.toLowerCase())) ||
    (!_isEmpty(filterByCurrency) && (w.currency.toLowerCase() !== filterByCurrency.toLowerCase()))
  )).map(w => ({
    ...w,
    currency: w.currency.toUpperCase(),
    inValueCurrency: w.currency.toUpperCase() === valueCCY
  }))

  if (balances.length === 0) {
    return debug('no wallets match provided filters')
  }

  debug('found %d balances', balances.length)

  // Pull in ticker data for balances which are not in the requested value ccy
  // Balance in BTC, value in USD -> We need to fetch tBTCUSD (last price)
  const lastPrices = {}
  const balancesToConvert = balances.filter(w => w.currency !== valueCCY)
  const symbols = _uniq(balancesToConvert.map(symbolForWallet))

  if (symbols.length > 0) {
    debug('fetching tickers for: %s', symbols.join(', '))
    const tickers = await rest.tickers(symbols)
    tickers.forEach(({ symbol, lastPrice }) => (lastPrices[symbol] = +lastPrice))
  }

  let totalValue = 0
  const rows = balances.map(({ currency, type, amount, available }) => {
    const value = currency !== valueCCY
      ? (lastPrices[symbolForWallet({ currency })] * +amount) || 0
      : +amount

    totalValue += value

    return [
      _capitalize(type),
      currency,
      prepareAmount(amount),
      prepareAmount(available),

      ...(_isFinite(value) ? [
        prepareAmount(value),
        currency !== valueCCY
          ? prepareAmount(lastPrices[symbolForWallet({ currency })])
          : 1
      ] : [
        '-',
        '-'
      ])
    ]
  })

  debugTable({
    rows,
    headers: [
      'Type', 'Symbol', 'Total', 'Available', `Value (${valueCCY})`,
      `Unit Price (${valueCCY})`
    ]
  })

  debug('total value: %d %s', prepareAmount(totalValue), valueCCY)
})
<commit_msg>removed deprecated examples<commit_after><|endoftext|>


<commit_before>/*
TODO:
[ ] Render status bar when highlighting a hex with someone on it
[ ] Render enemies names differently (font? color?)
*/

import { createRectangle } from 'pura/geometry/tuple';
import { fillText } from 'pura/canvas/tuple';
import { canvas, viewHeight, viewWidth } from 'dom';
import { heart, blackHeart } from 'emoji';

const textSize = 12;
const lineHeight = textSize * 1.2;

const name = `Avenger`;
const maxHealth = Math.random() * 80 + 20;
const health = Math.random() * (maxHealth - 10) + 10;

export default {
  geometry: createRectangle([0, -viewHeight / 2 + lineHeight / 2], 0, viewWidth, lineHeight),
  render({ geometry }) {
    let heartContainers = Math.ceil(maxHealth / 10) + 1;
    let filledContainers = Math.ceil(health / 10) + 1;
    while(--heartContainers >= 0) fillText({ font: `6px mono` }, [(viewWidth / 2 - 11) - 8 * heartContainers, 2], blackHeart);
    while(--filledContainers >= 0) fillText({ font: `6px mono` }, [(viewWidth / 2 - 11) - 8 * filledContainers, 2], heart);
    fillText({ style: `white`, font: `10px mono` }, [-viewWidth / 2, 2], name);
  }
};
<commit_msg>integrate statusbar<commit_after>/*
TODO:
[ ] Render status bar when highlighting a hex with someone on it
[ ] Render enemies names differently (font? color?)
*/

import { createRectangle } from 'pura/geometry/tuple';
import { fillText } from 'pura/canvas/tuple';
import { battleData } from 'battle/map';
import { canvas, viewHeight, viewWidth } from 'dom';
import { heart, blackHeart } from 'emoji';
import characters from 'characters';
import state from 'state';

const textSize = 12;
const lineHeight = textSize * 1.2;

const health = Math.random() * (maxHealth - 10) + 10;

export default {
  geometry: createRectangle([0, -viewHeight / 2 + lineHeight / 2], 0, viewWidth, lineHeight),
  render({ geometry }) {
    const hexData = battleData.get(state.target);
    if (!hexData || !hexData.entity) return;
    const { entity } = hexData;
    const { maxHealth, name } = characters[entity.name];
    let heartContainers = Math.ceil(maxHealth / 10) + 1;
    let filledContainers = Math.ceil(entity.health / 10) + 1;
    while(--heartContainers >= 0) fillText({ font: `6px mono` }, [(viewWidth / 2 - 11) - 8 * heartContainers, 2], blackHeart);
    while(--filledContainers >= 0) fillText({ font: `6px mono` }, [(viewWidth / 2 - 11) - 8 * filledContainers, 2], heart);
    fillText({ style: `white`, font: `10px mono` }, [-viewWidth / 2, 2], name);
  }
};
<|endoftext|>


<commit_before>var TYPE_REPLACE_ALL = "1";
var TYPE_REPLACE_SELECTED = "2";
var TYPE_APPEND_ALL = "3"
var TYPE_APPEND_SELECTED = "4"

var chromeApp = null;

var clearChromeText = function () {
  var win = chromeApp.windows[0];
  var tab = win.activeTab();
  tab.selectAll();
  tab.cutSelection();
  delay(0.1);
};

var getTextFromVim = function () {
  var currentApp = Application.currentApplication();
  currentApp.includeStandardAdditions = true;

  var textFromVim = currentApp.doShellScript('cat $HOME/.vim2browser/share.txt');
  var textFromVimArray = textFromVim.split(/\r\n|\r|\n/);
  var retText = '';

  textFromVimArray.forEach(function(textFromVim) {
    retText += textFromVim + '\n';
  });

  return retText;
};

var saveTextInClipboard = function (text) {
  chromeApp.setTheClipboardTo(text);
};

var pasteToChrome = function (vimAppName) {
  var vimApp = null;
  try {
    vimApp = Application(vimAppName);
  } catch(e) {
    console.log(e);
    return;
  }

  var systemEvemts = Application("System Events");
  chromeApp.activate();
  delay(0.5);

  // TODO: keycode other petern
  systemEvemts.keystroke("v",{ using:["command down", "shift down"]});
  vimApp.activate();

  // 書式ありver
  //var win = chromeApp.windows[0];
  //var tab = win.activeTab();
  //tab.selectAll();
  //tab.pasteSelection();
};

// argv[0] type
// argv[1] VimAppName
function run(argv){
  if (argv.length < 2) {
    console.log("Arguments are necessary more than two.");
    return;
  }

  try {
    chromeApp = Application('Google Chrome');
    chromeApp.includeStandardAdditions = true;
  } catch(e) {
    console.log(e);
    return;
  }

  if (argv[0] === TYPE_REPLACE_SELECTED || argv[0] === TYPE_REPLACE_ALL) {
    clearChromeText();
  }

  saveTextInClipboard(getTextFromVim());
  // argv[1]はVimAppName
  pasteToChrome(argv[1]);
}

<commit_msg>add space<commit_after>var TYPE_REPLACE_ALL = "1";
var TYPE_REPLACE_SELECTED = "2";
var TYPE_APPEND_ALL = "3"
var TYPE_APPEND_SELECTED = "4"

var chromeApp = null;

var clearChromeText = function () {
  var win = chromeApp.windows[0];
  var tab = win.activeTab();
  tab.selectAll();
  tab.cutSelection();
  delay(0.1);
};

var getTextFromVim = function () {
  var currentApp = Application.currentApplication();
  currentApp.includeStandardAdditions = true;

  var textFromVim = currentApp.doShellScript('cat $HOME/.vim2browser/share.txt');
  var textFromVimArray = textFromVim.split(/\r\n|\r|\n/);
  var retText = '';

  textFromVimArray.forEach(function (textFromVim) {
    retText += textFromVim + '\n';
  });

  return retText;
};

var saveTextInClipboard = function (text) {
  chromeApp.setTheClipboardTo(text);
};

var pasteToChrome = function (vimAppName) {
  var vimApp = null;
  try {
    vimApp = Application(vimAppName);
  } catch(e) {
    console.log(e);
    return;
  }

  var systemEvemts = Application("System Events");
  chromeApp.activate();
  delay(0.5);

  // TODO: keycode other petern
  systemEvemts.keystroke("v",{ using:["command down", "shift down"]});
  vimApp.activate();

  // 書式ありver
  //var win = chromeApp.windows[0];
  //var tab = win.activeTab();
  //tab.selectAll();
  //tab.pasteSelection();
};

// argv[0] type
// argv[1] VimAppName
function run(argv){
  if (argv.length < 2) {
    console.log("Arguments are necessary more than two.");
    return;
  }

  try {
    chromeApp = Application('Google Chrome');
    chromeApp.includeStandardAdditions = true;
  } catch(e) {
    console.log(e);
    return;
  }

  if (argv[0] === TYPE_REPLACE_SELECTED || argv[0] === TYPE_REPLACE_ALL) {
    clearChromeText();
  }

  saveTextInClipboard(getTextFromVim());
  // argv[1]はVimAppName
  pasteToChrome(argv[1]);
}

<|endoftext|>


<commit_before>const { waitForDb } = require('../app/src/infrastructure/mongodb')
const ProjectEntityUpdateHandler = require('../app/src/Features/Project/ProjectEntityUpdateHandler')
const ProjectEntityHandler = require('../app/src/Features/Project/ProjectEntityHandler')
const ProjectGetter = require('../app/src/Features/Project/ProjectGetter')

const ARGV = process.argv.slice(2)
const DEVELOPER_USER_ID = ARGV.shift()
const PROJECT_ID = ARGV.shift()
const FILE_NAMES_TO_RESTORE = ARGV

async function main() {
  const project = await ProjectGetter.promises.getProject(PROJECT_ID, {
    deletedDocs: 1
  })
  const docsToRestore = project.deletedDocs.filter(doc =>
    FILE_NAMES_TO_RESTORE.includes(doc.name)
  )
  for (const deletedDoc of docsToRestore) {
    const doc = await new Promise((resolve, reject) => {
      ProjectEntityHandler.getDoc(
        PROJECT_ID,
        deletedDoc._id,
        {
          include_deleted: true
        },
        (err, lines, rev, version, ranges) => {
          if (err) return reject(err)
          resolve({ lines, ranges })
        }
      )
    })

    const newDoc = await new Promise((resolve, reject) => {
      ProjectEntityUpdateHandler.addDocWithRanges(
        PROJECT_ID,
        null,
        `${new Date().toISOString().replace(/:/g, '-')}-${deletedDoc.name}`,
        doc.lines,
        doc.ranges,
        DEVELOPER_USER_ID,
        (err, doc, folderId) => {
          if (err) return reject(err)
          resolve({ doc, folderId })
        }
      )
    })
    console.log(newDoc)
  }
}

waitForDb()
  .then(main)
  .then(() => {
    process.exit(0)
  })
  .catch(error => {
    console.error(error)
    process.exit(1)
  })
<commit_msg>Use safe characters in filenames when restoring documents (#3659)<commit_after>const { waitForDb } = require('../app/src/infrastructure/mongodb')
const ProjectEntityUpdateHandler = require('../app/src/Features/Project/ProjectEntityUpdateHandler')
const ProjectEntityHandler = require('../app/src/Features/Project/ProjectEntityHandler')
const ProjectGetter = require('../app/src/Features/Project/ProjectGetter')
const Path = require('path')

const ARGV = process.argv.slice(2)
const DEVELOPER_USER_ID = ARGV.shift()
const PROJECT_ID = ARGV.shift()
const FILE_NAMES_TO_RESTORE = ARGV

async function main() {
  const project = await ProjectGetter.promises.getProject(PROJECT_ID, {
    deletedDocs: 1
  })
  const docsToRestore = project.deletedDocs.filter(doc =>
    FILE_NAMES_TO_RESTORE.includes(doc.name)
  )
  for (const deletedDoc of docsToRestore) {
    const doc = await new Promise((resolve, reject) => {
      ProjectEntityHandler.getDoc(
        PROJECT_ID,
        deletedDoc._id,
        {
          include_deleted: true
        },
        (err, lines, rev, version, ranges) => {
          if (err) return reject(err)
          resolve({ lines, ranges })
        }
      )
    })

    const formattedTimestamp = new Date()
      .toISOString()
      .replace('T', '-')
      .replace(/[^0-9-]/g, '')
    const extension = Path.extname(deletedDoc.name)
    const basename = Path.basename(deletedDoc.name, extension)
    const deletedDocName = `${basename}-${formattedTimestamp}${extension}`
    const newDoc = await new Promise((resolve, reject) => {
      ProjectEntityUpdateHandler.addDocWithRanges(
        PROJECT_ID,
        null,
        `${deletedDocName}`,
        doc.lines,
        doc.ranges,
        DEVELOPER_USER_ID,
        (err, doc, folderId) => {
          if (err) return reject(err)
          resolve({ doc, folderId })
        }
      )
    })
    console.log(newDoc)
  }
}

waitForDb()
  .then(main)
  .then(() => {
    process.exit(0)
  })
  .catch(error => {
    console.error(error)
    process.exit(1)
  })
<|endoftext|>


<commit_before>/*!
 * apiai
 * Copyright(c) 2015 http://api.ai/
 * Apache 2.0 Licensed
 */

var http = require('http');
var apiai = require("../module/apiai");

var app = apiai("ACCESS_TOKEN", "SUBSCRIPTION_KEY");

var server = http.createServer(function(request, response) {
    if (request.method = 'POST' && request.url == '/upload') {
        var outStream = fs.createWriteStream('qwe.wav');
        var voiceRequest = app.voiceRequest();

        voiceRequest.on('response', function(_response) {
            var json = JSON.stringify({'resolvedQuery': _response['result']['resolvedQuery']})
            response.end(json);
        });

        voiceRequest.on('error', function(error) {
            console.log(error);
            response.end();
        });

        request.on('data', function(chunk) {
            voiceRequest.write(chunk);
        });

        request.on('end', function() {
            voiceRequest.end();
        });
    } else {
        response.writeHead(code, {});
        response.end();
    }

    console.log(request.headers);
});

server.listen(8000);

// cat ann_smith.wav | curl -v -X POST --data-binary @- -H "Transfer-Encoding: chunked" -H "Content-Type: audio/wav" http://localhost:8000/upload
<commit_msg>Example changes<commit_after>/*!
 * apiai
 * Copyright(c) 2015 http://api.ai/
 * Apache 2.0 Licensed
 */

var http = require('http');
var apiai = require("../module/apiai");

var app = apiai("09604c7f91ce4cd8a4ede55eb5340b9d", "4c91a8e5-275f-4bf0-8f94-befa78ef92cd");

var server = http.createServer(function(request, response) {
    if (request.method = 'POST' && request.url == '/upload') {
        // var outStream = fs.createWriteStream('qwe.wav');
        var voiceRequest = app.voiceRequest();

        voiceRequest.on('response', function(_response) {
            response.end(JSON.stringify(_response));
            // var json = JSON.stringify({'resolvedQuery': _response['result']['resolvedQuery']})
            // response.end(json);
        });

        voiceRequest.on('error', function(error) {
            console.log(error);
            response.end();
        });

        request.on('data', function(chunk) {
            voiceRequest.write(chunk);
        });

        request.on('end', function() {
            voiceRequest.end();
        });
    } else {
        response.writeHead(code, {});
        response.end();
    }

    console.log(request.headers);
});

server.listen(8000);

// cat ann_smith.wav | curl -v -X POST --data-binary @- -H "Transfer-Encoding: chunked" -H "Content-Type: audio/wav" http://localhost:8000/upload
<|endoftext|>


<commit_before>/* jshint shadow: true */
'use strict';

var createPlot          = require('gl-plot3d'),
    m4FromQuat          = require('gl-mat4/fromQuat'),
    createAxesOptions   = require('./convert/axes'),
    createSpikeOptions  = require('./convert/spikes'),
    createScatterTrace  = require('./convert/scatter'),
    createSurfaceTrace  = require('./convert/surface'),
    computeTickMarks    = require('./lib/tick-marks'),
    createCamera        = require('./lib/camera'),
    str2RGBAarray       = require('./lib/str2rgbarray'),
    Plotly              = require('../plotly');

function render(scene) {
    computeTickMarks(scene);
    scene.glplot.axes.update(scene.axesOptions);

    var keys = Object.keys(scene.traces);
    for (var i = 0; i < keys.length; ++i) {
        var trace = scene.traces[keys[i]];
        trace.handlePick(scene.glplot.selection);

        if (trace.setContourLevels) trace.setContourLevels();
    }
}

function Scene(options, fullLayout) {

    //Create sub container for plot
    var sceneContainer = document.createElement('div');
    var plotContainer = options.container;

    /*
     * Tag the container with the sceneID
     */
    sceneContainer.id             = options.id;
    sceneContainer.style.position = 'absolute';
    sceneContainer.style.top      = sceneContainer.style.left = '0px';
    sceneContainer.style.width    = sceneContainer.style.height = '100%';
    plotContainer.appendChild(sceneContainer);

    this.fullLayout               = fullLayout;
    this.id                       = options.id || 'scene';
    /*
     * Move this to calc step? Why does it work here?
     */
    this.axesOptions      = createAxesOptions(fullLayout[this.id]);
    this.spikeOptions     = createSpikeOptions(fullLayout[this.id]);
    this.container        = sceneContainer;

    var glplotOptions = {
            container:  sceneContainer,
            axes:       this.axesOptions,
            spikes:     this.spikeOptions,
            pickRadius: 10,
            snapToData: true,
            autoScale:  true,
            autoBounds: false
    };

    if (options.staticPlot) {
        glplotOptions.pixelRatio = options.plot3dPixelRatio;
        glplotOptions.glOptions = {
            preserveDrawingBuffer: true,
            premultipliedAlpha:true
        };
    }

    try {
        this.glplot = createPlot(glplotOptions);
    } catch (e) {

        /*
         * createPlot will throw when webgl is not enabled in the client.
         * Lets return an instance of the module with all functions noop'd.
         * The destroy method - which will remove the container from the DOM
         * is overridden with a function that removes the container only.
         */
        var noop = function () {};
        for (var prop in this) if (typeof this[prop] === 'function') this[prop] = noop;
        this.destroy = function () {
            this.container.parentNode.removeChild(this.container);
        };

        var div = document.createElement('div');
        div.textContent = 'Webgl is not supported by your browser - visit http://get.webgl.org for more info';
        div.style.cursor = 'pointer';
        div.style.fontSize = '24px';
        div.style.color = Plotly.Color.defaults[0];

        this.container.appendChild(div);
        this.container.style.background = '#FFFFFF';
        this.container.onclick = function () {
            window.open('http://get.webgl.org');
        };

        /*
         * return before setting up camera and onrender methods
         */
        return;
    }

    var cameraPos = options.fullSceneLayout.cameraposition

    this.camera = createCamera(this.container, {
        center: [cameraPos.center.x, cameraPos.center.y, cameraPos.center.z],
        eye:    [cameraPos.eye.x, cameraPos.eye.y, cameraPos.eye.z],
        up:     [cameraPos.up.x, cameraPos.up.y, cameraPos.up.z],
        zoomMin: 0.1,
        zoomMax: 100,
        mode:   'orbit'
    });

    this.glplot.camera = this.camera;

    this.glplot.onrender = render.bind(null, this);

    //List of scene objects
    this.traces = {};

    this.contourLevels = [ [], [], [] ];
}

var proto = Scene.prototype;

var axisProperties = [ 'xaxis', 'yaxis', 'zaxis' ];

proto.plot = function(sceneData, fullLayout, layout) {

    var data, trace;
    var i, j;
    var fullSceneLayout = fullLayout[this.id];
    var sceneLayout = layout[this.id];

    if (fullSceneLayout.bgcolor) this.glplot.clearColor = str2RGBAarray(fullSceneLayout.bgcolor);
    else this.glplot.clearColor = [0, 0, 0, 0];

    //Update layout
    this.fullSceneLayout = fullSceneLayout;

    this.glplotLayout = fullSceneLayout;
    this.axesOptions.merge(fullSceneLayout);
    this.spikeOptions.merge(fullSceneLayout);

    //Update scene
    this.glplot.update({});

    // Update axes functions BEFORE updating traces
    for (i = 0; i < 3; ++i) {
        var axis = fullSceneLayout[axisProperties[i]];
        Plotly.Gl3dAxes.setConvert(axis);
    }

    //Update traces
    if (sceneData) {
        if(!Array.isArray(sceneData)) sceneData = [sceneData];

        for(i = 0; i < sceneData.length; ++i) {
            data = sceneData[i];
            if(data.visible!==true) {
                continue;
            }
            trace = this.traces[data.uid];
            if(trace) {
                trace.update(data);
            } else {
                switch(data.type) {
                    case 'scatter3d':
                        trace = createScatterTrace(this, data);
                    break;

                    case 'surface':
                        trace = createSurfaceTrace(this, data);
                    break;

                    default:
                }
                this.traces[data.uid] = trace;
            }
        }
    } else {
        sceneData = [];
    }

    var traceIds = Object.keys(this.traces);
trace_id_loop:
    for(i = 0; i<traceIds.length; ++i) {
        for(j = 0; j<sceneData.length; ++j) {
            if(sceneData[j].uid === traceIds[i] && sceneData[j].visible===true) {
                continue trace_id_loop;
            }
        }
        trace = this.traces[traceIds[i]];
        trace.dispose();
        delete this.traces[traceIds[i]];
    }

    //Update ranges (needs to be called *after* objects are added due to updates)
    var sceneBounds = this.glplot.bounds,
        axisDataRange = [];

    for(i = 0; i < 3; ++i) {
        var axis = fullSceneLayout[axisProperties[i]];

        if(axis.autorange) {
            sceneBounds[0][i] = Infinity;
            sceneBounds[1][i] = -Infinity;
            for(j = 0; j < this.glplot.objects.length; ++j) {
                var objBounds = this.glplot.objects[j].bounds;
                sceneBounds[0][i] = Math.min(sceneBounds[0][i], objBounds[0][i]);
                sceneBounds[1][i] = Math.max(sceneBounds[1][i], objBounds[1][i]);
            }
            if('rangemode' in axis && axis.rangemode === 'tozero') {
                sceneBounds[0][i] = Math.min(sceneBounds[0][i], 0);
                sceneBounds[1][i] = Math.max(sceneBounds[1][i], 0);
            }
            if(sceneBounds[0][i] > sceneBounds[1][i]) {
                sceneBounds[0][i] = -1;
                sceneBounds[1][i] =  1;
            } else {
                var d = sceneBounds[1][i] - sceneBounds[0][i];
                sceneBounds[0][i] -= d/32.0;
                sceneBounds[1][i] += d/32.0;
            }
        } else {
            var range = fullSceneLayout[axisProperties[i]].range;
            sceneBounds[0][i] = range[0];
            sceneBounds[1][i] = range[1];
        }
        if(sceneBounds[0][i] === sceneBounds[1][i]) {
            sceneBounds[0][i] -= 1;
            sceneBounds[1][i] += 1;
        }
        axisDataRange[i] = sceneBounds[1][i] - sceneBounds[0][i];
    }

    var axesScaleRatio = [],
        maxRange = Math.max.apply(null, axisDataRange);

    for (i = 0; i < 3; ++i) axesScaleRatio[i] = axisDataRange[i] / maxRange;

    /*
     * Dynamically set the aspect ratio depending on the users aspect settings
     */
    var axisAutoScaleFactor = 4;
    var aspectRatio;

    if (fullSceneLayout.aspectmode === 'auto') {
        if (Math.max.apply(null, axesScaleRatio)/Math.min.apply(null, axesScaleRatio) <= axisAutoScaleFactor) {

            /*
             * USE DATA MODE WHEN AXIS RANGE DIMENSIONS ARE RELATIVELY EQUAL
             */
            aspectRatio = axesScaleRatio;
        } else {

            /*
             * USE EQUAL MODE WHEN AXIS RANGE DIMENSIONS ARE HIGHLY UNEQUAL
             */
            aspectRatio = [1, 1, 1];
        }

    } else if (fullSceneLayout.aspectmode === 'cube') {
        aspectRatio = [1, 1, 1];

    } else if (fullSceneLayout.aspectmode === 'data') {
        aspectRatio = axesScaleRatio;

    } else if (fullSceneLayout.aspectmode === 'manual') {
        var userRatio = fullSceneLayout.aspectratio;
        aspectRatio = [userRatio.x, userRatio.y, userRatio.z];

    } else {
        throw new Error('scene.js aspectRatio was not one of the enumerated types');
    }

    /*
     * Write aspect Ratio back to user data and fullLayout so that it is modifies as user
     * manipulates the aspectmode settings and the fullLayout is up-to-date.
     */
    fullSceneLayout.aspectratio.x = sceneLayout.aspectratio.x = aspectRatio[0];
    fullSceneLayout.aspectratio.y = sceneLayout.aspectratio.y = aspectRatio[1];
    fullSceneLayout.aspectratio.z = sceneLayout.aspectratio.z = aspectRatio[2];

    /*
     * Finally assign the computed aspecratio to the glplot module. This will have an effect
     * on the next render cycle.
     */
    this.glplot.aspect = aspectRatio;

    //Update frame position for multi plots
    var domain = fullSceneLayout.domain || null,
        size = fullLayout._size || null;

    if (domain && size) {
        var containerStyle = this.container.style;
        containerStyle.position = 'absolute';
        containerStyle.left     = (size.l + domain.x[0] * size.w) + 'px';
        containerStyle.top      = (size.t + (1 - domain.y[1]) * size.h) + 'px';
        containerStyle.width    = (size.w * (domain.x[1] - domain.x[0])) + 'px';
        containerStyle.height   = (size.h * (domain.y[1] - domain.y[0])) + 'px';
    }
};

proto.destroy = function() {
    this.glplot.dispose();
    this.container.parentNode.removeChild(this.container);
};

// for reset camera button in modebar
proto.setCameraToDefault = function setCameraToDefault () {
    this.glplot.camera.lookAt(
        [1.25, 1.25, 1.25],
        [0   , 0   , 0   ],
        [0   , 0   , 1   ]
    );
};

// get camera position in plotly coords from 'orbit-camera' coords
proto.getCameraPosition = function getCameraPosition () {
    this.glplot.camera.view.recalcMatrix(this.camera.view.lastT());

    var up     = this.glplot.camera.up;
    var center = this.glplot.camera.center;
    var eye    = this.glplot.camera.eye;

    return {
        up:     {x:up[0], y:up[1], z:up[2]},
        center: {x:center[0], y:center[1], z:center[2]},
        eye:    {x:eye[0], y:eye[1], z:eye[2]}
    };
};

// set camera position with a set of plotly coords
proto.setCameraPosition = function setCameraPosition (camera) {
    var up      = camera.up;
    var center  = camera.center;
    var eye     = camera.eye;
    this.glplot.camera.lookAt(
      [eye.x, eye.y, eye.z],
      [center.x, center.y, center.z],
      [up.x, up.y, up.z]
    );
};

// save camera position to user layout (i.e. gd.layout)
proto.saveCamera = function saveCamera(layout) {
    var cameraposition = this.getCameraPosition();
    Plotly.Lib.nestedProperty(layout, this.id + '.cameraposition')
        .set(cameraposition);
};

proto.toImage = function (format) {
    if (!format) format = 'png';

    var gl = this.glplot.gl;
    var w = gl.drawingBufferWidth;
    var h = gl.drawingBufferHeight;

    gl.bindFramebuffer(gl.FRAMEBUFFER, null);

    var pixels = new Uint8Array(w * h * 4);
    gl.readPixels(0, 0, w, h, gl.RGBA, gl.UNSIGNED_BYTE, pixels);

    //Flip pixels
    for(var j=0,k=h-1; j<k; ++j, --k) {
        for(var i=0; i<w; ++i) {
            for(var l=0; l<4; ++l) {
                var tmp = pixels[4*(w*j+i)+l];
                pixels[4*(w*j+i)+l] = pixels[4*(w*k+i)+l];
                pixels[4*(w*k+i)+l] = tmp;
            }
        }
    }

    var canvas = document.createElement('canvas');
    canvas.width = w;
    canvas.height = h;
    var context = canvas.getContext('2d');
    var imageData = context.createImageData(w, h);
    imageData.data.set(pixels);
    context.putImageData(imageData, 0, 0);

    var dataURL;

    switch (format) {
        case 'jpeg':
            dataURL = canvas.toDataURL('image/jpeg');
            break;
        case 'webp':
            dataURL = canvas.toDataURL('image/webp');
            break;
        default:
        dataURL = canvas.toDataURL('image/png');
    }

    return dataURL;
};

module.exports = Scene;
<commit_msg>add logic around camera / cameraposition:<commit_after>/* jshint shadow: true */
'use strict';

var createPlot          = require('gl-plot3d'),
    m4FromQuat          = require('gl-mat4/fromQuat'),
    createAxesOptions   = require('./convert/axes'),
    createSpikeOptions  = require('./convert/spikes'),
    createScatterTrace  = require('./convert/scatter'),
    createSurfaceTrace  = require('./convert/surface'),
    computeTickMarks    = require('./lib/tick-marks'),
    createCamera        = require('./lib/camera'),
    str2RGBAarray       = require('./lib/str2rgbarray'),
    Plotly              = require('../plotly');

function render(scene) {
    computeTickMarks(scene);
    scene.glplot.axes.update(scene.axesOptions);

    var keys = Object.keys(scene.traces);
    for (var i = 0; i < keys.length; ++i) {
        var trace = scene.traces[keys[i]];
        trace.handlePick(scene.glplot.selection);

        if (trace.setContourLevels) trace.setContourLevels();
    }
}

function Scene(options, fullLayout) {

    //Create sub container for plot
    var sceneContainer = document.createElement('div');
    var plotContainer = options.container;

    /*
     * Tag the container with the sceneID
     */
    sceneContainer.id             = options.id;
    sceneContainer.style.position = 'absolute';
    sceneContainer.style.top      = sceneContainer.style.left = '0px';
    sceneContainer.style.width    = sceneContainer.style.height = '100%';
    plotContainer.appendChild(sceneContainer);

    this.fullLayout               = fullLayout;
    this.id                       = options.id || 'scene';
    /*
     * Move this to calc step? Why does it work here?
     */
    this.axesOptions      = createAxesOptions(fullLayout[this.id]);
    this.spikeOptions     = createSpikeOptions(fullLayout[this.id]);
    this.container        = sceneContainer;

    var glplotOptions = {
            container:  sceneContainer,
            axes:       this.axesOptions,
            spikes:     this.spikeOptions,
            pickRadius: 10,
            snapToData: true,
            autoScale:  true,
            autoBounds: false
    };

    if (options.staticPlot) {
        glplotOptions.pixelRatio = options.plot3dPixelRatio;
        glplotOptions.glOptions = {
            preserveDrawingBuffer: true,
            premultipliedAlpha:true
        };
    }

    try {
        this.glplot = createPlot(glplotOptions);
    } catch (e) {

        /*
         * createPlot will throw when webgl is not enabled in the client.
         * Lets return an instance of the module with all functions noop'd.
         * The destroy method - which will remove the container from the DOM
         * is overridden with a function that removes the container only.
         */
        var noop = function () {};
        for (var prop in this) if (typeof this[prop] === 'function') this[prop] = noop;
        this.destroy = function () {
            this.container.parentNode.removeChild(this.container);
        };

        var div = document.createElement('div');
        div.textContent = 'Webgl is not supported by your browser - visit http://get.webgl.org for more info';
        div.style.cursor = 'pointer';
        div.style.fontSize = '24px';
        div.style.color = Plotly.Color.defaults[0];

        this.container.appendChild(div);
        this.container.style.background = '#FFFFFF';
        this.container.onclick = function () {
            window.open('http://get.webgl.org');
        };

        /*
         * return before setting up camera and onrender methods
         */
        return;
    }

    var cameraPos;

    if(fullLayout.scene.cameraposition !== undefined) {
        cameraPos = this.cleanCamera(fullLayout.scene.cameraposition);
    }
    else cameraPos = fullLayout.scene.camera;

    this.camera = createCamera(this.container, {
        center: [cameraPos.center.x, cameraPos.center.y, cameraPos.center.z],
        eye:    [cameraPos.eye.x, cameraPos.eye.y, cameraPos.eye.z],
        up:     [cameraPos.up.x, cameraPos.up.y, cameraPos.up.z],
        zoomMin: 0.1,
        zoomMax: 100,
        mode:   'orbit'
    });

    this.glplot.camera = this.camera;

    this.glplot.onrender = render.bind(null, this);

    //List of scene objects
    this.traces = {};

    this.contourLevels = [ [], [], [] ];
}

var proto = Scene.prototype;

var axisProperties = [ 'xaxis', 'yaxis', 'zaxis' ];

proto.plot = function(sceneData, fullLayout, layout) {

    var data, trace;
    var i, j;
    var fullSceneLayout = fullLayout[this.id];
    var sceneLayout = layout[this.id];

    if (fullSceneLayout.bgcolor) this.glplot.clearColor = str2RGBAarray(fullSceneLayout.bgcolor);
    else this.glplot.clearColor = [0, 0, 0, 0];

    //Update layout
    this.fullSceneLayout = fullSceneLayout;

    this.glplotLayout = fullSceneLayout;
    this.axesOptions.merge(fullSceneLayout);
    this.spikeOptions.merge(fullSceneLayout);

    //Update scene
    this.glplot.update({});

    // Update axes functions BEFORE updating traces
    for (i = 0; i < 3; ++i) {
        var axis = fullSceneLayout[axisProperties[i]];
        Plotly.Gl3dAxes.setConvert(axis);
    }

    //Update traces
    if (sceneData) {
        if(!Array.isArray(sceneData)) sceneData = [sceneData];

        for(i = 0; i < sceneData.length; ++i) {
            data = sceneData[i];
            if(data.visible!==true) {
                continue;
            }
            trace = this.traces[data.uid];
            if(trace) {
                trace.update(data);
            } else {
                switch(data.type) {
                    case 'scatter3d':
                        trace = createScatterTrace(this, data);
                    break;

                    case 'surface':
                        trace = createSurfaceTrace(this, data);
                    break;

                    default:
                }
                this.traces[data.uid] = trace;
            }
        }
    } else {
        sceneData = [];
    }

    var traceIds = Object.keys(this.traces);
trace_id_loop:
    for(i = 0; i<traceIds.length; ++i) {
        for(j = 0; j<sceneData.length; ++j) {
            if(sceneData[j].uid === traceIds[i] && sceneData[j].visible===true) {
                continue trace_id_loop;
            }
        }
        trace = this.traces[traceIds[i]];
        trace.dispose();
        delete this.traces[traceIds[i]];
    }

    //Update ranges (needs to be called *after* objects are added due to updates)
    var sceneBounds = this.glplot.bounds,
        axisDataRange = [];

    for(i = 0; i < 3; ++i) {
        var axis = fullSceneLayout[axisProperties[i]];

        if(axis.autorange) {
            sceneBounds[0][i] = Infinity;
            sceneBounds[1][i] = -Infinity;
            for(j = 0; j < this.glplot.objects.length; ++j) {
                var objBounds = this.glplot.objects[j].bounds;
                sceneBounds[0][i] = Math.min(sceneBounds[0][i], objBounds[0][i]);
                sceneBounds[1][i] = Math.max(sceneBounds[1][i], objBounds[1][i]);
            }
            if('rangemode' in axis && axis.rangemode === 'tozero') {
                sceneBounds[0][i] = Math.min(sceneBounds[0][i], 0);
                sceneBounds[1][i] = Math.max(sceneBounds[1][i], 0);
            }
            if(sceneBounds[0][i] > sceneBounds[1][i]) {
                sceneBounds[0][i] = -1;
                sceneBounds[1][i] =  1;
            } else {
                var d = sceneBounds[1][i] - sceneBounds[0][i];
                sceneBounds[0][i] -= d/32.0;
                sceneBounds[1][i] += d/32.0;
            }
        } else {
            var range = fullSceneLayout[axisProperties[i]].range;
            sceneBounds[0][i] = range[0];
            sceneBounds[1][i] = range[1];
        }
        if(sceneBounds[0][i] === sceneBounds[1][i]) {
            sceneBounds[0][i] -= 1;
            sceneBounds[1][i] += 1;
        }
        axisDataRange[i] = sceneBounds[1][i] - sceneBounds[0][i];
    }

    var axesScaleRatio = [],
        maxRange = Math.max.apply(null, axisDataRange);

    for (i = 0; i < 3; ++i) axesScaleRatio[i] = axisDataRange[i] / maxRange;

    /*
     * Dynamically set the aspect ratio depending on the users aspect settings
     */
    var axisAutoScaleFactor = 4;
    var aspectRatio;

    if (fullSceneLayout.aspectmode === 'auto') {
        if (Math.max.apply(null, axesScaleRatio)/Math.min.apply(null, axesScaleRatio) <= axisAutoScaleFactor) {

            /*
             * USE DATA MODE WHEN AXIS RANGE DIMENSIONS ARE RELATIVELY EQUAL
             */
            aspectRatio = axesScaleRatio;
        } else {

            /*
             * USE EQUAL MODE WHEN AXIS RANGE DIMENSIONS ARE HIGHLY UNEQUAL
             */
            aspectRatio = [1, 1, 1];
        }

    } else if (fullSceneLayout.aspectmode === 'cube') {
        aspectRatio = [1, 1, 1];

    } else if (fullSceneLayout.aspectmode === 'data') {
        aspectRatio = axesScaleRatio;

    } else if (fullSceneLayout.aspectmode === 'manual') {
        var userRatio = fullSceneLayout.aspectratio;
        aspectRatio = [userRatio.x, userRatio.y, userRatio.z];

    } else {
        throw new Error('scene.js aspectRatio was not one of the enumerated types');
    }

    /*
     * Write aspect Ratio back to user data and fullLayout so that it is modifies as user
     * manipulates the aspectmode settings and the fullLayout is up-to-date.
     */
    fullSceneLayout.aspectratio.x = sceneLayout.aspectratio.x = aspectRatio[0];
    fullSceneLayout.aspectratio.y = sceneLayout.aspectratio.y = aspectRatio[1];
    fullSceneLayout.aspectratio.z = sceneLayout.aspectratio.z = aspectRatio[2];

    /*
     * Finally assign the computed aspecratio to the glplot module. This will have an effect
     * on the next render cycle.
     */
    this.glplot.aspect = aspectRatio;

    //Update frame position for multi plots
    var domain = fullSceneLayout.domain || null,
        size = fullLayout._size || null;

    if (domain && size) {
        var containerStyle = this.container.style;
        containerStyle.position = 'absolute';
        containerStyle.left     = (size.l + domain.x[0] * size.w) + 'px';
        containerStyle.top      = (size.t + (1 - domain.y[1]) * size.h) + 'px';
        containerStyle.width    = (size.w * (domain.x[1] - domain.x[0])) + 'px';
        containerStyle.height   = (size.h * (domain.y[1] - domain.y[0])) + 'px';
    }
};

proto.destroy = function() {
    this.glplot.dispose();
    this.container.parentNode.removeChild(this.container);
};

// for reset camera button in modebar
proto.setCameraToDefault = function setCameraToDefault () {
    this.glplot.camera.lookAt(
        [1.25, 1.25, 1.25],
        [0   , 0   , 0   ],
        [0   , 0   , 1   ]
    );
};

// get camera position in plotly coords from 'orbit-camera' coords
proto.getCameraPosition = function getCameraPosition () {
    this.glplot.camera.view.recalcMatrix(this.camera.view.lastT());

    var up     = this.glplot.camera.up;
    var center = this.glplot.camera.center;
    var eye    = this.glplot.camera.eye;

    return {
        up:     {x:up[0], y:up[1], z:up[2]},
        center: {x:center[0], y:center[1], z:center[2]},
        eye:    {x:eye[0], y:eye[1], z:eye[2]}
    };
};

// set camera position with a set of plotly coords
proto.setCameraPosition = function setCameraPosition (camera) {
    var up      = camera.up;
    var center  = camera.center;
    var eye     = camera.eye;
    this.glplot.camera.lookAt(
      [eye.x, eye.y, eye.z],
      [center.x, center.y, center.z],
      [up.x, up.y, up.z]
    );
};

// save camera to user layout (i.e. gd.layout)
proto.saveCamera = function saveCamera(layout) {
    var cameraposition = this.getCameraPosition();

    // save new camera api
    Plotly.Lib.nestedProperty(layout, this.id + '.camera')
        .set(cameraposition);

    // delete old
    delete layout.scene.cameraposition;
};

// convert old camera position api
proto.cleanCamera = function(cameraposition) {
    if (Array.isArray(cameraposition) && cameraposition[0].length === 4) {
        var rotation = cameraposition[0];
        var center   = cameraposition[1];
        var radius   = cameraposition[2];
        var mat = m4FromQuat([], rotation);
        var eye = [];
        for (var i = 0; i < 3; ++i) {
            eye[i] = center[i] + radius * mat[2+4*i];
        }
        return {
            eye: {x: eye[0], y: eye[1], z: eye[2]},
            center: {x: center[0], y: center[1], z: center[2]},
            up: {x: mat[1], y: mat[5], z: mat[9]}
        };
    }
    else return null;
};

proto.toImage = function (format) {
    if (!format) format = 'png';

    var gl = this.glplot.gl;
    var w = gl.drawingBufferWidth;
    var h = gl.drawingBufferHeight;

    gl.bindFramebuffer(gl.FRAMEBUFFER, null);

    var pixels = new Uint8Array(w * h * 4);
    gl.readPixels(0, 0, w, h, gl.RGBA, gl.UNSIGNED_BYTE, pixels);

    //Flip pixels
    for(var j=0,k=h-1; j<k; ++j, --k) {
        for(var i=0; i<w; ++i) {
            for(var l=0; l<4; ++l) {
                var tmp = pixels[4*(w*j+i)+l];
                pixels[4*(w*j+i)+l] = pixels[4*(w*k+i)+l];
                pixels[4*(w*k+i)+l] = tmp;
            }
        }
    }

    var canvas = document.createElement('canvas');
    canvas.width = w;
    canvas.height = h;
    var context = canvas.getContext('2d');
    var imageData = context.createImageData(w, h);
    imageData.data.set(pixels);
    context.putImageData(imageData, 0, 0);

    var dataURL;

    switch (format) {
        case 'jpeg':
            dataURL = canvas.toDataURL('image/jpeg');
            break;
        case 'webp':
            dataURL = canvas.toDataURL('image/webp');
            break;
        default:
        dataURL = canvas.toDataURL('image/png');
    }

    return dataURL;
};

module.exports = Scene;
<|endoftext|>


<commit_before>const ytdl = require('ytdl-core')
const youtube = new (require('youtube-node'))()

exports.name = 'YouTube'
exports.intents = {
  PlayVideo: (intent, cb) => {
    const title = intent.slots.Title.value
    youtube.setKey(process.env.YOUTUBE_KEY)
    youtube.addParam('type', 'video')
    youtube.search(title, 10, (err, result) => {
      if (!err && result && result.items) {
        const item = result.items[0]
        console.log('preparing video..', item)
        ytdl('https://www.youtube.com/watch?v=' + item.id.videoId,
            { quality: 'highest', filter: format => format.container === 'mp4' },
            (err, info) => {
              console.log('download response:', err, info)
              if (err || !info || !info.formats.length) {
                callback({ text: `Trouble playing YouTube video, please try again later.`, shouldEndSession: true })
              }  else {
                const video = info.formats[0]
                callback({ text: `Playing "${item.snippet.title}" from YouTube`, shouldEndSession: true, mediaUrl: video.url })
              }
            })
      } else {
        cb({ text: 'I could not find any results. Play something else?', shouldEndSession: false })
      }
    })
  },
}
<commit_msg>debugs<commit_after>const ytdl = require('ytdl-core')
const youtube = new (require('youtube-node'))()

exports.name = 'YouTube'
exports.intents = {
  PlayVideo: (intent, cb) => {
    const title = intent.slots.Title.value
    youtube.setKey(process.env.YOUTUBE_KEY)
    youtube.addParam('type', 'video')
    youtube.search(title, 10, (err, result) => {
      if (!err && result && result.items) {
        const item = result.items[0]
        console.log('preparing video..', item)
        ytdl('https://www.youtube.com/watch?v=' + item.id.videoId,
//            { quality: 'highest', filter: format => format.container === 'mp4' },
            (err, info) => {
              console.log('download response:', err, info)
              if (err || !info || !info.formats.length) {
                callback({ text: `Trouble playing YouTube video, please try again later.`, shouldEndSession: true })
              }  else {
                const video = info.formats[0]
                callback({ text: `Playing "${item.snippet.title}" from YouTube`, shouldEndSession: true, mediaUrl: video.url })
              }
            })
      } else {
        cb({ text: 'I could not find any results. Play something else?', shouldEndSession: false })
      }
    })
  },
}
<|endoftext|>


<commit_before>var log = require('db-migrate/lib/log');
var util = require('util');
var deasync = require('deasync');

function MigrationBuilder( primary )
{
   this.primary = primary;
   this.migrationTemplate = [
      "var dbm = require('db-migrate');\nvar type = dbm.dataType;\n\nexports.up = function(db, callback) {\n",
      "\n};\n\nexports.down = function(db, callback) {\n",
      "\n};\n"
   ];
}

MigrationBuilder.prototype = {

   table: function( table, columns, drop )
   {
      var createTable = util.format( "db.createTable('%s', {", table );
         var dropTable = util.format( "db.dropTable('%s', ifExists: true, callback);", table);

         createTable += this.Columns( "\n%s: { type: '%s'", columns, " }," );

         createTable += "\n}, callback);";

return this.createMigration( createTable, dropTable, drop );
},

   //ToDo: callback for all columns
   columns: function( table, columns, drop )
   {
      var addColumn = '', dropColumn = '';
      var aC = util.format( "db.addColumn('%s', '%%s', { type: '%%s'", table );
         var dC = util.format( "db.removeColumn('%s', '%%s', callback);", table );

         for( var i = 0; i < columns.length; ++i )
         {
            if( i > 0)
               dropColumn += '\n';

            dropColumn += util.format( dC, columns[i][0] );
         }

         addColumn += this.Columns( aC, columns, ' } );', true);

         return this.createMigration( addColumn, dropColumn, drop );
      },

      changeKeys: function( table, keys, drop )
      {
         var addKey = '', dropKey = '', firstLine = true, firstKey = true;
         var aK = util.format( "db.removeIndex('%s', '%%s', function() {\ndb.addIndex('%s', '%%s', [ ", table, table );
            var dK = util.format( "db.removeIndex('%s', '%%s', function() {\ndb.addIndex('%s', '%%s', [ ", table, table );

               Object.keys( keys ).forEach( function( key )
               {
                  var addUnique = false, dropUnique = false;

                  if( key === 'PRIMARY' )
                     return;

                  if( !firstLine )
                  {
                     dropKey += '\n';
                     addKey += '\n';
                  }
                  else
                     firstLine = false;

                  addKey += util.format( aK, key, key );
                  dropKey += util.format( dK, key, key );

                  Object.keys( keys[key] ).forEach( function( _key )
                  {
                     if( firstKey )
                     {
                        firstKey = false;
                        addKey += _key;
                        dropKey += _key;
                     }
                     else
                     {
                        addKey += ', ' + _key;
                        dropKey += ', ' + _key;
                     }

                     if( !addUnique )
                        addUnique = keys[key][_key][0][0];

                     if( !dropUnique )
                        dropUnique = keys[key][_key][1][0];
                  });

                  if( addUnique )
                     addKey += ' ], true );'
else
   addKey += ' ] );';

if( dropUnique )
   dropKey += ' ], true );'
else
   dropKey += ' ] );';

addKey += '\n});'
dropKey += '\n});'
});

      //removeIndex([tableName], indexName, callback);
      //addIndex(tableName, indexName, columns, [unique], callback);

      return this.createMigration( addKey, dropKey, drop );
   },

   keys: function( table, keys, drop )
   {
      var addKey = '', dropKey = '', firstLine = true;
      var aK = util.format( "db.addIndex('%s', '%%s', [ ", table );
         var dK = util.format( "db.removeIndex('%s', '%%s');", table );

         Object.keys( keys ).forEach( function( key )
         {
            if( key === 'PRIMARY' )
               return;

            if( !firstLine )
            {
               dropKey += '\n';
               addKey += '\n';
            }
            else
               firstLine = false;

            addKey += util.format( aK, key );
            dropKey += util.format( dK, key );

            addKey += keys[key][0][2];
            for( var i = 1; i < keys[key].length; ++i )
            {
               addKey += ', ' + keys[key][i][2];
            }

            if( keys[key][0][1] )
               addKey += ' ], true );'
         else
            addKey += ' ] );';
      });

      //removeIndex([tableName], indexName, callback);
      //addIndex(tableName, indexName, columns, [unique], callback);

      return this.createMigration( addKey, dropKey, drop );
   },

   engine: function( table, engines, drop )
   {
      var sql = util.format( "ALTER TABLE %s ENGINE = ?", table );
      var createEngine = "runSql('" + sql + "', '" + engines[0] + "', callback);";
      var dropEngine = '';

      if( engines[1] )
         dropEngine = "runSql('" + sql + "', '" + engines[1] + "', callback);";
      else
         dropEngine = "callback(); //irreversable migration";

      return  this.createMigration( createEngine, dropEngine, drop );
   },

   Columns: function( begin, columns, end, br )
   {
      var create = '';

      for( var i = 0; i < columns.length; ++i )
      {
         if( br && i > 0 )
            create += '\n';

         create += util.format( begin , columns[i][0], columns[i][1][0] );
         if( columns[i][1][2] )
            create += ", unsigned: true";

         if( !columns[i][2] )
            create += ", notNull: true";

         if( columns[i][3] )
            create += util.format( ", defaultValue: '%s'", columns[i][3] );

         //Some DBS may have no primary keys. But I like to have the primary key information in the creation information,
         //instead of storing them separated like the other keys.
         if( this.primary && columns[i][4] === 'PRI' )
            create += ", primaryKey: true";

         if( columns[i][5] )
            create += ", autoIncrement: true";

         create += util.format( ", length: %d", columns[i][1][1] );
         create += end;
      }

      return create;
   },

   createMigration: function( up, down, drop )
   {
      if( drop )
         return this.migrationTemplate[0] + down + this.migrationTemplate[1] + up + this.migrationTemplate[2];
      else
         return this.migrationTemplate[0] + up + this.migrationTemplate[1] + down + this.migrationTemplate[2];
   },

};

exports.connect = function(config, callback) {
   callback( null, new MigrationBuilder( config.primary ) );
};<commit_msg>rereindent<commit_after>var log = require('db-migrate/lib/log');
var util = require('util');
var deasync = require('deasync');

function MigrationBuilder( primary )
{
   this.primary = primary;
   this.migrationTemplate = [
     "var dbm = require('db-migrate');\nvar type = dbm.dataType;\n\nexports.up = function(db, callback) {\n",
     "\n};\n\nexports.down = function(db, callback) {\n",
     "\n};\n"
     ];
}

MigrationBuilder.prototype = {

   table: function( table, columns, drop )
   {
      var createTable = util.format( "db.createTable('%s', {", table );
      var dropTable = util.format( "db.dropTable('%s', ifExists: true, callback);", table);

      createTable += this.Columns( "\n%s: { type: '%s'", columns, " }," );

      createTable += "\n}, callback);";

      return this.createMigration( createTable, dropTable, drop );
   },

   //ToDo: callback for all columns
   columns: function( table, columns, drop )
   {
      var addColumn = '', dropColumn = '';
      var aC = util.format( "db.addColumn('%s', '%%s', { type: '%%s'", table );
      var dC = util.format( "db.removeColumn('%s', '%%s', callback);", table );

      for( var i = 0; i < columns.length; ++i )
      {
         if( i > 0)
            dropColumn += '\n';

         dropColumn += util.format( dC, columns[i][0] );
      }

      addColumn += this.Columns( aC, columns, ' } );', true);

      return this.createMigration( addColumn, dropColumn, drop );
   },

   changeKeys: function( table, keys, drop )
   {
      var addKey = '', dropKey = '', firstLine = true, firstKey = true;
      var aK = util.format( "db.removeIndex('%s', '%%s', function() {\ndb.addIndex('%s', '%%s', [ ", table, table );
      var dK = util.format( "db.removeIndex('%s', '%%s', function() {\ndb.addIndex('%s', '%%s', [ ", table, table );

      Object.keys( keys ).forEach( function( key )
      {
         var addUnique = false, dropUnique = false;

         if( key === 'PRIMARY' )
            return;

         if( !firstLine )
         {
            dropKey += '\n';
            addKey += '\n';
         }
         else
            firstLine = false;

         addKey += util.format( aK, key, key );
         dropKey += util.format( dK, key, key );

         Object.keys( keys[key] ).forEach( function( _key )
         {
            if( firstKey )
            {
               firstKey = false;
               addKey += _key;
               dropKey += _key;
            }
            else
            {
               addKey += ', ' + _key;
               dropKey += ', ' + _key;
            }

            if( !addUnique )
               addUnique = keys[key][_key][0][0];

            if( !dropUnique )
               dropUnique = keys[key][_key][1][0];
         });

         if( addUnique )
            addKey += ' ], true );'
         else
            addKey += ' ] );';

         if( dropUnique )
            dropKey += ' ], true );'
         else
            dropKey += ' ] );';

         addKey += '\n});'
         dropKey += '\n});'
      });

      //removeIndex([tableName], indexName, callback);
      //addIndex(tableName, indexName, columns, [unique], callback);

      return this.createMigration( addKey, dropKey, drop );
   },

   keys: function( table, keys, drop )
   {
      var addKey = '', dropKey = '', firstLine = true;
      var aK = util.format( "db.addIndex('%s', '%%s', [ ", table );
      var dK = util.format( "db.removeIndex('%s', '%%s');", table );

      Object.keys( keys ).forEach( function( key )
      {
         if( key === 'PRIMARY' )
            return;

         if( !firstLine )
         {
            dropKey += '\n';
            addKey += '\n';
         }
         else
            firstLine = false;

         addKey += util.format( aK, key );
         dropKey += util.format( dK, key );

         addKey += keys[key][0][2];
         for( var i = 1; i < keys[key].length; ++i )
         {
            addKey += ', ' + keys[key][i][2];
         }

         if( keys[key][0][1] )
            addKey += ' ], true );'
         else
            addKey += ' ] );';
      });

      //removeIndex([tableName], indexName, callback);
      //addIndex(tableName, indexName, columns, [unique], callback);

      return this.createMigration( addKey, dropKey, drop );
   },

   engine: function( table, engines, drop )
   {
      var sql = util.format( "ALTER TABLE %s ENGINE = ?", table );
      var createEngine = "runSql('" + sql + "', '" + engines[0] + "', callback);";
      var dropEngine = '';

      if( engines[1] )
         dropEngine = "runSql('" + sql + "', '" + engines[1] + "', callback);";
      else
         dropEngine = "callback(); //irreversable migration";

      return  this.createMigration( createEngine, dropEngine, drop );
   },

   Columns: function( begin, columns, end, br )
   {
      var create = '';

      for( var i = 0; i < columns.length; ++i )
      {
         if( br && i > 0 )
            create += '\n';

         create += util.format( begin , columns[i][0], columns[i][1][0] );
         if( columns[i][1][2] )
            create += ", unsigned: true";

         if( !columns[i][2] )
            create += ", notNull: true";

         if( columns[i][3] )
            create += util.format( ", defaultValue: '%s'", columns[i][3] );

         //Some DBS may have no primary keys. But I like to have the primary key information in the creation information,
         //instead of storing them separated like the other keys.
         if( this.primary && columns[i][4] === 'PRI' )
            create += ", primaryKey: true";

         if( columns[i][5] )
            create += ", autoIncrement: true";

         create += util.format( ", length: %d", columns[i][1][1] );
         create += end;
      }

      return create;
   },

   createMigration: function( up, down, drop )
   {
      if( drop )
         return this.migrationTemplate[0] + down + this.migrationTemplate[1] + up + this.migrationTemplate[2];
      else
         return this.migrationTemplate[0] + up + this.migrationTemplate[1] + down + this.migrationTemplate[2];
   },

};

exports.connect = function(config, callback) {
   callback( null, new MigrationBuilder( config.primary ) );
};<|endoftext|>


<commit_before>'use strict';

var EventHandler = require('./../utilities/event-handler');
var converter = require('best-timelineUI').converter;
var timelineHelper = require('./../helpers/helpers').timeline;

function Timelines(timelineGroups, states) {
    EventHandler.apply(this);

    this._timelineGroups = timelineGroups || {};
    this._states = states;

    this._currName = null;
    this._currTimeline = null;

    this._pausedTimelines = {};

    this._startAutoTimelines();
}

Timelines.prototype = Object.create(EventHandler.prototype);
Timelines.prototype.constructor = Timelines;

Timelines.prototype._startAutoTimelines = function _startAutoTimelines() {
    for (var timeline in this._timelineGroups) {
        if (this._timelineGroups[timeline].auto) {
            this.get(timeline).start();
        }
    }
}

Timelines.prototype.get = function get(timelineName) {
    this._currTimeline = this._timelineGroups[timelineName];

    this._currSpeed = this._currTimeline.speed || 1;
    this._currDuration = this._currTimeline.duration;

    this._currName = timelineName;
    this._currStateName = '__' + timelineName + 'Time';

    return this;
}

Timelines.prototype.start = function start() {
    var speed = this._currSpeed;
    var duration = this._currDuration;
    var transition = {duration: duration / speed};

    var convertedTimeline = converter.sweetToSalty(this._currTimeline);
    var stateTimelines = convertedTimeline.states;

    this._states.set(this._currStateName, 0);

    this._states.set(this._currStateName, duration, transition);
    this._setPaused(this._currName, false);

    // loops through each individual state timeline
    for (var state in stateTimelines) {
        var timeline = stateTimelines[state];
        var valueFunction = timelineHelper(timeline);

        (function(state, valueFunction) {
            this._states.subscribeTo(this._currStateName, function(key, time) {
                this._states.set(state, valueFunction(time));
            }.bind(this));
        }.bind(this))(state, valueFunction);
    }

}

Timelines.prototype.halt = function halt() {
    var timeElapsed = this._states.get(this._currStateName);

    // duration is needed until all states are stored in Transitionables
    this._states.set(this._currStateName, timeElapsed, {duration: 0});
    this._setPaused(this._currName, true);
}

Timelines.prototype.resume = function resume() {
    var speed = this._currSpeed;
    var totalTime = this._currDuration;
    var timeElapsed = this._states.get(this._currStateName);

    var timeLeft = totalTime - timeElapsed;
    var transition = {duration: timeLeft / speed};

    this._states.set(this._currStateName, totalTime, {duration: timeLeft / speed});
    this._setPaused(this._currName, false);
}

Timelines.prototype.rewind = function rewind() {
    var speed = this._currSpeed;
    var timeElapsed = this._states.get(this._currStateName);
    var transition = {duration: timeElapsed / speed};

    this._states.set(this._currStateName, 0, transition);
    this._setPaused(this._currName, false);
}

Timelines.prototype.isPaused = function isPaused() {
    return this._pausedTimelines[this._currName] || false;
}

Timelines.prototype._setPaused = function _setPaused(timelineName, bool) {
    this._pausedTimelines[timelineName] = bool;
}

module.exports = Timelines;<commit_msg>feat: make chainable<commit_after>'use strict';

var EventHandler = require('./../utilities/event-handler');
var converter = require('best-timelineUI').converter;
var timelineHelper = require('./../helpers/helpers').timeline;

function Timelines(timelineGroups, states) {
    EventHandler.apply(this);

    this._timelineGroups = timelineGroups || {};
    this._states = states;

    this._currName = null;
    this._currTimeline = null;

    this._pausedTimelines = {};

    this._startAutoTimelines();
}

Timelines.prototype = Object.create(EventHandler.prototype);
Timelines.prototype.constructor = Timelines;

Timelines.prototype._startAutoTimelines = function _startAutoTimelines() {
    for (var timeline in this._timelineGroups) {
        if (this._timelineGroups[timeline].auto) {
            this.get(timeline).start();
        }
    }
}

Timelines.prototype.get = function get(timelineName) {
    this._currTimeline = this._timelineGroups[timelineName];

    this._currSpeed = this._currTimeline.speed || 1;
    this._currDuration = this._currTimeline.duration;

    this._currName = timelineName;
    this._currStateName = '__' + timelineName + 'Time';

    return this;
}

Timelines.prototype.start = function start() {
    var speed = this._currSpeed;
    var duration = this._currDuration;
    var transition = {duration: duration / speed};

    var convertedTimeline = converter.sweetToSalty(this._currTimeline);
    var stateTimelines = convertedTimeline.states;

    this._states.set(this._currStateName, 0);

    this._states.set(this._currStateName, duration, transition);
    this._setPaused(this._currName, false);

    // loops through each individual state timeline
    for (var state in stateTimelines) {
        var timeline = stateTimelines[state];
        var valueFunction = timelineHelper(timeline);

        (function(state, valueFunction) {
            this._states.subscribeTo(this._currStateName, function(key, time) {
                this._states.set(state, valueFunction(time));
            }.bind(this));
        }.bind(this))(state, valueFunction);
    }

    return this;
}

Timelines.prototype.halt = function halt() {
    var timeElapsed = this._states.get(this._currStateName);

    // duration is needed until all states are stored in Transitionables
    this._states.set(this._currStateName, timeElapsed, {duration: 0});
    this._setPaused(this._currName, true);

    return this;
}

Timelines.prototype.resume = function resume() {
    var speed = this._currSpeed;
    var totalTime = this._currDuration;
    var timeElapsed = this._states.get(this._currStateName);

    var timeLeft = totalTime - timeElapsed;
    var transition = {duration: timeLeft / speed};

    this._states.set(this._currStateName, totalTime, {duration: timeLeft / speed});
    this._setPaused(this._currName, false);

    return this;
}

Timelines.prototype.rewind = function rewind() {
    var speed = this._currSpeed;
    var timeElapsed = this._states.get(this._currStateName);
    var transition = {duration: timeElapsed / speed};

    this._states.set(this._currStateName, 0, transition);
    this._setPaused(this._currName, false);

    return this;
}

Timelines.prototype.isPaused = function isPaused() {
    return this._pausedTimelines[this._currName] || false;
}

Timelines.prototype._setPaused = function _setPaused(timelineName, bool) {
    this._pausedTimelines[timelineName] = bool;
}

module.exports = Timelines;<|endoftext|>


<commit_before>var Command = require('es_command');

module.exports = function createTransactionHandler(service){

  return function transactionHandler(channel,command_string,cb){
    var c = new Command(command_string);
    var model = service.getModel(c.getDataType(),c.getDataId());
    c.execute(model,function(err){
      cb(err,c.getSerializedMessage());
    });
  };

}
<commit_msg>shim for user events so that they dont crash the server<commit_after>var Command = require('es_command');

module.exports = function createTransactionHandler(service){

  return function transactionHandler(channel,command_string,cb){
    var c = new Command(command_string);

    if(c.getDataType() == 'user') return cb(null,c.getSerializedMessage());

    var model = service.getModel(c.getDataType(),c.getDataId());
    c.execute(model,function(err){
      cb(err,c.getSerializedMessage());
    });
  };

}
<|endoftext|>