<commit_before>/*
Add the Material Design Style Ripple Effect on Click / Touch.
*/
(function ($) {
    var transparent;
    //only run this once. this addes an empty elment in boody root and gets the defintion of the browsers transparent color scheme.
    if (typeof (transparent) == "undefined") {
        // Get this browser's definition of no back ground / transprent, rgba(0,0,0,0) etc..
        // Must be appended else Chrome etc return 'initial'
        var $temp = $('
').appendTo('body');
        //now we just get the value given back to use by the browser for its spcific transparent color scheme.
        transparent = $temp.css('backgroundColor');
        //remove the temp object since were done with it.
        $temp.remove();
    }

    //add Material desing style rippple effect to a given element that animates on click / touch.
    $.fn.rippleEffect = function (options) {
        // Extend our default options with those provided.
        var opts = $.extend({}, $.fn.rippleEffect.defaults, options);

        return this.each(function () {

            $(this).on("click touchstart", function (e) {
                var $thisElement = $(this),
                eventPageX,
                eventPageY,
                inkX,
                inkY,
                maxDiameter,
                eventType = e.type,
                rippleColor,
                $inkSpan,
                $inkparent;

                //default append
                $inkparent = $thisElement;
                //check to see if were appending ink to a parent element other than the trigger
                //if you append to a parent item that item will have the ripple span and it may block access to links
                //all i had to do was give any of the siblings of the ripple a z-index of 1, some i had to set position to relative.
                if (opts.appendInkTo != "") {
                    $inkparent = $thisElement.closest(opts.appendInkTo);
                }

                // check to se if we have an ink, if not we need to add it in, we only need to do this once.
                if ($inkparent.find("." + opts.inkClass).length == 0) {
                    //add ink
                    $inkparent.append('');
                }
                //set the ink var targeting the ink within the element to prevent dup ink animates.
                $inkSpan = $inkparent.find("." + opts.inkContainerClass + " > " + " ." + opts.inkClass);

                //incase of quick double click or animate is present. remove the animation
                $inkSpan.removeClass("animate");

                //now if the ink has no height set we need to add it in.
                if (!$inkSpan.height() && !$inkSpan.width()) {
                    //use $thisElement width or height whichever is larger for the diameter to make a circle which can cover the entire element.
                    maxDiameter = Math.max($inkparent.outerWidth(), $inkparent.outerHeight());
                    //set width and height and get bg color for the
                    //see if ripple color was provided via data attr.

                    if (typeof ($thisElement.data("ripple")) != "undefined" && $thisElement.data("ripple") != "") {
                        rippleColor = $thisElement.data("ripple");
                    } else {
                        if (opts.inkColor != "") {
                            rippleColor = opts.inkColor;
                        } else {
                            //try and get from elemnt or parent what ever has a bg color and it will lighten or dark based on color.
                            rippleColor = getInkColor($inkparent, opts.inkDefaultColor);
                        }
                    }

                    //set h and w and ripple color.
                    $inkSpan.css({ height: maxDiameter, width: maxDiameter, "background-color": rippleColor });
                }

                //now that the ink is taken care of we need to set the position where it starts, which if from click.
                //get event type.
                if(eventType === "click"){
                    eventPageX = e.pageX;
                    eventPageY = e.pageY;
                } else if(eventType === "touchstart") {
                    var touch = (e.originalEvent.touches[0] || e.originalEvent.changedTouches[0]);
                    eventPageX = touch.pageX;
                    eventPageY = touch.pageY
                }

                inkX = eventPageX - $inkparent.offset().left - $inkSpan.width() / 2;
                inkY = eventPageY - $inkparent.offset().top - $inkSpan.height() / 2;
                $inkSpan.css({ top: inkY + 'px', left: inkX + 'px' }).addClass("animate");
                //remove animation after a little bit.
                setTimeout(function () {
                    $inkSpan.removeClass("animate")
                }, 800);

            });
        });
    };
    // Plugin defaults – added as a property on our plugin function.
    $.fn.rippleEffect.defaults = {
        inkContainerClass: "ripple",
        inkClass: "ink",
        //to avaoid a global default you can add data-ripple="#ff00ff" to the element that will have the ripple and that color will be used.
        inkDefaultColor: "#F0F0F0", //falback color to use if using parent traversing to get a bg color.
        inkColor: "", //the ink color you want the element to use, this will override any bg checks for element and parent traversing, but if the ement has data-ripple="#fff" the #fff will be used above all else
        //if you append to a parent item that item will have the ripple span and it may block access to links and child elements
        //all i had to do was give any of the children of the appended element a z-index of 1, some i had to set position to relative.
        appendInkTo: "" //append ink to a diffrent element. will find closest element matching.
    };

    //Now users can include a line like this in their scripts:
    //$.fn.rippleEffect.defaults.inkDefaultColor = "#0000FF";

    // Define our get background color function.
    //this will try and get a background color for the ink color manipulation
    //by starting with the element provided and going as far back to the body unless a value is found.
    //providing a falback value will make sure that an actual color is returned
    function getBackgroundColorForInk($element, fallback) {
        function getBgColor($elementToCheckForBg) {
            //here we check against the @transparent var that is set on load.
            if ($elementToCheckForBg.css('backgroundColor') == transparent) {
                //here we check if were not at body, if not, then run again on the elments parent, if were at body use fallback or the browers take on transparent.
                return !$elementToCheckForBg.is('body') ? getBgColor($elementToCheckForBg.parent()) : fallback || transparent;
            } else {
                //it was not transparent return this color.
                return $elementToCheckForBg.css('backgroundColor');
            }
        }
        //run the function which will repeate as long as it needs until it hits body to find a color to use.
        return getBgColor($element);
    };

    //create as a property so users can set make there own lum check.
    //returns the direction lumination should go for ink contrast.
    //get the lumination value for a given color.
    $.fn.rippleEffect.getLuminationValue = function (hexcolor) {
        var hexcolor = hexcolor.substring(1);      // strip #
        var rgb = parseInt(hexcolor, 16);   // convert rrggbb to decimal
        var r = (rgb >> 16) & 0xff;  // extract red
        var g = (rgb >> 8) & 0xff;  // extract green
        var b = (rgb >> 0) & 0xff;  // extract blue

        var luma = 0.2126 * r + 0.7152 * g + 0.0722 * b; // per ITU-R BT.709
        return luma;
    }

    //create as property, for user override.
    //this was from a site point article.
    //get a new color luminance -0.15 is darker by 15% and 0.20 is lighter by 20%
    $.fn.rippleEffect.getColorLuminance = function (hexcolor, lum) {
        // validate hex string
        hexcolor = String(hexcolor).replace(/[^0-9a-f]/gi, '');
        if (hexcolor.length < 6) {
            hexcolor = hexcolor[0] + hexcolor[0] + hexcolor[1] + hexcolor[1] + hexcolor[2] + hexcolor[2];
        }
        //set a default lum value.
        lum = lum || 0;

        // convert to decimal and change luminosity
        var resultHex = "#", c, i;
        for (i = 0; i < 3; i++) {
            c = parseInt(hexcolor.substr(i * 2, 2), 16);
            c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16);
            resultHex += ("00" + c).substr(c.length);
        }

        return resultHex;
    }

    //create property for overide if wanted, this converts an rgb value to hex.
    //it does not work right with rgba though it just returns the bas rgb part so the trans is not claculated in.
    $.fn.rippleEffect.colorToHex = function (rgb) {
        //first echeck to see if we already have a hex color, if so just return.
        if (rgb.substr(0, 1) === '#') {
            return color;
        }
        rgb = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
        return (rgb && rgb.length === 4) ? "#" +
         ("0" + parseInt(rgb[1], 10).toString(16)).slice(-2) +
         ("0" + parseInt(rgb[2], 10).toString(16)).slice(-2) +
         ("0" + parseInt(rgb[3], 10).toString(16)).slice(-2) : '';
    }

    //this is the base function that does all of the magic, it gets a bkg color,
    //then changes the colors lumanince so the ink is visiable when being animated.
    function getInkColor($element, fallBackColor) {
        // var $elem = $(this);
        var backgroundOrInhreitedBackGround,
            hex,
            luma,
            returnLumintion;
        //get back ground color of element / or parent with an actual color or use falback of a lighter gray
        // Call our getBackgroundColorForInk function.

        backgroundOrInhreitedBackGround = getBackgroundColorForInk($element, fallBackColor);
        //convert to hex, this returns hex if it is already hex.
        //call our colorToHex function
        hex = $.fn.rippleEffect.colorToHex(backgroundOrInhreitedBackGround);
        //now get the lumination value of this bg.
        //call our getLuminationValue function
        luma = $.fn.rippleEffect.getLuminationValue(hex);

        //239 for lighter lumination ok
        if (luma <= 239) {
            //go lighter alwasy prefered.
            //we need to make sure we are light enough though
            if (luma <= 70) {
                returnLumintion = $.fn.rippleEffect.getColorLuminance(hex, 0.80);
            } else {
                returnLumintion = $.fn.rippleEffect.getColorLuminance(hex, 0.20);
            }
        } else {
            //go darker
            returnLumintion = $.fn.rippleEffect.getColorLuminance(hex, -0.15);
        }
        return returnLumintion;
    };

    //appply
    $("[data-ripple]").rippleEffect();
})(jQuery);

