<commit_before>/*
 * MagicBootTabs
 * A nice way of styling and using Bootstrap tabs for content
 *
 * Author: Unreal Designs <contact@unreal-designs.co.uk>
 * Copyright: Unreal Designs 2015
 */

//Declare Version
var magicBootTabsVersion = "1.26";

// Colored Console Logging Function
var oldconsolelog = console.log;
console.log = function(){
	arguments = consolelog(arguments)
	oldconsolelog(arguments);
    oldconsolelog.apply(this, arguments);
}

function consolelog(message) {
	if (message != "") {
		var messages = Array();
		var styles = Array();

		messages.push("%cMagicBootTabs");
		styles.push("background: #222; color: #bada55;");

		for (index = 0; index < message.length; ++index) {
			args = message[index];
			oldconsolelog(args);
			args = args.split(" -- ");
			msg = args[0].trim();
			color = args[1].trim();
			if (args.length == 3) {
				bg = args[2].trim();
			} else {
				bg = "#222";
			}
			messages.push(" %c" + msg);
			styles.push("background: " + bg + "; color: " + color);
		}

		var arguments = Array();
		arguments.push(messages.join(""));
		for (index = 0; index < styles.length; ++index) {
			arguments.push(styles[index]);
		}

		return arguments;
	} else {
		return "";
	}
}

