<commit_before>/*global Marionette, Backbone, WebFormSession */

/**
 * The primary Marionette application managing menu navigation and launching form entry
 */

var FormplayerFrontend = new Marionette.Application();

var showError = hqImport('cloudcare/js/util.js').showError;
var showSuccess = hqImport('cloudcare/js/util.js').showSuccess;
var tfLoading = hqImport('cloudcare/js/util.js').tfLoading;
var tfLoadingComplete = hqImport('cloudcare/js/util.js').tfLoadingComplete;

FormplayerFrontend.on("before:start", function () {
    var RegionContainer = Marionette.LayoutView.extend({
        el: "#menu-container",

        regions: {
            main: "#menu-region",
        },
    });

    FormplayerFrontend.regions = new RegionContainer();
});

FormplayerFrontend.navigate = function (route, options) {
    options || (options = {});
    Backbone.history.navigate(route, options);
};

FormplayerFrontend.getCurrentRoute = function () {
    return Backbone.history.fragment;
};

/**
 * This function maps a jr:// media path to its HTML path IE
 * jr://images/icon/mother.png -> https://commcarehq.org/hq/multimedia/file/CommCareImage/[app_id]/mother.png
 * The actual mapping is contained in the app Couch document
 */
FormplayerFrontend.reqres.setHandler('resourceMap', function (resource_path, app_id) {
    var currentApp = FormplayerFrontend.request("appselect:getApp", app_id);
    if (resource_path.substring(0, 7) === 'http://') {
        return resource_path;
    } else if (currentApp.attributes.hasOwnProperty("multimedia_map") &&
        currentApp.attributes.multimedia_map.hasOwnProperty(resource_path)) {
        var resource = currentApp.attributes.multimedia_map[resource_path];
        var id = resource.multimedia_id;
        var media_type = resource.media_type;
        var name = _.last(resource_path.split('/'));
        return '/hq/multimedia/file/' + media_type + '/' + id + '/' + name;
    }
});

FormplayerFrontend.reqres.setHandler('currentUser', function () {
    if (!FormplayerFrontend.currentUser) {
        FormplayerFrontend.currentUser = new FormplayerFrontend.Entities.UserModel();
    }
    return FormplayerFrontend.currentUser;
});

FormplayerFrontend.reqres.setHandler('clearForm', function () {
    $('#webforms').html("");
});

FormplayerFrontend.reqres.setHandler('clearMenu', function () {
    $('#menu-region').html("");
});

FormplayerFrontend.reqres.setHandler('startForm', function (data) {
    FormplayerFrontend.request("clearMenu");

    data.onLoading = tfLoading;
    data.onLoadingComplete = tfLoadingComplete;
    data.xform_url = "/webforms/player_proxy";
    //TODO yeah
    data.domain = "test";
    data.onerror = function (resp) {
        showError(resp.human_readable_message || resp.message, $("#cloudcare-notifications"));
    };
    data.onsubmit = function (resp) {
        //TODO: Old Touchforms gets the "submit-all" action then returns the XML to the frontend
        // to be submitted (here). Is there any reason FormPlayer shouldn't do the submitting itself?
        var xml = resp.output;
        var postUrl = resp.postUrl;
        $.ajax({
            type: 'POST',
            url: postUrl,
            data: xml,
            success: function () {
                FormplayerFrontend.request("clearForm");
                // TODO form linking
                FormplayerFrontend.trigger("apps:list");
                showSuccess(gettext("Form successfully saved"), $("#cloudcare-notifications"), 2500);
            },
            error: function (resp, status, message) {
                if (message) {
                    message = gettext("Error saving!") + message;
                } else {
                    message = gettext("Unknown error: ") + status + " " + resp.status;
                    if (resp.status === 0) {
                        message = (message + ". "
                        + gettext("This can happen if you loaded CloudCare from a different address than the server address") + " (" + postUrl + ")");
                    }
                }
                data.onerror({message: message});
                // TODO change submit button text to something other than
                // "Submitting..." and prevent "All changes saved!" message
                // banner at top of the form.
            },
        });
    };
    var sess = new WebFormSession(data);
    sess.renderFormXml(data, $('#webforms'));
});

FormplayerFrontend.on("start", function (options) {
    var user = FormplayerFrontend.request('currentUser');
    user.username = options.username;
    user.language = options.language;
    user.apps = options.apps;
    user.domain = options.domain;
    user.formplayer_url = options.formplayer_url;
    if (Backbone.history) {
        Backbone.history.start();
        // will be the same for every domain. TODO: get domain/username/pass from django
        if (this.getCurrentRoute() === "") {
            FormplayerFrontend.trigger("apps:list", options.apps);
        }
    }
});<commit_msg>set formplayer url properly<commit_after>/*global Marionette, Backbone, WebFormSession */

/**
 * The primary Marionette application managing menu navigation and launching form entry
 */

var FormplayerFrontend = new Marionette.Application();

var showError = hqImport('cloudcare/js/util.js').showError;
var showSuccess = hqImport('cloudcare/js/util.js').showSuccess;
var tfLoading = hqImport('cloudcare/js/util.js').tfLoading;
var tfLoadingComplete = hqImport('cloudcare/js/util.js').tfLoadingComplete;

FormplayerFrontend.on("before:start", function () {
    var RegionContainer = Marionette.LayoutView.extend({
        el: "#menu-container",

        regions: {
            main: "#menu-region",
        },
    });

    FormplayerFrontend.regions = new RegionContainer();
});

FormplayerFrontend.navigate = function (route, options) {
    options || (options = {});
    Backbone.history.navigate(route, options);
};

FormplayerFrontend.getCurrentRoute = function () {
    return Backbone.history.fragment;
};

/**
 * This function maps a jr:// media path to its HTML path IE
 * jr://images/icon/mother.png -> https://commcarehq.org/hq/multimedia/file/CommCareImage/[app_id]/mother.png
 * The actual mapping is contained in the app Couch document
 */
FormplayerFrontend.reqres.setHandler('resourceMap', function (resource_path, app_id) {
    var currentApp = FormplayerFrontend.request("appselect:getApp", app_id);
    if (resource_path.substring(0, 7) === 'http://') {
        return resource_path;
    } else if (currentApp.attributes.hasOwnProperty("multimedia_map") &&
        currentApp.attributes.multimedia_map.hasOwnProperty(resource_path)) {
        var resource = currentApp.attributes.multimedia_map[resource_path];
        var id = resource.multimedia_id;
        var media_type = resource.media_type;
        var name = _.last(resource_path.split('/'));
        return '/hq/multimedia/file/' + media_type + '/' + id + '/' + name;
    }
});

FormplayerFrontend.reqres.setHandler('currentUser', function () {
    if (!FormplayerFrontend.currentUser) {
        FormplayerFrontend.currentUser = new FormplayerFrontend.Entities.UserModel();
    }
    return FormplayerFrontend.currentUser;
});

FormplayerFrontend.reqres.setHandler('clearForm', function () {
    $('#webforms').html("");
});

FormplayerFrontend.reqres.setHandler('clearMenu', function () {
    $('#menu-region').html("");
});

FormplayerFrontend.reqres.setHandler('startForm', function (data) {
    FormplayerFrontend.request("clearMenu");

    data.onLoading = tfLoading;
    data.onLoadingComplete = tfLoadingComplete;
    data.xform_url = FormplayerFrontend.request('currentUser').formplayer_url;
    data.formplayerEnabled = true;
    //TODO yeah
    data.domain = "test";
    data.onerror = function (resp) {
        showError(resp.human_readable_message || resp.message, $("#cloudcare-notifications"));
    };
    data.onsubmit = function (resp) {
        //TODO: Old Touchforms gets the "submit-all" action then returns the XML to the frontend
        // to be submitted (here). Is there any reason FormPlayer shouldn't do the submitting itself?
        var xml = resp.output;
        var postUrl = resp.postUrl;
        $.ajax({
            type: 'POST',
            url: postUrl,
            data: xml,
            success: function () {
                FormplayerFrontend.request("clearForm");
                // TODO form linking
                FormplayerFrontend.trigger("apps:list");
                showSuccess(gettext("Form successfully saved"), $("#cloudcare-notifications"), 2500);
            },
            error: function (resp, status, message) {
                if (message) {
                    message = gettext("Error saving!") + message;
                } else {
                    message = gettext("Unknown error: ") + status + " " + resp.status;
                    if (resp.status === 0) {
                        message = (message + ". "
                        + gettext("This can happen if you loaded CloudCare from a different address than the server address") + " (" + postUrl + ")");
                    }
                }
                data.onerror({message: message});
                // TODO change submit button text to something other than
                // "Submitting..." and prevent "All changes saved!" message
                // banner at top of the form.
            },
        });
    };
    var sess = new WebFormSession(data);
    sess.renderFormXml(data, $('#webforms'));
});

FormplayerFrontend.on("start", function (options) {
    var user = FormplayerFrontend.request('currentUser');
    user.username = options.username;
    user.language = options.language;
    user.apps = options.apps;
    user.domain = options.domain;
    user.formplayer_url = options.formplayer_url;
    if (Backbone.history) {
        Backbone.history.start();
        // will be the same for every domain. TODO: get domain/username/pass from django
        if (this.getCurrentRoute() === "") {
            FormplayerFrontend.trigger("apps:list", options.apps);
        }
    }
});<|endoftext|>


<commit_before>"use strict";

var fs = require("fs");
var async = require("async");
var Benchmark = require("benchmark");
var Connection = require("../lib/tedious").Connection;

function setupConnection(cb) {
  var config = JSON.parse(fs.readFileSync(process.env.HOME + '/.tedious/test-connection.json', 'utf8')).config;

  var connection = new Connection(config);
  connection.on("connect", function() {
    cb(connection);
  });
}

function createBenchmark(test) {
  if (process.argv.indexOf("--profile") != -1) {
    process.nextTick(function() {
      runProfile(test);
    });
  } else {
    process.nextTick(function() {
      runBenchmark(test);
    });
  }
}

function runBenchmark(test) {
  var memStart, memMax = memStart = process.memoryUsage().rss;

  setupConnection(function(connection) {
    test.setup(connection, function(err) {
      if (err) throw err;

      var bm = new Benchmark(test.name, {
        defer: true,
        fn: function(deferred) {
          test.exec(connection, function(err) {
            if (err) throw err;

            memMax = Math.max(memMax, process.memoryUsage().rss);

            deferred.resolve();
          });
        }
      });

      bm.on("complete", function(event) {
        console.log(String(event.target))
        console.log("Memory:", (memMax - memStart)/1024/1024, "MiB")

        test.teardown(connection, function(err) {
          if (err) throw err;

          connection.close();
        });
      });

      bm.run({ "async": true });
    });
  });
}

function runProfile(test) {
  setupConnection(function(connection) {
    test.setup(connection, function(err) {
      if (err) throw err;

      async.timesSeries(test.profileIterations, function(n, done) {
        console.log("[Iteration " +  n + "]");
        test.exec(connection, done);
      }, function(err) {
        if (err) throw err;

        test.teardown(connection, function(err) {
          if (err) throw err;

          connection.close();
        });
      });
    });
  });
}

module.exports.createBenchmark = createBenchmark;
<commit_msg>Ensure `RangeError: Maximum call stack size exceeded` is not thrown.<commit_after>"use strict";

var fs = require("fs");
var async = require("async");
var Benchmark = require("benchmark");
var Connection = require("../lib/tedious").Connection;

function setupConnection(cb) {
  var config = JSON.parse(fs.readFileSync(process.env.HOME + '/.tedious/test-connection.json', 'utf8')).config;

  var connection = new Connection(config);
  connection.on("connect", function() {
    cb(connection);
  });
}

function createBenchmark(test) {
  if (process.argv.indexOf("--profile") != -1) {
    process.nextTick(function() {
      runProfile(test);
    });
  } else {
    process.nextTick(function() {
      runBenchmark(test);
    });
  }
}

function runBenchmark(test) {
  var memStart, memMax = memStart = process.memoryUsage().rss;

  setupConnection(function(connection) {
    test.setup(connection, function(err) {
      if (err) throw err;

      var bm = new Benchmark(test.name, {
        defer: true,
        fn: function(deferred) {
          test.exec(connection, function(err) {
            if (err) throw err;

            memMax = Math.max(memMax, process.memoryUsage().rss);

            deferred.resolve();
          });
        }
      });

      bm.on("complete", function(event) {
        console.log(String(event.target))
        console.log("Memory:", (memMax - memStart)/1024/1024, "MiB")

        test.teardown(connection, function(err) {
          if (err) throw err;

          connection.close();
        });
      });

      bm.run({ "async": true });
    });
  });
}