<commit_msg>Added a way to use a target id for ripple color<commit_after>/*
Add the Material Design Style Ripple Effect on Click / Touch.
*/
(function ($) {
    var transparent;
    //only run this once. this addes an empty elment in boody root and gets the defintion of the browsers transparent color scheme.
    if (typeof (transparent) == "undefined") {
        // Get this browser's definition of no back ground / transprent, rgba(0,0,0,0) etc..
        // Must be appended else Chrome etc return 'initial'
        var $temp = $('
').appendTo('body');
        //now we just get the value given back to use by the browser for its spcific transparent color scheme.
        transparent = $temp.css('backgroundColor');
        //remove the temp object since were done with it.
        $temp.remove();
    }

    //add Material desing style rippple effect to a given element that animates on click / touch.
    $.fn.rippleEffect = function (options) {
        // Extend our default options with those provided.
        var opts = $.extend({}, $.fn.rippleEffect.defaults, options);

        return this.each(function () {

            $(this).on("click", function (e) {
                var $thisElement = $(this),
                eventPageX,
                eventPageY,
                inkX,
                inkY,
                maxDiameter,
                eventType = e.type,
                rippleColor,
                $inkSpan,
                $inkparent;

                //default append
                $inkparent = $thisElement;

                function getRippleColorFromTraverse() {
                    if (opts.inkColor != "") {
                        return opts.inkColor;
                    } else {
                        //try and get from elemnt or parent what ever has a bg color and it will lighten or dark based on color.
                        return getInkColor($inkparent, opts.inkDefaultColor);
                    }
                }
                //check to see if were appending ink to a parent element other than the trigger
                //if you append to a parent item that item will have the ripple span and it may block access to links
                //all i had to do was give any of the siblings of the ripple a z-index of 1, some i had to set position to relative.
                if (opts.appendInkTo != "") {
                    $inkparent = $thisElement.closest(opts.appendInkTo);
                }
                // check to se if we have an ink, if not we need to add it in, we only need to do this once.
                if ($inkparent.find("." + opts.inkClass).length == 0) {
                    //add ink
                    $inkparent.append('');
                }
                //set the ink var targeting the ink within the element to prevent dup ink animates.
                $inkSpan = $inkparent.find("." + opts.inkContainerClass + " > " + " ." + opts.inkClass);
                //incase of quick double click or animate is present. remove the animation
                $inkSpan.removeClass("animate");

                //now if the ink has no height set we need to add it in.
                if (!$inkSpan.height() && !$inkSpan.width()) {
                    //use $thisElement width or height whichever is larger for the diameter to make a circle which can cover the entire element.
                    maxDiameter = Math.max($inkparent.outerWidth(), $inkparent.outerHeight());
                    //set width and height and get bg color for the
                    //see if ripple color was provided via data attr.
                    if (typeof ($thisElement.data("ripple")) != "undefined" && $thisElement.data("ripple") != "") {
                        rippleColor = $thisElement.data("ripple");
                    } else {
                        //check if a target element id to get a ripple color from is provided
                        if (typeof ($thisElement.data("ripple-getcolorfromid")) != "undefined" && $thisElement.data("ripple-getcolorfromid") != "") {
                            var idToUse = $thisElement.data("ripple-getcolorfromid");
                            //make sure element is on page.
                            if ($(idToUse).length > 0) {
                                //set from given elmements bgcolor.
                                rippleColor = $(idToUse).css("background-color");
                            } else {
                                //get from default ways
                                rippleColor = getRippleColorFromTraverse();
                            }
                        } else {
                            //get from default ways
                            rippleColor = getRippleColorFromTraverse();
                        }
                    }
                    //set h and w and ripple color.
                    $inkSpan.css({ height: maxDiameter, width: maxDiameter, "background-color": rippleColor });
                }

                //now that the ink is taken care of we need to set the position where it starts, which if from click.
                //get event type.
                if(eventType === "click"){
                    eventPageX = e.pageX;
                    eventPageY = e.pageY;
                } else if(eventType === "touchstart") {
                    var touch = (e.originalEvent.touches[0] || e.originalEvent.changedTouches[0]);
                    eventPageX = touch.pageX;
                    eventPageY = touch.pageY
                }

                inkX = (eventPageX - $inkparent.offset().left - $inkSpan.width() / 2);
                inkY = (eventPageY - $inkparent.offset().top - $inkSpan.height() / 2);
                $inkSpan.css({ top: inkY + 'px', left: inkX + 'px' }).addClass("animate");
                //remove animation after a little bit.
                setTimeout(function () {
                    $inkSpan.removeClass("animate")
                }, 800);

            });
        });
    };
    // Plugin defaults – added as a property on our plugin function.
    $.fn.rippleEffect.defaults = {
        inkContainerClass: "ripple",
        inkClass: "ink",
        //to avoid a global default you can add data-ripple="#ff00ff" to the element that will have the ripple and that color will be used.
        //or to use a tagrget elements background color for the ripple you can set the data-ripple="" and data-ripple-getcolorfromid="#elmentWIthBGColorToUSe"
        inkDefaultColor: "#F0F0F0", //falback color to use if using parent traversing to get a bg color.
        inkColor: "", //the ink color you want the element to use, this will override any bg checks for element and parent traversing, but if the ement has data-ripple="#fff" the #fff will be used above all else
        //if you append to a parent item that item will have the ripple span and it may block access to links and child elements
        //all i had to do was give any of the children of the appended element a z-index of 1, some i had to set position to relative.
        appendInkTo: "" //append ink to a diffrent element. will find closest element matching.
    };

    //Now users can include a line like this in their scripts:
    //$.fn.rippleEffect.defaults.inkDefaultColor = "#0000FF";

    // Define our get background color function.
    //this will try and get a background color for the ink color manipulation
    //by starting with the element provided and going as far back to the body unless a value is found.
    //providing a falback value will make sure that an actual color is returned
    function getBackgroundColorForInk($element, fallback) {
        function getBgColor($elementToCheckForBg) {
            //here we check against the @transparent var that is set on load.
            if ($elementToCheckForBg.css('backgroundColor') == transparent) {
                //here we check if were not at body, if not, then run again on the elments parent, if were at body use fallback or the browers take on transparent.
                return !$elementToCheckForBg.is('body') ? getBgColor($elementToCheckForBg.parent()) : fallback || transparent;
            } else {
                //it was not transparent return this color.
                return $elementToCheckForBg.css('backgroundColor');
            }
        }
        //run the function which will repeate as long as it needs until it hits body to find a color to use.
        return getBgColor($element);
    };

    //create as a property so users can set make there own lum check.
    //returns the direction lumination should go for ink contrast.
    //get the lumination value for a given color.
    $.fn.rippleEffect.getLuminationValue = function (hexcolor) {
        var hexcolor = hexcolor.substring(1);      // strip #
        var rgb = parseInt(hexcolor, 16);   // convert rrggbb to decimal
        var r = (rgb >> 16) & 0xff;  // extract red
        var g = (rgb >> 8) & 0xff;  // extract green
        var b = (rgb >> 0) & 0xff;  // extract blue

        var luma = 0.2126 * r + 0.7152 * g + 0.0722 * b; // per ITU-R BT.709
        return luma;
    }

    //create as property, for user override.
    //this was from a site point article.
    //get a new color luminance -0.15 is darker by 15% and 0.20 is lighter by 20%
    $.fn.rippleEffect.getColorLuminance = function (hexcolor, lum) {
        // validate hex string
        hexcolor = String(hexcolor).replace(/[^0-9a-f]/gi, '');
        if (hexcolor.length < 6) {
            hexcolor = hexcolor[0] + hexcolor[0] + hexcolor[1] + hexcolor[1] + hexcolor[2] + hexcolor[2];
        }
        //set a default lum value.
        lum = lum || 0;

        // convert to decimal and change luminosity
        var resultHex = "#", c, i;
        for (i = 0; i < 3; i++) {
            c = parseInt(hexcolor.substr(i * 2, 2), 16);
            c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16);
            resultHex += ("00" + c).substr(c.length);
        }

        return resultHex;
    }

    //create property for overide if wanted, this converts an rgb value to hex.
    //it does not work right with rgba though it just returns the bas rgb part so the trans is not claculated in.
    $.fn.rippleEffect.colorToHex = function (rgb) {
        //first echeck to see if we already have a hex color, if so just return.
        if (rgb.substr(0, 1) === '#') {
            return color;
        }
        rgb = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
        return (rgb && rgb.length === 4) ? "#" +
         ("0" + parseInt(rgb[1], 10).toString(16)).slice(-2) +
         ("0" + parseInt(rgb[2], 10).toString(16)).slice(-2) +
         ("0" + parseInt(rgb[3], 10).toString(16)).slice(-2) : '';
    }

    //this is the base function that does all of the magic, it gets a bkg color,
    //then changes the colors lumanince so the ink is visiable when being animated.
    function getInkColor($element, fallBackColor) {
        var backgroundOrInhreitedBackGround,
            hex,
            luma,
            returnLumintion;
        //get back ground color of element / or parent with an actual color or use fallback of a lighter gray
        // Call our getBackgroundColorForInk function.

        backgroundOrInhreitedBackGround = getBackgroundColorForInk($element, fallBackColor);
        //convert to hex, this returns hex if it is already hex.
        //call our colorToHex function
        hex = $.fn.rippleEffect.colorToHex(backgroundOrInhreitedBackGround);
        //now get the lumination value of this bg.
        //call our getLuminationValue function
        luma = $.fn.rippleEffect.getLuminationValue(hex);

        //239 for lighter lumination ok
        if (luma <= 239) {
            //go lighter alwasy prefered.
            //we need to make sure we are light enough though
            if (luma <= 70) {
                returnLumintion = $.fn.rippleEffect.getColorLuminance(hex, 0.80);
            } else {
                returnLumintion = $.fn.rippleEffect.getColorLuminance(hex, 0.20);
            }
        } else {
            //go darker
            returnLumintion = $.fn.rippleEffect.getColorLuminance(hex, -0.15);
        }
        return returnLumintion;
    };

    //appply
    $("[data-ripple]").rippleEffect();
})(jQuery);

<|endoftext|>


<commit_before>'use strict';

var unserializeValue = require('dbjs/_setup/unserialize/value')
  , serializeValue   = require('dbjs/_setup/serialize/value')
  , getDbSet         = require('eregistrations/server/utils/get-db-set');

module.exports = function (storage, officials, step) {
	var id = step.shortPath, officialsArray, lastIndex,
		path = step.__id__.slice(step.master.__id__.length + 1);

	officialsArray = officials.toArray();

	var addAssignee = function (businessProcessId) {
		return storage.get(businessProcessId + '/' + path + '/assignee')(function (data) {
			if (data && data.value[0] === '7') return;
			var officialId, nextIndex, businessProcess;
			lastIndex = nextIndex = officialsArray[lastIndex + 1] ? lastIndex + 1 : 0;
			officialId = officialsArray[nextIndex];
			businessProcess = storage.db.BusinessProcess.getById(businessProcessId);
			businessProcess.resolveSKeyPath(path).value.assignee =
				storage.db.User.getById(officialId);
			storage.store('processingStepAutoAssignLastIndex/' + id, serializeValue(nextIndex));
//      Use the below two lines once dbjs listens to storage changes
//      storage.store(businessProcessId + '/' + path + '/assignee', 7 + officialId)(function () {
//      storage.store('processingStepAutoAssignLastIndex/' + id, serializeValue(nextIndex));
		});
	};

	storage.get('processingStepAutoAssignLastIndex/' + id)(function (data) {
		return (data && unserializeValue(data.value)) || 0;
	}).then(function (index) {
		lastIndex = index;
		getDbSet('computed', path + '/resolvedStatus',
			serializeValue('pending'))(function (businessProcesses) {
			businessProcesses.on('change', function (ev) {
				if (ev.type === 'delete') return;
				if (ev.type === 'add') {
					addAssignee(ev.value);
					return;
				}
				if (ev.type === 'batch') {
					if (!ev.added) return;
					ev.added.forEach(addAssignee);
					return;
				}

				throw new Error("Unsupported event: " + ev.type);
			});

			businessProcesses.forEach(addAssignee);
		});
	});
};
<commit_msg>#1075 removed redundant variable<commit_after>'use strict';

var unserializeValue = require('dbjs/_setup/unserialize/value')
  , serializeValue   = require('dbjs/_setup/serialize/value')
  , getDbSet         = require('eregistrations/server/utils/get-db-set');

module.exports = function (storage, officials, step) {
	var id = step.shortPath, officialsArray, lastIndex,
		path = step.__id__.slice(step.master.__id__.length + 1);

	officialsArray = officials.toArray();

	var addAssignee = function (businessProcessId) {
		return storage.get(businessProcessId + '/' + path + '/assignee')(function (data) {
			if (data && data.value[0] === '7') return;
			var officialId, businessProcess;
			lastIndex = officialsArray[lastIndex + 1] ? lastIndex + 1 : 0;
			officialId = officialsArray[lastIndex];
			businessProcess = storage.db.BusinessProcess.getById(businessProcessId);
			businessProcess.resolveSKeyPath(path).value.assignee =
				storage.db.User.getById(officialId);
			storage.store('processingStepAutoAssignLastIndex/' + id, serializeValue(lastIndex));
//      Use the below two lines once dbjs listens to storage changes
//      storage.store(businessProcessId + '/' + path + '/assignee', 7 + officialId)(function () {
//      storage.store('processingStepAutoAssignLastIndex/' + id, serializeValue(lastIndex));
		});
	};

	storage.get('processingStepAutoAssignLastIndex/' + id)(function (data) {
		return (data && unserializeValue(data.value)) || 0;
	}).then(function (index) {
		lastIndex = index;
		getDbSet('computed', path + '/resolvedStatus',
			serializeValue('pending'))(function (businessProcesses) {
			businessProcesses.on('change', function (ev) {
				if (ev.type === 'delete') return;
				if (ev.type === 'add') {
					addAssignee(ev.value);
					return;
				}
				if (ev.type === 'batch') {
					if (!ev.added) return;
					ev.added.forEach(addAssignee);
					return;
				}

				throw new Error("Unsupported event: " + ev.type);
			});

			businessProcesses.forEach(addAssignee);
		});
	});
};
<|endoftext|>