// JQuery Check
if (typeof jQuery != 'undefined') {

	// Bootstrap JS Tabs Check
	if (typeof($.fn.tab) != 'undefined') {

		// Log - Plugin Loaded And Version In Console
		consolelog(Array(
			"A magical way of styling and using Bootstrap tabs for content. -- #6BB9F0"
		));
		consolelog(Array(
			"Version -- #6BB9F0",
			magicBootTabsVersion + " -- #F27935",
			"Loaded! -- #6BB9F0"
		));

		// Load in CSS File
		$("head").append("<link>");
		var css = $("head").children(":last");
		css.attr({
			rel: "stylesheet",
			type: "text/css",
			href: "//rawgithub.com/MattCowley/MagicBootTabs/master/src/jquery.magicBootTabs.css"
		});

		// Create Style Tag For MagicBootTab Colors
		$("head").append("");
		var styles = $("head").children(":last");
		styles.attr({
			id: "magicBootTabsStyles",
			type: "text/css"
		});

		// Log Styles Loaded In Console
		consolelog(Array(
			"CSS File Linked In Head, Style Holder Created! -- #6BB9F0"
		));

		// Begin magicBootTab JQuery Function
		$.fn.magicBootTab = function(options) {

			//Check Options Is Passed
			options = options || {};

			// Set Option Defaults If Not Set
			options.lnColor 	= options.hasOwnProperty('lnColor') 	? options.lnColor 	: "#4144FF";
			options.acColor 	= options.hasOwnProperty('acColor') 	? options.acColor 	: "#4183D7";
			options.speed 		= options.hasOwnProperty('speed') 	? options.speed 	: 400;
			options.advAnimation 	= options.hasOwnProperty('advAnimation') 	? options.advAnimation 	: false;

			// Create Usable Plugin Variables
			$tabId = this;
			tabIdAttr = this.attr("id");
			$tabId.append("

");
			var $magicLine = $("#magic-line[magic-tab='" + tabIdAttr + "']");

			//Create Line Break Before Tab Info
			consolelog("");

			// Log Basic MagicBootTab Info
			consolelog(Array(
				"Tab -- #F27935",
				"#" + tabIdAttr + " -- #F27935",
				"Using Line Color -- #6BB9F0",
				options.lnColor + " -- " + options.lnColor + " -- #fff",
				", Using Active Color -- #6BB9F0",
				options.acColor + " -- " + options.acColor + " -- #fff"
			));

			consolelog(Array(
				"Tab -- #F27935",
				"#" + tabIdAttr + " -- #F27935",
				"Using Animation Speed -- #6BB9F0",
				options.speed + " -- #4183D7" + " -- #fff"
			));

			if (options.advAnimation) {
				consolelog(Array(
					"Tab -- #F27935",
					"#" + tabIdAttr + " -- #F27935",
					"Advanced Animation Mode Enabled -- #6BB9F0"
				));
			} else {
				consolelog(Array(
					"Tab -- #F27935",
					"#" + tabIdAttr + " -- #F27935",
					"Advanced Animation Mode Disabled -- #6BB9F0"
				));
			}

			// Set Custom Colors For MagicBootTab
			$("head style#magicBootTabsStyles").append(".nav-tabs#" + tabIdAttr + " > li.active > a { color: " + options.acColor + "; }\n");
			$("head style#magicBootTabsStyles").append(".nav-tabs#" + tabIdAttr + " > li#magic-line { background: " + options.lnColor + " }\n");

			// Log Tab Info In Console
			consolelog(Array(
				"Tab -- #F27935",
				"#" + tabIdAttr + " -- #F27935",
				"MagicBootTab Created! -- #6BB9F0"
			));

			//Begin - Set Original Values
			$magicLine
				.width($(".active").width())
				.height(3)
				.css("left", $(".active a").position().left)
				.css("zIndex", 0)
				.data("origLeft", $magicLine.position().left)
				.data("origWidth", $magicLine.width());

			if (!options.advAnimation) {
				//Hover Event
				$tabId.find("li a").hover(function() {
					$el = $(this);
					leftPos = $el.position().left;
					newWidth = $el.parent().width();
					$magicLine.stop().animate({
						left: leftPos,
						width: newWidth
					}, options.speed);
				}, function() {
					$magicLine.stop().animate({
						left: $magicLine.data("origLeft"),
						width: $magicLine.data("origWidth")
					}, options.speed);
				});

				//Click Event
				$tabId.find("li a").click(function() {
					$el = $(this);
					leftPos = $el.position().left
					newWidth = $el.parent().width();
					$magicLine.stop().animate({
						left: leftPos,
						width: newWidth
					}, options.speed, function() {
						$magicLine
							.width($el.parent().width())
							.css("left", $el.position().left)
							.data("origLeft", $magicLine.position().left)
							.data("origWidth", $magicLine.width());
					});
				});
			} else {
				//Set Org Height
				$magicLine.stop().animate({
					height: $tabId.find("li.active").height()
				}, options.speed/1.5, function() {
					$magicLine.data("origHeight", $magicLine.height());
				});

				//Hover Event
				$tabId.find("li a").hover(function() {
					$el = $(this);
					leftPos = $el.position().left;
					newWidth = $el.parent().width();
					newHeight = $el.parent().height();
					$magicLine.stop().animate({
						height: 3
					}, options.speed/1.5, function() {
						$magicLine.animate({
							left: leftPos,
							width: newWidth
						}, options.speed/1.5, function() {
							$magicLine.animate({
								height: newHeight
							}, options.speed/1.5);
						});
					});
				}, function() {
					$magicLine.stop().animate({
						height: 3
					}, options.speed/1.5, function() {
						$magicLine.animate({
							left: $magicLine.data("origLeft"),
							width: $magicLine.data("origWidth")
						}, options.speed/1.5, function() {
							$magicLine.animate({
								height: $magicLine.data("origHeight")
							}, options.speed/1.5);
						});
					});
				});

				//Click Event
				$tabId.find("li a").click(function() {
					$el = $(this);
					leftPos = $el.position().left
					newWidth = $el.parent().width();
					newHeight = $el.parent().height();
					$magicLine.stop().animate({
						height: 3
					}, options.speed/1.5, function() {
						$magicLine.animate({
							left: leftPos,
							width: newWidth
						}, options.speed/1.5, function() {
							$magicLine.animate({
								height: newHeight
							}, options.speed/1.5, function() {
								$magicLine
									.width($el.parent().width())
									.css("left", $el.position().left)
									.data("origLeft", $magicLine.position().left)
									.data("origHeight", $magicLine.height())
									.data("origWidth", $magicLine.width());
							});
						});
					});
				});
			}

			// Return JQuery Selector For Function Chaining
			return this;
		}

	} else {

		// Log Bootstrap JS Error In Console
		consolelog(Array(
			"Plugin Requires Bootstrap 3 (JS - Tabs)! -- #F53C2B"
		));
	}

} else {

	// Log JQuery Error In Console
	consolelog(Array(
		"Plugin Requires JQuery! -- #F53C2B"
	));
}
<commit_msg>Console.log<commit_after>/*
 * MagicBootTabs
 * A nice way of styling and using Bootstrap tabs for content
 *
 * Author: Unreal Designs <contact@unreal-designs.co.uk>
 * Copyright: Unreal Designs 2015
 */

//Declare Version
var magicBootTabsVersion = "1.27";

// Colored Console Logging Function
(function() {
	var original = console['log'];
	console['log'] = function() {
		if (original.apply){
            // Do this for normal browsers
            original.apply(console, consolelog(arguments))
        }else{
            // Do this for IE
            var message = Array.prototype.slice.apply(arguments).join(' ')
            original(message)
        }
	}
}());

function consolelog(message) {
	if (message != "") {
		var messages = Array();
		var styles = Array();

		messages.push("%cMagicBootTabs");
		styles.push("background: #222; color: #bada55;");

		for (index = 0; index < message.length; ++index) {
			args = message[index];
			oldconsolelog(args);
			args = args.split(" -- ");
			msg = args[0].trim();
			color = args[1].trim();
			if (args.length == 3) {
				bg = args[2].trim();
			} else {
				bg = "#222";
			}
			messages.push(" %c" + msg);
			styles.push("background: " + bg + "; color: " + color);
		}

		var arguments = Array();
		arguments.push(messages.join(""));
		for (index = 0; index < styles.length; ++index) {
			arguments.push(styles[index]);
		}

		return arguments;
	} else {
		return "";
	}
}

// JQuery Check
if (typeof jQuery != 'undefined') {

	// Bootstrap JS Tabs Check
	if (typeof($.fn.tab) != 'undefined') {

		// Log - Plugin Loaded And Version In Console
		consolelog(Array(
			"A magical way of styling and using Bootstrap tabs for content. -- #6BB9F0"
		));
		consolelog(Array(
			"Version -- #6BB9F0",
			magicBootTabsVersion + " -- #F27935",
			"Loaded! -- #6BB9F0"
		));

		// Load in CSS File
		$("head").append("<link>");
		var css = $("head").children(":last");
		css.attr({
			rel: "stylesheet",
			type: "text/css",
			href: "//rawgithub.com/MattCowley/MagicBootTabs/master/src/jquery.magicBootTabs.css"
		});

		// Create Style Tag For MagicBootTab Colors
		$("head").append("");
		var styles = $("head").children(":last");
		styles.attr({
			id: "magicBootTabsStyles",
			type: "text/css"
		});

		// Log Styles Loaded In Console
		consolelog(Array(
			"CSS File Linked In Head, Style Holder Created! -- #6BB9F0"
		));

		// Begin magicBootTab JQuery Function
		$.fn.magicBootTab = function(options) {

			//Check Options Is Passed
			options = options || {};

			// Set Option Defaults If Not Set
			options.lnColor 	= options.hasOwnProperty('lnColor') 	? options.lnColor 	: "#4144FF";
			options.acColor 	= options.hasOwnProperty('acColor') 	? options.acColor 	: "#4183D7";
			options.speed 		= options.hasOwnProperty('speed') 	? options.speed 	: 400;
			options.advAnimation 	= options.hasOwnProperty('advAnimation') 	? options.advAnimation 	: false;

			// Create Usable Plugin Variables
			$tabId = this;
			tabIdAttr = this.attr("id");
			$tabId.append("

");
			var $magicLine = $("#magic-line[magic-tab='" + tabIdAttr + "']");

			//Create Line Break Before Tab Info
			consolelog("");

			// Log Basic MagicBootTab Info
			consolelog(Array(
				"Tab -- #F27935",
				"#" + tabIdAttr + " -- #F27935",
				"Using Line Color -- #6BB9F0",
				options.lnColor + " -- " + options.lnColor + " -- #fff",
				", Using Active Color -- #6BB9F0",
				options.acColor + " -- " + options.acColor + " -- #fff"
			));

			consolelog(Array(
				"Tab -- #F27935",
				"#" + tabIdAttr + " -- #F27935",
				"Using Animation Speed -- #6BB9F0",
				options.speed + " -- #4183D7" + " -- #fff"
			));

			if (options.advAnimation) {
				consolelog(Array(
					"Tab -- #F27935",
					"#" + tabIdAttr + " -- #F27935",
					"Advanced Animation Mode Enabled -- #6BB9F0"
				));
			} else {
				consolelog(Array(
					"Tab -- #F27935",
					"#" + tabIdAttr + " -- #F27935",
					"Advanced Animation Mode Disabled -- #6BB9F0"
				));
			}

			// Set Custom Colors For MagicBootTab
			$("head style#magicBootTabsStyles").append(".nav-tabs#" + tabIdAttr + " > li.active > a { color: " + options.acColor + "; }\n");
			$("head style#magicBootTabsStyles").append(".nav-tabs#" + tabIdAttr + " > li#magic-line { background: " + options.lnColor + " }\n");

			// Log Tab Info In Console
			consolelog(Array(
				"Tab -- #F27935",
				"#" + tabIdAttr + " -- #F27935",
				"MagicBootTab Created! -- #6BB9F0"
			));

			//Begin - Set Original Values
			$magicLine
				.width($(".active").width())
				.height(3)
				.css("left", $(".active a").position().left)
				.css("zIndex", 0)
				.data("origLeft", $magicLine.position().left)
				.data("origWidth", $magicLine.width());

			if (!options.advAnimation) {
				//Hover Event
				$tabId.find("li a").hover(function() {
					$el = $(this);
					leftPos = $el.position().left;
					newWidth = $el.parent().width();
					$magicLine.stop().animate({
						left: leftPos,
						width: newWidth
					}, options.speed);
				}, function() {
					$magicLine.stop().animate({
						left: $magicLine.data("origLeft"),
						width: $magicLine.data("origWidth")
					}, options.speed);
				});

				//Click Event
				$tabId.find("li a").click(function() {
					$el = $(this);
					leftPos = $el.position().left
					newWidth = $el.parent().width();
					$magicLine.stop().animate({
						left: leftPos,
						width: newWidth
					}, options.speed, function() {
						$magicLine
							.width($el.parent().width())
							.css("left", $el.position().left)
							.data("origLeft", $magicLine.position().left)
							.data("origWidth", $magicLine.width());
					});
				});
			} else {
				//Set Org Height
				$magicLine.stop().animate({
					height: $tabId.find("li.active").height()
				}, options.speed/1.5, function() {
					$magicLine.data("origHeight", $magicLine.height());
				});

				//Hover Event
				$tabId.find("li a").hover(function() {
					$el = $(this);
					leftPos = $el.position().left;
					newWidth = $el.parent().width();
					newHeight = $el.parent().height();
					$magicLine.stop().animate({
						height: 3
					}, options.speed/1.5, function() {
						$magicLine.animate({
							left: leftPos,
							width: newWidth
						}, options.speed/1.5, function() {
							$magicLine.animate({
								height: newHeight
							}, options.speed/1.5);
						});
					});
				}, function() {
					$magicLine.stop().animate({
						height: 3
					}, options.speed/1.5, function() {
						$magicLine.animate({
							left: $magicLine.data("origLeft"),
							width: $magicLine.data("origWidth")
						}, options.speed/1.5, function() {
							$magicLine.animate({
								height: $magicLine.data("origHeight")
							}, options.speed/1.5);
						});
					});
				});

				//Click Event
				$tabId.find("li a").click(function() {
					$el = $(this);
					leftPos = $el.position().left
					newWidth = $el.parent().width();
					newHeight = $el.parent().height();
					$magicLine.stop().animate({
						height: 3
					}, options.speed/1.5, function() {
						$magicLine.animate({
							left: leftPos,
							width: newWidth
						}, options.speed/1.5, function() {
							$magicLine.animate({
								height: newHeight
							}, options.speed/1.5, function() {
								$magicLine
									.width($el.parent().width())
									.css("left", $el.position().left)
									.data("origLeft", $magicLine.position().left)
									.data("origHeight", $magicLine.height())
									.data("origWidth", $magicLine.width());
							});
						});
					});
				});
			}

			// Return JQuery Selector For Function Chaining
			return this;
		}

	} else {

		// Log Bootstrap JS Error In Console
		consolelog(Array(
			"Plugin Requires Bootstrap 3 (JS - Tabs)! -- #F53C2B"
		));
	}

} else {

	// Log JQuery Error In Console
	consolelog(Array(
		"Plugin Requires JQuery! -- #F53C2B"
	));
}
<|endoftext|>


<commit_before>/*
 * ext-server_opensave.js
 *
 * Licensed under the Apache License, Version 2
 *
 * Copyright(c) 2010 Alexis Deveria
 *
 */

svgEditor.addExtension("server_opensave", {
	callback: function() {

		var save_svg_action = 'extensions/filesave.php';
		var save_png_action = 'extensions/filesave.php';

		// Create upload target (hidden iframe)
		var target = $('<iframe name="output_frame" src="#"/>').hide().appendTo('body');

		svgEditor.setCustomHandlers({
			save: function(win, data) {
				var svg = "<?xml version='1.0'?>\n" + data;

				var title = svgCanvas.getDocumentTitle();
				var filename = title.replace(/[^a-z0-9\.\_\-]+/gi, '_');

				var form = $('<form>').attr({
					method: 'post',
					action: save_svg_action,
					target: 'output_frame'
				})	.append('<input type="hidden" name="output_svg" value="' + encodeURI(svg) + '">')
					.append('<input type="hidden" name="filename" value="' + filename + '">')
					.appendTo('body')
					.submit().remove();
			},
			pngsave: function(win, data) {
				var issues = data.issues;

				if(!$('#export_canvas').length) {
					$('<canvas>', {id: 'export_canvas'}).hide().appendTo('body');
				}
				var c = $('#export_canvas')[0];

				c.width = svgCanvas.contentW;
				c.height = svgCanvas.contentH;
				canvg(c, data.svg);

				// Timeout to allow canvg to run a bit
				setTimeout(function() {
					var datauri = c.toDataURL('image/png');

					var uiStrings = svgEditor.uiStrings;
					var note = '';

					// Check if there's issues
					if(issues.length) {
						var pre = "\n \u2022 ";
						note += ("\n\n" + pre + issues.join(pre));
					}

					if(note.length) {
						alert(note);
					}

					var title = svgCanvas.getDocumentTitle();
					var filename = title.replace(/[^a-z0-9\.\_\-]+/gi, '_');

					var form = $('<form>').attr({
						method: 'post',
						action: save_png_action,
						target: 'output_frame'
					})	.append('<input type="hidden" name="output_png" value="' + datauri + '">')
						.append('<input type="hidden" name="filename" value="' + filename + '">')
						.appendTo('body')
						.submit().remove();
				}, 1000);

			}
		});

		// Do nothing if client support is found
		if(window.FileReader) return;

		var cancelled = false;

		// Change these to appropriate script file
		var open_svg_action = 'extensions/fileopen.php?type=load_svg';
		var import_svg_action = 'extensions/fileopen.php?type=import_svg';
		var import_img_action = 'extensions/fileopen.php?type=import_img';

		// Set up function for PHP uploader to use
		svgEditor.processFile = function(str64, type) {
			if(cancelled) {
				cancelled = false;
				return;
			}

			$('#dialog_box').hide();

			if(type != 'import_img') {
				var xmlstr = svgCanvas.Utils.decode64(str64);
			}

			switch ( type ) {
				case 'load_svg':
					svgCanvas.clear();
					svgCanvas.setSvgString(xmlstr);
					svgEditor.updateCanvas();
					break;
				case 'import_svg':
					svgCanvas.importSvgString(xmlstr);
					svgEditor.updateCanvas();
					break;
				case 'import_img':
					svgCanvas.setGoodImage(str64);
					break;
			}
		}

		// Create upload form
		var open_svg_form = $('<form>');
		open_svg_form.attr({
			enctype: 'multipart/form-data',
			method: 'post',
			action: open_svg_action,
			target: 'output_frame'
		});

		// Create import form
		var import_svg_form = open_svg_form.clone().attr('action', import_svg_action);

		// Create image form
		var import_img_form = open_svg_form.clone().attr('action', import_img_action);

		// It appears necessory to rebuild this input every time a file is
		// selected so the same file can be picked and the change event can fire.
		function rebuildInput(form) {
			form.empty();
			var inp = $('<input type="file" name="svg_file">').appendTo(form);

			function submit() {
				// This submits the form, which returns the file data using svgEditor.uploadSVG
				form.submit();

				rebuildInput(form);
				$.process_cancel("Uploading...", function() {
					cancelled = true;
					$('#dialog_box').hide();
				});
			}

			if(form[0] == open_svg_form[0]) {
				inp.change(function() {
					// This takes care of the "are you sure" dialog box
					svgEditor.openPrep(function(ok) {
						if(!ok) {
							rebuildInput(form);
							return;
						}
						submit();
					});
				});
			} else {
				inp.change(function() {
					// This submits the form, which returns the file data using svgEditor.uploadSVG
					submit();
				});
			}
		}

		// Create the input elements
		rebuildInput(open_svg_form);
		rebuildInput(import_svg_form);
		rebuildInput(import_img_form);

		// Add forms to buttons
		$("#tool_open").show().prepend(open_svg_form);
		$("#tool_import").show().prepend(import_svg_form);
		$("#tool_image").prepend(import_img_form);
	}
});

<commit_msg>Added canvg callback to opensave extension<commit_after>/*
 * ext-server_opensave.js
 *
 * Licensed under the Apache License, Version 2
 *
 * Copyright(c) 2010 Alexis Deveria
 *
 */

svgEditor.addExtension("server_opensave", {
	callback: function() {

		var save_svg_action = 'extensions/filesave.php';
		var save_png_action = 'extensions/filesave.php';

		// Create upload target (hidden iframe)
		var target = $('<iframe name="output_frame" src="#"/>').hide().appendTo('body');

		svgEditor.setCustomHandlers({
			save: function(win, data) {
				var svg = "<?xml version='1.0'?>\n" + data;

				var title = svgCanvas.getDocumentTitle();
				var filename = title.replace(/[^a-z0-9\.\_\-]+/gi, '_');

				var form = $('<form>').attr({
					method: 'post',
					action: save_svg_action,
					target: 'output_frame'
				})	.append('<input type="hidden" name="output_svg" value="' + encodeURI(svg) + '">')
					.append('<input type="hidden" name="filename" value="' + filename + '">')
					.appendTo('body')
					.submit().remove();
			},
			pngsave: function(win, data) {
				var issues = data.issues;

				if(!$('#export_canvas').length) {
					$('<canvas>', {id: 'export_canvas'}).hide().appendTo('body');
				}
				var c = $('#export_canvas')[0];

				c.width = svgCanvas.contentW;
				c.height = svgCanvas.contentH;
				canvg(c, data.svg, {renderCallback: function() {
					var datauri = c.toDataURL('image/png');

					var uiStrings = svgEditor.uiStrings;
					var note = '';

					// Check if there's issues
					if(issues.length) {
						var pre = "\n \u2022 ";
						note += ("\n\n" + pre + issues.join(pre));
					}

					if(note.length) {
						alert(note);
					}

					var title = svgCanvas.getDocumentTitle();
					var filename = title.replace(/[^a-z0-9\.\_\-]+/gi, '_');

					var form = $('<form>').attr({
						method: 'post',
						action: save_png_action,
						target: 'output_frame'
					})	.append('<input type="hidden" name="output_png" value="' + datauri + '">')
						.append('<input type="hidden" name="filename" value="' + filename + '">')
						.appendTo('body')
						.submit().remove();
				}});

			}
		});

		// Do nothing if client support is found
		if(window.FileReader) return;

		var cancelled = false;

		// Change these to appropriate script file
		var open_svg_action = 'extensions/fileopen.php?type=load_svg';
		var import_svg_action = 'extensions/fileopen.php?type=import_svg';
		var import_img_action = 'extensions/fileopen.php?type=import_img';

		// Set up function for PHP uploader to use
		svgEditor.processFile = function(str64, type) {
			if(cancelled) {
				cancelled = false;
				return;
			}

			$('#dialog_box').hide();

			if(type != 'import_img') {
				var xmlstr = svgCanvas.Utils.decode64(str64);
			}

			switch ( type ) {
				case 'load_svg':
					svgCanvas.clear();
					svgCanvas.setSvgString(xmlstr);
					svgEditor.updateCanvas();
					break;
				case 'import_svg':
					svgCanvas.importSvgString(xmlstr);
					svgEditor.updateCanvas();
					break;
				case 'import_img':
					svgCanvas.setGoodImage(str64);
					break;
			}
		}

		// Create upload form
		var open_svg_form = $('<form>');
		open_svg_form.attr({
			enctype: 'multipart/form-data',
			method: 'post',
			action: open_svg_action,
			target: 'output_frame'
		});

		// Create import form
		var import_svg_form = open_svg_form.clone().attr('action', import_svg_action);

		// Create image form
		var import_img_form = open_svg_form.clone().attr('action', import_img_action);

		// It appears necessory to rebuild this input every time a file is
		// selected so the same file can be picked and the change event can fire.
		function rebuildInput(form) {
			form.empty();
			var inp = $('<input type="file" name="svg_file">').appendTo(form);

			function submit() {
				// This submits the form, which returns the file data using svgEditor.uploadSVG
				form.submit();

				rebuildInput(form);
				$.process_cancel("Uploading...", function() {
					cancelled = true;
					$('#dialog_box').hide();
				});
			}

			if(form[0] == open_svg_form[0]) {
				inp.change(function() {
					// This takes care of the "are you sure" dialog box
					svgEditor.openPrep(function(ok) {
						if(!ok) {
							rebuildInput(form);
							return;
						}
						submit();
					});
				});
			} else {
				inp.change(function() {
					// This submits the form, which returns the file data using svgEditor.uploadSVG
					submit();
				});
			}
		}

		// Create the input elements
		rebuildInput(open_svg_form);
		rebuildInput(import_svg_form);
		rebuildInput(import_img_form);

		// Add forms to buttons
		$("#tool_open").show().prepend(open_svg_form);
		$("#tool_import").show().prepend(import_svg_form);
		$("#tool_image").prepend(import_img_form);
	}
});

<|endoftext|>


<commit_before>import React from 'react';

import List from '../../../src/List/List.js';

class ListExample extends React.Component {

  constructor() {
    super();
    this.state = {
      itemAdded: false
    };
    this.handleToggleExtraItem = this.handleToggleExtraItem.bind(this);
  }

  handleToggleExtraItem() {
    this.setState({
      itemAdded: !this.state.itemAdded
    });
  }

  getComplexNestedList() {
    // Here's an example of a list with customized list items.

    var complexNestedList = [
      {
        value: 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit.'
      },
      {
        items: [
          {
            attributes: {
              className: 'text-uppercase',
              style: {
                display: 'block'
              }
            },
            tag: 'strong',
            value: 'Cu movet numquam.'
          },
          {
            attributes: {
              className: 'list a'
            },
            tag: 'ol',
            items: [
              {
                value: 'Aliquam tincidunt mauris eu risus.'
              },
              {
                items: [
                  {
                    tag: 'em',
                    value: 'Mauris placerat eleifend leo.'
                  },
                  {
                    attributes: {
                      className: 'list I'
                    },
                    tag: 'ol',
                    items: [
                      {
                        value: 'Suspendisse laoreet. Fusce ut est sed dolor.'
                      },
                      {
                        value:

                            Gravida convallis. Morbi vitae ante.

                      }
                    ]
                  }
                ]
              }
            ]
          }
        ]
      },
      {
        value: 'Vestibulum auctor dapibus neque.'
      }
    ];

    if (this.state.itemAdded) {
      complexNestedList.push({value: 'A wild transitioned list item appears.'});
    }

    return complexNestedList;
  }

  render() {
    let toggleText = 'Add item';

    if (this.state.itemAdded) {
      toggleText = 'Remove item';
    }

    return (

                  Lists

                  Create lists with custom elements and transitions.

                        <List
                          items={this.getComplexNestedList()}
                          tag="ol"
                          transition={true}
                          transitionName="list-item" />

                        <button
                          className="button button-small button-primary button-stroke"
                          onClick={this.handleToggleExtraItem}>
                          {toggleText}
                        </button>

{`var complexNestedList = [
  {
    value: 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit.'
  },
  {
    items: [
      {
        attributes: {
          className: 'text-uppercase',
          style: {
            display: 'block'
          }
        },
        tag: 'strong',
        value: 'Cu movet numquam.'
      },
      {
        attributes: {
          className: 'list a'
        },
        tag: 'ol',
        items: [
          {
            value: 'Aliquam tincidunt mauris eu risus.'
          },
          {
            items: [
              {
                tag: 'em',
                value: 'Mauris placerat eleifend leo.'
              },
              {
                attributes: {
                  className: 'list I'
                },
                tag: 'ol',
                items: [
                  {
                    value: 'Suspendisse laoreet. Fusce ut est sed dolor.'
                  },
                  {
                    value:

                        Gravida convallis. Morbi vitae ante.

                  }
                ]
              }
            ]
          }
        ]
      }
    ]
  },
  {
    value: 'Vestibulum auctor dapibus neque.'
  }
];`}

    );
  }

}

React.render(<ListExample />, document.getElementById('list'));
<commit_msg>include link to source<commit_after>import React from 'react';

import List from '../../../src/List/List.js';

class ListExample extends React.Component {

  constructor() {
    super();
    this.state = {
      itemAdded: false
    };
    this.handleToggleExtraItem = this.handleToggleExtraItem.bind(this);
  }

  handleToggleExtraItem() {
    this.setState({
      itemAdded: !this.state.itemAdded
    });
  }

  getComplexNestedList() {
    // Here's an example of a list with customized list items.

    var complexNestedList = [
      {
        value: 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit.'
      },
      {
        items: [
          {
            attributes: {
              className: 'text-uppercase',
              style: {
                display: 'block'
              }
            },
            tag: 'strong',
            value: 'Cu movet numquam.'
          },
          {
            attributes: {
              className: 'list a'
            },
            tag: 'ol',
            items: [
              {
                value: 'Aliquam tincidunt mauris eu risus.'
              },
              {
                items: [
                  {
                    tag: 'em',
                    value: 'Mauris placerat eleifend leo.'
                  },
                  {
                    attributes: {
                      className: 'list I'
                    },
                    tag: 'ol',
                    items: [
                      {
                        value: 'Suspendisse laoreet. Fusce ut est sed dolor.'
                      },
                      {
                        value:

                            Gravida convallis. Morbi vitae ante.

                      }
                    ]
                  }
                ]
              }
            ]
          }
        ]
      },
      {
        value: 'Vestibulum auctor dapibus neque.'
      }
    ];

    if (this.state.itemAdded) {
      complexNestedList.push({value: 'A wild transitioned list item appears.'});
    }

    return complexNestedList;
  }

  render() {
    let toggleText = 'Add item';

    if (this.state.itemAdded) {
      toggleText = 'Remove item';
    }

    return (

                  Lists

                  Create lists with custom elements and transitions.
                  View full source
                   here.

                        <List
                          items={this.getComplexNestedList()}
                          tag="ol"
                          transition={true}
                          transitionName="list-item" />

                        <button
                          className="button button-small button-primary button-stroke"
                          onClick={this.handleToggleExtraItem}>
                          {toggleText}
                        </button>

{`import List from 'List.js';

[...]

var complexNestedList = [
  {
    value: 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit.'
  },
  {
    items: [
      {
        attributes: {
          className: 'text-uppercase',
          style: {
            display: 'block'
          }
        },
        tag: 'strong',
        value: 'Cu movet numquam.'
      },
      {
        attributes: {
          className: 'list a'
        },
        tag: 'ol',
        items: [
          {
            value: 'Aliquam tincidunt mauris eu risus.'
          },
          {
            items: [
              {
                tag: 'em',
                value: 'Mauris placerat eleifend leo.'
              },
              {
                attributes: {
                  className: 'list I'
                },
                tag: 'ol',
                items: [
                  {
                    value: 'Suspendisse laoreet. Fusce ut est sed dolor.'
                  },
                  {
                    value:

                        Gravida convallis. Morbi vitae ante.

                  }
                ]
              }
            ]
          }
        ]
      }
    ]
  },
  {
    value: 'Vestibulum auctor dapibus neque.'
  }
];

[...]`}

    );
  }

}

React.render(<ListExample />, document.getElementById('list'));
<|endoftext|>


<commit_before>steal('jquery', 'jquery/dom/styles').then(function ($) {

	// Overwrites `jQuery.fn.animate` to use CSS 3 animations if possible

	var
		// The global animation counter
		animationNum = 0,
		// The stylesheet for our animations
		styleSheet = null,
		// The animation cache
		cache = [],
		// Stores the browser properties like transition end event name and prefix
		browser = null,
		// Store the original $.fn.animate
		oldanimate = $.fn.animate,

		// Return the stylesheet, create it if it doesn't exists
		getStyleSheet = function () {
			if(!styleSheet) {
				var style = document.createElement('style');
				style.setAttribute("type", "text/css");
				style.setAttribute("media", "screen");

				document.getElementsByTagName('head')[0].appendChild(style);
				if (!window.createPopup) { /* For Safari */
					style.appendChild(document.createTextNode(''));
				}

				styleSheet = style.sheet;
			}

			return styleSheet;
		},

		//removes an animation rule from a sheet
		removeAnimation = function (sheet, name) {
			for (var j = sheet.cssRules.length - 1; j >= 0; j--) {
				var rule = sheet.cssRules[j];
				// 7 means the keyframe rule
				if (rule.type === 7 && rule.name == name) {
					sheet.deleteRule(j)
					return;
				}
			}
		},

		// Returns whether the animation should be passed to the original $.fn.animate.
		passThrough = function (props, ops) {
			var nonElement = !(this[0] && this[0].nodeType),
				isInline = !nonElement && $(this).css("display") === "inline" && $(this).css("float") === "none";

			for (var name in props) {
				if (props[name] == 'show' || props[name] == 'hide' // jQuery does something with these two values
					|| $.isArray(props[name]) // Arrays for individual easing
					|| props[name] < 0 // Negative values not handled the same
					|| name == 'zIndex' || name == 'z-index'
					) {  // unit-less value
					return true;
				}
			}

			return props.jquery === true || browser === null ||
				// Animating empty properties
				$.isEmptyObject(props) ||
				// Second parameter is an object - we can only handle primitives
				$.isPlainObject(ops) ||
				// Second parameter is a string like 'slow' TODO: remove
				typeof ops == 'string' ||
				// Inline and non elements
				isInline || nonElement;
		},

		// Gets a CSS number (with px added as the default unit if the value is a number)
		cssValue = function(origName, value) {
			if (typeof value === "number" && !$.cssNumber[ origName ]) {
				return value += "px";
			}
			return value;
		},

		// Feature detection borrowed by http://modernizr.com/
		getBrowser = function(){
			if(!browser) {
				var t,
					el = document.createElement('fakeelement'),
					transitions = {
						'transition': {
							transitionEnd : 'transitionEnd',
							prefix : ''
						},
	//					'OTransition': {
	//						transitionEnd : 'oAnimationEnd',
	//						prefix : '-o-'
	//					},
	//					'MSTransition': {
	//						transitionEnd : 'msTransitionEnd',
	//						prefix : '-ms-'
	//					},
						'MozTransition': {
							transitionEnd : 'animationend',
							prefix : '-moz-'
						},
						'WebkitTransition': {
							transitionEnd : 'webkitAnimationEnd',
							prefix : '-webkit-'
						}
					}

				for(t in transitions){
					if( el.style[t] !== undefined ){
						browser = transitions[t];
					}
				}
			}
			return browser;
		},

		// Properties that Firefox can't animate if set to 'auto':
		// https://bugzilla.mozilla.org/show_bug.cgi?id=571344
		// Provides a converter that returns the actual value
		ffProps = {
			top : function(el) {
				return el.position().top;
			},
			left : function(el) {
				return el.position().left;
			},
			width : function(el) {
				return el.width();
			},
			height : function(el) {
				return el.height();
			},
			fontSize : function(el) {
				return '1em';
			}
		},

		// Add browser specific prefix
		addPrefix = function(properties) {
			var result = {};
			$.each(properties, function(name, value) {
				result[browser.prefix + name] = value;
			});
			return result;
		},

		// Returns the animation name for a given style. It either uses a cached
		// version or adds it to the stylesheet, removing the oldest style if the
		// cache has reached a certain size.
		getAnimation = function(style) {
			var sheet, name, last;

			// Look up the cached style, set it to that name and reset age if found
			// increment the age for any other animation
			$.each(cache, function(i, animation) {
				if(style === animation.style) {
					name = animation.name;
					animation.age = 0;
				} else {
					animation.age += 1;
				}
			});

			if(!name) { // Add a new style
				sheet = getStyleSheet();
				name = "jquerypp_animation_" + (animationNum++);
				// get the last sheet and insert this rule into it
				sheet.insertRule("@" + browser.prefix + "keyframes " + name + ' ' + style,
					(sheet.cssRules && sheet.cssRules.length) || 0);
				cache.push({
					name : name,
					style : style,
					age : 0
				});

				// Sort the cache by age
				cache.sort(function(first, second) {
					return first.age - second.age;
				});

				// Remove the last (oldest) item from the cache if it has more than 20 items
				if(cache.length > 20) {
					last = cache.pop();
					removeAnimation(sheet, last.name);
				}
			}

			return name;
		};

	/**
	 * @function $.fn.animate
	 * @parent $.animate
	 *
	 * Animate CSS properties using native CSS animations, if possible.
	 * Uses the original [$.fn.animate()](http://api.$.com/animate/) otherwise.
	 *
	 * @param {Object} props The CSS properties to animate
	 * @param {Integer|String|Object} [speed=400] The animation duration in ms.
	 * Will use $.fn.animate if a string or object is passed
	 * @param {Function} [callback] A callback to execute once the animation is complete
	 * @return {jQuery} The jQuery element
	 */
	$.fn.animate = function (props, speed, callback) {
		//default to normal animations if browser doesn't support them
		if (passThrough.apply(this, arguments)) {
			return oldanimate.apply(this, arguments);
		}
		if ($.isFunction(speed)) {
			callback = speed;
		}

		// Add everything to the animation queue
		this.queue('fx', function(done) {
			var
				//current CSS values
				current,
				// The list of properties passed
				properties = [],
				to = "",
				prop,
				self = $(this),
				duration = $.fx.speeds[speed] || speed || $.fx.speeds._default,
				//the animation keyframe name
				animationName,
				// The key used to store the animation hook
				dataKey,
				//the text for the keyframe
				style = "{ from {",
				// The animation end event handler.
				// Will be called both on animation end and after calling .stop()
				animationEnd = function (currentCSS, exec) {
					self.css(currentCSS);

					self.css(addPrefix({
						"animation-duration" : "",
						"animation-name" : "",
						"animation-fill-mode" : ""
					}));

					if (callback && exec) {
						// Call success, pass the DOM element as the this reference
						callback.call(self[0], true)
					}

					$.removeData(self, dataKey, true);
				}

			for(prop in props) {
				properties.push(prop);
			}

			if(browser.prefix === '-moz-') {
				// Normalize 'auto' properties in FF
				$.each(properties, function(i, prop) {
					var converter = ffProps[$.camelCase(prop)];
					if(converter && self.css(prop) == 'auto') {
						self.css(prop, converter(self));
					}
				});
			}

			// Use $.styles
			current = self.styles.apply(self, properties);
			$.each(properties, function(i, cur) {
				// Convert a camelcased property name
				var name = cur.replace(/([A-Z]|^ms)/g, "-$1" ).toLowerCase();
				style += name + " : " + cssValue(cur, current[cur]) + "; ";
				to += name + " : " + cssValue(cur, props[cur]) + "; ";
			});

			style += "} to {" + to + " }}";

			animationName = getAnimation(style);
			dataKey = animationName + '.run';

			// Add a hook which will be called when the animation stops
			$._data(this, dataKey, {
				stop : function(gotoEnd) {
					// Pause the animation
					self.css(addPrefix({
						'animation-play-state' : 'paused'
					}));
					// Unbind the animation end handler
					self.off(browser.transitionEnd, animationEnd);
					if(!gotoEnd) {
						// We were told not to finish the animation
						// Call animationEnd but set the CSS to the current computed style
						animationEnd(self.styles.apply(self, properties), false);
					} else {
						// Finish animaion
						animationEnd(props, true);
					}
				}
			});

			// set this element to point to that animation
			self.css(addPrefix({
				"animation-duration" : duration + "ms",
				"animation-name" : animationName,
				"animation-fill-mode": "forwards"
			}));

			// Attach the transition end event handler to run only once
			self.one(browser.transitionEnd, function() {
				// Call animationEnd using the passed properties
				animationEnd(props, true);
				done();
			});

		});

		return this;
	};
});
<commit_msg>Fixing jQuery.animate to use getBrowser()<commit_after>steal('jquery', 'jquery/dom/styles').then(function ($) {

	// Overwrites `jQuery.fn.animate` to use CSS 3 animations if possible

	var
		// The global animation counter
		animationNum = 0,
		// The stylesheet for our animations
		styleSheet = null,
		// The animation cache
		cache = [],
		// Stores the browser properties like transition end event name and prefix
		browser = null,
		// Store the original $.fn.animate
		oldanimate = $.fn.animate,

		// Return the stylesheet, create it if it doesn't exists
		getStyleSheet = function () {
			if(!styleSheet) {
				var style = document.createElement('style');
				style.setAttribute("type", "text/css");
				style.setAttribute("media", "screen");

				document.getElementsByTagName('head')[0].appendChild(style);
				if (!window.createPopup) { /* For Safari */
					style.appendChild(document.createTextNode(''));
				}

				styleSheet = style.sheet;
			}

			return styleSheet;
		},

		//removes an animation rule from a sheet
		removeAnimation = function (sheet, name) {
			for (var j = sheet.cssRules.length - 1; j >= 0; j--) {
				var rule = sheet.cssRules[j];
				// 7 means the keyframe rule
				if (rule.type === 7 && rule.name == name) {
					sheet.deleteRule(j)
					return;
				}
			}
		},

		// Returns whether the animation should be passed to the original $.fn.animate.
		passThrough = function (props, ops) {
			var nonElement = !(this[0] && this[0].nodeType),
				isInline = !nonElement && $(this).css("display") === "inline" && $(this).css("float") === "none";

			for (var name in props) {
				if (props[name] == 'show' || props[name] == 'hide' // jQuery does something with these two values
					|| $.isArray(props[name]) // Arrays for individual easing
					|| props[name] < 0 // Negative values not handled the same
					|| name == 'zIndex' || name == 'z-index'
					) {  // unit-less value
					return true;
				}
			}

			return props.jquery === true || getBrowser() === null ||
				// Animating empty properties
				$.isEmptyObject(props) ||
				// Second parameter is an object - we can only handle primitives
				$.isPlainObject(ops) ||
				// Second parameter is a string like 'slow' TODO: remove
				typeof ops == 'string' ||
				// Inline and non elements
				isInline || nonElement;
		},

		// Gets a CSS number (with px added as the default unit if the value is a number)
		cssValue = function(origName, value) {
			if (typeof value === "number" && !$.cssNumber[ origName ]) {
				return value += "px";
			}
			return value;
		},

		// Feature detection borrowed by http://modernizr.com/
		getBrowser = function(){
			if(!browser) {
				var t,
					el = document.createElement('fakeelement'),
					transitions = {
						'transition': {
							transitionEnd : 'transitionEnd',
							prefix : ''
						},
//						'OTransition': {
//							transitionEnd : 'oTransitionEnd',
//							prefix : '-o-'
//						},
//						'MSTransition': {
//							transitionEnd : 'msTransitionEnd',
//							prefix : '-ms-'
//						},
						'MozTransition': {
							transitionEnd : 'animationend',
							prefix : '-moz-'
						},
						'WebkitTransition': {
							transitionEnd : 'webkitAnimationEnd',
							prefix : '-webkit-'
						}
					}

				for(t in transitions){
					if( el.style[t] !== undefined ){
						browser = transitions[t];
					}
				}
			}
			return browser;
		},

		// Properties that Firefox can't animate if set to 'auto':
		// https://bugzilla.mozilla.org/show_bug.cgi?id=571344
		// Provides a converter that returns the actual value
		ffProps = {
			top : function(el) {
				return el.position().top;
			},
			left : function(el) {
				return el.position().left;
			},
			width : function(el) {
				return el.width();
			},
			height : function(el) {
				return el.height();
			},
			fontSize : function(el) {
				return '1em';
			}
		},

		// Add browser specific prefix
		addPrefix = function(properties) {
			var result = {};
			$.each(properties, function(name, value) {
				result[getBrowser().prefix + name] = value;
			});
			return result;
		},

		// Returns the animation name for a given style. It either uses a cached
		// version or adds it to the stylesheet, removing the oldest style if the
		// cache has reached a certain size.
		getAnimation = function(style) {
			var sheet, name, last;

			// Look up the cached style, set it to that name and reset age if found
			// increment the age for any other animation
			$.each(cache, function(i, animation) {
				if(style === animation.style) {
					name = animation.name;
					animation.age = 0;
				} else {
					animation.age += 1;
				}
			});

			if(!name) { // Add a new style
				sheet = getStyleSheet();
				name = "jquerypp_animation_" + (animationNum++);
				// get the last sheet and insert this rule into it
				sheet.insertRule("@" + getBrowser().prefix + "keyframes " + name + ' ' + style,
					(sheet.cssRules && sheet.cssRules.length) || 0);
				cache.push({
					name : name,
					style : style,
					age : 0
				});

				// Sort the cache by age
				cache.sort(function(first, second) {
					return first.age - second.age;
				});

				// Remove the last (oldest) item from the cache if it has more than 20 items
				if(cache.length > 20) {
					last = cache.pop();
					removeAnimation(sheet, last.name);
				}
			}

			return name;
		};

	/**
	 * @function $.fn.animate
	 * @parent $.animate
	 *
	 * Animate CSS properties using native CSS animations, if possible.
	 * Uses the original [$.fn.animate()](http://api.$.com/animate/) otherwise.
	 *
	 * @param {Object} props The CSS properties to animate
	 * @param {Integer|String|Object} [speed=400] The animation duration in ms.
	 * Will use $.fn.animate if a string or object is passed
	 * @param {Function} [callback] A callback to execute once the animation is complete
	 * @return {jQuery} The jQuery element
	 */
	$.fn.animate = function (props, speed, callback) {
		//default to normal animations if browser doesn't support them
		if (passThrough.apply(this, arguments)) {
			return oldanimate.apply(this, arguments);
		}
		if ($.isFunction(speed)) {
			callback = speed;
		}

		// Add everything to the animation queue
		this.queue('fx', function(done) {
			var
				//current CSS values
				current,
				// The list of properties passed
				properties = [],
				to = "",
				prop,
				self = $(this),
				duration = $.fx.speeds[speed] || speed || $.fx.speeds._default,
				//the animation keyframe name
				animationName,
				// The key used to store the animation hook
				dataKey,
				//the text for the keyframe
				style = "{ from {",
				// The animation end event handler.
				// Will be called both on animation end and after calling .stop()
				animationEnd = function (currentCSS, exec) {
					self.css(currentCSS);

					self.css(addPrefix({
						"animation-duration" : "",
						"animation-name" : "",
						"animation-fill-mode" : ""
					}));

					if (callback && exec) {
						// Call success, pass the DOM element as the this reference
						callback.call(self[0], true)
					}

					$.removeData(self, dataKey, true);
				}

			for(prop in props) {
				properties.push(prop);
			}

			if(getBrowser().prefix === '-moz-') {
				// Normalize 'auto' properties in FF
				$.each(properties, function(i, prop) {
					var converter = ffProps[$.camelCase(prop)];
					if(converter && self.css(prop) == 'auto') {
						self.css(prop, converter(self));
					}
				});
			}

			// Use $.styles
			current = self.styles.apply(self, properties);
			$.each(properties, function(i, cur) {
				// Convert a camelcased property name
				var name = cur.replace(/([A-Z]|^ms)/g, "-$1" ).toLowerCase();
				style += name + " : " + cssValue(cur, current[cur]) + "; ";
				to += name + " : " + cssValue(cur, props[cur]) + "; ";
			});

			style += "} to {" + to + " }}";

			animationName = getAnimation(style);
			dataKey = animationName + '.run';

			// Add a hook which will be called when the animation stops
			$._data(this, dataKey, {
				stop : function(gotoEnd) {
					// Pause the animation
					self.css(addPrefix({
						'animation-play-state' : 'paused'
					}));
					// Unbind the animation end handler
					self.off(getBrowser().transitionEnd, animationEnd);
					if(!gotoEnd) {
						// We were told not to finish the animation
						// Call animationEnd but set the CSS to the current computed style
						animationEnd(self.styles.apply(self, properties), false);
					} else {
						// Finish animaion
						animationEnd(props, true);
					}
				}
			});

			// set this element to point to that animation
			self.css(addPrefix({
				"animation-duration" : duration + "ms",
				"animation-name" : animationName,
				"animation-fill-mode": "forwards"
			}));

			// Attach the transition end event handler to run only once
			self.one(getBrowser().transitionEnd, function() {
				// Call animationEnd using the passed properties
				animationEnd(props, true);
				done();
			});

		});

		return this;
	};
});
<|endoftext|>


<commit_before>define([], function () {
    var config = {};

    config.version = '0.2.7';

    config.API_ROOT_URL = 'http://dev.keeleressursid.ee/';
    config.API_AUTH_URL = config.API_ROOT_URL+'api/auth/login/';
    config.API_URL = config.API_ROOT_URL + 'api/v1/';

    config.user = {
        roles: ['regular', 'admin']
    };

    config.hearbeat_interval = 3600;

    return config;

});
<commit_msg>Suurendan versiooninumbrit pärast Ivari muudatusi.<commit_after>define([], function () {
    var config = {};

    config.version = '0.3.0';

    config.API_ROOT_URL = 'http://dev.keeleressursid.ee/';
    config.API_AUTH_URL = config.API_ROOT_URL+'api/auth/login/';
    config.API_URL = config.API_ROOT_URL + 'api/v1/';

    config.user = {
        roles: ['regular', 'admin']
    };

    config.hearbeat_interval = 3600;

    return config;

});
<|endoftext|>


<commit_before>#!/usr/bin/env node
var child_process = require('child_process');

function log(msg) {
	process.stdout.write(msg + '\n');
}

module.exports = function(context) {
	var fs = context.requireCordovaModule('fs');
	var path = context.requireCordovaModule('path');
	var deferral = context.requireCordovaModule('q').defer();

	var make_platform_dir = function(base) {
		return path.join(base, 'platforms', 'ios');
	}
	var pluginDir = path.join(context.opts.projectRoot, 'plugins', context.opts.plugin.id);
	var hooksDir = path.join(make_platform_dir(pluginDir), 'hooks');

	var addHook = function() {
		var XmlHelpers = context.requireCordovaModule("cordova-lib/src/util/xml-helpers");
		var et = context.requireCordovaModule('elementtree');

		var configFile = path.join(context.opts.projectRoot, 'config.xml');
		var xml = XmlHelpers.parseElementtreeSync(configFile);
		log('Processing XML: ' + JSON.stringify(xml, null, '\t'));

		var getParent = function(tag, name) {
			log('getParent: ' + tag + '(name=' + name + ')');
			var list = xml.findall(tag);
			log('Finding ios in: ' + list);
			var ios = list.find(function(e) {
				return e.get('name') === name;
			});
			log('Found platform(name=ios): ' + ios);
			if (!ios) {
				log('Creating tag: ' + tag + '(name=' + name + ')');
				ios = el.makeelement(tag, {name: name});
				xml.append(ios);
			}
			return ios;
		}
		var child = et.XML('<hook type="after_plugin_add" src="' + path.join(hooksDir, 'add-bridging_header.sh') + '" />');
		getParent('platform', 'ios').append(child);

		fs.writeFileSync(configFile, xml.write({indent: 4}), 'utf-8');
	}

	var main = function() {
		log("################################ Start preparing\n");
		addHook();

		var script = path.join(hooksDir, 'after_plugin_install.sh');
		var child = child_process.execFile(script, [ context.opts.plugin.id ], {
			cwd : make_platform_dir(context.opts.projectRoot)
		}, function(error) {
			if (error) {
				deferral.reject(error);
			} else {
				log("################################ Finish preparing\n\n");
				deferral.resolve();
			}
		});
		child.stdout.on('data', function(data) {
			log(data);
		});
		child.stderr.on('data', function(data) {
			process.stderr.write(data);
		});
	}
	main();
	return deferral.promise;
};
<commit_msg>Array.find が使えないので forEach で検索<commit_after>#!/usr/bin/env node
var child_process = require('child_process');

function log(msg) {
	process.stdout.write(msg + '\n');
}

module.exports = function(context) {
	var fs = context.requireCordovaModule('fs');
	var path = context.requireCordovaModule('path');
	var deferral = context.requireCordovaModule('q').defer();

	var make_platform_dir = function(base) {
		return path.join(base, 'platforms', 'ios');
	}
	var pluginDir = path.join(context.opts.projectRoot, 'plugins', context.opts.plugin.id);
	var hooksDir = path.join(make_platform_dir(pluginDir), 'hooks');

	var addHook = function() {
		var XmlHelpers = context.requireCordovaModule("cordova-lib/src/util/xml-helpers");
		var et = context.requireCordovaModule('elementtree');

		var configFile = path.join(context.opts.projectRoot, 'config.xml');
		var xml = XmlHelpers.parseElementtreeSync(configFile);
		log('Processing XML: ' + JSON.stringify(xml, null, '\t'));

		var getParent = function(tag, name) {
			log('getParent: ' + tag + '(name=' + name + ')');
			var list = xml.findall(tag);
			log('Finding ios in: ' + list);
			var ios;
			list.forEach(function(e) {
				if (e.get('name') === name) ios = e;
			});
			log('Found platform(name=ios): ' + ios);
			if (!ios) {
				log('Creating tag: ' + tag + '(name=' + name + ')');
				ios = el.makeelement(tag, {name: name});
				xml.append(ios);
			}
			return ios;
		}
		var child = et.XML('<hook type="after_plugin_add" src="' + path.join(hooksDir, 'add-bridging_header.sh') + '" />');
		getParent('platform', 'ios').append(child);

		fs.writeFileSync(configFile, xml.write({indent: 4}), 'utf-8');
	}

	var main = function() {
		log("################################ Start preparing\n");
		addHook();

		var script = path.join(hooksDir, 'after_plugin_install.sh');
		var child = child_process.execFile(script, [ context.opts.plugin.id ], {
			cwd : make_platform_dir(context.opts.projectRoot)
		}, function(error) {
			if (error) {
				deferral.reject(error);
			} else {
				log("################################ Finish preparing\n\n");
				deferral.resolve();
			}
		});
		child.stdout.on('data', function(data) {
			log(data);
		});
		child.stderr.on('data', function(data) {
			process.stderr.write(data);
		});
	}
	main();
	return deferral.promise;
};
<|endoftext|>


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

    const DAG = (() => {
        function DAG(vertexKeys, edgeList) {
            const tmpArray = init(vertexKeys);
            this.vertices = tmpArray[0];
            this.adjacencyList = tmpArray[1];
            buildAdjacencyList(edgeList, this.vertices, this.adjacencyList);
        }

        DAG.prototype = {
            constructor: DAG,

            topoSort: function () {
                dfs(this.vertices, this.adjacencyList);
                return this.vertices
                    .slice(1) // remove index 0 (undefined)
                    .sort((a, b) => b.postOrder - a.postOrder) // reverse post order
                    .map((vertex) => vertex.id); // only interested in keys
            }
        };

        const Vertex = (() => {
            function Vertex(id) {
                this.id = id;
                this.visited = false;
                this.postOrder = 0;
            }
            return Vertex;
        })();

        function init(vertexKeys) {
            let vertices = [],
                adjacencyList = [];
            for (let vertexKey = 1; vertexKey <= vertexKeys; vertexKey++) {
                vertices[vertexKey] = new Vertex(vertexKey);
                adjacencyList[vertexKey] = [];
            }
            return [vertices, adjacencyList];
        }

        function buildAdjacencyList(edgeList, vertices, adjacencyList) {
            for (let i = 0; i < edgeList.length; i++) {
                let keyFrom = parseInt(edgeList[i].split(' ')[0]);
                let keyTo = parseInt(edgeList[i].split(' ')[1]);
                let vertexFrom = vertices[keyFrom];
                let vertexTo = vertices[keyTo];
                if (adjacencyList[vertexFrom.id].indexOf(vertexTo.id) === -1) {
                    adjacencyList[vertexFrom.id].push(vertexTo);
                }
            }
        }

        function dfs(vertices, adjacencyList) {
            let clock = 0;
            for (let v = 1; v < vertices.length; v++) {
                if (vertices[v].visited === false) {
                    clock = explore(vertices[v], adjacencyList, clock);
                }
            }
        }

        function explore(vertex, adjacencyList, clock) {
            vertex.visited = true;
            for (let i = 0; i < adjacencyList[vertex.id].length; i++) {
                const nextAdjacentVertex = adjacencyList[vertex.id][i];
                if (nextAdjacentVertex.visited === false) {
                    clock = explore(nextAdjacentVertex, adjacencyList, clock);
                }
            }
            vertex.postOrder = ++clock;
            return clock;
        }

        return DAG;
    })();

    ////////////////////////////////

    const fs = require('fs');
    const input = (process.argv.length === 3) ? process.argv[2] : '/dev/stdin';

    let data = [];
    try {
        data = fs.readFileSync(input,'utf8');
    } catch (e) {
        if (e.code === 'ENOENT') {
            console.log('File not found!');
            process.exit();
        }
        throw e;
    }

    const lines = data.match(/[^\r\n]+/g);
    const verticesEdges = lines.shift();
    const vertexKeys = parseInt(verticesEdges.split(' ')[0]);
    // note: lines = edgeList
    console.log((new DAG(vertexKeys, lines)).topoSort().join(' '));

})();
<commit_msg>pa2 - arrow on main block<commit_after>(() => { 'use strict';

    const DAG = (() => {
        function DAG(vertexKeys, edgeList) {
            const tmpArray = init(vertexKeys);
            this.vertices = tmpArray[0];
            this.adjacencyList = tmpArray[1];
            buildAdjacencyList(edgeList, this.vertices, this.adjacencyList);
        }

        DAG.prototype = {
            constructor: DAG,

            topoSort: function () {
                dfs(this.vertices, this.adjacencyList);
                return this.vertices
                    .slice(1) // remove index 0 (undefined)
                    .sort((a, b) => b.postOrder - a.postOrder) // reverse post order
                    .map((vertex) => vertex.id); // only interested in keys
            }
        };

        const Vertex = (() => {
            function Vertex(id) {
                this.id = id;
                this.visited = false;
                this.postOrder = 0;
            }
            return Vertex;
        })();

        function init(vertexKeys) {
            let vertices = [],
                adjacencyList = [];
            for (let vertexKey = 1; vertexKey <= vertexKeys; vertexKey++) {
                vertices[vertexKey] = new Vertex(vertexKey);
                adjacencyList[vertexKey] = [];
            }
            return [vertices, adjacencyList];
        }

        function buildAdjacencyList(edgeList, vertices, adjacencyList) {
            for (let i = 0; i < edgeList.length; i++) {
                let keyFrom = parseInt(edgeList[i].split(' ')[0]);
                let keyTo = parseInt(edgeList[i].split(' ')[1]);
                let vertexFrom = vertices[keyFrom];
                let vertexTo = vertices[keyTo];
                if (adjacencyList[vertexFrom.id].indexOf(vertexTo.id) === -1) {
                    adjacencyList[vertexFrom.id].push(vertexTo);
                }
            }
        }

        function dfs(vertices, adjacencyList) {
            let clock = 0;
            for (let v = 1; v < vertices.length; v++) {
                if (vertices[v].visited === false) {
                    clock = explore(vertices[v], adjacencyList, clock);
                }
            }
        }

        function explore(vertex, adjacencyList, clock) {
            vertex.visited = true;
            for (let i = 0; i < adjacencyList[vertex.id].length; i++) {
                const nextAdjacentVertex = adjacencyList[vertex.id][i];
                if (nextAdjacentVertex.visited === false) {
                    clock = explore(nextAdjacentVertex, adjacencyList, clock);
                }
            }
            vertex.postOrder = ++clock;
            return clock;
        }

        return DAG;
    })();

    ////////////////////////////////

    const fs = require('fs');
    const input = (process.argv.length === 3) ? process.argv[2] : '/dev/stdin';

    let data = [];
    try {
        data = fs.readFileSync(input,'utf8');
    } catch (e) {
        if (e.code === 'ENOENT') {
            console.log('File not found!');
            process.exit();
        }
        throw e;
    }

    const lines = data.match(/[^\r\n]+/g);
    const verticesEdges = lines.shift();
    const vertexKeys = parseInt(verticesEdges.split(' ')[0]);
    // note: lines = edgeList
    console.log((new DAG(vertexKeys, lines)).topoSort().join(' '));

})();
<|endoftext|>