function runProfile(test) {
  setupConnection(function(connection) {
    test.setup(connection, function(err) {
      if (err) throw err;

      async.timesSeries(test.profileIterations, function(n, done) {
        async.setImmediate(function() {
          console.log("[Iteration " +  n + "]");
          test.exec(connection, done);
        });
      }, function(err) {
        if (err) throw err;

        test.teardown(connection, function(err) {
          if (err) throw err;

          connection.close();
        });
      });
    });
  });
}

module.exports.createBenchmark = createBenchmark;
<|endoftext|>


<commit_before>/*
*
*   Original code from  Pierre-Alexandre Losson -- http://www.telio.be/blog
*   email : plosson@users.sourceforge.net
*
* $Id$
*/

function refreshProgress() {
    progressMonitor.getUploadInfo(updateProgress);
}
function updateProgress(int percent) {
    if (percent == 100) {
      document.getElementById("uploadbutton").disabled = false;
      document.getElementById("progressBarText").innerHTML = "Upload Finished";
     }
     else
        document.getElementById("uploadbutton").disabled = true;
        document.getElementById("progressBarText").innerHTML = "Upload in progress: " + percent + "%";
        document.getElementById("progressBarBoxContent").style.width = parseInt(percent * 3.5) + "px";
        window.setTimeout("refreshProgress()", 1000);

    return true;
}
function startProgress() {
    document.getElementById("progressBar").style.display = "block";
    document.getElementById("progressBarText").innerHTML = "Upload in progress: 0%";
    document.getElementById("uploadbutton").disabled = true;

    // wait a little while to make sure the upload has started ..
    window.setTimeout("refreshProgress()", 1500);
    return true;
}
<commit_msg>updated to use data package<commit_after>/*
*
*   Original code from  Pierre-Alexandre Losson -- http://www.telio.be/blog
*   email : plosson@users.sourceforge.net
*
* $Id$
*/

function refreshProgress() {
    progressMonitor.getUploadInfo(updateProgress);
}
function updateProgress(ProgressData data) {
    if (data.isDone) {
      document.getElementById("uploadbutton").disabled = false;
      document.getElementById("progressBarText").innerHTML = data.getDescription();
     }
     else
        document.getElementById("uploadbutton").disabled = true;
        document.getElementById("progressBarText").innerHTML = "Upload in progress: " + data.getPercent() + "%";
        document.getElementById("progressBarBoxContent").style.width = parseInt(percent * 3.5) + "px";
        window.setTimeout("refreshProgress()", 1000);

    return true;
}
function startProgress() {
    document.getElementById("progressBar").style.display = "block";
    document.getElementById("progressBarText").innerHTML = "Job in progress: 0%";
    document.getElementById("uploadbutton").disabled = true;

    // wait a little while to make sure the upload has started ..
    window.setTimeout("refreshProgress()", 1500);
    return true;
}
<|endoftext|>


<commit_before>/* QuickGuide book */

function updateDepth(book, newPage) {

	var page = book.turn('page'),
		pages = book.turn('pages'),
		depthWidth = 16*Math.min(1, page*2/pages);

		newPage = newPage || page;

	if (newPage>3)
		$('.sj-book .p2 .depth').css({
			width: depthWidth,
			left: 20 - depthWidth
		});
	else
		$('.sj-book .p2 .depth').css({width: 0});

		depthWidth = 16*Math.min(1, (pages-page)*2/pages);

	if (newPage<pages-3)
		$('.sj-book .p111 .depth').css({
			width: depthWidth,
			right: 20 - depthWidth
		});
	else
		$('.sj-book .p111 .depth').css({width: 0});

}

function loadPage(page) {

	$.ajax({url: 'pages/page' + page + '.html'}).
		done(function(pageHtml) {
			$('.sj-book .p' + page).html(pageHtml.replace('samples/quickguide/', ''));
		});

}