<commit_before>const fs = require('fs');
const request = require('request');

const dir = __dirname.replace(/\/scripts\/?$/, '');
const leagues = require(`${dir}/data/leagues.json`);
const prefix = 'schedule-';
const teams = require(`${dir}/data/teams.json`);
let [league, team] = process.argv.slice(2);

if (!leagues[league]) {
	console.error(`Invalid league: ${league}`);
	process.exit();
} else
	league = leagues[league];

if (!teams[team]) {
	console.error(`Invalid team: ${team}`);
	process.exit();
} else
	team = teams[team];

const path = `${dir}/data/${prefix}${league.id}-${team.id}.json`;
console.log(`Downloading schedule for S${league.season} ${league.name} ${team.name}`);

function downloadSchedule() {
	let regex0 = new RegExp(`
]+)?>]+)?>(.*?)	]+)?>.*?	]+)?>]+)?page=game&(?:amp;)?gameid=(\\d+)&(?:amp;)?leagueid=${league.id}&(?:amp;)?seasonid=${league.season}(?:[^>]+)?>]+)?/team(\\d+).png(?:[^>]+)?>(.*?)(?: - (\\d+))? @ ]+)?/team(\\d+).png(?:[^>]+)?>(.*?)(?: - (\\d+))?
`, 'ig');
	let regex1 = new RegExp(regex0.source, regex0.flags.replace('g', ''));

	request(`http://www.leaguegaming.com/forums/index.php?leaguegaming/league&action=league_page&page=team_page_schedule&teamid=${team.id}&leagueid=${league.id}&seasonid=${league.season}`, (err, res, html) => {
		if (!err) {
			if (res.statusCode != 200)
				err = new Error(`Failed to fetch schedule for S${league.season} ${league.name} ${team.name} (status=${res.statusCode})`);
			else if (!/^text\/html/.test(res.headers['content-type']))
				err = new Error(`Failed to fetch schedule for S${league.season} ${league.name} ${team.name} (content-type=${res.headers['content-type']})`);
		}

		if (err) {
			console.error(err.message);
			return resolve();
		}

		let data = html.replace(/>\s+</g, '><').match(regex0);

		if (!data)
			process.exit();

		let oldSchedule = require(path), newSchedule = {}, updated = false, updating = !!Object.keys(oldSchedule).length;

		for (let i = 0, end = data.length; i < end; i++) {
			let gameData = data[i].match(regex1);

			if (!gameData)
				continue;

			let game = {date: gameData[1].replace(' -  ', ''), home: {id: parseInt(gameData[6]), name: gameData[7].trim(), score: !isNaN(gameData[8]) ? parseInt(gameData[8]) : null}, id: parseInt(gameData[2]), updated: false, visitor: {id: parseInt(gameData[3]), name: gameData[4].trim(), score: !isNaN(gameData[5]) ? parseInt(gameData[5]) : null}};

			if (oldSchedule[game.id])
				game.updated = JSON.stringify(oldSchedule[game.id]).replace(/,"updated":.*?/, '') != JSON.stringify(game).replace(/,"updated":.*?/, '');
			else
				game.updated = updating;

			newSchedule[game.id] = game;
			udpates = updated || game.updated;
		}

		if (!updated)
			process.exit();

		fs.writeFile(path, JSON.stringify(newSchedule), err => {
			if (err)
				console.error(err.message);

			process.exit();
		 });
	});
}

fs.stat(path, err => {
	if (err)
		fs.writeFile(path, '{}', downloadSchedule);
	else
		downloadSchedule();
});<commit_msg>Fixed typo<commit_after>const fs = require('fs');
const request = require('request');

const dir = __dirname.replace(/\/scripts\/?$/, '');
const leagues = require(`${dir}/data/leagues.json`);
const prefix = 'schedule-';
const teams = require(`${dir}/data/teams.json`);
let [league, team] = process.argv.slice(2);

if (!leagues[league]) {
	console.error(`Invalid league: ${league}`);
	process.exit();
} else
	league = leagues[league];

if (!teams[team]) {
	console.error(`Invalid team: ${team}`);
	process.exit();
} else
	team = teams[team];

const path = `${dir}/data/${prefix}${league.id}-${team.id}.json`;
console.log(`Downloading schedule for S${league.season} ${league.name} ${team.name}`);

function downloadSchedule() {
	let regex0 = new RegExp(`
]+)?>]+)?>(.*?)	]+)?>.*?	]+)?>]+)?page=game&(?:amp;)?gameid=(\\d+)&(?:amp;)?leagueid=${league.id}&(?:amp;)?seasonid=${league.season}(?:[^>]+)?>]+)?/team(\\d+).png(?:[^>]+)?>(.*?)(?: - (\\d+))? @ ]+)?/team(\\d+).png(?:[^>]+)?>(.*?)(?: - (\\d+))?
`, 'ig');
	let regex1 = new RegExp(regex0.source, regex0.flags.replace('g', ''));

	request(`http://www.leaguegaming.com/forums/index.php?leaguegaming/league&action=league_page&page=team_page_schedule&teamid=${team.id}&leagueid=${league.id}&seasonid=${league.season}`, (err, res, html) => {
		if (!err) {
			if (res.statusCode != 200)
				err = new Error(`Failed to fetch schedule for S${league.season} ${league.name} ${team.name} (status=${res.statusCode})`);
			else if (!/^text\/html/.test(res.headers['content-type']))
				err = new Error(`Failed to fetch schedule for S${league.season} ${league.name} ${team.name} (content-type=${res.headers['content-type']})`);
		}

		if (err) {
			console.error(err.message);
			return resolve();
		}

		let data = html.replace(/>\s+</g, '><').match(regex0);

		if (!data)
			process.exit();

		let oldSchedule = require(path), newSchedule = {}, updated = false, updating = !!Object.keys(oldSchedule).length;

		for (let i = 0, end = data.length; i < end; i++) {
			let gameData = data[i].match(regex1);

			if (!gameData)
				continue;

			let game = {date: gameData[1].replace(' -  ', ''), home: {id: parseInt(gameData[6]), name: gameData[7].trim(), score: !isNaN(gameData[8]) ? parseInt(gameData[8]) : null}, id: parseInt(gameData[2]), updated: false, visitor: {id: parseInt(gameData[3]), name: gameData[4].trim(), score: !isNaN(gameData[5]) ? parseInt(gameData[5]) : null}};

			if (oldSchedule[game.id])
				game.updated = JSON.stringify(oldSchedule[game.id]).replace(/,"updated":.*?/, '') != JSON.stringify(game).replace(/,"updated":.*?/, '');
			else
				game.updated = updating;

			newSchedule[game.id] = game;
			updated = updated || game.updated;
		}

		if (!updated)
			process.exit();

		fs.writeFile(path, JSON.stringify(newSchedule), err => {
			if (err)
				console.error(err.message);

			process.exit();
		 });
	});
}

fs.stat(path, err => {
	if (err)
		fs.writeFile(path, '{}', downloadSchedule);
	else
		downloadSchedule();
});<|endoftext|>


<commit_before>var TMT = TMT || {};
//title screen
TMT.Achievements = function () {};

var arr = [];

TMT.Achievements.prototype = {
	preload: function () {},
	create: function () {
		var handtime = '';
		var desttime = '';
		var harmtime = '';

		// Set background and give background speed in x
		this.background = this.game.add.tileSprite(0, 0, this.game.width, this.game.height, 'peaks');

		// Add back button
		this.backButton = this.game.add.button(this.game.width / 2, this.game.height * 0.9, 'backUp', this.backClickEvent, this);
		this.backButton.events.onInputDown.add(this.touchDown, this);
		this.backButton.anchor.setTo(0.5, 0.8);
		this.backButton.scale.set(0.5, 0.5);

		if(3 > 0) {
		//if (arr.length > 0) {
			// Add text title: player and score
			this.game.add.text(this.game.width / 2 - 80, 64, 'Achievements', {
				font: "25px Arial",
				fill: this.generateHexColor(),
				stroke: '#000000',
				strokeThickness: 5
			});
			this.game.add.text(this.game.width / 2 - 200, 64 + 1 * 32, 'Name', {
				font: "25px Arial",
				fill: this.generateHexColor(),
				stroke: '#000000',
				strokeThickness: 5
			});
			this.game.add.text(this.game.width / 2, 64 + 1 * 32, 'Description', {
				font: "25px Arial",
				fill: this.generateHexColor(),
				stroke: '#000000',
				strokeThickness: 4
			});
			// add all data
				this.game.add.text(this.game.width / 2 - 200, this.game.height * 0.3, 'No Hands!', {
					font: "20px Arial",
					fill: this.generateHexColor(),
					stroke: '#000000',
					strokeThickness: 4
				});
				this.game.add.text(this.game.width / 2 - 200, this.game.height * 0.5, 'Vehicular \nDestruction!',{
					font: "20px Arial",
					fill: this.generateHexColor(),
					stroke: '#000000',
					strokeThickness: 4
				});
			this.game.add.text(this.game.width / 2 - 200, this.game.height * 0.7, 'Unharmed!', {
					font: "20px Arial",
					fill: this.generateHexColor(),
					stroke: '#000000',
					strokeThickness: 4
				});
			this.readBoardData();
			// add all data
            for (var i = 0; i < arr.length; i++)
            {//arr[i][1]
                if (arr[i][0] === $('#Name').val()){
					if (arr[i][1] === 'nohands'){
						NOHANDS = true;
						handtime = arr[i][2];
					}
					if (arr[i][1] === 'destruction'){
						VEHICULARDESTRUCTION = true;
						desttime = arr[i][2];
					}
					if (arr[i][1] === 'unharmed'){
						UNHARMED = true;
						harmtime = arr[i][2];
					}
				}
            }

			var unharmed;
			var vehicular;
			var nohands;
			var nope = 'Not yet achieved';
			//UNHARMED = VEHICULARDESTRUCTION = NOHANDS = true;
			if(UNHARMED)
				unharmed = 'You spared a vehicle\'s life!';
			else
				unharmed = nope;

			if(VEHICULARDESTRUCTION)
				vehicular = 'You murdered a vehicle!';
			else
				vehicular = nope;

			if(NOHANDS)
				nohands = 'You didn\'t touch any \ntiles that round';
			else
				nohands = nope;

			this.game.add.text(this.game.width / 2, this.game.height * 0.3, unharmed + '\n' + harmtime, {
					font: "20px Arial",
					fill: this.generateHexColor(),
					stroke: '#000000',
					strokeThickness: 4
				});
			this.game.add.text(this.game.width / 2, this.game.height * 0.5, vehicular+ '\n' + desttime, {
					font: "20px Arial",
					fill: this.generateHexColor(),
					stroke: '#000000',
					strokeThickness: 4
				});
			this.game.add.text(this.game.width / 2, this.game.height * 0.7, nohands+ '\n' + handtime, {
					font: "20px Arial",
					fill: this.generateHexColor(),
					stroke: '#000000',
					strokeThickness: 4
				});
			arr = [];
		}
	},
	update: function () {
		/*
		    If arr array has data, then we draw text into the page.
		*/

	},

	touchDown: function () {
		if (this.game.input.pointer1.isDown) {
			this.backButton.loadTexture('backDown');
		}
		this.backButton.loadTexture('backDown');
	},
	getData: function() {

	},
	/*
	    This ajax method will set a GET request to server and receive back a JSON data.
	    Then it convert JSON data into JavaScript array.
	*/
	readBoardData: function () {
		$.ajax({
			type: "GET",
			url: "getAchievements.php",
			data: "",
			dataType: 'json',
			success: function (data) {
				for (var i = 0; i < data.length; i++) {
					arr[i] = $.map(data[i], function (el) {
						return el;
					});
				}
				// console.log(data);
				// console.log(arr);
			},
			error: function (xhr, status, error) {
				// check status && error
				alert(xhr + "\n" + status + "\n" + error);
			},
		});
	},

	// Generate a random color code
	generateHexColor: function () {
		return '#' + ((0.5 + 0.5 * Math.random()) * 0xFFFFFF << 0).toString(16);
	},//
	// Event for Back Button
	backClickEvent: function () {
		this.game.state.start('MainMenu');
	}
};<commit_msg>Getting achievements works if the user is correct.<commit_after>var TMT = TMT || {};
//title screen
TMT.Achievements = function () {};