<commit_before>var app = new KC3();

// If awaiting activation
var waiting = false;

// Show game screens
function ActivateGame(){
	waiting = false;
	$(".box-wrap").css("background", "#fff");
	$(".box-wait").hide();
	$(".box-game .game-swf").attr("src", localStorage.absoluteswf);
	$(".box-game").show();
}

$(document).on("ready", function(){

	// Apply initial configuration
	app.Config.init();
	app.Logging.init();

	// Apply interface configs
	$(".box-wrap").css("margin-top", app.Config.gambox_margin);
	if(app.Config.background.substring(0,1) == "#"){
		$("body").css("background", app.Config.background);
	}else{
		$("body").css("background-size", "cover");
		$("body").css("background-repeat", "no-repeat");
		$("body").css("background-image", "url("+app.Config.background+")");
	}

	// Load game meta data
	app.Meta.init("../../data/");

	// API link determines which screen to show
	var absoluteSwf = localStorage.absoluteswf;
	if(absoluteSwf){
		$(".api_txt textarea").text(localStorage.absoluteswf);
		$(".box-wait").show();
		waiting = true;
	}else{
		$(".box-nolink").show();
	}

	// Update API Link
	$(".api_submit").on('click', function(){
		if($(".api_text").val().indexOf("mainD2.swf") > -1){
			localStorage.absoluteswf = $(".api_text").val();
			window.location.reload();
		}
	});

	// Forget API Link
	$(".forget_btn").on('click', function(){
		localStorage.absoluteswf = "";
		window.location.reload();
	});

	// Quick Play
	$(".play_btn").on('click', function(){
		ActivateGame();
	});

	// API link select all textarea
	$(".api_txt textarea").on("focus", function() {
		var $this = $(this);
		$this.select();
		$this.mouseup(function() {
			$this.unbind("mouseup");
			return false;
		});
	});

});