function addPage(page, book) {

	var id, pages = book.turn('pages');

	if (!book.turn('hasPage', page)) {

		var element = $('
',
			{'class': 'own-size',
				css: {width: 460, height: 582}
			}).
			html('

');

		if (book.turn('addPage', element, page)) {
			loadPage(page);
		}

	}
}

function numberOfViews(book) {

	return book.turn('pages') / 2 + 1;

}

function getViewNumber(book, page) {

	return parseInt((page || book.turn('page'))/2 + 1, 10);

}

function zoomHandle(e) {

	if ($('.sj-book').data().zoomIn)
		zoomOut();
	else if (e.target && $(e.target).hasClass('zoom-this')) {
		zoomThis($(e.target));
	}

}

function zoomThis(pic) {

	var	position, translate,
		tmpContainer = $('
', {'class': 'zoom-pic'}),
		transitionEnd = $.cssTransitionEnd(),
		tmpPic = $(''),
		zCenterX = $('#book-zoom').width()/2,
		zCenterY = $('#book-zoom').height()/2,
		bookPos = $('#book-zoom').offset(),
		picPos = {
			left: pic.offset().left - bookPos.left,
			top: pic.offset().top - bookPos.top
		},
		completeTransition = function() {
			$('#book-zoom').unbind(transitionEnd);

			if ($('.sj-book').data().zoomIn) {
				tmpContainer.appendTo($('body'));

				$('body').css({'overflow': 'hidden'});

				tmpPic.css({
					margin: position.top + 'px ' + position.left+'px'
				}).
				appendTo(tmpContainer).
				fadeOut(0).
				fadeIn(500);
			}
		};

		$('.sj-book').data().zoomIn = true;

		$('.sj-book').turn('disable', true);

		$(window).resize(zoomOut);

		tmpContainer.click(zoomOut);

		tmpPic.load(function() {
			var realWidth = $(this)[0].width,
				realHeight = $(this)[0].height,
				zoomFactor = realWidth/pic.width(),
				picPosition = {
					top:  (picPos.top - zCenterY)*zoomFactor + zCenterY + bookPos.top,
					left: (picPos.left - zCenterX)*zoomFactor + zCenterX + bookPos.left
				};

			position = {
				top: ($(window).height()-realHeight)/2,
				left: ($(window).width()-realWidth)/2
			};

			translate = {
				top: position.top-picPosition.top,
				left: position.left-picPosition.left
			};

			$('.samples .bar').css({visibility: 'hidden'});
			$('#slider-bar').hide();

			$('#book-zoom').transform(
				'translate('+translate.left+'px, '+translate.top+'px)' +
				'scale('+zoomFactor+', '+zoomFactor+')');

			if (transitionEnd)
				$('#book-zoom').bind(transitionEnd, completeTransition);
			else
				setTimeout(completeTransition, 1000);

		});

		tmpPic.attr('src', pic.attr('src'));

}

function zoomOut() {

	var transitionEnd = $.cssTransitionEnd(),
		completeTransition = function(e) {
			$('#book-zoom').unbind(transitionEnd);
			$('.sj-book').turn('disable', false);
			$('body').css({'overflow': 'auto'});
			moveBar(false);
		};

	$('.sj-book').data().zoomIn = false;

	$(window).unbind('resize', zoomOut);

	moveBar(true);

	$('.zoom-pic').remove();
	$('#book-zoom').transform('scale(1, 1)');
	$('.samples .bar').css({visibility: 'visible'});
	$('#slider-bar').show();

	if (transitionEnd)
		$('#book-zoom').bind(transitionEnd, completeTransition);
	else
		setTimeout(completeTransition, 1000);
}

function moveBar(yes) {
	if (Modernizr && Modernizr.csstransforms) {
		$('#slider .ui-slider-handle').css({zIndex: yes ? -1 : 10000});
	}
}

function setPreview(view) {

	var previewWidth = 115,
		previewHeight = 73,
		previewSrc = 'pages/preview.jpg',
		preview = $(_thumbPreview.children(':first')),
		numPages = (view==1 || view==$('#slider').slider('option', 'max')) ? 1 : 2,
		width = (numPages==1) ? previewWidth/2 : previewWidth;

	_thumbPreview.
		addClass('no-transition').
		css({width: width + 15,
			height: previewHeight + 15,
			top: -previewHeight - 30,
			left: ($($('#slider').children(':first')).width() - width - 15)/2
		});

	preview.css({
		width: width,
		height: previewHeight
	});

	if (preview.css('background-image')==='' ||
		preview.css('background-image')=='none') {

		preview.css({backgroundImage: 'url(' + previewSrc + ')'});

		setTimeout(function(){
			_thumbPreview.removeClass('no-transition');
		}, 0);

	}

	preview.css({backgroundPosition:
		'0px -'+((view-1)*previewHeight)+'px'
	});
}

function isChrome() {

	// Chrome's unsolved bug
	// http://code.google.com/p/chromium/issues/detail?id=128488

	return navigator.userAgent.indexOf('Chrome')!=-1;

}<commit_msg>changes 3 -> 2<commit_after>/* QuickGuide book */

function updateDepth(book, newPage) {

	var page = book.turn('page'),
		pages = book.turn('pages'),
		depthWidth = 16*Math.min(1, page*2/pages);

		newPage = newPage || page;

	if (newPage>2)
		$('.sj-book .p2 .depth').css({
			width: depthWidth,
			left: 20 - depthWidth
		});
	else
		$('.sj-book .p2 .depth').css({width: 0});

		depthWidth = 16*Math.min(1, (pages-page)*2/pages);

	if (newPage<pages-2)
		$('.sj-book .p111 .depth').css({
			width: depthWidth,
			right: 20 - depthWidth
		});
	else
		$('.sj-book .p111 .depth').css({width: 0});

}

function loadPage(page) {

	$.ajax({url: 'pages/page' + page + '.html'}).
		done(function(pageHtml) {
			$('.sj-book .p' + page).html(pageHtml.replace('samples/quickguide/', ''));
		});

}

function addPage(page, book) {

	var id, pages = book.turn('pages');

	if (!book.turn('hasPage', page)) {

		var element = $('
',
			{'class': 'own-size',
				css: {width: 460, height: 582}
			}).
			html('

');

		if (book.turn('addPage', element, page)) {
			loadPage(page);
		}

	}
}

function numberOfViews(book) {

	return book.turn('pages') / 2 + 1;

}

function getViewNumber(book, page) {

	return parseInt((page || book.turn('page'))/2 + 1, 10);

}

function zoomHandle(e) {

	if ($('.sj-book').data().zoomIn)
		zoomOut();
	else if (e.target && $(e.target).hasClass('zoom-this')) {
		zoomThis($(e.target));
	}

}

function zoomThis(pic) {

	var	position, translate,
		tmpContainer = $('
', {'class': 'zoom-pic'}),
		transitionEnd = $.cssTransitionEnd(),
		tmpPic = $(''),
		zCenterX = $('#book-zoom').width()/2,
		zCenterY = $('#book-zoom').height()/2,
		bookPos = $('#book-zoom').offset(),
		picPos = {
			left: pic.offset().left - bookPos.left,
			top: pic.offset().top - bookPos.top
		},
		completeTransition = function() {
			$('#book-zoom').unbind(transitionEnd);

			if ($('.sj-book').data().zoomIn) {
				tmpContainer.appendTo($('body'));

				$('body').css({'overflow': 'hidden'});

				tmpPic.css({
					margin: position.top + 'px ' + position.left+'px'
				}).
				appendTo(tmpContainer).
				fadeOut(0).
				fadeIn(500);
			}
		};

		$('.sj-book').data().zoomIn = true;

		$('.sj-book').turn('disable', true);

		$(window).resize(zoomOut);

		tmpContainer.click(zoomOut);

		tmpPic.load(function() {
			var realWidth = $(this)[0].width,
				realHeight = $(this)[0].height,
				zoomFactor = realWidth/pic.width(),
				picPosition = {
					top:  (picPos.top - zCenterY)*zoomFactor + zCenterY + bookPos.top,
					left: (picPos.left - zCenterX)*zoomFactor + zCenterX + bookPos.left
				};

			position = {
				top: ($(window).height()-realHeight)/2,
				left: ($(window).width()-realWidth)/2
			};

			translate = {
				top: position.top-picPosition.top,
				left: position.left-picPosition.left
			};

			$('.samples .bar').css({visibility: 'hidden'});
			$('#slider-bar').hide();

			$('#book-zoom').transform(
				'translate('+translate.left+'px, '+translate.top+'px)' +
				'scale('+zoomFactor+', '+zoomFactor+')');

			if (transitionEnd)
				$('#book-zoom').bind(transitionEnd, completeTransition);
			else
				setTimeout(completeTransition, 1000);

		});

		tmpPic.attr('src', pic.attr('src'));

}

function zoomOut() {

	var transitionEnd = $.cssTransitionEnd(),
		completeTransition = function(e) {
			$('#book-zoom').unbind(transitionEnd);
			$('.sj-book').turn('disable', false);
			$('body').css({'overflow': 'auto'});
			moveBar(false);
		};

	$('.sj-book').data().zoomIn = false;

	$(window).unbind('resize', zoomOut);

	moveBar(true);

	$('.zoom-pic').remove();
	$('#book-zoom').transform('scale(1, 1)');
	$('.samples .bar').css({visibility: 'visible'});
	$('#slider-bar').show();

	if (transitionEnd)
		$('#book-zoom').bind(transitionEnd, completeTransition);
	else
		setTimeout(completeTransition, 1000);
}

function moveBar(yes) {
	if (Modernizr && Modernizr.csstransforms) {
		$('#slider .ui-slider-handle').css({zIndex: yes ? -1 : 10000});
	}
}

function setPreview(view) {

	var previewWidth = 115,
		previewHeight = 73,
		previewSrc = 'pages/preview.jpg',
		preview = $(_thumbPreview.children(':first')),
		numPages = (view==1 || view==$('#slider').slider('option', 'max')) ? 1 : 2,
		width = (numPages==1) ? previewWidth/2 : previewWidth;

	_thumbPreview.
		addClass('no-transition').
		css({width: width + 15,
			height: previewHeight + 15,
			top: -previewHeight - 30,
			left: ($($('#slider').children(':first')).width() - width - 15)/2
		});

	preview.css({
		width: width,
		height: previewHeight
	});

	if (preview.css('background-image')==='' ||
		preview.css('background-image')=='none') {

		preview.css({backgroundImage: 'url(' + previewSrc + ')'});

		setTimeout(function(){
			_thumbPreview.removeClass('no-transition');
		}, 0);

	}

	preview.css({backgroundPosition:
		'0px -'+((view-1)*previewHeight)+'px'
	});
}

function isChrome() {

	// Chrome's unsolved bug
	// http://code.google.com/p/chromium/issues/detail?id=128488

	return navigator.userAgent.indexOf('Chrome')!=-1;

}<|endoftext|>


<commit_before>"use strict";

function resourceNotFound(req, res, next){
    res.writeHead(404, {"Content-Type": "text/html"});
    res.end("Static File not found: '" + req.parsedURL.pathname + "' \n");
}

/**
 * we respond with 404 if the path is an asset-path
 * if it's no asset, we next, so the index.html will be returned
 * @param req
 * @param res
 * @param next
 */
function notFoundAsset(req, res, next) {

    var parsedURL = req.parsedURL;

    //check for assets folder and all requests containing a "." for file extensions
    if((parsedURL.pathname).indexOf("/assets/") === 0 || (parsedURL.pathname).indexOf(".") !== -1) {
        resourceNotFound(req, res, next);
        return;
    }

    next();

}

module.exports = notFoundAsset;

<commit_msg>- using regex instead of indexOf test to determine assets<commit_after>"use strict";

var isFile = /\.[a-z]{3,4}$/i;

function resourceNotFound(req, res, next){
    res.writeHead(404, {"Content-Type": "text/html"});
    res.end("Static File not found: '" + req.parsedURL.pathname + "' \n");
}

/**
 * we respond with 404 if the path is an asset-path
 * if it's no asset, we next, so the index.html will be returned
 * @param req
 * @param res
 * @param next
 */
function notFoundAsset(req, res, next) {

    var parsedURL = req.parsedURL;

    //check for assets folder and all requests containing a "." for file extensions
    if(isFile.test(parsedURL.pathname)) {
        resourceNotFound(req, res, next);
        return;
    }

    next();
}

module.exports = notFoundAsset;

<|endoftext|>


<commit_before>/*
 eslint-disable no-param-reassign
*/

import { Router } from 'express';
import expressJwt from 'express-jwt';
import { getToken } from './utils'
import YktManager from './YktManager';

import { database_connectionLimit, database_host, database_user, database_password, database_database, secret } from './config';

const router = new Router();
const yktManager = new YktManager({
  connectionLimit : database_connectionLimit,
  host            : database_host,
  user            : database_user,
  password        : database_password,
  database        : database_database,
});

const expressJwtOptions = {
  secret: secret,
  credentialsRequired: true,
  getToken: getToken
};

// 获取所有商户的信息
// GET /shop/all?token=TOKEN
router.get('/all', expressJwt(expressJwtOptions), async (req, res) => {
  try {
    const shops = await yktManager.getShops();
    res.json({ ret: 0, data: shops });
  } catch (err) {
    res.json({ ret: 500, data: err });
  }
});

// 获取指定商户信息
// GET /shop/:shopId?token=TOKEN
router.get('/:shopId', expressJwt(expressJwtOptions), async (req, res) => {
  try {
    const shopId = req.params.shopId;
    const shop = await yktManager.getShop(shopId);
    res.json({ ret: 0, data: shop });
  } catch (err) {
    res.json({ ret: 500, data: err });
  }
});

// 获取指定日期所有商户的日账单
// GET /shop/all/daily-bill/:accDate?token=TOKEN
router.get('/all/daily-bill/:accDate', expressJwt(expressJwtOptions), async (req, res) => {
  try {
    const accDate = req.params.accDate;
    const shopBills = await yktManager.getShopBillsByAccDate(accDate);
    res.json({ ret: 0, data: shopBills });
  } catch (err) {
    res.json({ ret: 500, data: err });
  }
});

// 获取指定商户单日账单
// GET /shop/:shopId/daily-bill/:accDate?token=TOKEN
router.get('/:shopId/daily-bill/:accDate', expressJwt(expressJwtOptions), async (req, res) => {
  try {
    const shopId = req.params.shopId;
    const accDate = req.params.accDate;
    const shopBill = await yktManager.getShopBill(shopId, accDate);
    res.json({ ret: 0, data: shopBill });
  } catch (err) {
    res.json({ ret: 500, data: err });
  }
});

// 获取指定商户日账单列表
// GET /shop/:shopId/daily-bill?token=TOKEN
router.get('/:shopId/daily-bill', expressJwt(expressJwtOptions), async (req, res) => {
  try {
    const shopId = req.params.shopId;
    const shopBills = await yktManager.getShopBillsByShopId(shopId);
    res.json({ ret: 0, data: shopBills });
  } catch (err) {
    res.json({ ret: 500, data: err });
  }
});

// 获取子商户单日账单列表
// GET /shop/:fShopId/sub-shop-daily-bills/:accDate?token=TOKEN
router.get('/:fShopId/sub-shop-daily-bills/:accDate', expressJwt(expressJwtOptions), async (req, res) => {
  try {
    const fShopId = req.params.fShopId;
    const accDate = req.params.accDate;
    const shopBills = await yktManager.getShopBills(fShopId, accDate);
    res.json({ ret: 0, data: shopBills });
  } catch (err) {
    res.json({ ret: 500, data: err });
  }
});

// 获取所属商户的设备的日账单列表
// GET /shop/:shopId/device-daily-bills/:accDate?token=TOKEN
router.get('/:shopId/device-daily-bills/:accDate', expressJwt(expressJwtOptions), async (req, res) => {
  try {
    const shopId = req.params.shopId;
    const accDate = req.params.accDate;
    const shopBills = await yktManager.getDeviceBills(shopId, accDate);
    res.json({ ret: 0, data: shopBills });
  } catch (err) {
    res.json({ ret: 500, data: err });
  }
});

// 获取指定商户单月账单
// GET /shop/:shopId/monthly-bill/:accDate?token=TOKEN
router.get('/:shopId/monthly-bill/:accDate', expressJwt(expressJwtOptions), async (req, res) => {
  try {
    const shopId = req.params.shopId;
    const accDate = req.params.accDate;
    const shopBill = await yktManager.getShopBillMonth(shopId, accDate);
    res.json({ ret: 0, data: shopBill });
  } catch (err) {
    res.json({ ret: 500, data: err });
  }
});

// 获取子商户月账单列表
// GET /shop/:fShopId/sub-shop-monthly-bills/:accDate?token=TOKEN
router.get('/:fShopId/sub-shop-monthly-bills/:accDate', expressJwt(expressJwtOptions), async (req, res) => {
  try {
    const fShopId = req.params.fShopId;
    const accDate = req.params.accDate;
    const shopBills = await yktManager.getShopBillsMonth(fShopId, accDate);
    res.json({ ret: 0, data: shopBills });
  } catch (err) {
    res.json({ ret: 500, data: err });
  }
});

// 获取所属商户的设备的月账单列表
// GET /shop/:shopId/device-monthly-bills/:accDate?token=TOKEN
router.get('/:shopId/device-monthly-bill/:accDate', expressJwt(expressJwtOptions), async (req, res) => {
  try {
    const shopId = req.params.shopId;
    const accDate = req.params.accDate;
    // const deviceBills = await yktManager.getDeviceBillsMonth(shopId, accDate);
    const deviceBills = {};
    res.json({ ret: 0, data: deviceBills });
  } catch (err) {
    res.json({ ret: 500, data: err });
  }
});

// 获取指定商户节点的所有祖先节点
// GET /shop/:shopId/ancestors?token=TOKEN
router.get('/:shopId/ancestors', expressJwt(expressJwtOptions), async (req, res) => {
  try {
    const shopId = req.params.shopId;
    const shops = await yktManager.getAncestorShops(shopId);
    res.json({ ret: 0, data: shops });
  } catch (err) {
    res.json({ ret: 500, data: err });
  }
});

export default router;
<commit_msg>add /shop/all/monthly-bill/:accDate<commit_after>/*
 eslint-disable no-param-reassign
*/

import { Router } from 'express';
import expressJwt from 'express-jwt';
import { getToken } from './utils'
import YktManager from './YktManager';

import { database_connectionLimit, database_host, database_user, database_password, database_database, secret } from './config';

const router = new Router();
const yktManager = new YktManager({
  connectionLimit : database_connectionLimit,
  host            : database_host,
  user            : database_user,
  password        : database_password,
  database        : database_database,
});

const expressJwtOptions = {
  secret: secret,
  credentialsRequired: true,
  getToken: getToken
};

// 获取所有商户的信息
// GET /shop/all?token=TOKEN
router.get('/all', expressJwt(expressJwtOptions), async (req, res) => {
  try {
    const shops = await yktManager.getShops();
    res.json({ ret: 0, data: shops });
  } catch (err) {
    res.json({ ret: 500, data: err });
  }
});

// 获取指定商户信息
// GET /shop/:shopId?token=TOKEN
router.get('/:shopId', expressJwt(expressJwtOptions), async (req, res) => {
  try {
    const shopId = req.params.shopId;
    const shop = await yktManager.getShop(shopId);
    res.json({ ret: 0, data: shop });
  } catch (err) {
    res.json({ ret: 500, data: err });
  }
});

// 获取指定日期所有商户的日账单
// GET /shop/all/daily-bill/:accDate?token=TOKEN
router.get('/all/daily-bill/:accDate', expressJwt(expressJwtOptions), async (req, res) => {
  try {
    const accDate = req.params.accDate;
    const shopBills = await yktManager.getShopBillsByAccDate(accDate);
    res.json({ ret: 0, data: shopBills });
  } catch (err) {
    res.json({ ret: 500, data: err });
  }
});

// 获取指定商户单日账单
// GET /shop/:shopId/daily-bill/:accDate?token=TOKEN
router.get('/:shopId/daily-bill/:accDate', expressJwt(expressJwtOptions), async (req, res) => {
  try {
    const shopId = req.params.shopId;
    const accDate = req.params.accDate;
    const shopBill = await yktManager.getShopBill(shopId, accDate);
    res.json({ ret: 0, data: shopBill });
  } catch (err) {
    res.json({ ret: 500, data: err });
  }
});

// 获取指定商户日账单列表
// GET /shop/:shopId/daily-bill?token=TOKEN
router.get('/:shopId/daily-bill', expressJwt(expressJwtOptions), async (req, res) => {
  try {
    const shopId = req.params.shopId;
    const shopBills = await yktManager.getShopBillsByShopId(shopId);
    res.json({ ret: 0, data: shopBills });
  } catch (err) {
    res.json({ ret: 500, data: err });
  }
});

// 获取子商户单日账单列表
// GET /shop/:fShopId/sub-shop-daily-bills/:accDate?token=TOKEN
router.get('/:fShopId/sub-shop-daily-bills/:accDate', expressJwt(expressJwtOptions), async (req, res) => {
  try {
    const fShopId = req.params.fShopId;
    const accDate = req.params.accDate;
    const shopBills = await yktManager.getShopBills(fShopId, accDate);
    res.json({ ret: 0, data: shopBills });
  } catch (err) {
    res.json({ ret: 500, data: err });
  }
});

// 获取所属商户的设备的日账单列表
// GET /shop/:shopId/device-daily-bills/:accDate?token=TOKEN
router.get('/:shopId/device-daily-bills/:accDate', expressJwt(expressJwtOptions), async (req, res) => {
  try {
    const shopId = req.params.shopId;
    const accDate = req.params.accDate;
    const shopBills = await yktManager.getDeviceBills(shopId, accDate);
    res.json({ ret: 0, data: shopBills });
  } catch (err) {
    res.json({ ret: 500, data: err });
  }
});

// 获取指定商户单月账单
// GET /shop/:shopId/monthly-bill/:accDate?token=TOKEN
router.get('/:shopId/monthly-bill/:accDate', expressJwt(expressJwtOptions), async (req, res) => {
  try {
    const shopId = req.params.shopId;
    const accDate = req.params.accDate;
    const shopBill = await yktManager.getShopBillMonth(shopId, accDate);
    res.json({ ret: 0, data: shopBill });
  } catch (err) {
    res.json({ ret: 500, data: err });
  }
});

// 获取指定日期所有商户的月账单
// GET /shop/all/monthly-bill/:accDate?token=TOKEN
router.get('/all/monthly-bill/:accDate', expressJwt(expressJwtOptions), async (req, res) => {
  try {
    const accDate = req.params.accDate;
    const shopBills = await yktManager.getShopBillsMonth(null, accDate);
    res.json({ ret: 0, data: shopBills });
  } catch (err) {
    res.json({ ret: 500, data: err });
  }
});

// 获取子商户月账单列表
// GET /shop/:fShopId/sub-shop-monthly-bills/:accDate?token=TOKEN
router.get('/:fShopId/sub-shop-monthly-bills/:accDate', expressJwt(expressJwtOptions), async (req, res) => {
  try {
    const fShopId = req.params.fShopId;
    const accDate = req.params.accDate;
    const shopBills = await yktManager.getShopBillsMonth(fShopId, accDate);
    res.json({ ret: 0, data: shopBills });
  } catch (err) {
    res.json({ ret: 500, data: err });
  }
});

// 获取所属商户的设备的月账单列表
// GET /shop/:shopId/device-monthly-bills/:accDate?token=TOKEN
router.get('/:shopId/device-monthly-bill/:accDate', expressJwt(expressJwtOptions), async (req, res) => {
  try {
    const shopId = req.params.shopId;
    const accDate = req.params.accDate;
    // const deviceBills = await yktManager.getDeviceBillsMonth(shopId, accDate);
    const deviceBills = {};
    res.json({ ret: 0, data: deviceBills });
  } catch (err) {
    res.json({ ret: 500, data: err });
  }
});

// 获取指定商户节点的所有祖先节点
// GET /shop/:shopId/ancestors?token=TOKEN
router.get('/:shopId/ancestors', expressJwt(expressJwtOptions), async (req, res) => {
  try {
    const shopId = req.params.shopId;
    const shops = await yktManager.getAncestorShops(shopId);
    res.json({ ret: 0, data: shops });
  } catch (err) {
    res.json({ ret: 500, data: err });
  }
});

export default router;
<|endoftext|>


<commit_before>//This function plays a sound from the last item in the grid.  The last item in the grid will
//always be the grid that the user is playing wth.

SoundBoard.prototype.playSounds = function( frequencyOrSound, volume, start){

  var currentBoard = this.Grids[this.Grids.length -1];
  var duration = 60/currentBoard.BPM/2;
  var osc = context.createBufferSource();
  var gainNode = context.createGain();
  gainNode.gain.value = volume;
  var buffer = currentBoard.soundHash[frequencyOrSound];
  osc.buffer = buffer;
  osc.loop = false;
  osc.connect(gainNode);
  gainNode.connect(context.destination);
  osc.start(start);
};<commit_msg>Included comments in code<commit_after>//This function plays a sound from the last item in the grid.  The last item in the grid will
//always be the grid that the user is playing wth.

SoundBoard.prototype.playSounds = function( frequencyOrSound, volume, start){
  /*** Sound Configuration ***/
  //The currentBoard is the board that the user will currently be working with.  It will allways
  //be the last board in the Grids array
  var currentBoard = this.Grids[this.Grids.length -1];
  //This is the duration of the sound
  var duration = 60/currentBoard.BPM/2;
  //The sound data, PCM data is stored in a buffer.
  var osc = context.createBufferSource();
  //The gain node lets you alter the volume of the sound
  var gainNode = context.createGain();
  gainNode.gain.value = volume;
  //here, we look to our soundhash table to get the sound data and play it.
  var buffer = currentBoard.soundHash[frequencyOrSound];
  osc.buffer = buffer;
  //if this is not set to false, then the sound will continue to loop and play.
  osc.loop = false;

  /*** Play Sound ***/
  osc.connect(gainNode);
  //Finally connect the gain node to the speaker.  context.destination represents the computer speakers.
  //the web audio API has a precise timer that will play a sound whenever you schedule it for.
  //context.currentTime gives you the current time.  If you give a time that is in the past, then it will
  //play immediately.
  gainNode.connect(context.destination);
  osc.start(start);
};<|endoftext|>


<commit_before>// Libs
var http = require('http');
var url = require('url');
var crypto = require('crypto');
var path = require('path');
var fs = require('fs');
var _ = require('underscore');
var request = require('request');

// "Global" vars
var port = process.env.PORT || 5000;
var domainRegex = process.env.AG_PROXY_DOMAIN_REGEX || '';
var cacheMinutes = process.env.AG_PROXY_CACHE_TIME || 20;
var cacheLocation = process.env.AG_PROXY_CACHE_LOCATION || 'cache';
var defaultResponse = 'This is a basic proxy server, see code at https://github.com/MinnPost/all-good-proxy';
var currentDir = __dirname;

// Process environment variables
port = (_.isNumber(parseInt(port, 10))) ? port : 5000;
domainRegex = (_.isString(domainRegex)) ? new RegExp(domainRegex) : new RegExp('');
cacheMinutes = (_.isNumber(parseInt(cacheMinutes, 10))) ? cacheMinutes : 20;
cacheLocation = (_.isString(cacheLocation)) ? cacheLocation : 'cache';

// Handle a request
function makeRequest(options, done, error) {
  var req = request(options, function(reqError, res, data) {
    if (reqError) {
      error(reqError);
    }
    else {
      if (_.isNumber(res.statusCode) && res.statusCode >= 200 &&
        res.statusCode < 300) {
        done(res, data);
      }
      else {
        error(res, data);
      }
    }
  });
}

// Check if whitelisted
function checkDomain(url) {
  return url.match(domainRegex);
}

// Save cache
function cacheSave(id, data, done) {
  var hash = crypto.createHash('md5').update(id).digest('hex');
  var store = path.join(currentDir, cacheLocation, hash);

  data.time = new Date().getTime();
  data.headers = data.headers || {};
  data.headers['ag-proxy-cache'] = hash;
  data.headers['ag-proxy-time'] = data.time;
  data = JSON.stringify(data);

  fs.writeFile(store, data, function(err) {
    if (err) {
      console.log(err);
    }
    if (_.isFunction(done)) {
      done(err);
    }
  });
}

// Save cache
function cacheLoad(id, done) {
  var hash = crypto.createHash('md5').update(id).digest('hex');
  var store = path.join(currentDir, cacheLocation, hash);

  fs.exists(store, function(exists) {
    if (exists) {
      fs.readFile(store, function(err, data) {
        data = JSON.parse(data);
        done(err, data);
      });
    }
    else {
      done('No cache');
    }
  });
}

// Cache and display
function cacheAndDisplay(res, id, code, headers, data) {
  cacheSave(id, {
    code: code,
    headers: headers,
    data: data
  });
  res.writeHead(code, headers);
  res.end(data);
}

// Main proxy logic
function proxy(req, res, proxyURL) {
  var proxyReq = url.parse(proxyURL);
  var proxyOptions = {};
  var cache = false;
  var now = new Date().getTime();
  var cacheDiff;

  // Check if url fits domain
  if (!checkDomain(proxyReq.host || proxyURL)) {
    res.statusCode = 404;
    res.end(defaultResponse);
  }

  // Make request options
  proxyOptions = {
    uri: proxyURL,
    host: proxyReq.host,
    hostname: proxyReq.hostname,
    port: proxyReq.port || 80,
    method: req.method,
    path: proxyReq.path,
    //headers: req.headers,
  };
  //delete proxyOptions.headers.cookie;
  //delete proxyOptions.headers.host;

  // Get cache
  cacheLoad(proxyURL, function(err, cacheData) {
    if (err) {
      console.log(err);
    }
    else if (cacheData) {
      cache = true;
    }

    // Check cache
    if (cache) {
      // If cache, check time (in minutes)
      cacheDiff = (now - cacheData.time) / 60 / 1000;

      // If not past time, serve up cache
      if (cacheDiff < cacheMinutes) {
        res.writeHead(cacheData.code, cacheData.headers);
        res.end(cacheData.data);
      }
      else {
        // If past time, try to make a new request, otherwise, use
        // old cache and update time.  Force a small-ish timeout.
        proxyOptions.timeout = 5000;
        makeRequest(proxyOptions, function(proxyRes, data) {
          delete proxyRes.headers['content-disposition'];
          cacheAndDisplay(res, proxyURL, proxyRes.statusCode, proxyRes.headers, data);
        },
        function(proxyRes, data) {
          cacheAndDisplay(res, proxyURL, cacheData.code, cacheData.headers, cacheData.data);
        });
      }
    }
    else {
      makeRequest(proxyOptions, function(proxyRes, data) {
        delete proxyRes.headers['content-disposition'];
        cacheAndDisplay(res, proxyURL, proxyRes.statusCode, proxyRes.headers, data);
      },
      function(proxyRes, data) {
        // No cache and error, so just return what was
        if (data) {
          res.writeHead(proxyRes.statusCode, proxyRes.headers);
          res.end(data);
        }
        else {
          res.statusCode = 500;
          res.end(defaultResponse);
        }
      });
    }
  });
}

// Main server
function server(req, res) {
  var queryParams = url.parse(req.url, true).query;
  var proxyURL = (_.isObject(queryParams)) ? queryParams.url : false;

  // if incoming url req
  if (proxyURL) {
    proxy(req, res, proxyURL)
  }
  else {
    res.end(defaultResponse);
  }
}

// Start server
http.createServer(server).listen(port);
console.log('Operating on port: ' + port);<commit_msg>No need to remove header as that was needed becuase of typo.<commit_after>// Libs
var http = require('http');
var url = require('url');
var crypto = require('crypto');
var path = require('path');
var fs = require('fs');
var _ = require('underscore');
var request = require('request');

// "Global" vars
var port = process.env.PORT || 5000;
var domainRegex = process.env.AG_PROXY_DOMAIN_REGEX || '';
var cacheMinutes = process.env.AG_PROXY_CACHE_TIME || 20;
var cacheLocation = process.env.AG_PROXY_CACHE_LOCATION || 'cache';
var defaultResponse = 'This is a basic proxy server, see code at https://github.com/MinnPost/all-good-proxy';
var currentDir = __dirname;

// Process environment variables
port = (_.isNumber(parseInt(port, 10))) ? port : 5000;
domainRegex = (_.isString(domainRegex)) ? new RegExp(domainRegex) : new RegExp('');
cacheMinutes = (_.isNumber(parseInt(cacheMinutes, 10))) ? cacheMinutes : 20;
cacheLocation = (_.isString(cacheLocation)) ? cacheLocation : 'cache';

// Handle a request
function makeRequest(options, done, error) {
  var req = request(options, function(reqError, res, data) {
    if (reqError) {
      error(reqError);
    }
    else {
      if (_.isNumber(res.statusCode) && res.statusCode >= 200 &&
        res.statusCode < 300) {
        done(res, data);
      }
      else {
        error(res, data);
      }
    }
  });
}

// Check if whitelisted
function checkDomain(url) {
  return url.match(domainRegex);
}

// Save cache
function cacheSave(id, data, done) {
  var hash = crypto.createHash('md5').update(id).digest('hex');
  var store = path.join(currentDir, cacheLocation, hash);

  data.time = new Date().getTime();
  data.headers = data.headers || {};
  data.headers['ag-proxy-cache'] = hash;
  data.headers['ag-proxy-time'] = data.time;
  data = JSON.stringify(data);

  fs.writeFile(store, data, function(err) {
    if (err) {
      console.log(err);
    }
    if (_.isFunction(done)) {
      done(err);
    }
  });
}

// Save cache
function cacheLoad(id, done) {
  var hash = crypto.createHash('md5').update(id).digest('hex');
  var store = path.join(currentDir, cacheLocation, hash);

  fs.exists(store, function(exists) {
    if (exists) {
      fs.readFile(store, function(err, data) {
        data = JSON.parse(data);
        done(err, data);
      });
    }
    else {
      done('No cache');
    }
  });
}

// Cache and display
function cacheAndDisplay(res, id, code, headers, data) {
  cacheSave(id, {
    code: code,
    headers: headers,
    data: data
  });
  res.writeHead(code, headers);
  res.end(data);
}

// Main proxy logic
function proxy(req, res, proxyURL) {
  var proxyReq = url.parse(proxyURL);
  var proxyOptions = {};
  var cache = false;
  var now = new Date().getTime();
  var cacheDiff;

  // Check if url fits domain
  if (!checkDomain(proxyReq.host || proxyURL)) {
    res.statusCode = 404;
    res.end(defaultResponse);
  }

  // Make request options
  proxyOptions = {
    uri: proxyURL,
    host: proxyReq.host,
    hostname: proxyReq.hostname,
    port: proxyReq.port || 80,
    method: req.method,
    path: proxyReq.path,
    //headers: req.headers,
  };
  //delete proxyOptions.headers.cookie;
  //delete proxyOptions.headers.host;

  // Get cache
  cacheLoad(proxyURL, function(err, cacheData) {
    if (err) {
      console.log(err);
    }
    else if (cacheData) {
      cache = true;
    }

    // Check cache
    if (cache) {
      // If cache, check time (in minutes)
      cacheDiff = (now - cacheData.time) / 60 / 1000;

      // If not past time, serve up cache
      if (cacheDiff < cacheMinutes) {
        res.writeHead(cacheData.code, cacheData.headers);
        res.end(cacheData.data);
      }
      else {
        // If past time, try to make a new request, otherwise, use
        // old cache and update time.  Force a small-ish timeout.
        proxyOptions.timeout = 5000;
        makeRequest(proxyOptions, function(proxyRes, data) {
          cacheAndDisplay(res, proxyURL, proxyRes.statusCode, proxyRes.headers, data);
        },
        function(proxyRes, data) {
          cacheAndDisplay(res, proxyURL, cacheData.code, cacheData.headers, cacheData.data);
        });
      }
    }
    else {
      makeRequest(proxyOptions, function(proxyRes, data) {
        cacheAndDisplay(res, proxyURL, proxyRes.statusCode, proxyRes.headers, data);
      },
      function(proxyRes, data) {
        // No cache and error, so just return what was
        if (data) {
          res.writeHead(proxyRes.statusCode, proxyRes.headers);
          res.end(data);
        }
        else {
          res.statusCode = 500;
          res.end(defaultResponse);
        }
      });
    }
  });
}

// Main server
function server(req, res) {
  var queryParams = url.parse(req.url, true).query;
  var proxyURL = (_.isObject(queryParams)) ? queryParams.url : false;

  // if incoming url req
  if (proxyURL) {
    proxy(req, res, proxyURL)
  }
  else {
    res.end(defaultResponse);
  }
}

// Start server
http.createServer(server).listen(port);
console.log('Operating on port: ' + port);<|endoftext|>


<commit_before>// Functions for estimating the number of rows produced by nodes and other quantities

'use strict';

var dot = require('dot');

var estimatedCountTemplate = dot.template('EXPLAIN (FORMAT JSON) {{=it.sourceQuery}}');
var exactCountTemplate = dot.template([
        'SELECT count(*) AS result_rows',
        'FROM ({{=it.sourceQuery}}) _cdb_analysis_source'
    ].join('\n'));
var countDistinctValuesTemplate = dot.template([
    'SELECT COUNT(*) AS count_distict_values FROM (',
    '  SELECT DISTINCT {{=it.column}}',
    '  FROM (',
    '    {{=it.source}}',
    '  ) AS _cdb_analysis_query',
    ') AS _cdb_analysis_count_distinct'
    ].join('\n'));

// Estimated number of rows in the result of a node.
// A LimitsContext object must be provided.
// This is an asynchronous method; an error object and the number of estimated rows will
// be passed to the callback provided.
// This uses PostgreSQL query planner and statistics; it could fail, returning a null count
// if no stats are available or if a timeout occurs.
function estimatedNumberOfRows(node, context, callback) {
    var sql = estimatedCountTemplate({
        sourceQuery: node.sql()
    });
    context.runSQL(sql, function(err, resultSet){
        var estimated_rows = null;
        if (!err) {
            estimated_rows = resultSet.rows[0]['QUERY PLAN'][0].Plan['Plan Rows'];
        }
        return callback(err, estimated_rows);
    });
}

// Number of rows in the result of the node.
// A LimitsContext object must be provided.
// This is an asynchronous method; an error object and the number of estimated rows will
// be passed to the callback provided.
// This can be slow for large tables or complex queries.
function numberOfRows(node, context, callback) {
    var sql = exactCountTemplate({
        sourceQuery: node.sql()
    });
    context.runSQL(sql, function(err, resultSet){
        var counted_rows = null;
        if (!err) {
            counted_rows = resultSet.rows[0].result_rows;
        }
        return callback(err, counted_rows);
    });
}

// Estimate number of distict values of a column in a node's query.
function numberOfDistinctValues(node, context, columnName, callback) {
    var sql = countDistinctValuesTemplate({
        source: node.sql(),
        column: columnName
    });
    context.runSQL(sql, function(err, resultSet){
        var number = null;
        if (!err) {
            number = resultSet.rows[0].count_distict_values;
        }
        return callback(err, number);
    });
}

module.exports = {
    estimatedNumberOfRows: estimatedNumberOfRows,
    numberOfRows: numberOfRows,
    numberOfDistinctValues: numberOfDistinctValues
};
<commit_msg>Fix workflow-image<commit_after>// Functions for estimating the number of rows produced by nodes and other quantities

'use strict';

var dot = require('dot');

var estimatedCountTemplate = dot.template('EXPLAIN (FORMAT JSON) {{=it.sourceQuery}}');
var exactCountTemplate = dot.template([
        'SELECT count(*) AS result_rows',
        'FROM ({{=it.sourceQuery}}) _cdb_analysis_source'
    ].join('\n'));
var countDistinctValuesTemplate = dot.template([
    'SELECT COUNT(*) AS count_distict_values FROM (',
    '  SELECT DISTINCT {{=it.column}}',
    '  FROM (',
    '    {{=it.source}}',
    '  ) AS _cdb_analysis_query',
    ') AS _cdb_analysis_count_distinct'
    ].join('\n'));

// Estimated number of rows in the result of a node.
// A LimitsContext object must be provided.
// This is an asynchronous method; an error object and the number of estimated rows will
// be passed to the callback provided.
// This uses PostgreSQL query planner and statistics; it could fail, returning a null count
// if no stats are available or if a timeout occurs.
function estimatedNumberOfRows(node, context, callback) {
    var sql = estimatedCountTemplate({
        sourceQuery: node.sql()
    });
    context.runSQL(sql, function(err, resultSet){
        var estimated_rows = null;
        if (!err) {
            if (resultSet.rows) {
                estimated_rows = resultSet.rows[0]['QUERY PLAN'][0].Plan['Plan Rows'];
            } else {
                // If we get no results (e.g. working with a fake db)
                // we make a most permissive estimate
                estimated_rows = 0;
            }
        }
        return callback(err, estimated_rows);
    });
}

// Number of rows in the result of the node.
// A LimitsContext object must be provided.
// This is an asynchronous method; an error object and the number of estimated rows will
// be passed to the callback provided.
// This can be slow for large tables or complex queries.
function numberOfRows(node, context, callback) {
    var sql = exactCountTemplate({
        sourceQuery: node.sql()
    });
    context.runSQL(sql, function(err, resultSet){
        var counted_rows = null;
        if (!err) {
            counted_rows = resultSet.rows[0].result_rows;
        }
        return callback(err, counted_rows);
    });
}

// Estimate number of distict values of a column in a node's query.
function numberOfDistinctValues(node, context, columnName, callback) {
    var sql = countDistinctValuesTemplate({
        source: node.sql(),
        column: columnName
    });
    context.runSQL(sql, function(err, resultSet){
        var number = null;
        if (!err) {
            number = resultSet.rows[0].count_distict_values;
        }
        return callback(err, number);
    });
}

module.exports = {
    estimatedNumberOfRows: estimatedNumberOfRows,
    numberOfRows: numberOfRows,
    numberOfDistinctValues: numberOfDistinctValues
};
<|endoftext|>


<commit_before>//See LICENSE file for licensing details, available in the "psdle" repository on GitHub. TL;DR: MIT, do what you want.

try { repod; } catch(e) { repod = {}; }
repod.muh_games = {
	gamelist: [],
    init: function() {
		this.config = {
			totalgames: parseInt(/(\d+) Matches$/.exec($(".statsText").text())[1]),
			past: "",
            timerID: 0,
            delay: 3000
		}
		this.injectCSS();
		this.genDisplay();
        this.startTimer();
        return 1;
	},
	parsePage: function() {
		if ($(".gridViewportPaneWrapper").html() !== this.config.past) {
            this.config.past = $(".gridViewportPaneWrapper").html();
			$("#sub_container").html("Parsing page "+(this.gamelist.length/24+1)+" out of "+Math.ceil(this.config.totalgames/24)+". ("+Math.round((repod.muh_games.gamelist.length / repod.muh_games.config.totalgames) * 100)+"%)");
			$("li.cellDlItemGame").each(function() {
				var info = $(this).find(".mediaInfo");
				var gametitle = info.find(".gameTitle").text();
				var size = info.find(".size").text().replace("|","");
				var platform = [];
				var date = info.find(".purchaseDate").text().replace("|","");
				var icon = $(this).find(".thumbPane").find("img").attr("src");
				var url = $(this).find(".thumbPane").parent().attr("href");
				info.find(".playableOn").children("a").each(function() { platform.push($(this).text()) });
				repod.muh_games.gamelist.push({title:gametitle,size:size,platform:platform,date:date,url:url,icon:icon});
			});
			if (this.gamelist.length >= this.config.totalgames) {
				clearInterval(this.config.timerID);
				this.genTable();
			} else {
				 this.nextPage();
			}
		}
        return 1;
	},
	startTimer: function(delay) {
        var delay = (delay) ? delay : this.config.delay;
        this.config.timerID = setInterval(function(){repod.muh_games.parsePage();},delay);
		return 1;
	},
	nextPage: function() {
		$(".navLinkNext").trigger("click"); //Anonymous functions, please.
        return 1;
	},
	genDisplay:function() {
		$("body").append("
");
		$("#muh_games_container").append("
");
		return 1;
	},
	genTable: function() {
		$("#sub_container").html(this.genSearchOptions());
		$("#sub_container").hide().append("
"+this.genTableContents()+"
").show();
		return 1;
	},
	regenTable: function() {
		$("#muh_table > tbody").html(this.genTableContents());
		return 1
	},
	genTableContents: function() {
		var temp = "
Icon	Name	Platform	Size	Date
";
		var safesys = this.safeSystemCheck();
		$.each(repod.muh_games.gamelist,function(index,val) {
			var sys = repod.muh_games.safeGuessSystem(val['platform']);
			if ($.inArray(sys,safesys) > -1) {
				//Valid system.
				var a = true;
				var t = val['title']; var t2 = t.toLowerCase();
				if ($("#filter_avatar").hasClass("toggled_off") && t2.indexOf("avatar") > -1) a = false;
				if ($("#filter_demo").hasClass("toggled_off") && t2.indexOf("demo") > -1) a = false;
				if ($("#filter_unlock").hasClass("toggled_off") && t2.indexOf("unlock") > -1) a = false;
				if ($("#filter_pass").hasClass("toggled_off") && t2.indexOf("pass") > -1) a = false;
				if ($("#filter_pack").hasClass("toggled_off") && t2.indexOf("pack") > -1) a = false;
				if (a) {
					var u = val['url'];
					temp += "
	"+t+"	"+sys+"	"+val['size']+"	"+val['date']+"
";
				}
			}
		});
		return temp;
	},
	genSearchOptions: function() {
		//TO-DO: Make scalable.
		$(document).on("click","span[id^=system_], span[id^=filter_]", function() { repod.muh_games.toggleButton($(this)); });
		$(document).on("click","span#psdle_regen", function() { repod.muh_games.regenTable(); });
		var temp = '
' +
					'PS3' +
					'PS4' +
					'PSP' +
					'PS Vita' +
					'
' +
					'Avatars' +
					'Demos' +
					'Unlocks' +
					'Passes' +
					'Packs' +
					'
' +
					'Regenerate' +
					'
';
		return temp;
	},
	toggleButton: function(e) {
		$(e).toggleClass("toggled_off");
		return 1
	},
	safeSystemCheck: function() {
		var temp = [];
		$("span[id^=system_]:not('.toggled_off')").each(function() {
			temp.push($(this).text());
		});
		return temp;
	},
	safeGuessSystem: function(e) {
		//Quick, dirty, and easy.
		var sys = e.join(" ");
		if (sys == "PS3 PSP PS Vita" || sys == "PS3 PSP") sys = "PSP";
		if (sys == "PS3 PS Vita") sys = "PS Vita";
		if (sys == "PS3") sys = sys;
		if (sys == "PS4") sys = sys;
		return sys;
	},
	injectCSS: function() {
		var temp = "";
		temp += "table,th,td{border:1px solid #999;border-collapse:collapse;} th {padding:5px;} td a.psdle_game_link {display:block;width:100%;height:100%;color:#000 !important;padding-left:2px;} th, tr:hover{background-color:#ccc;}"; //Table
		temp += "span[id^=system_], span[id^=filter_], span#psdle_regen { border-radius:5px;border:1px solid #fff;font-weight:bold;text-transform:uppercase;font-size:small;color:#fff;padding:1px 3px;bottom:3px;display:inline-block;vertical-align:20%;background-color:#000;cursor:pointer; } .toggled_off { opacity:0.4; }"; //Search buttons
		temp += ".psdle_game_icon { max-width:100%;vertical-align:middle }"; //Content icons
		$("").appendTo("head");
		return 1;
	}
}
repod.muh_games.init();
<commit_msg>PSDLE - New keyword and regex.<commit_after>//See LICENSE file for licensing details, available in the "psdle" repository on GitHub. TL;DR: MIT, do what you want.

try { repod; } catch(e) { repod = {}; }
repod.muh_games = {
	gamelist: [],
    init: function() {
		this.config = {
			totalgames: parseInt(/(\d+) Matches$/.exec($(".statsText").text())[1]),
			past: "",
            timerID: 0,
            delay: 3000
		}
		this.injectCSS();
		this.genDisplay();
        this.startTimer();
        return 1;
	},
	parsePage: function() {
		if ($(".gridViewportPaneWrapper").html() !== this.config.past) {
            this.config.past = $(".gridViewportPaneWrapper").html();
			$("#sub_container").html("Parsing page "+(this.gamelist.length/24+1)+" out of "+Math.ceil(this.config.totalgames/24)+". ("+Math.round((repod.muh_games.gamelist.length / repod.muh_games.config.totalgames) * 100)+"%)");
			$("li.cellDlItemGame").each(function() {
				var info = $(this).find(".mediaInfo");
				var gametitle = info.find(".gameTitle").text();
				var size = info.find(".size").text().replace("|","");
				var platform = [];
				var date = info.find(".purchaseDate").text().replace("|","");
				var icon = $(this).find(".thumbPane").find("img").attr("src");
				var url = $(this).find(".thumbPane").parent().attr("href");
				info.find(".playableOn").children("a").each(function() { platform.push($(this).text()) });
				repod.muh_games.gamelist.push({title:gametitle,size:size,platform:platform,date:date,url:url,icon:icon});
			});
			if (this.gamelist.length >= this.config.totalgames) {
				clearInterval(this.config.timerID);
				this.genTable();
			} else {
				 this.nextPage();
			}
		}
        return 1;
	},
	startTimer: function(delay) {
        var delay = (delay) ? delay : this.config.delay;
        this.config.timerID = setInterval(function(){repod.muh_games.parsePage();},delay);
		return 1;
	},
	nextPage: function() {
		$(".navLinkNext").trigger("click"); //Anonymous functions, please.
        return 1;
	},
	genDisplay:function() {
		$("body").append("
");
		$("#muh_games_container").append("
");
		return 1;
	},
	genTable: function() {
		$("#sub_container").html(this.genSearchOptions());
		$("#sub_container").hide().append("
"+this.genTableContents()+"
").show();
		return 1;
	},
	regenTable: function() {
		$("#muh_table > tbody").html(this.genTableContents());
		return 1
	},
	genTableContents: function() {
		var temp = "
Icon	Name	Platform	Size	Date
";
		var safesys = this.safeSystemCheck();
		$.each(repod.muh_games.gamelist,function(index,val) {
			var sys = repod.muh_games.safeGuessSystem(val['platform']);
			if ($.inArray(sys,safesys) > -1) {
				//Valid system.
				var a = true; var t = val['title'];
				if ($("#filter_avatar").hasClass("toggled_off") && / Avatar$/i.test(t)) a = false;
				if ($("#filter_demo").hasClass("toggled_off") && / Demo$/i.test(t)) a = false;
				if ($("#filter_unlock").hasClass("toggled_off") && / Unlock$/i.test(t)) a = false;
				if ($("#filter_pass").hasClass("toggled_off") && / Pass$/i.test(t)) a = false;
				if ($("#filter_pack").hasClass("toggled_off") && / Pack$/i.test(t)) a = false;
				if ($("#filter_pack").hasClass("toggled_off") && / Theme$/i.test(t)) a = false;
				if (a) {
					var u = val['url'];
					temp += "
	"+t+"	"+sys+"	"+val['size']+"	"+val['date']+"
";
				}
			}
		});
		return temp;
	},
	genSearchOptions: function() {
		//TO-DO: Make scalable.
		$(document).on("click","span[id^=system_], span[id^=filter_]", function() { repod.muh_games.toggleButton($(this)); });
		$(document).on("click","span#psdle_regen", function() { repod.muh_games.regenTable(); });
		var temp = '
' +
					'PS3' +
					'PS4' +
					'PSP' +
					'PS Vita' +
					'
' +
					'Avatars' +
					'Demos' +
					'Unlocks' +
					'Passes' +
					'Packs' +
					'Themes' +
					'
' +
					'Regenerate' +
					'
';
		return temp;
	},
	toggleButton: function(e) {
		$(e).toggleClass("toggled_off");
		return 1
	},
	safeSystemCheck: function() {
		var temp = [];
		$("span[id^=system_]:not('.toggled_off')").each(function() {
			temp.push($(this).text());
		});
		return temp;
	},
	safeGuessSystem: function(e) {
		//Quick, dirty, and easy.
		var sys = e.join(" ");
		if (sys == "PS3 PSP PS Vita" || sys == "PS3 PSP") sys = "PSP";
		if (sys == "PS3 PS Vita") sys = "PS Vita";
		if (sys == "PS3") sys = sys;
		if (sys == "PS4") sys = sys;
		return sys;
	},
	injectCSS: function() {
		var temp = "";
		temp += "table,th,td{border:1px solid #999;border-collapse:collapse;} th {padding:5px;} td a.psdle_game_link {display:block;width:100%;height:100%;color:#000 !important;padding-left:2px;} th, tr:hover{background-color:#ccc;}"; //Table
		temp += "span[id^=system_], span[id^=filter_], span#psdle_regen { border-radius:5px;border:1px solid #fff;font-weight:bold;text-transform:uppercase;font-size:small;color:#fff;padding:1px 3px;bottom:3px;display:inline-block;vertical-align:20%;background-color:#000;cursor:pointer; } .toggled_off { opacity:0.4; }"; //Search buttons
		temp += ".psdle_game_icon { max-width:100%;vertical-align:middle }"; //Content icons
		$("").appendTo("head");
		return 1;
	}
}
repod.muh_games.init();
<|endoftext|>


<commit_before>/**
 * @author TristanVALCKE / https://github.com/Itee
 */
/* global QUnit */

import { AnimationAction } from '../../../../src/animation/AnimationAction';
import { AnimationMixer } from '../../../../src/animation/AnimationMixer';
import { AnimationClip } from '../../../../src/animation/AnimationClip';
import { NumberKeyframeTrack } from '../../../../src/animation/tracks/NumberKeyframeTrack';
import { Object3D } from '../../../../src/core/Object3D';
import { LoopOnce, LoopRepeat, LoopPingPong } from '../../../../src/constants';

function createAnimation(){

    var root = new Object3D();
	var mixer = new AnimationMixer(root);
	var track = new NumberKeyframeTrack( ".rotation[x]", [ 0, 1000 ], [ 0, 360 ] );
	var clip = new AnimationClip( "clip1", 1000, [track] );

    var animationAction = mixer.clipAction( clip );
    return {
        root: root,
        mixer: mixer,
        track: track,
        clip: clip,
        animationAction: animationAction
    };

}

export default QUnit.module( 'Animation', () => {

	QUnit.module( 'AnimationAction', () => {

		// INSTANCING
		QUnit.test( "Instancing", ( assert ) => {

			var mixer = new AnimationMixer();
			var clip = new AnimationClip( "nonname", - 1, [] );

			var animationAction = new AnimationAction( mixer, clip );
			assert.ok( animationAction, "animationAction instanciated" );

		} );

		// PUBLIC STUFF
		QUnit.test( "play", ( assert ) => {

			var {mixer,animationAction} = createAnimation();
			var animationAction2 = animationAction.play();
			assert.equal( animationAction, animationAction2, "AnimationAction.play can be chained." );

			var UserException = function () {

				this.message = "AnimationMixer must activate AnimationAction on play.";

			};
			mixer._activateAction = function ( action ) {

				if ( action === animationAction ) {

					throw new UserException();

				}

			};
			assert.throws( () => {

				animationAction.play();

			}, new UserException() );

		} );

		QUnit.test( "stop", ( assert ) => {

			var {mixer,animationAction} = createAnimation();
			var animationAction2 = animationAction.stop();
			assert.equal( animationAction, animationAction2, "AnimationAction.stop can be chained." );

			var UserException = function () {

				this.message = "AnimationMixer must deactivate AnimationAction on stop.";

			};
			mixer._deactivateAction = function ( action ) {

				if ( action === animationAction ) {

					throw new UserException();

				}

			};
			assert.throws( () => {

				animationAction.stop();

			}, new UserException() );

		} );

		QUnit.test( "reset", ( assert ) => {

			var {mixer,animationAction} = createAnimation();
			var animationAction2 = animationAction.stop();
			assert.equal( animationAction, animationAction2, "AnimationAction.reset can be chained." );
			assert.equal( animationAction2.paused, false, "AnimationAction.reset() sets paused false" );
			assert.equal( animationAction2.enabled, true, "AnimationAction.reset() sets enabled true" );
			assert.equal( animationAction2.time, 0, "AnimationAction.reset() resets time." );
			assert.equal( animationAction2._loopCount, - 1, "AnimationAction.reset() resets loopcount." );
			assert.equal( animationAction2._startTime, null, "AnimationAction.reset() removes starttime." );

		} );

		QUnit.test( "isRunning", ( assert ) => {

			var {mixer,animationAction} = createAnimation();
			assert.notOk( animationAction.isRunning(), "When an animation is just made, it is not running." );
			animationAction.play();
			assert.ok( animationAction.isRunning(), "When an animation is started, it is running." );
			animationAction.stop();
			assert.notOk( animationAction.isRunning(), "When an animation is stopped, it is not running." );
			animationAction.play();
			animationAction.paused = true;
			assert.notOk( animationAction.isRunning(), "When an animation is paused, it is not running." );
			animationAction.paused = false;
			animationAction.enabled = false;
			assert.notOk( animationAction.isRunning(), "When an animation is not enabled, it is not running." );
			animationAction.enabled = true;
			assert.ok( animationAction.isRunning(), "When an animation is enabled, it is running." );

		} );

		QUnit.test( "isScheduled", ( assert ) => {

			var {mixer,animationAction} = createAnimation();
			assert.notOk( animationAction.isScheduled(), "When an animation is just made, it is not scheduled." );
			animationAction.play();
			assert.ok( animationAction.isScheduled(), "When an animation is started, it is scheduled." );
			mixer.update(1);
			assert.ok( animationAction.isScheduled(), "When an animation is updated, it is scheduled." );
			animationAction.stop();
			assert.notOk( animationAction.isScheduled(), "When an animation is stopped, it isn't scheduled anymore." );

		} );

		QUnit.test( "startAt", ( assert ) => {

			var {mixer,animationAction} = createAnimation();
			animationAction.startAt(2);
			animationAction.play();
			assert.notOk( animationAction.isRunning(), "When an animation is started at a specific time, it is not running." );
			assert.ok( animationAction.isScheduled(), "When an animation is started at a specific time, it is scheduled." );
			mixer.update(1);
			assert.notOk( animationAction.isRunning(), "When an animation is started at a specific time and the interval is not passed, it is not running." );
			assert.ok( animationAction.isScheduled(), "When an animation is started at a specific time and the interval is not passed, it is scheduled." );
			mixer.update(1);
			assert.ok( animationAction.isRunning(), "When an animation is started at a specific time and the interval is passed, it is running." );
			assert.ok( animationAction.isScheduled(), "When an animation is started at a specific time and the interval is passed, it is scheduled." );
			animationAction.stop();
			assert.notOk( animationAction.isRunning(), "When an animation is stopped, it is not running." );
			assert.notOk( animationAction.isScheduled(), "When an animation is stopped, it is not scheduled." );

		} );

		QUnit.test( "setLoop LoopOnce", ( assert ) => {

			var {mixer,animationAction} = createAnimation();
			animationAction.setLoop(LoopOnce);
			animationAction.play();
			assert.ok( animationAction.isRunning(), "When an animation is started, it is running." );
			mixer.update(500);
			assert.ok( animationAction.isRunning(), "When an animation is in the first loop, it is running." );
			mixer.update(500);
			assert.notOk( animationAction.isRunning(), "When an animation is ended, it is not running." );
			mixer.update(500);
			assert.notOk( animationAction.isRunning(), "When an animation is ended, it is not running." );

		} );

		QUnit.test( "setLoop LoopRepeat", ( assert ) => {

			var {mixer,animationAction} = createAnimation();
			animationAction.setLoop(LoopRepeat,3);
			animationAction.play();
			assert.ok( animationAction.isRunning(), "When an animation is started, it is running." );
			mixer.update(500);
			assert.ok( animationAction.isRunning(), "When an animation is in the first loop, it is running." );
			mixer.update(1000);
			assert.ok( animationAction.isRunning(), "When an animation is in second loop when in looprepeat 3 times, it is running." );
			mixer.update(1000);
			assert.ok( animationAction.isRunning(), "When an animation is in third loop when in looprepeat 3 times, it is running." );
			mixer.update(1000);
			assert.ok( animationAction.isRunning(), "When an animation is in fourth loop when in looprepeat 3 times, it is running." );
			mixer.update(1000);
			assert.notOk( animationAction.isRunning(), "When an animation ended his third loop when in looprepeat 3 times, it stays not running anymore." );

		} );

		QUnit.test( "setLoop LoopPingPong", ( assert ) => {

			var {mixer,animationAction} = createAnimation();
			animationAction.setLoop(LoopPingPong,3);
			animationAction.play();
			assert.ok( animationAction.isRunning(), "When an animation is started, it is running." );
			mixer.update(500);
			assert.ok( animationAction.isRunning(), "When an animation is in the first loop, it is running." );
			mixer.update(1000);
			assert.ok( animationAction.isRunning(), "When an animation is in second loop when in looprepeat 3 times, it is running." );
			mixer.update(1000);
			assert.ok( animationAction.isRunning(), "When an animation is in third loop when in looprepeat 3 times, it is running." );
			mixer.update(1000);
			assert.ok( animationAction.isRunning(), "When an animation is in fourth loop when in looprepeat 3 times, it is running." );
			mixer.update(1000);
			assert.notOk( animationAction.isRunning(), "When an animation ended his third loop when in looprepeat 3 times, it stays not running anymore." );

		} );

		QUnit.todo( "setEffectiveWeight", ( assert ) => {

			assert.ok( false, "everything's gonna be alright" );

		} );

		QUnit.todo( "getEffectiveWeight", ( assert ) => {

			assert.ok( false, "everything's gonna be alright" );

		} );

		QUnit.todo( "fadeIn", ( assert ) => {

			assert.ok( false, "everything's gonna be alright" );

		} );

		QUnit.todo( "fadeOut", ( assert ) => {

			assert.ok( false, "everything's gonna be alright" );

		} );

		QUnit.todo( "crossFadeFrom", ( assert ) => {

			assert.ok( false, "everything's gonna be alright" );

		} );

		QUnit.todo( "crossFadeTo", ( assert ) => {

			assert.ok( false, "everything's gonna be alright" );

		} );

		QUnit.todo( "stopFading", ( assert ) => {

			assert.ok( false, "everything's gonna be alright" );

		} );

		QUnit.todo( "setEffectiveTimeScale", ( assert ) => {

			assert.ok( false, "everything's gonna be alright" );

		} );

		QUnit.todo( "getEffectiveTimeScale", ( assert ) => {

			assert.ok( false, "everything's gonna be alright" );

		} );

		QUnit.todo( "setDuration", ( assert ) => {

			assert.ok( false, "everything's gonna be alright" );

		} );

		QUnit.todo( "syncWith", ( assert ) => {

			assert.ok( false, "everything's gonna be alright" );

		} );

		QUnit.todo( "halt", ( assert ) => {

			assert.ok( false, "everything's gonna be alright" );

		} );

		QUnit.todo( "warp", ( assert ) => {

			assert.ok( false, "everything's gonna be alright" );

		} );

		QUnit.todo( "stopWarping", ( assert ) => {

			assert.ok( false, "everything's gonna be alright" );

		} );

		QUnit.test( "getMixer", ( assert ) => {

            var { mixer, animationAction } = createAnimation();
            var mixer2 = animationAction.getMixer();
            assert.equal( mixer, mixer2, "mixer should be returned by getMixer." );

		} );

        QUnit.test("getClip", (assert) => {

            var { clip, animationAction } = createAnimation();
            var clip2 = animationAction.getClip();
            assert.equal( clip, clip2, "clip should be returned by getClip." );

		} );

		QUnit.test( "getRoot", ( assert ) => {

            var { root, animationAction } = createAnimation();
            var root2 = animationAction.getRoot();
            assert.equal(root, root2, "root should be returned by getRoot." );

		} );

	} );

} );
<commit_msg>fix soft tabs<commit_after>/**
 * @author TristanVALCKE / https://github.com/Itee
 */
/* global QUnit */

import { AnimationAction } from '../../../../src/animation/AnimationAction';
import { AnimationMixer } from '../../../../src/animation/AnimationMixer';
import { AnimationClip } from '../../../../src/animation/AnimationClip';
import { NumberKeyframeTrack } from '../../../../src/animation/tracks/NumberKeyframeTrack';
import { Object3D } from '../../../../src/core/Object3D';
import { LoopOnce, LoopRepeat, LoopPingPong } from '../../../../src/constants';

function createAnimation(){

	var root = new Object3D();
	var mixer = new AnimationMixer(root);
	var track = new NumberKeyframeTrack( ".rotation[x]", [ 0, 1000 ], [ 0, 360 ] );
	var clip = new AnimationClip( "clip1", 1000, [track] );

	var animationAction = mixer.clipAction( clip );
	return {
		root: root,
		mixer: mixer,
		track: track,
		clip: clip,
		animationAction: animationAction
	};

}

export default QUnit.module( 'Animation', () => {

	QUnit.module( 'AnimationAction', () => {

		// INSTANCING
		QUnit.test( "Instancing", ( assert ) => {

			var mixer = new AnimationMixer();
			var clip = new AnimationClip( "nonname", - 1, [] );

			var animationAction = new AnimationAction( mixer, clip );
			assert.ok( animationAction, "animationAction instanciated" );

		} );

		// PUBLIC STUFF
		QUnit.test( "play", ( assert ) => {

			var {mixer,animationAction} = createAnimation();
			var animationAction2 = animationAction.play();
			assert.equal( animationAction, animationAction2, "AnimationAction.play can be chained." );

			var UserException = function () {

				this.message = "AnimationMixer must activate AnimationAction on play.";

			};
			mixer._activateAction = function ( action ) {

				if ( action === animationAction ) {

					throw new UserException();

				}

			};
			assert.throws( () => {

				animationAction.play();

			}, new UserException() );

		} );

		QUnit.test( "stop", ( assert ) => {

			var {mixer,animationAction} = createAnimation();
			var animationAction2 = animationAction.stop();
			assert.equal( animationAction, animationAction2, "AnimationAction.stop can be chained." );

			var UserException = function () {

				this.message = "AnimationMixer must deactivate AnimationAction on stop.";

			};
			mixer._deactivateAction = function ( action ) {

				if ( action === animationAction ) {

					throw new UserException();

				}

			};
			assert.throws( () => {

				animationAction.stop();

			}, new UserException() );

		} );

		QUnit.test( "reset", ( assert ) => {

			var {mixer,animationAction} = createAnimation();
			var animationAction2 = animationAction.stop();
			assert.equal( animationAction, animationAction2, "AnimationAction.reset can be chained." );
			assert.equal( animationAction2.paused, false, "AnimationAction.reset() sets paused false" );
			assert.equal( animationAction2.enabled, true, "AnimationAction.reset() sets enabled true" );
			assert.equal( animationAction2.time, 0, "AnimationAction.reset() resets time." );
			assert.equal( animationAction2._loopCount, - 1, "AnimationAction.reset() resets loopcount." );
			assert.equal( animationAction2._startTime, null, "AnimationAction.reset() removes starttime." );

		} );

		QUnit.test( "isRunning", ( assert ) => {

			var {mixer,animationAction} = createAnimation();
			assert.notOk( animationAction.isRunning(), "When an animation is just made, it is not running." );
			animationAction.play();
			assert.ok( animationAction.isRunning(), "When an animation is started, it is running." );
			animationAction.stop();
			assert.notOk( animationAction.isRunning(), "When an animation is stopped, it is not running." );
			animationAction.play();
			animationAction.paused = true;
			assert.notOk( animationAction.isRunning(), "When an animation is paused, it is not running." );
			animationAction.paused = false;
			animationAction.enabled = false;
			assert.notOk( animationAction.isRunning(), "When an animation is not enabled, it is not running." );
			animationAction.enabled = true;
			assert.ok( animationAction.isRunning(), "When an animation is enabled, it is running." );

		} );

		QUnit.test( "isScheduled", ( assert ) => {

			var {mixer,animationAction} = createAnimation();
			assert.notOk( animationAction.isScheduled(), "When an animation is just made, it is not scheduled." );
			animationAction.play();
			assert.ok( animationAction.isScheduled(), "When an animation is started, it is scheduled." );
			mixer.update(1);
			assert.ok( animationAction.isScheduled(), "When an animation is updated, it is scheduled." );
			animationAction.stop();
			assert.notOk( animationAction.isScheduled(), "When an animation is stopped, it isn't scheduled anymore." );

		} );

		QUnit.test( "startAt", ( assert ) => {

			var {mixer,animationAction} = createAnimation();
			animationAction.startAt(2);
			animationAction.play();
			assert.notOk( animationAction.isRunning(), "When an animation is started at a specific time, it is not running." );
			assert.ok( animationAction.isScheduled(), "When an animation is started at a specific time, it is scheduled." );
			mixer.update(1);
			assert.notOk( animationAction.isRunning(), "When an animation is started at a specific time and the interval is not passed, it is not running." );
			assert.ok( animationAction.isScheduled(), "When an animation is started at a specific time and the interval is not passed, it is scheduled." );
			mixer.update(1);
			assert.ok( animationAction.isRunning(), "When an animation is started at a specific time and the interval is passed, it is running." );
			assert.ok( animationAction.isScheduled(), "When an animation is started at a specific time and the interval is passed, it is scheduled." );
			animationAction.stop();
			assert.notOk( animationAction.isRunning(), "When an animation is stopped, it is not running." );
			assert.notOk( animationAction.isScheduled(), "When an animation is stopped, it is not scheduled." );

		} );

		QUnit.test( "setLoop LoopOnce", ( assert ) => {

			var {mixer,animationAction} = createAnimation();
			animationAction.setLoop(LoopOnce);
			animationAction.play();
			assert.ok( animationAction.isRunning(), "When an animation is started, it is running." );
			mixer.update(500);
			assert.ok( animationAction.isRunning(), "When an animation is in the first loop, it is running." );
			mixer.update(500);
			assert.notOk( animationAction.isRunning(), "When an animation is ended, it is not running." );
			mixer.update(500);
			assert.notOk( animationAction.isRunning(), "When an animation is ended, it is not running." );

		} );

		QUnit.test( "setLoop LoopRepeat", ( assert ) => {

			var {mixer,animationAction} = createAnimation();
			animationAction.setLoop(LoopRepeat,3);
			animationAction.play();
			assert.ok( animationAction.isRunning(), "When an animation is started, it is running." );
			mixer.update(500);
			assert.ok( animationAction.isRunning(), "When an animation is in the first loop, it is running." );
			mixer.update(1000);
			assert.ok( animationAction.isRunning(), "When an animation is in second loop when in looprepeat 3 times, it is running." );
			mixer.update(1000);
			assert.ok( animationAction.isRunning(), "When an animation is in third loop when in looprepeat 3 times, it is running." );
			mixer.update(1000);
			assert.ok( animationAction.isRunning(), "When an animation is in fourth loop when in looprepeat 3 times, it is running." );
			mixer.update(1000);
			assert.notOk( animationAction.isRunning(), "When an animation ended his third loop when in looprepeat 3 times, it stays not running anymore." );

		} );

		QUnit.test( "setLoop LoopPingPong", ( assert ) => {

			var {mixer,animationAction} = createAnimation();
			animationAction.setLoop(LoopPingPong,3);
			animationAction.play();
			assert.ok( animationAction.isRunning(), "When an animation is started, it is running." );
			mixer.update(500);
			assert.ok( animationAction.isRunning(), "When an animation is in the first loop, it is running." );
			mixer.update(1000);
			assert.ok( animationAction.isRunning(), "When an animation is in second loop when in looprepeat 3 times, it is running." );
			mixer.update(1000);
			assert.ok( animationAction.isRunning(), "When an animation is in third loop when in looprepeat 3 times, it is running." );
			mixer.update(1000);
			assert.ok( animationAction.isRunning(), "When an animation is in fourth loop when in looprepeat 3 times, it is running." );
			mixer.update(1000);
			assert.notOk( animationAction.isRunning(), "When an animation ended his third loop when in looprepeat 3 times, it stays not running anymore." );

		} );

		QUnit.todo( "setEffectiveWeight", ( assert ) => {

			assert.ok( false, "everything's gonna be alright" );

		} );

		QUnit.todo( "getEffectiveWeight", ( assert ) => {

			assert.ok( false, "everything's gonna be alright" );

		} );

		QUnit.todo( "fadeIn", ( assert ) => {

			assert.ok( false, "everything's gonna be alright" );

		} );

		QUnit.todo( "fadeOut", ( assert ) => {

			assert.ok( false, "everything's gonna be alright" );

		} );

		QUnit.todo( "crossFadeFrom", ( assert ) => {

			assert.ok( false, "everything's gonna be alright" );

		} );

		QUnit.todo( "crossFadeTo", ( assert ) => {

			assert.ok( false, "everything's gonna be alright" );

		} );

		QUnit.todo( "stopFading", ( assert ) => {

			assert.ok( false, "everything's gonna be alright" );

		} );

		QUnit.todo( "setEffectiveTimeScale", ( assert ) => {

			assert.ok( false, "everything's gonna be alright" );

		} );

		QUnit.todo( "getEffectiveTimeScale", ( assert ) => {

			assert.ok( false, "everything's gonna be alright" );

		} );

		QUnit.todo( "setDuration", ( assert ) => {

			assert.ok( false, "everything's gonna be alright" );

		} );

		QUnit.todo( "syncWith", ( assert ) => {

			assert.ok( false, "everything's gonna be alright" );

		} );

		QUnit.todo( "halt", ( assert ) => {

			assert.ok( false, "everything's gonna be alright" );

		} );

		QUnit.todo( "warp", ( assert ) => {

			assert.ok( false, "everything's gonna be alright" );

		} );

		QUnit.todo( "stopWarping", ( assert ) => {

			assert.ok( false, "everything's gonna be alright" );

		} );

		QUnit.test( "getMixer", ( assert ) => {

			var { mixer, animationAction } = createAnimation();
			var mixer2 = animationAction.getMixer();
			assert.equal( mixer, mixer2, "mixer should be returned by getMixer." );

		} );

		QUnit.test("getClip", (assert) => {

			var { clip, animationAction } = createAnimation();
			var clip2 = animationAction.getClip();
			assert.equal( clip, clip2, "clip should be returned by getClip." );

		} );

		QUnit.test( "getRoot", ( assert ) => {

			var { root, animationAction } = createAnimation();
			var root2 = animationAction.getRoot();
			assert.equal(root, root2, "root should be returned by getRoot." );

		} );

	} );

} );
<|endoftext|>


<commit_before>import React from 'react';
import {extendObservable} from 'mobx';
import { Button, Glyphicon } from 'react-bootstrap';
const dateFormat = require('dateformat');

export default class WheelStore {
  constructor(){
    extendObservable(this, {
      date: "",
      segs: [
        {value: 'Career', score: 0},
        {value: 'Financial', score: 0},
        {value: 'Spiritual', score: 0},
        {value: 'Health', score: 0},
        {value: 'Intellectual', score: 0},
        {value: 'Family', score: 0},
        {value: 'Social', score: 0},
        {value: 'Environmental', score: 0}
      ],
      wheels: [],
      wheelDates: [],
      min: 1,
      step: 1,
      historyIndex: 0
    });
    // this.handleDelete = this.handleDelete.bind(this);
    this.loadWheelsFromServer = this.loadWheelsFromServer.bind(this);
    this.setDate = this.setDate.bind(this);
    this.addNewWheel = this.addNewWheel.bind(this);
    this.loadCanvas = this.loadCanvas.bind(this);
  }
  setDate(){
    let date = new Date;
    this.date = date;
    return dateFormat(date, "dddd, mmmm dS, yyyy, h:MM TT");
  }
  addNewWheel(wheel) {
    let segs = [];
    for(let i = 0; i < this.segs.length; i++){
      segs.push({
        value: this.segs[i].value,
        score: this.segs[i].score
      });
    }
    fetch('/wheel/wheels', {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        date: this.date,
        segs: segs
      })
    })
    .then(result => result.json())
    .then(result => this.wheels.push(result))
    .then(result => this.wheelDates.push(dateFormat(wheel.date,
      "mm/dd/yy")));
  }

  loadWheelsFromServer() {
    fetch('/wheel/wheels')
       .then(result => result.json())
       .then(wheels => this.wheels = wheels)
       .then(wheels => wheels.forEach(wheel => this.wheelDates.push(dateFormat(wheel.date,
         "mm/dd/yy"))))
       .then(wheels => console.log(this.wheelDates));
  }

  loadCanvas(){
    let theCanvas = document.getElementById('Canvas1');
    if (theCanvas && theCanvas.getContext) {
      let ctx = theCanvas.getContext("2d");
      if (ctx) {
        let x = 350;
        let y = 350;
        let r = 325;
        let a = 360/this.segs.length;
        let colorArr = ["red", "orange", "yellow", "brown", "blue", "indigo", "violet", "pink"];
        let symbolArr = [
          // "Career", "Financial", "Spiritual", "Health", "Intellectual", "Family",
          // "Social", "Environmental"
          '\uf0b1',
          '\uf155',
          '\uf2dd',
          '\uf21e',
          '\uf02d',
          '\uf0c0',
          '\uf2b5',
          '\uf0ac'

        ];

        let rad = a * (Math.PI / 180);
        ctx.strokeStyle = "black";
        ctx.fillStyle = "grey";
        ctx.lineWidth = 5;
        ctx.beginPath();
        ctx.arc(x,y,r,0,2*Math.PI);
        ctx.stroke();
        ctx.fill();
        ctx.strokeStyle = "black";
        ctx.lineWidth = 1;
        for(let i = 0; i < this.segs.length; i++){
          ctx.beginPath();
          ctx.moveTo(x,y);
          ctx.arc(x, y, this.segs[i].score * (r / 10), (i * rad), (i * rad) + rad, false);
          ctx.fillStyle = colorArr[i];
          ctx.fill();
          ctx.stroke();
        }
        for(let i = 0; i < this.segs.length; i++){
          ctx.beginPath();
          ctx.moveTo(x,y);
          ctx.lineTo( x + (r * Math.cos(i * rad)), y + (r * Math.sin(i * rad)));
          ctx.stroke();
          ctx.font='50px FontAwesome';
          ctx.fillText(symbolArr[i], x + ((r * 0.75) * Math.cos((i * rad)+(rad/2))), y + ((r * 0.75) * Math.sin((i * rad)+(rad/2))));
          // ctx.drawImage(symbolArr[i], x + (r * Math.cos(i * rad)), y + (r * Math.sin(i * rad)));
        }
      }
    }
    return theCanvas;
  }
}

//   handleDelete(imgId) {
//     let newList = this.images.filter(img => img._id !== imgId);
//     let allnewList = this.allImages.filter(img => img._id !== imgId);
//     this.images = newList;
//     this.allImages = allnewList;
//     fetch('/gifs/' + imgId, {
//       method: 'DELETE'
//     });
//   }
<commit_msg>fixed centering issue with font awesome<commit_after>import React from 'react';
import {extendObservable} from 'mobx';
import { Button, Glyphicon } from 'react-bootstrap';
const dateFormat = require('dateformat');

export default class WheelStore {
  constructor(){
    extendObservable(this, {
      date: "",
      segs: [
        {value: 'Career', score: 0},
        {value: 'Financial', score: 0},
        {value: 'Spiritual', score: 0},
        {value: 'Health', score: 0},
        {value: 'Intellectual', score: 0},
        {value: 'Family', score: 0},
        {value: 'Social', score: 0},
        {value: 'Environmental', score: 0}
      ],
      wheels: [],
      wheelDates: [],
      min: 1,
      step: 1,
      historyIndex: 0
    });
    // this.handleDelete = this.handleDelete.bind(this);
    this.loadWheelsFromServer = this.loadWheelsFromServer.bind(this);
    this.setDate = this.setDate.bind(this);
    this.addNewWheel = this.addNewWheel.bind(this);
    this.loadCanvas = this.loadCanvas.bind(this);
  }
  setDate(){
    let date = new Date;
    this.date = date;
    return dateFormat(date, "dddd, mmmm dS, yyyy, h:MM TT");
  }
  addNewWheel(wheel) {
    let segs = [];
    for(let i = 0; i < this.segs.length; i++){
      segs.push({
        value: this.segs[i].value,
        score: this.segs[i].score
      });
    }
    fetch('/wheel/wheels', {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        date: this.date,
        segs: segs
      })
    })
    .then(result => result.json())
    .then(result => this.wheels.push(result))
    .then(result => this.wheelDates.push(dateFormat(wheel.date,
      "mm/dd/yy")));
  }

  loadWheelsFromServer() {
    fetch('/wheel/wheels')
       .then(result => result.json())
       .then(wheels => this.wheels = wheels)
       .then(wheels => wheels.forEach(wheel => this.wheelDates.push(dateFormat(wheel.date,
         "mm/dd/yy"))))
       .then(wheels => console.log(this.wheelDates));
  }

  loadCanvas(){
    let theCanvas = document.getElementById('Canvas1');
    if (theCanvas && theCanvas.getContext) {
      let ctx = theCanvas.getContext("2d");
      if (ctx) {
        let x = 350;
        let y = 350;
        let r = 325;
        let a = 360/this.segs.length;
        let colorArr = ["red", "orange", "yellow", "brown", "blue", "indigo", "violet", "pink"];
        let symbolArr = [
          // "Career", "Financial", "Spiritual", "Health", "Intellectual", "Family",
          // "Social", "Environmental"
          '\uf0b1',
          ' \uf155',
          '\uf2dd',
          '\uf21e',
          '\uf02d',
          '\uf0c0',
          '\uf2b5',
          '\uf0ac'

        ];

        let rad = a * (Math.PI / 180);
        ctx.strokeStyle = "black";
        ctx.fillStyle = "grey";
        ctx.lineWidth = 1;
        ctx.beginPath();
        ctx.arc(x,y,r,0,2*Math.PI);
        ctx.stroke();
        ctx.fill();
        ctx.strokeStyle = "black";

        for(let i = 0; i < this.segs.length; i++){
          ctx.beginPath();
          ctx.moveTo(x,y);
          ctx.arc(x, y, this.segs[i].score * (r / 10), (i * -rad), (i * -rad) - rad, true);
          ctx.fillStyle = colorArr[i];
          ctx.fill();
          // ctx.stroke();
        }
        for(let i = 0; i < this.segs.length; i++){
          ctx.beginPath();
          ctx.moveTo(x,y);
          ctx.lineTo( x + (r * Math.cos(i * -rad)), y + (r * Math.sin(i * -rad)));
          ctx.stroke();
          ctx.font='50px FontAwesome';
          ctx.fillText(symbolArr[i], x - 28 + ((r * 0.75) * Math.cos((i * -rad) - (rad/2))), y + 15 + ((r * 0.75) * Math.sin((i * -rad) - (rad/2))));
          // ctx.drawImage(symbolArr[i], x + (r * Math.cos(i * rad)), y + (r * Math.sin(i * rad)));
        }
      }
    }
    return theCanvas;
  }
}

//   handleDelete(imgId) {
//     let newList = this.images.filter(img => img._id !== imgId);
//     let allnewList = this.allImages.filter(img => img._id !== imgId);
//     this.images = newList;
//     this.allImages = allnewList;
//     fetch('/gifs/' + imgId, {
//       method: 'DELETE'
//     });
//   }
<|endoftext|>