var arr = [];
var handtime = '';
	var desttime = '';
	var harmtime = '';
TMT.Achievements.prototype = {
	preload: function () {},
	create: function () {

		// Set background and give background speed in x
		this.background = this.game.add.tileSprite(0, 0, this.game.width, this.game.height, 'peaks');

		// Add back button
		this.backButton = this.game.add.button(this.game.width / 2, this.game.height * 0.9, 'backUp', this.backClickEvent, this);
		this.backButton.events.onInputDown.add(this.touchDown, this);
		this.backButton.anchor.setTo(0.5, 0.8);
		this.backButton.scale.set(0.5, 0.5);

		// Add text title: player and score
		this.game.add.text(this.game.width / 2 - 80, 64, 'Achievements', {
			font: "25px Arial",
			fill: this.generateHexColor(),
			stroke: '#000000',
			strokeThickness: 5
		});
		this.game.add.text(this.game.width / 2 - 200, 64 + 1 * 32, 'Name', {
			font: "25px Arial",
			fill: this.generateHexColor(),
			stroke: '#000000',
			strokeThickness: 5
		});
		this.game.add.text(this.game.width / 2, 64 + 1 * 32, 'Description', {
			font: "25px Arial",
			fill: this.generateHexColor(),
			stroke: '#000000',
			strokeThickness: 4
		});
		// add all data
			this.game.add.text(this.game.width / 2 - 200, this.game.height * 0.3, 'No Hands!', {
				font: "20px Arial",
				fill: this.generateHexColor(),
				stroke: '#000000',
				strokeThickness: 4
			});
			this.game.add.text(this.game.width / 2 - 200, this.game.height * 0.5, 'Vehicular \nDestruction!',{
				font: "20px Arial",
				fill: this.generateHexColor(),
				stroke: '#000000',
				strokeThickness: 4
			});
		this.game.add.text(this.game.width / 2 - 200, this.game.height * 0.7, 'Unharmed!', {
				font: "20px Arial",
				fill: this.generateHexColor(),
				stroke: '#000000',
				strokeThickness: 4
			});
		this.readBoardData();

	},
	update: function () {
		/*
		    If arr array has data, then we draw text into the page.
		*/
		if (arr.length > 0) {
					// add all data
			for (var i = 0; i < arr.length; i++)
			{//arr[i][1]
				if (arr[i][0] === $('#Name').val()){
					if (arr[i][1] === 'nohands'){
						NOHANDS = true;
						handtime = arr[i][2];
					}
					if (arr[i][1] === 'destruction'){
						VEHICULARDESTRUCTION = true;
						desttime = arr[i][2];
					}
					if (arr[i][1] === 'unharmed'){
						UNHARMED = true;
						harmtime = arr[i][2];
					}
				}
			}

			var unharmed;
			var vehicular;
			var nohands;
			var nope = 'Not yet achieved';
			//UNHARMED = VEHICULARDESTRUCTION = NOHANDS = true;
			if(UNHARMED)
				unharmed = 'You spared a vehicle\'s life';
			else
				unharmed = nope;

			if(VEHICULARDESTRUCTION)
				vehicular = 'You murdered a vehicle!';
			else
				vehicular = nope;

			if(NOHANDS)
				nohands = 'You didn\'t touch any \ntiles for a round';
			else
				nohands = nope;

			//console.log('read data' + arr.length);
			this.game.add.text(this.game.width / 2, this.game.height * 0.3, unharmed + '\n' + harmtime, {
					font: "20px Arial",
					fill: this.generateHexColor(),
					stroke: '#000000',
					strokeThickness: 4
				});
			this.game.add.text(this.game.width / 2, this.game.height * 0.5, vehicular+ '\n' + desttime, {
					font: "20px Arial",
					fill: this.generateHexColor(),
					stroke: '#000000',
					strokeThickness: 4
				});
			this.game.add.text(this.game.width / 2, this.game.height * 0.7, nohands+ '\n' + handtime, {
					font: "20px Arial",
					fill: this.generateHexColor(),
					stroke: '#000000',
					strokeThickness: 4
				});
			arr = [];
		}

	},

	touchDown: function () {
		if (this.game.input.pointer1.isDown) {
			this.backButton.loadTexture('backDown');
		}
		this.backButton.loadTexture('backDown');
	},
	getData: function() {

	},
	/*
	    This ajax method will set a GET request to server and receive back a JSON data.
	    Then it convert JSON data into JavaScript array.
	*/
	readBoardData: function () {
		$.ajax({
			type: "GET",
			url: "getAchievements.php",
			data: "",
			dataType: 'json',
			success: function (data) {
				for (var i = 0; i < data.length; i++) {
					arr[i] = $.map(data[i], function (el) {
						return el;
					});
				}
				 //console.log(data);
				 //console.log(arr);
			},
			error: function (xhr, status, error) {
				// check status && error
				alert(xhr + "\n" + status + "\n" + error);
			},
		});
	},

	// Generate a random color code
	generateHexColor: function () {
		return '#' + ((0.5 + 0.5 * Math.random()) * 0xFFFFFF << 0).toString(16);
	},//
	// Event for Back Button
	backClickEvent: function () {
		handtime = '';
		desttime = '';
		harmtime = '';
		this.game.state.start('MainMenu');
	}
};<|endoftext|>


<commit_before>/**
 * This should be included on every page.
 */
jQuery(document).ready(function () {
    if (!getCookie("hideBanner")) { //cookie to hide banner for 1 day
        jQuery('#message_banner').show();
    }
    $('[data-toggle="tooltip"]').tooltip({container: 'body'}); //enable tooltips

    jQuery('[data-toggle="offcanvas"]').click(function () {
        jQuery('.row-offcanvas').toggleClass('active');
        jQuery('body').toggleClass('hidden-overflow-x');
    });
    jQuery('[data-toggle="search"]').click(function () {
        var target = $(this).data().target;
        jQuery(target).css('margin-top', '32px');
        jQuery(target).toggleClass('hidden-xs');
    });
    jQuery('[data-dismiss="alert"]').click(function() {
        setCookie('hideBanner',"true", 1);
    });

    jQuery('[data-toggle="theater"]').click(function (e){
        e.preventDefault();
        var img_src = $(this).data().image;
        jQuery('.img-theater').css('top', jQuery(document).scrollTop())
        $('.img-theater').show();
        $('#img_append_target').html('<//img>'
            .replace("{{src}}", img_src)
            .replace("{{h}}", jQuery(window).height() - 20 + 'px'))
        $(document).on('keyup.hideTheater', function (e){
            if (e.keyCode == 27) {
                $('.img-theater').hide();
                $(document).unbind('keyup.hideTheater');
            }
        })
    });

    jQuery('[data-dismiss="theater"]').click(function (e){
        e.preventDefault();
        $('.img-theater').hide('slow');
    });

    function setCookie(cname, cvalue, exdays) {
        var d = new Date();
        d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
        var expires = "expires=" + d.toUTCString();
        document.cookie = cname + "=" + cvalue + "; " + expires;
    }

    function getCookie(cname) {
        var name = cname + "=";
        var ca = document.cookie.split(';');
        for(var i=0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') c = c.substring(1);
            if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
        }
        return undefined;
    }

});
<commit_msg>Should fix tooltips and the expand icon in browsers that don't have native $ selectors.<commit_after>/**
 * This should be included on every page.
 */
jQuery(document).ready(function () {
    if (!getCookie("hideBanner")) { //cookie to hide banner for 1 day
        jQuery('#message_banner').show();
    }
    jQuery('[data-toggle="tooltip"]').tooltip({container: 'body'}); //enable tooltips

    jQuery('[data-toggle="offcanvas"]').click(function () {
        jQuery('.row-offcanvas').toggleClass('active');
        jQuery('body').toggleClass('hidden-overflow-x');
    });
    jQuery('[data-toggle="search"]').click(function () {
        var target = $(this).data().target;
        jQuery(target).css('margin-top', '32px');
        jQuery(target).toggleClass('hidden-xs');
    });
    jQuery('[data-dismiss="alert"]').click(function() {
        setCookie('hideBanner',"true", 1);
    });

    jQuery('[data-toggle="theater"]').click(function (e){
        e.preventDefault();
        var img_src = jQuery(this).data().image;
        jQuery('.img-theater').css('top', jQuery(document).scrollTop())
        $('.img-theater').show();
        $('#img_append_target').html('<//img>'
            .replace("{{src}}", img_src)
            .replace("{{h}}", jQuery(window).height() - 20 + 'px'))
        $(document).on('keyup.hideTheater', function (e){
            if (e.keyCode == 27) {
                $('.img-theater').hide();
                $(document).unbind('keyup.hideTheater');
            }
        })
    });

    jQuery('[data-dismiss="theater"]').click(function (e){
        e.preventDefault();
        $('.img-theater').hide('slow');
    });

    function setCookie(cname, cvalue, exdays) {
        var d = new Date();
        d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
        var expires = "expires=" + d.toUTCString();
        document.cookie = cname + "=" + cvalue + "; " + expires;
    }

    function getCookie(cname) {
        var name = cname + "=";
        var ca = document.cookie.split(';');
        for(var i=0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') c = c.substring(1);
            if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
        }
        return undefined;
    }

});
<|endoftext|>


<commit_before>import React from 'react';

import SPELLS from 'common/SPELLS';
import Wrapper from 'common/Wrapper';
import SpellIcon from 'common/SpellIcon';
import SpellLink from 'common/SpellLink';
import Analyzer from 'Parser/Core/Analyzer';

import Combatants from '../Combatants';

/**
 * @property {Combatants} combatants
 */
class TalentsDisplay extends Analyzer {
  static dependencies = {
    combatants: Combatants,
  };

  // This is a special module, we're giving it a custom position. Normally we'd use "statistic" instead.
  render() {
    const talents = this.combatants.selected.talents;
    const rows = [15, 30, 45, 60, 75, 90, 100];

    return (

            Talents

            {talents.map((spellId, index) => (

                    {rows[index]}

                  {spellId ? (
                    <Wrapper>

                        <SpellIcon id={spellId} style={{ width: '2em', height: '2em' }} />

                        <SpellLink id={spellId} icon={false}>
                          {SPELLS[spellId].name}
                        </SpellLink>

                    </Wrapper>
                  ) : (

                      No talent active

                  )}

            ))}

    );
  }
}

export default TalentsDisplay;
<commit_msg>Don't crash character panel when talent is not supported yet<commit_after>import React from 'react';

import SPELLS from 'common/SPELLS';
import Wrapper from 'common/Wrapper';
import SpellIcon from 'common/SpellIcon';
import SpellLink from 'common/SpellLink';
import Analyzer from 'Parser/Core/Analyzer';

import Combatants from '../Combatants';

/**
 * @property {Combatants} combatants
 */
class TalentsDisplay extends Analyzer {
  static dependencies = {
    combatants: Combatants,
  };