// Extension Interaction
chrome.runtime.onMessage.addListener(function(request, sender, response) {
	if(request.game==="kancolle" && request.type==="game"){
		switch(request.action){

			// Admiral Dashboard opened, activate game
			case "activate":
				if(waiting){
					ActivateGame();
					response({success:true});
				}else{
					response({success:false});
				}
				break;

			// Quest Overlay
			case "quest_overlay":
				$(".box-game .overlays").html("");
				var qci, tmpQuest;
				for(qci in request.questlist){
					if(request.questlist[qci]!=-1){
						tmpQuest = app.Meta.quest(request.questlist[qci].api_no);

						var tmpQuestOverlay = $("#factory .ol_quest").clone().appendTo(".box-game .overlays");
						tmpQuestOverlay.css("top", (parseInt(app.Config.gambox_margin,10)+113+(qci*68))+"px");

						if(tmpQuest){
							$(".name", tmpQuestOverlay).text(tmpQuest.name);
							$(".desc", tmpQuestOverlay).text(tmpQuest.desc);
						}else{
							$(".name", tmpQuestOverlay).text(request.questlist[qci].api_title);
							$(".desc", tmpQuestOverlay).text(request.questlist[qci].api_detail);
						}
					}
				}
				response({success:true});
				break;

			// Remove overlays
			case "clear_overlays":
				$(".box-game .overlays").html("");
				response({success:true});
				break;

			// Take Screenshot
			case "screenshot":
				(new KCScreenshot()).start(request.playerIndex, $(".box-wrap"));
				break;

			default: response({success:false, message:"Unknown action"}); break;
		}
	}
});

// Confirm exit
function confirmOnPageExit(){
	app.Config.load();
	if(app.Config.askExit==1){ return "Ahh! you are closing the game!"; }
}
window.onbeforeunload = confirmOnPageExit;<commit_msg>No exit confirmation on artificial reload<commit_after>var app = new KC3();

// If awaiting activation
var waiting = false;

// If trusted exit
var trustedExit = false;

// Show game screens
function ActivateGame(){
	waiting = false;
	$(".box-wrap").css("background", "#fff");
	$(".box-wait").hide();
	$(".box-game .game-swf").attr("src", localStorage.absoluteswf);
	$(".box-game").show();
}

$(document).on("ready", function(){

	// Apply initial configuration
	app.Config.init();
	app.Logging.init();

	// Apply interface configs
	$(".box-wrap").css("margin-top", app.Config.gambox_margin);
	if(app.Config.background.substring(0,1) == "#"){
		$("body").css("background", app.Config.background);
	}else{
		$("body").css("background-size", "cover");
		$("body").css("background-repeat", "no-repeat");
		$("body").css("background-image", "url("+app.Config.background+")");
	}

	// Load game meta data
	app.Meta.init("../../data/");

	// API link determines which screen to show
	var absoluteSwf = localStorage.absoluteswf;
	if(absoluteSwf){
		$(".api_txt textarea").text(localStorage.absoluteswf);
		$(".box-wait").show();
		waiting = true;
	}else{
		$(".box-nolink").show();
	}

	// Update API Link
	$(".api_submit").on('click', function(){
		if($(".api_text").val().indexOf("mainD2.swf") > -1){
			localStorage.absoluteswf = $(".api_text").val();
			trustedExit = true;
			window.location.reload();
		}
	});

	// Forget API Link
	$(".forget_btn").on('click', function(){
		localStorage.absoluteswf = "";
		trustedExit = true;
		window.location.reload();
	});

	// Quick Play
	$(".play_btn").on('click', function(){
		ActivateGame();
	});

	// API link select all textarea
	$(".api_txt textarea").on("focus", function() {
		var $this = $(this);
		$this.select();
		$this.mouseup(function() {
			$this.unbind("mouseup");
			return false;
		});
	});

});