  // This is a special module, we're giving it a custom position. Normally we'd use "statistic" instead.
  render() {
    const talents = this.combatants.selected.talents;
    const rows = [15, 30, 45, 60, 75, 90, 100];

    return (

            Talents

            {talents.map((spellId, index) => (

                    {rows[index]}

                  {spellId ? (
                    <Wrapper>

                        <SpellIcon id={spellId} style={{ width: '2em', height: '2em' }} />

                        <SpellLink id={spellId} icon={false}>
                          {SPELLS[spellId] ? SPELLS[spellId].name : `Unknown spell: ${spellId}`}
                        </SpellLink>

                    </Wrapper>
                  ) : (

                      No talent active

                  )}

            ))}

    );
  }
}

export default TalentsDisplay;
<|endoftext|>


<commit_before>// window.location.origin = window.location.protocol + "//" + window.location.host  unless window.location.origin

$(document).ready(function() {
  $("#master-search").typeahead([{
    remote: '/books.json?search=%QUERY',
    name: 'search',
    valueKey: 'title',
    template: function(item) {
      return HandlebarsTemplates['search-item']({item: item});
    },
    engine: Handlebars
  }]).on('typeahead:selected', onSelected);

  function onSelected($e, datum){
  	window.location = window.location.origin + "/books/" + datum.id;
  }

  $("#master-search").keyup(function (event){
  	if(event.keyCode == 13){
  		window.location = window.location.origin + "/books/?search=" + $("#master-search").val();
  	}
  });
});

$("#isbn-add").focus()
<commit_msg>I think we are good with typeahead<commit_after>// window.location.origin = window.location.protocol + "//" + window.location.host  unless window.location.origin

$(document).ready(function() {
  $("#master-search").typeahead([{
    remote: {
        url: "/books.json?search=%QUERY&limit=9",
        filter: function( data ){
        if(!data[0]){
          data = [{
            title: $("#master-search")[0].value,
            id: "none",
            none: true
          }]
        } else if(data.length > 8){
          data[8] = {
            title: $("#master-search")[0].value,
            id: "more",
            more: true
          }
        }
        return data;
      }
    },
    name: 'search',
    valueKey: 'title',
    template: function(item) {
      return HandlebarsTemplates['search-item']({item: item});
    },
    engine: Handlebars
  }]).on('typeahead:selected', onSelected);

  function onSelected($e, datum){
     if(datum.id != "none" && datum.id != "more"){
        window.location = window.location.origin + "/books/" + datum.id
      }
      if(datum.id == "more" || datum.id == "none"){
        window.location = window.location.origin + "/books?search=" +
          $("#master-search")[0].value;
      }
  }

  $("#master-search").keyup(function (event){
  	if(event.keyCode == 13){
  		window.location = window.location.origin + "/books/?search=" + $("#master-search").val();
  	}
  });
});

$("#isbn-add").focus()
<|endoftext|>


<commit_before>import React from 'react';

import Icon from 'common/Icon';
import MainCombatLogParser from 'Parser/Core/CombatLogParser';

// Unused
// import SpellIcon from 'common/SpellIcon';

import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';
import StatisticBox from 'Main/StatisticBox';
import SuggestionsTab from 'Main/SuggestionsTab';
import Tab from 'Main/Tab';
import Talents from 'Main/Talents';
import getCastEfficiency from 'Parser/Core/getCastEfficiency';

import ISSUE_IMPORTANCE from 'Parser/Core/ISSUE_IMPORTANCE';

import AlwaysBeCasting from './Modules/Features/AlwaysBeCasting';

import CPM_ABILITIES from './CPM_ABILITIES';

function formatThousands(number) {
  return (Math.round(number || 0) + '').replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
}

function formatNumber(number) {
  if (number > 1000000) {
    return `${(number / 1000000).toFixed(2)}m`;
  }
  if (number > 10000) {
    return `${Math.round(number / 1000)}k`;
  }
  return formatThousands(number);
}

function formatPercentage(percentage) {
  return (Math.round((percentage || 0) * 10000) / 100).toFixed(2);
}

function getIssueImportance(value, regular, major, higherIsWorse = false) {
  if (higherIsWorse ? value > major : value < major) {
    return ISSUE_IMPORTANCE.MAJOR;
  }
  if (higherIsWorse ? value > regular : value < regular) {
    return ISSUE_IMPORTANCE.REGULAR;
  }
  return ISSUE_IMPORTANCE.MINOR;
}

const damageType = {
  1: 'Physical',
  2: 'Holy',
  4: 'Fire',
  8: 'Nature',
  16: 'Frost',
  28: 'Elemental',
  32: 'Shadow',
  33: 'Shadowstrike',
  34: 'Twilight',
  36: 'Shadowflame',
  40: 'Plague',
  48: 'Shadowfrost',
  64: 'Arcane',
  96: 'Spellshadow',
  100: 'Special',
  124: 'Chaos',
};

function getMagicDescription(type) {
  if (damageType[type] === undefined) {
    return 'Chaos';
  }
  return damageType[type];
}

class CombatLogParser extends MainCombatLogParser {
  static specModules = {
    // Features
    alwaysBeCasting: AlwaysBeCasting,
  };

  damageBySchool = {};
  on_toPlayer_damage(event) {
    if (this.damageBySchool[event.ability.type] === undefined) {
      this.damageBySchool[event.ability.type] = 0;
    }
    this.damageBySchool[event.ability.type] += event.amount + (event.absorbed || 0);
    super.on_toPlayer_damage(event);
  }

  generateResults() {

    const results = super.generateResults();

    const fightDuration = this.fightDuration;

    const deadTimePercentage = this.modules.alwaysBeCasting.totalTimeWasted / fightDuration;

    // As soon as the information is ready to be analysed, gets it and put it in variables
    // This is done to not get the 'cannot read property of undefined' error
    if(this.modules.abilityTracker.abilities[SPELLS.SOUL_FRAGMENT.id] !== undefined)  {

        this.soulFragmentsCasts = this.modules.abilityTracker.abilities[SPELLS.SOUL_FRAGMENT.id].casts;

        this.immolationAuraUptime = this.selectedCombatant.getBuffUptime(SPELLS.IMMOLATION_AURA.id);

        this.immolationAuraDamage = this.modules.abilityTracker.abilities[SPELLS.IMMOLATION_AURA.firstStrikeSpellId].damangeEffective + this.modules.abilityTracker.abilities[SPELLS.IMMOLATION_AURA.normalStrikeSpellId].damangeEffective;

        this.empowerWardsUptime = this.selectedCombatant.getBuffUptime(SPELLS.EMPOWER_WARDS.id);

        this.demonSpikesUptime = this.selectedCombatant.getBuffUptime(SPELLS.DEMON_SPIKES.buffId);
    }

    if (deadTimePercentage > 0.2) {
      results.addIssue({
        issue: `Your dead GCD time can be improved. Try to Always Be Casting (ABC).`,
        stat: `${Math.round(deadTimePercentage * 100)}% dead GCD time (<20% is recommended)`,
        icon: 'spell_mage_altertime',
        importance: getIssueImportance(deadTimePercentage, 0.35, 0.4, true),
      });
    }

    const castEfficiency = getCastEfficiency(CPM_ABILITIES, this);
    castEfficiency.forEach((cpm) => {
      if (cpm.canBeImproved && !cpm.ability.noSuggestion) {
        results.addIssue({
          issue: Try to cast <SpellLink id={cpm.ability.spell.id} /> more often ({cpm.casts}/{cpm.maxCasts} casts: {Math.round(cpm.castEfficiency * 100)}% cast efficiency). The recommended cast efficiency is {Math.round(cpm.recommendedCastEfficiency * 100)}%. {cpm.ability.extraSuggestion || ''},
          icon: cpm.ability.spell.icon,
          importance: cpm.ability.importance || getIssueImportance(cpm.castEfficiency, cpm.recommendedCastEfficiency - 0.05, cpm.recommendedCastEfficiency - 0.15),
        });
      }
    });

    results.statistics = [
      <StatisticBox
        icon={<Icon icon="class_demonhunter" alt="Damage done" />}
        value={`${formatNumber(this.totalDamageDone / this.fightDuration * 1000)} DPS`}
        label='Damage done'
        tooltip={`The total damage done was ${formatThousands(this.totalDamageDone)}.`}
      />,
      <StatisticBox
        icon={<Icon icon="spell_holy_devotionaura" alt="Damage taken" />}
        value={`${formatNumber(this.totalDamageTaken / this.fightDuration * 1000)} DTPS`}
        label='Damage taken'
        tooltip={`Damage taken breakdown:

              ${Object.keys(this.damageBySchool).reduce((v, x) => {return v+=`<li>${getMagicDescription(x)} damage taken ${formatThousands(this.damageBySchool[x])} (${formatPercentage(this.damageBySchool[x]/this.totalDamageTaken)}%)</li>`; }, '')}

            Total damage taken ${formatThousands(this.totalDamageTaken)}`}
      />,
      <StatisticBox
        icon={<Icon icon="spell_mage_altertime" alt="Dead GCD time" />}
        value={`${formatPercentage(deadTimePercentage)} %`}
        label='Dead GCD time'
        tooltip="Dead GCD time is available casting time not used. This can be caused by latency, cast interrupting, not casting anything (e.g. due to movement/stunned), etc."
      />,
      <StatisticBox
      icon={(

      )}
      value={`${formatNumber(this.totalHealing / this.fightDuration * 1000)} HPS`}
      label='Healing done'
      tooltip={`The total healing done was ${formatThousands(this.totalHealing)}.`}
      />,
      <StatisticBox
        icon={<Icon icon="ability_druid_naturalperfection" alt="Damage absorbed" />}
        value={`${formatNumber(this.totalDamageTakenAbsorb / this.fightDuration * 1000)} DAPS`}
        label='Damage absorbed'
        tooltip={`The total damage absorbed was ${formatThousands(this.totalDamageTakenAbsorb)}.`}
      />,
      <StatisticBox
        icon={<Icon icon="spell_shadow_soulgem" alt="Soul Fragments Generated" />}
        value={`${formatNumber((this.soulFragmentsCasts / this.fightDuration * 1000) * 60)}`}
        label='Soul Fragments Generated per Minute'
        tooltip={`The total Soul Fragments generated was ${formatThousands(this.soulFragmentsCasts)}.`}
      />,
      <StatisticBox
        icon={<Icon icon="ability_demonhunter_immolation" alt="Immolation Aura" />}
        value={`${formatPercentage(this.immolationAuraUptime / this.fightDuration)}%`}
        label='Immolation Aura Uptime'
        tooltip={`The Immolation Aura total damage was ${formatThousands(this.immolationAuraDamage)}.<br/>The Immolation Aura total uptime was ${formatNumber(this.immolationAuraUptime / 1000)} seconds.`}
      />,
      <StatisticBox
        icon={<Icon icon="ability_demonhunter_demonspikes" alt="Demon Spikes" />}
        value={`${formatPercentage(this.demonSpikesUptime / this.fightDuration)}%`}
        label='Demon Spikes Uptime'
        tooltip={`The Demon Spikes total uptime was ${formatNumber(this.demonSpikesUptime / 1000)} seconds.`}
      />,
      <StatisticBox
        icon={<Icon icon="ability_demonhunter_empowerwards" alt="Empower Wards" />}
        value={`${formatPercentage(this.empowerWardsUptime / this.fightDuration)}%`}
        label='Empower Wards Uptime'
        tooltip={`The Empower Wards total uptime was ${formatNumber(this.empowerWardsUptime / 1000)} seconds.`}
      />,
  ];

    results.tabs = [
      {
        title: 'Suggestions',
        url: 'suggestions',
        render: () => (
          <SuggestionsTab issues={results.issues} />
        ),
      },
      {
        title: 'Talents',
        url: 'talents',
        render: () => (
          <Tab title="Talents">
            <Talents combatant={this.selectedCombatant} />
          </Tab>
        ),
      },
      ...results.tabs,
    ];

    return results;
  }
}

export default CombatLogParser;
<commit_msg>Added Spirit Bomb tooltip using enemies.getBuffUptime() for a correct tracking of Frailty debuff<commit_after>import React from 'react';