// Extension Interaction
chrome.runtime.onMessage.addListener(function(request, sender, response) {
	if(request.game==="kancolle" && request.type==="game"){
		switch(request.action){

			// Admiral Dashboard opened, activate game
			case "activate":
				if(waiting){
					ActivateGame();
					response({success:true});
				}else{
					response({success:false});
				}
				break;

			// Quest Overlay
			case "quest_overlay":
				$(".box-game .overlays").html("");
				var qci, tmpQuest;
				for(qci in request.questlist){
					if(request.questlist[qci]!=-1){
						tmpQuest = app.Meta.quest(request.questlist[qci].api_no);

						var tmpQuestOverlay = $("#factory .ol_quest").clone().appendTo(".box-game .overlays");
						tmpQuestOverlay.css("top", (parseInt(app.Config.gambox_margin,10)+113+(qci*68))+"px");

						if(tmpQuest){
							$(".name", tmpQuestOverlay).text(tmpQuest.name);
							$(".desc", tmpQuestOverlay).text(tmpQuest.desc);
						}else{
							$(".name", tmpQuestOverlay).text(request.questlist[qci].api_title);
							$(".desc", tmpQuestOverlay).text(request.questlist[qci].api_detail);
						}
					}
				}
				response({success:true});
				break;

			// Remove overlays
			case "clear_overlays":
				$(".box-game .overlays").html("");
				response({success:true});
				break;

			// Take Screenshot
			case "screenshot":
				(new KCScreenshot()).start(request.playerIndex, $(".box-wrap"));
				break;

			default: response({success:false, message:"Unknown action"}); break;
		}
	}
});

// Confirm exit
function confirmOnPageExit(){
	app.Config.load();
	if(app.Config.askExit==1 && !trustedExit){ return "Ahh! you are closing the game!"; }
}
window.onbeforeunload = confirmOnPageExit;<|endoftext|>


<commit_before>var BTCE = require('btce');
var btce = new BTCE();
var http = require('http');

function capitalize(str) {
  if(str === '') return '';
  return str[0].toUpperCase() + str.slice(1);
}

function getDogecoinData(callback) {
  http.get('http://pubapi.cryptsy.com/api.php?method=singlemarketdata&marketid=132', function(res) {
    var j = '';
    res.on('data', function(c) { j += c; });
    res.on('end', function() {
      try {
        j = JSON.parse(j.toString());
        var dgc_to_btc_last = j.return.markets.DOGE.lasttradeprice;
        var dgc_to_btc_avg = j.return.markets.DOGE.recenttrades.map(function(l) { return parseFloat(l.price); });
        dgc_to_btc_avg = dgc_to_btc_avg.reduce(function(l,r){return l+r;}) / dgc_to_btc_avg.length;
        btce.ticker({pair: "btc_usd"}, function(err, data) {
          if(err || !data || !data.ticker) return callback("Error occured getting BTC prices");
          data = data.ticker;
          callback("Last: $" + data.last * dgc_to_btc_last + " | Avg: $" + data.avg * dgc_to_btc_avg);
        });
      } catch(ex) {
        callback(ex);
        callback("Could not get doge");
      }
    });
  });
}