import Icon from 'common/Icon';
import MainCombatLogParser from 'Parser/Core/CombatLogParser';

// Unused
// import SpellIcon from 'common/SpellIcon';

import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';

import StatisticBox from 'Main/StatisticBox';
import SuggestionsTab from 'Main/SuggestionsTab';
import Tab from 'Main/Tab';
import Talents from 'Main/Talents';
import getCastEfficiency from 'Parser/Core/getCastEfficiency';

import ISSUE_IMPORTANCE from 'Parser/Core/ISSUE_IMPORTANCE';

import Enemies from 'Parser/Core/Modules/Enemies';

import AlwaysBeCasting from './Modules/Features/AlwaysBeCasting';

import CPM_ABILITIES from './CPM_ABILITIES';

function formatThousands(number) {
  return (Math.round(number || 0) + '').replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
}

function formatNumber(number) {
  if (number > 1000000) {
    return `${(number / 1000000).toFixed(2)}m`;
  }
  if (number > 10000) {
    return `${Math.round(number / 1000)}k`;
  }
  return formatThousands(number);
}

function formatPercentage(percentage) {
  return (Math.round((percentage || 0) * 10000) / 100).toFixed(2);
}

function getIssueImportance(value, regular, major, higherIsWorse = false) {
  if (higherIsWorse ? value > major : value < major) {
    return ISSUE_IMPORTANCE.MAJOR;
  }
  if (higherIsWorse ? value > regular : value < regular) {
    return ISSUE_IMPORTANCE.REGULAR;
  }
  return ISSUE_IMPORTANCE.MINOR;
}

const damageType = {
  1: 'Physical',
  2: 'Holy',
  4: 'Fire',
  8: 'Nature',
  16: 'Frost',
  28: 'Elemental',
  32: 'Shadow',
  33: 'Shadowstrike',
  34: 'Twilight',
  36: 'Shadowflame',
  40: 'Plague',
  48: 'Shadowfrost',
  64: 'Arcane',
  96: 'Spellshadow',
  100: 'Special',
  124: 'Chaos',
};

function getMagicDescription(type) {
  if (damageType[type] === undefined) {
    return 'Chaos';
  }
  return damageType[type];
}

class CombatLogParser extends MainCombatLogParser {
  static specModules = {
    // Features
    alwaysBeCasting: AlwaysBeCasting,
    enemies: Enemies,
  };

  damageBySchool = {};
  on_toPlayer_damage(event) {
    if (this.damageBySchool[event.ability.type] === undefined) {
      this.damageBySchool[event.ability.type] = 0;
    }
    this.damageBySchool[event.ability.type] += event.amount + (event.absorbed || 0);
    super.on_toPlayer_damage(event);
  }

  generateResults() {

    const results = super.generateResults();

    const fightDuration = this.fightDuration;

    const deadTimePercentage = this.modules.alwaysBeCasting.totalTimeWasted / fightDuration;

    const spiritBombUptime = this.modules.enemies.getBuffUptime(SPELLS.FRAILTY_SPIRIT_BOMB_DEBUFF.id);

    const spiritBombUptimePercentage = spiritBombUptime / fightDuration;

    // As soon as the information is ready to be analysed, gets it and put it in variables
    // This is done to not get the 'cannot read property of undefined' error
    if(this.modules.abilityTracker.abilities[SPELLS.SOUL_FRAGMENT.id] !== undefined)  {

        this.soulFragmentsCasts = this.modules.abilityTracker.abilities[SPELLS.SOUL_FRAGMENT.id].casts;

        this.immolationAuraUptime = this.selectedCombatant.getBuffUptime(SPELLS.IMMOLATION_AURA.id);

        this.immolationAuraDamage = this.modules.abilityTracker.abilities[SPELLS.IMMOLATION_AURA.firstStrikeSpellId].damangeEffective + this.modules.abilityTracker.abilities[SPELLS.IMMOLATION_AURA.normalStrikeSpellId].damangeEffective;

        this.empowerWardsUptime = this.selectedCombatant.getBuffUptime(SPELLS.EMPOWER_WARDS.id);

        this.demonSpikesUptime = this.selectedCombatant.getBuffUptime(SPELLS.DEMON_SPIKES.buffId);
    }

    if (deadTimePercentage > 0.2) {
      results.addIssue({
        issue: `Your dead GCD time can be improved. Try to Always Be Casting (ABC).`,
        stat: `${Math.round(deadTimePercentage * 100)}% dead GCD time (<20% is recommended)`,
        icon: 'spell_mage_altertime',
        importance: getIssueImportance(deadTimePercentage, 0.35, 0.4, true),
      });
    }

    if (spiritBombUptimePercentage < 1.0 && this.selectedCombatant.hasTalent(SPELLS.SPIRIT_BOMB_TALENT.id)) {
      results.addIssue({
        issue: Try to cast <SpellLink id={SPELLS.SPIRIT_BOMB_TALENT.id} /> more often. This is your core healing ability. Try to refresh it even if you have just one <SpellLink id={SPELLS.SOUL_FRAGMENT.id} /> available.,
        stat: {Math.round(spiritBombUptimePercentage * 100)}% <SpellLink id={SPELLS.FRAILTY_SPIRIT_BOMB_DEBUFF.id} /> debuff total uptime (100% uptime is recommended) ,
        icon: SPELLS.FRAILTY_SPIRIT_BOMB_DEBUFF.icon,
        importance: getIssueImportance(spiritBombUptimePercentage, 0.90, 0.80),
      });
    }

    const castEfficiency = getCastEfficiency(CPM_ABILITIES, this);
    castEfficiency.forEach((cpm) => {
      if (cpm.canBeImproved && !cpm.ability.noSuggestion) {
        results.addIssue({
          issue: Try to cast <SpellLink id={cpm.ability.spell.id} /> more often ({cpm.casts}/{cpm.maxCasts} casts: {Math.round(cpm.castEfficiency * 100)}% cast efficiency). The recommended cast efficiency is above  {Math.round(cpm.recommendedCastEfficiency * 100)}%. {cpm.ability.extraSuggestion || ''},
          icon: cpm.ability.spell.icon,
          importance: cpm.ability.importance || getIssueImportance(cpm.castEfficiency, cpm.recommendedCastEfficiency - 0.05, cpm.recommendedCastEfficiency - 0.15),
        });
      }
    });

    results.statistics = [
      <StatisticBox
        icon={<Icon icon="class_demonhunter" alt="Damage done" />}
        value={`${formatNumber(this.totalDamageDone / this.fightDuration * 1000)} DPS`}
        label='Damage done'
        tooltip={`The total damage done was ${formatThousands(this.totalDamageDone)}.`}
      />,
      <StatisticBox
        icon={<Icon icon="spell_holy_devotionaura" alt="Damage taken" />}
        value={`${formatNumber(this.totalDamageTaken / this.fightDuration * 1000)} DTPS`}
        label='Damage taken'
        tooltip={`Damage taken breakdown:

              ${Object.keys(this.damageBySchool).reduce((v, x) => {return v+=`<li>${getMagicDescription(x)} damage taken ${formatThousands(this.damageBySchool[x])} (${formatPercentage(this.damageBySchool[x]/this.totalDamageTaken)}%)</li>`; }, '')}

            Total damage taken ${formatThousands(this.totalDamageTaken)}`}
      />,
      <StatisticBox
        icon={<Icon icon="spell_mage_altertime" alt="Dead GCD time" />}
        value={`${formatPercentage(deadTimePercentage)} %`}
        label='Dead GCD time'
        tooltip="Dead GCD time is available casting time not used. This can be caused by latency, cast interrupting, not casting anything (e.g. due to movement/stunned), etc."
      />,
      <StatisticBox
      icon={(

      )}
      value={`${formatNumber(this.totalHealing / this.fightDuration * 1000)} HPS`}
      label='Healing done'
      tooltip={`The total healing done was ${formatThousands(this.totalHealing)}.`}
      />,
      <StatisticBox
        icon={<Icon icon="ability_druid_naturalperfection" alt="Damage absorbed" />}
        value={`${formatNumber(this.totalDamageTakenAbsorb / this.fightDuration * 1000)} APS`}
        label='Damage absorbed'
        tooltip={`The total damage absorbed was ${formatThousands(this.totalDamageTakenAbsorb)}.`}
      />,
      <StatisticBox
        icon={<Icon icon="spell_shadow_soulgem" alt="Soul Fragments Generated" />}
        value={`${formatNumber((this.soulFragmentsCasts / this.fightDuration * 1000) * 60)}`}
        label='Soul Fragments Generated per Minute'
        tooltip={`The total Soul Fragments generated was ${formatThousands(this.soulFragmentsCasts)}.`}
      />,
      <StatisticBox
        icon={<Icon icon="ability_demonhunter_immolation" alt="Immolation Aura" />}
        value={`${formatPercentage(this.immolationAuraUptime / this.fightDuration)}%`}
        label='Immolation Aura Uptime'
        tooltip={`The Immolation Aura total damage was ${formatThousands(this.immolationAuraDamage)}.<br/>The Immolation Aura total uptime was ${formatNumber(this.immolationAuraUptime / 1000)} seconds.`}
      />,
      <StatisticBox
        icon={<Icon icon="ability_demonhunter_demonspikes" alt="Demon Spikes" />}
        value={`${formatPercentage(this.demonSpikesUptime / this.fightDuration)}%`}
        label='Demon Spikes Uptime'
        tooltip={`The Demon Spikes total uptime was ${formatNumber(this.demonSpikesUptime / 1000)} seconds.`}
      />,
      <StatisticBox
        icon={<Icon icon="ability_demonhunter_empowerwards" alt="Empower Wards" />}
        value={`${formatPercentage(this.empowerWardsUptime / this.fightDuration)}%`}
        label='Empower Wards Uptime'
        tooltip={`The Empower Wards total uptime was ${formatNumber(this.empowerWardsUptime / 1000)} seconds.`}
      />,
  ];

    results.tabs = [
      {
        title: 'Suggestions',
        url: 'suggestions',
        render: () => (
          <SuggestionsTab issues={results.issues} />
        ),
      },
      {
        title: 'Talents',
        url: 'talents',
        render: () => (
          <Tab title="Talents">
            <Talents combatant={this.selectedCombatant} />
          </Tab>
        ),
      },
      ...results.tabs,
    ];

    return results;
  }
}

export default CombatLogParser;
<|endoftext|>