function getTickerData(coin, metric, callback) {
  if(coin === 'dgc') {
    return getDogecoinData(callback);
  }
  btce.ticker({pair: coin+"_usd"}, function(err, data) {
    if(err || !data || !data.ticker) return callback("Error occured getting BTC prices");
    data = data.ticker;
    if(data[metric.toLowerCase()]) {
      callback(capitalize(metric) + ": $" + data[metric.toLowerCase()]);
    } else {
      callback("Last: $" + data.last + " | Avg: $" + data.avg);
    }
  });
}

module.exports.commands = ['btc', 'ltc', 'dgc'];
module.exports.run = function(remainder, parts, reply, command, from, to, text, raw) {
  getTickerData(command, remainder, reply);
};
<commit_msg>Add etherium to crypto currency and support for arbitrary currency<commit_after>var BTCE = require('btce');
var btce = new BTCE();
var http = require('http');

function capitalize(str) {
  if(str === '') return '';
  return str[0].toUpperCase() + str.slice(1);
}

function getDogecoinData(callback) {
  http.get('http://pubapi.cryptsy.com/api.php?method=singlemarketdata&marketid=132', function(res) {
    var j = '';
    res.on('data', function(c) { j += c; });
    res.on('end', function() {
      try {
        j = JSON.parse(j.toString());
        var dgc_to_btc_last = j.return.markets.DOGE.lasttradeprice;
        var dgc_to_btc_avg = j.return.markets.DOGE.recenttrades.map(function(l) { return parseFloat(l.price); });
        dgc_to_btc_avg = dgc_to_btc_avg.reduce(function(l,r){return l+r;}) / dgc_to_btc_avg.length;
        btce.ticker({pair: "btc_usd"}, function(err, data) {
          if(err || !data || !data.ticker) return callback("Error occured getting BTC prices");
          data = data.ticker;
          callback("Last: $" + data.last * dgc_to_btc_last + " | Avg: $" + data.avg * dgc_to_btc_avg);
        });
      } catch(ex) {
        callback(ex);
        callback("Could not get doge");
      }
    });
  });
}

function getTickerData(coin, metric, callback) {
  if(coin === 'dgc') {
    return getDogecoinData(callback);
  }
  btce.ticker({pair: coin+"_usd"}, function(err, data) {
    if(err || !data || !data.ticker) return callback("Error occured getting BTC prices");
    data = data.ticker;
    if(data[metric.toLowerCase()]) {
      callback(capitalize(metric) + ": $" + data[metric.toLowerCase()]);
    } else {
      callback("Last: $" + data.last + " | Avg: $" + data.avg);
    }
  });
}

module.exports.commands = ['btc', 'ltc', 'dgc', 'eth'];
module.exports.run = function(remainder, parts, reply, command, from, to, text, raw) {
  getTickerData(command, remainder, reply);
};

module.exports.run_cryptoval = function(remainder, parts, reply, command, from, to, text, raw) {
  if(parts.length > 0) {
    var cryptoCurrency = parts.shift();
    getTickerData(cryptoCurrency, parts.join(" "), reply);
  }
};
<|endoftext|>