<commit_before>define([
    "intern!object",
    "intern/chai!assert",
    "tests/support/helper"
], function ( registerSuite, assert, testHelper ) {
    registerSuite({
        name: "Comic: delete",

        "Comic can be deleted.": function () {
            var title = testHelper.getUniqueString();
            var slug = testHelper.getUniqueString();

            return testHelper.cleanupDashboardTest(
                testHelper.getDashboardAuthorizedAsAdmin( this )
                .then( function () {
                    /** Create entity. */
                    testHelper.createEntity( "Comic.Entity.Comic", { title: title } );
                })
                .execute( function () {
                    /** Reload page. */
                    location.reload();
                    return true;
                })
                /** Open "Comics" tab. */
                .findByCssSelector( "ul.root-tabs" )
                    .setFindTimeout( testHelper.getTimeoutForPageAction() )
                    .findByCssSelector( "li.tab.comics a" )
                        .click()
                        .end()
                    .end()
                .setFindTimeout( testHelper.getTimeoutForAjaxRequests() )
                /** Find first comic on the list. It should be entity created in this test. */
                .findByCssSelector( ".admin-comics-list .list-group-item" )
                    /** Click for "Edit" and "Delete" buttons to appear. */
                    .click()
                    /** Assert that the title matches. */
                    .findByCssSelector( ".title" )
                        .getVisibleText()
                        .then( function ( visibleTitle ) {
                            assert.equal( visibleTitle, title );
                        })
                        .end()
                    /** Click "Delete" button. */
                    .findByCssSelector( ".comics-delete" )
                        .click()
                        .end()
                    .end()
                .setFindTimeout( testHelper.getTimeoutForPageAction() )
                /** Find dialog and click "Confirm" button. */
                .findByCssSelector( ".comics-delete-dialog" )
                    .findByCssSelector( ".comics-delete-confirm" )
                        .click()
                        .end()
                    .findByCssSelector( ".comics-delete-confirm" )
                        .isEnabled( function ( enabled ) {
                            /** Assert that "Confirm" button is disabled after clicking. */
                            assert.notOk( enabled );
                        })
                        .end()
                    .end()
                .setFindTimeout( testHelper.getTimeoutForAjaxRequests() )
                /** Check if the comics was created. */
                .findByCssSelector( ".alertify-log-success" )
                    .getVisibleText()
                    .then( function ( visibleText ) {
                        assert.equal( visibleText, "Comic \"" + title + "\" was deleted." );
                    })
                    .end()
            );
        }
    });
});<commit_msg>Let's try to remove this one too, to fix IE<commit_after>define([
    "intern!object",
    "intern/chai!assert",
    "tests/support/helper"
], function ( registerSuite, assert, testHelper ) {
    registerSuite({
        name: "Comic: delete",

        "Comic can be deleted.": function () {
            var title = testHelper.getUniqueString();
            var slug = testHelper.getUniqueString();

            return testHelper.cleanupDashboardTest(
                testHelper.getDashboardAuthorizedAsAdmin( this )
                .then( function () {
                    /** Create entity. */
                    testHelper.createEntity( "Comic.Entity.Comic", { title: title } );
                })
                .execute( function () {
                    /** Reload page. */
                    location.reload();
                    return true;
                })
                /** Open "Comics" tab. */
                .findByCssSelector( "ul.root-tabs" )
                    .setFindTimeout( testHelper.getTimeoutForPageAction() )
                    .findByCssSelector( "li.tab.comics a" )
                        .click()
                        .end()
                    .end()
                .setFindTimeout( testHelper.getTimeoutForAjaxRequests() )
                /** Find first comic on the list. It should be entity created in this test. */
                .findByCssSelector( ".admin-comics-list .list-group-item" )
                    /** Click for "Edit" and "Delete" buttons to appear. */
                    .click()
                    /** Assert that the title matches. */
                    .findByCssSelector( ".title" )
                        .getVisibleText()
                        .then( function ( visibleTitle ) {
                            assert.equal( visibleTitle, title );
                        })
                        .end()
                    /** Click "Delete" button. */
                    .findByCssSelector( ".comics-delete" )
                        .click()
                        .end()
                    .end()
                .setFindTimeout( testHelper.getTimeoutForPageAction() )
                /** Find dialog and click "Confirm" button. */
                .findByCssSelector( ".comics-delete-dialog" )
                    .findByCssSelector( ".comics-delete-confirm" )
                        .click()
                        .end()
                    .end()
                .setFindTimeout( testHelper.getTimeoutForAjaxRequests() )
                /** Check if the comics was created. */
                .findByCssSelector( ".alertify-log-success" )
                    .getVisibleText()
                    .then( function ( visibleText ) {
                        assert.equal( visibleText, "Comic \"" + title + "\" was deleted." );
                    })
                    .end()
            );
        }
    });
});<|endoftext|>


<commit_before>/*=============================================================================
 * Orange - Time System Variables
 * By Hudell - www.hudell.com
 * OrangeTimeSystemVariables.js
 * Version: 1.0
 * Free for commercial and non commercial use.
 *=============================================================================*/
 /*:
 * @plugindesc Exports Orange Time System data to variables
 *
 * @author Hudell
 *
 * @param secondVariable
 * @desc The number of the variable where you want to store the seconds
 * @default 0
 *
 * @param minuteVariable
 * @desc The number of the variable where you want to store the minutes
 * @default 0
 *
 * @param hourVariable
 * @desc The number of the variable where you want to store the hours
 * @default 0
 *
 * @param dayVariable
 * @desc The number of the variable where you want to store the days
 * @default 0
 *
 * @param monthVariable
 * @desc The number of the variable where you want to store the months
 * @default 0
 *
 * @param yearVariable
 * @desc The number of the variable where you want to store the years
 * @default 0
 *
 * @param weekDayVariable
 * @desc The number of the variable where you want to store the week day
 * @default 0
 *
 * @param dayPeriodVariable
 * @desc The number of the variable where you want to store the day period
 * @default 0
 *
 *
 * @help
 * ============================================================================
 * Latest Version
 * ============================================================================
 *
 * Get the latest version of this script on
 * http://link.hudell.com/time-system-variables
 *
 *=============================================================================*/

var Imported = Imported || {};
var OrangeTimeSystemVariables = OrangeTimeSystemVariables || {};

if (Imported['MVCommons'] === undefined) {
  console.log('Download MVCommons: http://link.hudell.com/mvcommons');
  throw new Error("This library needs MVCommons to work properly!");
}

if (PluginManager.version('OrangeTimeSystem', '>=', '0.1.0') === false) {
  console.log('Download MVCommons: http://link.hudell.com/time-system');
  throw new Error("This library requires the OrangeTimeSystem!");
}

(function($) {
  "use strict";

  $.Parameters = PluginManager.parameters('OrangeTimeSystemVariables');
  $.Param = $.Param || {};

  $.Param.secondVariable = Number($.Parameters['secondVariable'] || 0);
  $.Param.minuteVariable = Number($.Parameters['minuteVariable'] || 0);
  $.Param.hourVariable = Number($.Parameters['hourVariable'] || 0);
  $.Param.dayVariable = Number($.Parameters['dayVariable'] || 0);
  $.Param.monthVariable = Number($.Parameters['monthVariable'] || 0);
  $.Param.yearVariable = Number($.Parameters['yearVariable'] || 0);
  $.Param.weekDayVariable = Number($.Parameters['weekDayVariable'] || 0);
  $.Param.dayPeriodVariable = Number($.Parameters['dayPeriodVariable'] || 0);

  $.configureVariables = function() {
    if ($.Param.secondVariable !== undefined && $.Param.secondVariable > 0) {
      $gameVariables.setValue($.Param.secondVariable, OrangeTimeSystem.seconds);
    }
    if ($.Param.minuteVariable !== undefined && $.Param.minuteVariable > 0) {
      $gameVariables.setValue($.Param.minuteVariable, OrangeTimeSystem.minute);
    }
    if ($.Param.hourVariable !== undefined && $.Param.hourVariable > 0) {
      $gameVariables.setValue($.Param.hourVariable, OrangeTimeSystem.hour);
    }
    if ($.Param.dayVariable !== undefined && $.Param.dayVariable > 0) {
      $gameVariables.setValue($.Param.dayVariable, OrangeTimeSystem.day);
    }
    if ($.Param.monthVariable !== undefined && $.Param.monthVariable > 0) {
      $gameVariables.setValue($.Param.monthVariable, OrangeTimeSystem.month);
    }
    if ($.Param.yearVariable !== undefined && $.Param.yearVariable > 0) {
      $gameVariables.setValue($.Param.yearVariable, OrangeTimeSystem.year);
    }
    if ($.Param.weekDayVariable !== undefined && $.Param.weekDayVariable > 0) {
      $gameVariables.setValue($.Param.weekDayVariable, OrangeTimeSystem.weekDay);
    }
    if ($.Param.dayPeriodVariable !== undefined && $.Param.dayPeriodVariable > 0) {
      $gameVariables.setValue($.Param.dayPeriodVariable, OrangeTimeSystem.dayPeriod);
    }
  };

  // Updates the variables every in-game second
  OrangeTimeSystem.on('changeSecond', $.configureVariables);
})(OrangeTimeSystemVariables);

PluginManager.register("OrangeTimeSystemVariables", "1.0.0", "Exports Orange Time System data to variables", {
  email: "plugins@hudell.com",
  name: "Hudell",
  website: "http://www.hudell.com"
}, "2015-10-22");
<commit_msg>Changed version number<commit_after>/*=============================================================================
 * Orange - Time System Variables
 * By Hudell - www.hudell.com
 * OrangeTimeSystemVariables.js
 * Version: 1.0.1
 * Free for commercial and non commercial use.
 *=============================================================================*/
 /*:
 * @plugindesc Exports Orange Time System data to variables
 *
 * @author Hudell
 *
 * @param secondVariable
 * @desc The number of the variable where you want to store the seconds
 * @default 0
 *
 * @param minuteVariable
 * @desc The number of the variable where you want to store the minutes
 * @default 0
 *
 * @param hourVariable
 * @desc The number of the variable where you want to store the hours
 * @default 0
 *
 * @param dayVariable
 * @desc The number of the variable where you want to store the days
 * @default 0
 *
 * @param monthVariable
 * @desc The number of the variable where you want to store the months
 * @default 0
 *
 * @param yearVariable
 * @desc The number of the variable where you want to store the years
 * @default 0
 *
 * @param weekDayVariable
 * @desc The number of the variable where you want to store the week day
 * @default 0
 *
 * @param dayPeriodVariable
 * @desc The number of the variable where you want to store the day period
 * @default 0
 *
 *
 * @help
 * ============================================================================
 * Latest Version
 * ============================================================================
 *
 * Get the latest version of this script on
 * http://link.hudell.com/time-system-variables
 *
 *=============================================================================*/

var Imported = Imported || {};
var OrangeTimeSystemVariables = OrangeTimeSystemVariables || {};

if (Imported['MVCommons'] === undefined) {
  console.log('Download MVCommons: http://link.hudell.com/mvcommons');
  throw new Error("This library needs MVCommons to work properly!");
}

if (PluginManager.version('OrangeTimeSystem', '>=', '0.1.0') === false) {
  console.log('Download MVCommons: http://link.hudell.com/time-system');
  throw new Error("This library requires the OrangeTimeSystem!");
}

(function($) {
  "use strict";

  $.Parameters = PluginManager.parameters('OrangeTimeSystemVariables');
  $.Param = $.Param || {};

  $.Param.secondVariable = Number($.Parameters['secondVariable'] || 0);
  $.Param.minuteVariable = Number($.Parameters['minuteVariable'] || 0);
  $.Param.hourVariable = Number($.Parameters['hourVariable'] || 0);
  $.Param.dayVariable = Number($.Parameters['dayVariable'] || 0);
  $.Param.monthVariable = Number($.Parameters['monthVariable'] || 0);
  $.Param.yearVariable = Number($.Parameters['yearVariable'] || 0);
  $.Param.weekDayVariable = Number($.Parameters['weekDayVariable'] || 0);
  $.Param.dayPeriodVariable = Number($.Parameters['dayPeriodVariable'] || 0);

  $.configureVariables = function() {
    if ($.Param.secondVariable !== undefined && $.Param.secondVariable > 0) {
      $gameVariables.setValue($.Param.secondVariable, OrangeTimeSystem.seconds);
    }
    if ($.Param.minuteVariable !== undefined && $.Param.minuteVariable > 0) {
      $gameVariables.setValue($.Param.minuteVariable, OrangeTimeSystem.minute);
    }
    if ($.Param.hourVariable !== undefined && $.Param.hourVariable > 0) {
      $gameVariables.setValue($.Param.hourVariable, OrangeTimeSystem.hour);
    }
    if ($.Param.dayVariable !== undefined && $.Param.dayVariable > 0) {
      $gameVariables.setValue($.Param.dayVariable, OrangeTimeSystem.day);
    }
    if ($.Param.monthVariable !== undefined && $.Param.monthVariable > 0) {
      $gameVariables.setValue($.Param.monthVariable, OrangeTimeSystem.month);
    }
    if ($.Param.yearVariable !== undefined && $.Param.yearVariable > 0) {
      $gameVariables.setValue($.Param.yearVariable, OrangeTimeSystem.year);
    }
    if ($.Param.weekDayVariable !== undefined && $.Param.weekDayVariable > 0) {
      $gameVariables.setValue($.Param.weekDayVariable, OrangeTimeSystem.weekDay);
    }
    if ($.Param.dayPeriodVariable !== undefined && $.Param.dayPeriodVariable > 0) {
      $gameVariables.setValue($.Param.dayPeriodVariable, OrangeTimeSystem.dayPeriod);
    }
  };

  // Updates the variables every in-game second
  OrangeTimeSystem.on('changeSecond', $.configureVariables);
})(OrangeTimeSystemVariables);

PluginManager.register("OrangeTimeSystemVariables", "1.0.1", "Exports Orange Time System data to variables", {
  email: "plugins@hudell.com",
  name: "Hudell",
  website: "http://www.hudell.com"
}, "2015-10-22");
<|endoftext|>


<commit_before>#!/usr/bin/env node

var fs         = require('fs');
var path       = require('path');
var uglifyjs   = require('uglify-js');
var browserify = require('browserify');

function bundle(file, callback) {
  var opts = { standalone: 'PF' };
  browserify(file).bundle(opts, callback);
}

function addBanner(source) {
  var banner = fs.readFileSync(__dirname + '/banner').toString();
  return banner + source;
}

function minify(source) {
  var opts = { fromString: true };
  return uglifyjs.minify(source, opts).code;
}

function build(dest, options) {
  options = options || {};

  var src = __dirname + '/../src/PathFinding.js';

  bundle(src, function (err, bundled) {
    var bannered = addBanner(bundled);
    var content = options.minify ? minify(bannered) : bannered;
    fs.writeFileSync(dest, content);
    console.log('built', path.resolve(dest));
  });
}

build(__dirname + '/../lib/pathfinding-browser.js');
build(__dirname + '/../lib/pathfinding-browser.min.js', { minify: true });
<commit_msg>moved opts to constructor for new browserify version<commit_after>#!/usr/bin/env node

var fs         = require('fs');
var path       = require('path');
var uglifyjs   = require('uglify-js');
var browserify = require('browserify');

function bundle(file, callback) {
  var opts = { standalone: 'PF' };
  browserify(file, opts).bundle(callback);
}

function addBanner(source) {
  var banner = fs.readFileSync(__dirname + '/banner').toString();
  return banner + source;
}

function minify(source) {
  var opts = { fromString: true };
  return uglifyjs.minify(source, opts).code;
}

function build(dest, options) {
  options = options || {};

  var src = __dirname + '/../src/PathFinding.js';

  bundle(src, function (err, bundled) {
    var bannered = addBanner(bundled);
    var content = options.minify ? minify(bannered) : bannered;
    fs.writeFileSync(dest, content);
    console.log('built', path.resolve(dest));
  });
}

build(__dirname + '/../lib/pathfinding-browser.js');
build(__dirname + '/../lib/pathfinding-browser.min.js', { minify: true });
<|endoftext|>


<commit_before>/*

This script is meant to be used with an OWL file downloaded from the Semantic Analysis Tool.

It will parse the RDF format, extract all leaves, and create (or update) records in a couchdb instance.

*/
var argv = require('optimist')
    .usage('Usage: node import.js --url http://couch-db-host:port/db/ --username username --password password --file /path/to/file.csv')
    .demand(['url', 'username', 'password', 'file'])
    .argv;

var rdf = require('rdf');
var fs = require('promised-io/fs.js');

var Q = require('q');
Q.longStackSupport = true;

var body = "";
var graph = {};

function storeContent(result) {
    console.info("Storing content...");

    body = result.toString();
}

function parseRdf() {
    var environment = {}, filter={};

    console.info("Parsing RDF content...");

    // We should be able to use this to filter the list of nodes without writing our own code

    var parser = new rdf.TurtleParser(environment);
    return Q.invoke(parser.parse(body, {}, 'http://foo.bar/', filter, {}));
}

function showResults() {
    console.log("Results:" + graph.toString());
}

function showError(err) {
    console.error("Error:" + err);
}

fs.readFile(argv.file).then(storeContent, showError).then(parseRdf, showError).then(showResults, showError);<commit_msg>Removed previous RDF import script, which never worked.<commit_after><|endoftext|>


<commit_before>var socketio;

function loadBGM(url) {
  var bgm = document.getElementById("bgm");
  bgm.src = url;
  bgm.load();
}

function playBGM() {
  document.getElementById("bgm").play();
}

function stopBGM() {
  var bgm = document.getElementById("bgm");
  bgm.stop();
  bgm.currentTime = 0;
}

function setKeyup() {
  document.addEventListener("keyup", function (e) {
    if (e.key.match(/^[a-z]$/)){
      var listeners = arguments.callee;
      socketio.emit("next");
      document.removeEventListener("keyup", listeners, false);
    }
  });
}

function removeClasses(element, start = 0, end = -1)
{
  if (end === -1){
    end = element.classList.length;
  }
  var len = end - start;
  for (var i = 0; i < len; ++i){
    element.classList.remove(element.classList[start]);
  }
}

function playVoice(state, result) {
  var VOICE = "Voice";
  var symbolVoice = document.getElementById(state.symbol + VOICE);
  var noVoice = document.getElementById("no" + VOICE);
  var ten = (result / 10 | 0) * 10;
  var tenVoice = document.getElementById(ten + VOICE);
  var one = result % 10;
  var oneVoice = document.getElementById(one + VOICE);

  symbolVoice.play();
  window.setTimeout(function(){
    noVoice.play();
  }, 600);
  window.setTimeout(function(){
    if (tenVoice){
      tenVoice.play();
      window.setTimeout(function(){
        oneVoice.play();
        setKeyup();
      }, 700);
    }
    else {
      oneVoice.play();
      setKeyup();
    }
  }, 1200);
}

function showNext(result, colorize = true) {
  var state = getState(result);
  var element = document.getElementById("showNext");

  element.innerHTML = state.str;
  if (colorize){
    if (element.classList.contains(state.symbol + "num") !== true){
      removeClasses(element, 2);
      element.classList.add(state.symbol + "num");
    }
  }
  else if (element.classList.contains("empty") !== true){
      removeClasses(element, 2);
    element.classList.add("empty");
  }
}

function roulette(result) {
  var first = window.setInterval(function() {
    showNext(Math.random() * 75 | 0 + 1, false);
  }, 50);

  var state = getState(result);
  var start = ((result - 1) / 15 | 0) * 15 + 1;
  var current = 0;

  window.setTimeout(function() {
    window.clearInterval(first);

    var second = window.setInterval(function() {
      showNext(start + current);
      current = (current + 1) % 15;
    }, 200);
    window.setTimeout(function() {
      window.clearInterval(second);
    }, 2000);
  }, 3000);

  window.setTimeout(function() {
    var third = window.setInterval(function() {
      showNext(start + current);
      if (start + current === result){
        window.clearInterval(third);
        playVoice(state, result);
        socketio.emit("show");
      }

      current = (current + 1) % 15;
    }, 500);
  }, 5000);
}

document.addEventListener('DOMContentLoaded', function() {
  socketio = io.connect("http://localhost:8080");

  socketio.on("overrun", function() {
    window.alert("これ以上回せません");
  });
  socketio.on("next", function(next) {
    roulette(next);
  });

  document.getElementById("next").addEventListener("click", function(ev) {
    socketio.emit("next");
  });

  document.getElementById("reset").addEventListener("click", function(ev) {
    document.getElementById("showNext").innerHTML = "";
    socketio.emit("reset");
  });

  document.getElementById("bgmFile").addEventListener("change", function(ev) {
    var file = ev.target.files[0];
    var reader = new FileReader();

    reader.addEventListener("load", function(ev) {
      console.log(ev.target.result);
      loadBGM(ev.target.result);
    });

    reader.readAsDataURL(file);
  });

  setKeyup();
});
<commit_msg>stopじゃなくてpauseだった<commit_after>var socketio;

function loadBGM(url) {
  var bgm = document.getElementById("bgm");
  bgm.src = url;
  bgm.load();
}

function playBGM() {
  document.getElementById("bgm").play();
}

function stopBGM() {
  var bgm = document.getElementById("bgm");
  bgm.pause();
  bgm.currentTime = 0;
}

function setKeyup() {
  document.addEventListener("keyup", function (e) {
    if (e.key.match(/^[a-z]$/)){
      var listeners = arguments.callee;
      socketio.emit("next");
      document.removeEventListener("keyup", listeners, false);
    }
  });
}

function removeClasses(element, start = 0, end = -1)
{
  if (end === -1){
    end = element.classList.length;
  }
  var len = end - start;
  for (var i = 0; i < len; ++i){
    element.classList.remove(element.classList[start]);
  }
}

function playVoice(state, result) {
  var VOICE = "Voice";
  var symbolVoice = document.getElementById(state.symbol + VOICE);
  var noVoice = document.getElementById("no" + VOICE);
  var ten = (result / 10 | 0) * 10;
  var tenVoice = document.getElementById(ten + VOICE);
  var one = result % 10;
  var oneVoice = document.getElementById(one + VOICE);

  symbolVoice.play();
  window.setTimeout(function(){
    noVoice.play();
  }, 600);
  window.setTimeout(function(){
    if (tenVoice){
      tenVoice.play();
      window.setTimeout(function(){
        oneVoice.play();
        setKeyup();
      }, 700);
    }
    else {
      oneVoice.play();
      setKeyup();
    }
  }, 1200);
}

function showNext(result, colorize = true) {
  var state = getState(result);
  var element = document.getElementById("showNext");

  element.innerHTML = state.str;
  if (colorize){
    if (element.classList.contains(state.symbol + "num") !== true){
      removeClasses(element, 2);
      element.classList.add(state.symbol + "num");
    }
  }
  else if (element.classList.contains("empty") !== true){
      removeClasses(element, 2);
    element.classList.add("empty");
  }
}

function roulette(result) {
  var first = window.setInterval(function() {
    showNext(Math.random() * 75 | 0 + 1, false);
  }, 50);

  var state = getState(result);
  var start = ((result - 1) / 15 | 0) * 15 + 1;
  var current = 0;

  window.setTimeout(function() {
    window.clearInterval(first);

    var second = window.setInterval(function() {
      showNext(start + current);
      current = (current + 1) % 15;
    }, 200);
    window.setTimeout(function() {
      window.clearInterval(second);
    }, 2000);
  }, 3000);

  window.setTimeout(function() {
    var third = window.setInterval(function() {
      showNext(start + current);
      if (start + current === result){
        window.clearInterval(third);
        playVoice(state, result);
        socketio.emit("show");
      }

      current = (current + 1) % 15;
    }, 500);
  }, 5000);
}

document.addEventListener('DOMContentLoaded', function() {
  socketio = io.connect("http://localhost:8080");

  socketio.on("overrun", function() {
    window.alert("これ以上回せません");
  });
  socketio.on("next", function(next) {
    roulette(next);
  });

  document.getElementById("next").addEventListener("click", function(ev) {
    socketio.emit("next");
  });

  document.getElementById("reset").addEventListener("click", function(ev) {
    document.getElementById("showNext").innerHTML = "";
    socketio.emit("reset");
  });

  document.getElementById("bgmFile").addEventListener("change", function(ev) {
    var file = ev.target.files[0];
    var reader = new FileReader();

    reader.addEventListener("load", function(ev) {
      console.log(ev.target.result);
      loadBGM(ev.target.result);
    });

    reader.readAsDataURL(file);
  });

  setKeyup();
});
<|endoftext|>