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

	htmlLint.panel = {};

	htmlLint.panel.metaData = function () {
		var errors = 0,
			output = '
',

			$head = $('head'),
			$metaTags = $head.find('meta'),
			$title = $head.find('title').html(),
			$charset = $metaTags.filter('meta[charset], meta[http-equiv="content-type"], meta[http-equiv="Content-Type"]'),
			$description = $metaTags.filter('meta[name="description"], meta[name="Description"]'),
			$keywords = $metaTags.filter('meta[name="keywords"], meta[name="Keywords"]'),
			$viewport = $metaTags.filter('meta[name="viewport"]'),

			checkTag = function (tag) {
				if (!tag) {
					tag = htmlLint.utility.error();
					errors += 1;
				}
				return tag;
			};

		// title
		output += '
<title>

' + checkTag($title) + '
';

		// charset
		if ($charset.length < 1) {
			output += '
charset

' + htmlLint.utility.error() + '
';
			errors += 1;
		} else if ($charset[0] !== $head.children()[0]) {
			output += '
Character Encoding

' + htmlLint.utility.error('not first child of <head>') + '
';
			errors += 1;
		}

		// description
		if ($description.length < 1) {
			output += '
description

' + htmlLint.utility.error() + '
';
			errors += 1;
		}

		$metaTags.not('meta[property^="og:"], meta[property^="fb:"]').each(function (index, value) {
			var $value = $(value),
				contentAttr = $value.attr('content');

			if ($value.attr('name')) {
				output += '
' + $value.attr('name') + '
';
			} else if ($value.attr('property')) {
				output += '
' + $value.attr('property') + '
';
			} else if ($value.attr('charset')) {
				output += '
charset
';
			} else if ($value.attr('http-equiv')) {
				output += '
' + $value.attr('http-equiv') + '
';
			} else if ($value.attr('itemprop')) {
				output += '
itemprop="' + $value.attr('itemprop') + '"
';
			}

			output += '
';

			if (contentAttr) {
				if ($value.attr('name') === 'msapplication-TileImage') {
					output += '';
				} else if (
					contentAttr.indexOf('http') === 0 ||
					contentAttr.indexOf('.txt') > 0
				) {
					output += '' + contentAttr + '';
				} else {
					output += contentAttr;
				}

				//  minimal-ui
				if (contentAttr.indexOf('minimal-ui') > 0) {
					output += ' ' + htmlLint.utility.error('minimal-ui has been retired');
				}

				// viewport
				if (
					// http://adrianroselli.com/2015/10/dont-disable-zoom.html
					contentAttr.indexOf('user-scalable=0') > 0 ||
					contentAttr.indexOf('user-scalable=no') > 0 ||
					contentAttr.indexOf('maximum-scale') > 0 ||
					contentAttr.indexOf('minimum-scale') > 0
				) {
					output += ' ' + htmlLint.utility.error('don’t prevent user zoom');
				}
			} else if ($value.attr('charset')) {
				output += $value.attr('charset');
			} else {
				output += htmlLint.utility.error('missing value');
				errors += 1;
			}

			output += '
';
		});

		output += '
';

		htmlLint.addPanel('Meta Data', output, errors);
	};

	htmlLint.panel.openGraph = function () {
		var errors = 0,
			$head = $('head'),
			$metaOG = $head.find('meta[property^="og:"]'),
			$metaFB = $head.find('meta[property^="fb:"]'),
			output = '
';

		if ($metaOG.length !== 0 || $metaFB.length !== 0) {
			// OG
			if ($metaOG.length !== 0) {
				$metaOG.each(function () {
					var $property = $(this).attr('property'),
						$content = $(this).attr('content');

					output += '
' + $property + '
';

					if ($content) {
						if ($property === 'og:image') {
							if ($content.indexOf('.gif') !== -1 || $content.indexOf('.jpg') !== -1 || $content.indexOf('.png') !== -1) {
								output += '

';
							} else {
								output += '
' + htmlLint.utility.error() + ' = ' + $content + '
';
							}
						} else if ($property === 'og:url') {
							output += '
' + $content + '
';
						} else {
							output += '
' + $content + '
';
						}
					} else {
						output += '
' + htmlLint.utility.error('missing value') + '
';
						errors += 1;
					}
				});
			}

			// FB
			if ($metaFB.length !== 0) {
				$metaFB.each(function () {
					var $property = $(this).attr('property'),
						$content = $(this).attr('content'),
						adminIds,
						adminLinks = '';

					output += '
' + $property + '
';

					if ($content) {
						if ($property === 'fb:app_id') {
							output += '
' + $content + '
';
						} else if ($property === 'fb:admins') {
							adminIds = $content.split(',');

							$.each(adminIds, function (index, value) {
								adminLinks += '' + value + ' ';
							});

							output += '
' + adminLinks + '
';
						} else {
							output += '
' + $content + '
';
						}
					} else {
						output += '
' + htmlLint.utility.error('missing value') + '
';
						errors += 1;
					}
				});
			}
		} else {
			output += '
Open Graph

' + htmlLint.utility.error('missing tags') + '
';
			errors += 1;
		}

		output += '
';

		htmlLint.addPanel('Open Graph', output, errors);
	};

	htmlLint.panel.overview = function () {
		var errors = 0,
			$appleTouchIcons = $('link[rel*="apple-touch-icon"]'),
			$shortcutIcons = $('link[rel="shortcut icon"], link[rel="icon"]'),
			$icons = $appleTouchIcons.add($shortcutIcons),
			output = '
';

		if ($icons.length > 0) {
			$icons.each(function (index, value) {
				var $value = $(value);

				output += '
' +
					$value.attr('rel') +
					($value.attr('sizes') ? ' (' + $value.attr('sizes') + ')' : '') +
					'
' +
					'
' +
					'' +
					'
';
			});
		}

		// no apple-touch-icon
		if ($appleTouchIcons.length < 0) {
			output += '
apple-touch-icon

' + htmlLint.utility.error() + '
';
			errors += 1;
		}

		// no shortcut icon
		if ($shortcutIcons.length < 0) {
			output += '
shortcut icon

' + htmlLint.utility.error() + '
';
			errors += 1;
		}

		output += '
';

		htmlLint.addPanel('Overview', output, errors);
	};

	htmlLint.panel.technology = function () {
		var errors = 0,
			output = '
';

		// TODO - write this all better

		/* ---- Chartbeat ---- */
		if (window._sf_async_config) {
			output += '
Chartbeat

-
';
		}

		/* ---- Cufon ---- */
		if (window.Cufon) {
			output += '
Cufon
';
			output += '
' + htmlLint.utility.error('obsolete') + '
';
			errors += 1;
		}

		/* ---- Disqus ---- */
		if (window.disqus_domain) {
			output += '
Disqus

-
';
		}

		/* ---- Google Analytics ---- */
		if (window._gaq || window._gat) {
			output += '
Google Analytics

-
';
		}

		/* ---- Hotjar ---- */
		// https://docs.hotjar.com/docs/hotjar-tracking-code
		if (window.hj) {
			output += '
Hotjar

-
';
		}

		/* ---- jQuery ---- */
		if (!(htmlLint.utility.jQueryAdded)) {
			output += '
jQuery

' + $.fn.jquery;

			if ($.fn.jquery !== htmlLint.utility.jQuery[0] && $.fn.jquery !== htmlLint.utility.jQuery[1]) {
				output += ' ' + htmlLint.utility.error('update to ' + htmlLint.utility.jQuery[0] + ' or ' + htmlLint.utility.jQuery[1]);
				errors += 1;
			}

			output += '
';
		}

		/* ---- jQuery UI ---- */
		if ($.ui) {
			output += '
jQuery UI

' + $.ui.version;

			if ($.ui.version !== htmlLint.utility.jQueryUI) {
				output += ' ' + htmlLint.utility.error('update to ' + htmlLint.utility.jQueryUI);
				errors += 1;
			}

			output += '
';
		}

		/* ---- KISS Insights ---- */
		if (window.$KI) {
			output += '
KISS Insights

-
';
		}

		/* ---- Mint ---- */
		if (window.Mint) {
			output += '
Mint

-
';
		}

		/* ---- Modernizr ---- */
		if (window.Modernizr) {
			output += '
Modernizr

' + Modernizr._version;

			if (Modernizr._version !== htmlLint.utility.Modernizr) {
				output += ' ' + htmlLint.utility.error('update to ' + htmlLint.utility.Modernizr);
				errors += 1;
			}

			output += '
';
		}

		/* ---- MooTools ---- */
		if (window.MooTools) {
			output += '
MooTools

' + MooTools.version;

			if (MooTools.version !== htmlLint.utility.MooTools) {
				output += ' ' + htmlLint.utility.error('update to ' + htmlLint.utility.MooTools);
				errors += 1;
			}

			output += '
';
		}

		/* ---- New Relic ---- */
		if (window.NREUM) {
			output += '
New Relic

-
';
		}

		/* ---- Optimizely ---- */
		if (window.optly) {
			output += '
Optimizely

-
';
		}

		/* ---- Prototype ---- */
		if (window.Prototype) {
			output += '
Prototype
';
			output += '
' + window.Prototype.Version + ' ' + htmlLint.utility.error('who uses Prototype anymore?') + '
';
			errors += 1;
		}

		/* ---- RequireJS ---- */
		if (window.require) {
			output += '
RequireJS

' + require.version;

			if (require.version !== htmlLint.utility.RequireJS) {
				output += ' ' + htmlLint.utility.error('update to ' + htmlLint.utility.RequireJS);
				errors += 1;
			}

			output += '
';
		}

		/* ---- Respond.js ---- */
		if (window.respond && window.respond.mediaQueriesSupported) {
			output += '
Respond.js

-
';
		}

		/* ---- SWFObject ---- */
		if (window.swfobject || window.SWFObject) {
			output += '
SWFObject

-
';
		}

		/* ---- Tealium ---- */
		if (window.utag) {
			output += '
Tealium

' + utag.cfg.v + '
';
		}

		/* ---- Typekit ---- */
		if (window.Typekit) {
			output += '
Typekit
';
			output += '
' + $('html').attr('class') + '
';
		}

		/* ---- WebFontConfig ---- */
		if (window.WebFontConfig) {
			if (window.WebFontConfig.google) {
				output += '
Google Webfonts
';
				output += '
' + WebFontConfig.google.families + '
';
			} else if (window.WebFontConfig.fontdeck) {
				output += '
Fontdeck
';
				output += '
-
';
			} else if (window.WebFontConfig.custom) {
				output += '
WebFonts (Fontdeck?)
';
				output += '
' + WebFontConfig.custom.families.join('
') + '
';
			}
		}

		/* ---- Wufoo ---- */
		if (window.__wufooForms) {
			output += '
Wufoo Forms

-
';
		}

		/* ---- YUI ---- */
		if (window.YUI) {
			output += '
YUI
';
			output += '
' + window.YUI.version + ' ' + htmlLint.utility.error('YUI is no longer in development') + '
';
			errors += 1;
		}

		/* ---- YepNope ---- */
		if (window.window.yepnope) {
			output += '
yepnope

-
';
		}

		output += '
';

		if (output === '

') {
			output = '';
		}

		htmlLint.addPanel('Technology', output, errors);
	};

	htmlLint.panel.tests = function () {
		htmlLint.handleErrors(htmlLint.tests);
	};
}(window.htmlLint = window.htmlLint || {}));
<commit_msg>adding more image previews<commit_after>(function (htmlLint) {
	'use strict';

	htmlLint.panel = {};

	htmlLint.panel.metaData = function () {
		var errors = 0,
			output = '
',

			$head = $('head'),
			$metaTags = $head.find('meta'),
			$title = $head.find('title').html(),
			$charset = $metaTags.filter('meta[charset], meta[http-equiv="content-type"], meta[http-equiv="Content-Type"]'),
			$description = $metaTags.filter('meta[name="description"], meta[name="Description"]'),
			$keywords = $metaTags.filter('meta[name="keywords"], meta[name="Keywords"]'),
			$viewport = $metaTags.filter('meta[name="viewport"]'),

			checkTag = function (tag) {
				if (!tag) {
					tag = htmlLint.utility.error();
					errors += 1;
				}
				return tag;
			};

		// title
		output += '
<title>

' + checkTag($title) + '
';

		// charset
		if ($charset.length < 1) {
			output += '
charset

' + htmlLint.utility.error() + '
';
			errors += 1;
		} else if ($charset[0] !== $head.children()[0]) {
			output += '
Character Encoding

' + htmlLint.utility.error('not first child of <head>') + '
';
			errors += 1;
		}

		// description
		if ($description.length < 1) {
			output += '
description

' + htmlLint.utility.error() + '
';
			errors += 1;
		}

		$metaTags.not('meta[property^="og:"], meta[property^="fb:"]').each(function (index, value) {
			var $value = $(value),
				contentAttr = $value.attr('content');

			if ($value.attr('name')) {
				output += '
' + $value.attr('name') + '
';
			} else if ($value.attr('property')) {
				output += '
' + $value.attr('property') + '
';
			} else if ($value.attr('charset')) {
				output += '
charset
';
			} else if ($value.attr('http-equiv')) {
				output += '
' + $value.attr('http-equiv') + '
';
			} else if ($value.attr('itemprop')) {
				output += '
itemprop="' + $value.attr('itemprop') + '"
';
			}

			output += '
';

			if (contentAttr) {
				if ($value.attr('name') === 'msapplication-TileImage') {
					output += '';
				if ($value.attr('name') === 'twitter:image') {
					output += '';
				} else if (
					contentAttr.indexOf('http') === 0 ||
					contentAttr.indexOf('.txt') > 0
				) {
					output += '' + contentAttr + '';
				} else {
					output += contentAttr;
				}

				//  minimal-ui
				if (contentAttr.indexOf('minimal-ui') > 0) {
					output += ' ' + htmlLint.utility.error('minimal-ui has been retired');
				}

				// viewport
				if (
					// http://adrianroselli.com/2015/10/dont-disable-zoom.html
					contentAttr.indexOf('user-scalable=0') > 0 ||
					contentAttr.indexOf('user-scalable=no') > 0 ||
					contentAttr.indexOf('maximum-scale') > 0 ||
					contentAttr.indexOf('minimum-scale') > 0
				) {
					output += ' ' + htmlLint.utility.error('don’t prevent user zoom');
				}
			} else if ($value.attr('charset')) {
				output += $value.attr('charset');
			} else {
				output += htmlLint.utility.error('missing value');
				errors += 1;
			}

			output += '
';
		});

		output += '
';

		htmlLint.addPanel('Meta Data', output, errors);
	};

	htmlLint.panel.openGraph = function () {
		var errors = 0;
		var $head = $('head');
		var $metaOG = $head.find('meta[property^="og:"]');
		var $metaFB = $head.find('meta[property^="fb:"]');
		var output = '
';

		if ($metaOG.length !== 0 || $metaFB.length !== 0) {
			// OG
			if ($metaOG.length !== 0) {
				$metaOG.each(function () {
					var $property = $(this).attr('property');
					var $content = $(this).attr('content');

					var isImageProperty = $property === 'og:image' || $property === 'og:image:secure_url';

					var hasImage = $content.indexOf('.gif') !== -1 ||
						$content.indexOf('.jpg') !== -1 ||
						$content.indexOf('.png') !== -1;

					output += '
' + $property + '
';

					if ($content) {
						if (isImageProperty) {
							if (hasImage) {
								output += '

';
							} else {
								output += '
' + htmlLint.utility.error() + ' = ' + $content + '
';
							}
						} else if ($property === 'og:url') {
							output += '
' + $content + '
';
						} else {
							output += '
' + $content + '
';
						}
					} else {
						output += '
' + htmlLint.utility.error('missing value') + '
';
						errors += 1;
					}
				});
			}

			// FB
			if ($metaFB.length !== 0) {
				$metaFB.each(function () {
					var $property = $(this).attr('property'),
						$content = $(this).attr('content'),
						adminIds,
						adminLinks = '';

					output += '
' + $property + '
';

					if ($content) {
						if ($property === 'fb:app_id') {
							output += '
' + $content + '
';
						} else if ($property === 'fb:admins') {
							adminIds = $content.split(',');

							$.each(adminIds, function (index, value) {
								adminLinks += '' + value + ' ';
							});

							output += '
' + adminLinks + '
';
						} else {
							output += '
' + $content + '
';
						}
					} else {
						output += '
' + htmlLint.utility.error('missing value') + '
';
						errors += 1;
					}
				});
			}
		} else {
			output += '
Open Graph

' + htmlLint.utility.error('missing tags') + '
';
			errors += 1;
		}

		output += '
';

		htmlLint.addPanel('Open Graph', output, errors);
	};

	htmlLint.panel.overview = function () {
		var errors = 0,
			$appleTouchIcons = $('link[rel*="apple-touch-icon"]'),
			$shortcutIcons = $('link[rel="shortcut icon"], link[rel="icon"]'),
			$icons = $appleTouchIcons.add($shortcutIcons),
			output = '
';

		if ($icons.length > 0) {
			$icons.each(function (index, value) {
				var $value = $(value);

				output += '
' +
					$value.attr('rel') +
					($value.attr('sizes') ? ' (' + $value.attr('sizes') + ')' : '') +
					'
' +
					'
' +
					'' +
					'
';
			});
		}

		// no apple-touch-icon
		if ($appleTouchIcons.length < 0) {
			output += '
apple-touch-icon

' + htmlLint.utility.error() + '
';
			errors += 1;
		}

		// no shortcut icon
		if ($shortcutIcons.length < 0) {
			output += '
shortcut icon

' + htmlLint.utility.error() + '
';
			errors += 1;
		}

		output += '
';

		htmlLint.addPanel('Overview', output, errors);
	};

	htmlLint.panel.technology = function () {
		var errors = 0,
			output = '
';

		// TODO - write this all better

		/* ---- Chartbeat ---- */
		if (window._sf_async_config) {
			output += '
Chartbeat

-
';
		}

		/* ---- Cufon ---- */
		if (window.Cufon) {
			output += '
Cufon
';
			output += '
' + htmlLint.utility.error('obsolete') + '
';
			errors += 1;
		}

		/* ---- Disqus ---- */
		if (window.disqus_domain) {
			output += '
Disqus

-
';
		}

		/* ---- Google Analytics ---- */
		if (window._gaq || window._gat) {
			output += '
Google Analytics

-
';
		}

		/* ---- Hotjar ---- */
		// https://docs.hotjar.com/docs/hotjar-tracking-code
		if (window.hj) {
			output += '
Hotjar

-
';
		}

		/* ---- jQuery ---- */
		if (!(htmlLint.utility.jQueryAdded)) {
			output += '
jQuery

' + $.fn.jquery;

			if ($.fn.jquery !== htmlLint.utility.jQuery[0] && $.fn.jquery !== htmlLint.utility.jQuery[1]) {
				output += ' ' + htmlLint.utility.error('update to ' + htmlLint.utility.jQuery[0] + ' or ' + htmlLint.utility.jQuery[1]);
				errors += 1;
			}

			output += '
';
		}

		/* ---- jQuery UI ---- */
		if ($.ui) {
			output += '
jQuery UI

' + $.ui.version;

			if ($.ui.version !== htmlLint.utility.jQueryUI) {
				output += ' ' + htmlLint.utility.error('update to ' + htmlLint.utility.jQueryUI);
				errors += 1;
			}

			output += '
';
		}

		/* ---- KISS Insights ---- */
		if (window.$KI) {
			output += '
KISS Insights

-
';
		}

		/* ---- Mint ---- */
		if (window.Mint) {
			output += '
Mint

-
';
		}

		/* ---- Modernizr ---- */
		if (window.Modernizr) {
			output += '
Modernizr

' + Modernizr._version;

			if (Modernizr._version !== htmlLint.utility.Modernizr) {
				output += ' ' + htmlLint.utility.error('update to ' + htmlLint.utility.Modernizr);
				errors += 1;
			}

			output += '
';
		}

		/* ---- MooTools ---- */
		if (window.MooTools) {
			output += '
MooTools

' + MooTools.version;

			if (MooTools.version !== htmlLint.utility.MooTools) {
				output += ' ' + htmlLint.utility.error('update to ' + htmlLint.utility.MooTools);
				errors += 1;
			}

			output += '
';
		}

		/* ---- New Relic ---- */
		if (window.NREUM) {
			output += '
New Relic

-
';
		}

		/* ---- Optimizely ---- */
		if (window.optly) {
			output += '
Optimizely

-
';
		}

		/* ---- Prototype ---- */
		if (window.Prototype) {
			output += '
Prototype
';
			output += '
' + window.Prototype.Version + ' ' + htmlLint.utility.error('who uses Prototype anymore?') + '
';
			errors += 1;
		}

		/* ---- RequireJS ---- */
		if (window.require) {
			output += '
RequireJS

' + require.version;

			if (require.version !== htmlLint.utility.RequireJS) {
				output += ' ' + htmlLint.utility.error('update to ' + htmlLint.utility.RequireJS);
				errors += 1;
			}

			output += '
';
		}

		/* ---- Respond.js ---- */
		if (window.respond && window.respond.mediaQueriesSupported) {
			output += '
Respond.js

-
';
		}

		/* ---- SWFObject ---- */
		if (window.swfobject || window.SWFObject) {
			output += '
SWFObject

-
';
		}

		/* ---- Tealium ---- */
		if (window.utag) {
			output += '
Tealium

' + utag.cfg.v + '
';
		}

		/* ---- Typekit ---- */
		if (window.Typekit) {
			output += '
Typekit
';
			output += '
' + $('html').attr('class') + '
';
		}

		/* ---- WebFontConfig ---- */
		if (window.WebFontConfig) {
			if (window.WebFontConfig.google) {
				output += '
Google Webfonts
';
				output += '
' + WebFontConfig.google.families + '
';
			} else if (window.WebFontConfig.fontdeck) {
				output += '
Fontdeck
';
				output += '
-
';
			} else if (window.WebFontConfig.custom) {
				output += '
WebFonts (Fontdeck?)
';
				output += '
' + WebFontConfig.custom.families.join('
') + '
';
			}
		}

		/* ---- Wufoo ---- */
		if (window.__wufooForms) {
			output += '
Wufoo Forms

-
';
		}

		/* ---- YUI ---- */
		if (window.YUI) {
			output += '
YUI
';
			output += '
' + window.YUI.version + ' ' + htmlLint.utility.error('YUI is no longer in development') + '
';
			errors += 1;
		}

		/* ---- YepNope ---- */
		if (window.window.yepnope) {
			output += '
yepnope

-
';
		}

		output += '
';

		if (output === '

') {
			output = '';
		}

		htmlLint.addPanel('Technology', output, errors);
	};

	htmlLint.panel.tests = function () {
		htmlLint.handleErrors(htmlLint.tests);
	};
}(window.htmlLint = window.htmlLint || {}));
<|endoftext|>


<commit_before>define(['require', 'exports', './commandParser', './argument'], function(require, exports, cmdParser, argument) {
	var Argument = argument.Argument;
	var CommandParser = cmdParser.CommandParser;

	var AutoCompleter = exports.AutoCompleter = (function() {
		function AutoCompleter(terminal) {
			this.terminal = terminal;

			this.autoCompleteCmdParser = new CommandParser(terminal && terminal.env ? terminal.env : { vars: {} });
			this.findPosCmdParser = new CommandParser({
				vars: {
					PATH: '/bin:/usr/bin'
				}
			});
		}

		AutoCompleter.prototype.autoComplete = function autoComplete(cmdLine, position, terminal) {
			var cmdName, args, parsed;

			if(typeof(cmdLine) == 'object' && typeof(cmdLine.length) != 'undefined') {
				parsed = cmdLine;
				cmdLine = parsed.text;
			} else {
				parsed = this.parse(cmdLine);
			}

			if(typeof(position) == 'number') position = this.positionFromCursorPos(parsed, position);

			args = parsed[position && position.length > 0 ? position[0] : parsed.length - 1].args;

			if(args.length <= 1 && args[0] && args[0].length <= 0) {
				while(args[0] && args[0].length <= 0) {
					args.splice(0, 1);
				}
			}

			cmdName = args.splice(0, 1)[0];
			terminal = terminal || this.terminal;

			var autoCompleteCMD = position && position.length > 0 ? parsed[position[0]] : parsed[parsed.length - 1];
			var autoCompleteFile = terminal.findCMD(cmdName || '');
			if(autoCompleteFile) {
				var autoCompleteArgIndex = position && position.length > 1 ? position[1] : autoCompleteCMD.args.length - 1;
				var autoCompleteArg = autoCompleteCMD.args[autoCompleteArgIndex];
				var autoCompleteArgDef = autoCompleteFile.command.params ? autoCompleteFile.command.params[autoCompleteArgIndex] : undefined;
				if(autoCompleteArgDef) {
					var autoCompleteBefore = position && position.length > 2 ? autoCompleteArg.substr(0, position[3]) : autoCompleteArg;

					rtn = ((new Argument(( typeof(autoCompleteArgDef.type) == 'string' ? autoCompleteArgDef.type : autoCompleteArgDef.type.name ),
							( typeof(autoCompleteArgDef.type) == 'object' ? autoCompleteArgDef.type : {} )))
							.setInput(autoCompleteArg).autoComplete(autoCompleteBefore) || []).map(function(completion) {
								return {
									name: completion,
									full: cmdLine.substr(0, autoCompleteArg.begin) + completion + cmdLine.substr(autoCompleteArg.end)
								};
							});
					rtn.index = autoCompleteArg.begin;
				} else if(autoCompleteArgIndex == -1) {
					var cmdSplit = cmdName ? cmdName.split('/') : [];
					rtn = terminal.getPath(terminal.fs.getFile(cmdSplit.slice(0, cmdSplit.length - 1).join('/'), terminal.currentDir))
						.filter(function(file) {
							return file.executable && ( cmdName ? file.name.substr(0, cmdSplit[cmdSplit.length - 1].length) == cmdSplit[cmdSplit.length - 1] : true );
						}).map(function(file) {
							return {
								name: ( cmdSplit.length > 1 ? terminal.fs.pathTo(file) : file.name ),
								full: ( autoCompleteCMD ? cmdLine.substr(0, autoCompleteCMD.begin) : '' ) +
									( cmdSplit.length > 1 ? terminal.fs.pathTo(file) : file.name ) +
									( cmdName ? cmdLine.substr(cmdName.end) : '' )
							};
						});
				} else {
					rtn = [];
				}

				rtn.index = autoCompleteArg ? autoCompleteArg.begin : 0;
			} else {
				var cmdSplit = cmdName ? cmdName.split('/') : [];
				rtn = terminal.getPath(terminal.fs.getFile(cmdSplit.slice(0, cmdSplit.length - 1).join('/'), terminal.currentDir))
					.filter(function(file) {
						return file.executable && ( cmdName ? file.name.substr(0, cmdSplit[cmdSplit.length - 1].length) == cmdSplit[cmdSplit.length - 1] : true );
					}).map(function(file) {
						return {
							name: ( cmdSplit.length > 1 ? terminal.fs.pathTo(file) : file.name ),
							full: ( autoCompleteCMD ? cmdLine.substr(0, autoCompleteCMD.begin) : '' ) +
								( cmdSplit.length > 1 ? terminal.fs.pathTo(file) : file.name ) +
								( cmdName ? cmdLine.substr(cmdName.end) : '' )
						};
					});
				rtn.index = 0;
			}

			return rtn;
		};

		AutoCompleter.prototype.parse = function parse(cmdLine, parser) {
			var errMatch;

			try {
				return (parser || this.autoCompleteCmdParser).parse(cmdLine, undefined, function(cmd) { return cmd; }, {
					checkCmd: false,
					checkStr: false,
					checkArgs: false
				});
			} catch(e) {
				if(errMatch = /Unclosed quotation at\: (\d*|end) type\: ("|')/.exec(e)) {
					if(errMatch[1] == 'end') {
						return this.parse(cmdLine + errMatch[2]);
					}
				} else {
					console.log('Unknown error:', e, e.stack, e.message);
				}
			}
		};

		AutoCompleter.prototype.positionFromCursorPos = function positionFromCursorPos(value, cursor) {
			var parsed = ( typeof(value) == 'object' && typeof(value.length) != 'undefined' ? value : this.parse(value, this.findPosCmdParser) ), args;

			for(var i = 0; i < parsed.length; i++) {
				if(parsed[i].begin <= cursor && parsed[i].end >= cursor) {
					args = parsed[i].args;

					for(var e = 0; e < args.length; e++) {
						if(args[e].begin <= cursor && args[e].end >= cursor) {
							return [i, e - 1, (cursor - 1) - args[e].begin];
						}
					}
				}
			}
		};

		AutoCompleter.prototype.isValid = function isValid(cmdLine) {

		};

		return AutoCompleter;
	})();
});
<commit_msg>Switch some return values from 0 to correct value<commit_after>define(['require', 'exports', './commandParser', './argument'], function(require, exports, cmdParser, argument) {
	var Argument = argument.Argument;
	var CommandParser = cmdParser.CommandParser;

	var AutoCompleter = exports.AutoCompleter = (function() {
		function AutoCompleter(terminal) {
			this.terminal = terminal;

			this.autoCompleteCmdParser = new CommandParser(terminal && terminal.env ? terminal.env : { vars: {} });
			this.findPosCmdParser = new CommandParser({
				vars: {
					PATH: '/bin:/usr/bin'
				}
			});
		}

		AutoCompleter.prototype.autoComplete = function autoComplete(cmdLine, position, terminal) {
			var cmdName, args, parsed;

			if(typeof(cmdLine) == 'object' && typeof(cmdLine.length) != 'undefined') {
				parsed = cmdLine;
				cmdLine = parsed.text;
			} else {
				parsed = this.parse(cmdLine);
			}

			if(typeof(position) == 'number') position = this.positionFromCursorPos(parsed, position);

			args = parsed[position && position.length > 0 ? position[0] : parsed.length - 1].args;

			if(args.length <= 1 && args[0] && args[0].length <= 0) {
				while(args[0] && args[0].length <= 0) {
					args.splice(0, 1);
				}
			}

			cmdName = args.splice(0, 1)[0];
			terminal = terminal || this.terminal;

			var autoCompleteCMD = position && position.length > 0 ? parsed[position[0]] : parsed[parsed.length - 1];
			var autoCompleteFile = terminal.findCMD(cmdName || '');
			if(autoCompleteFile) {
				var autoCompleteArgIndex = position && position.length > 1 ? position[1] : autoCompleteCMD.args.length - 1;
				var autoCompleteArg = autoCompleteCMD.args[autoCompleteArgIndex];
				var autoCompleteArgDef = autoCompleteFile.command.params ? autoCompleteFile.command.params[autoCompleteArgIndex] : undefined;
				if(autoCompleteArgDef) {
					var autoCompleteBefore = position && position.length > 2 ? autoCompleteArg.substr(0, position[3]) : autoCompleteArg;

					rtn = ((new Argument(( typeof(autoCompleteArgDef.type) == 'string' ? autoCompleteArgDef.type : autoCompleteArgDef.type.name ),
							( typeof(autoCompleteArgDef.type) == 'object' ? autoCompleteArgDef.type : {} )))
							.setInput(autoCompleteArg).autoComplete(autoCompleteBefore) || []).map(function(completion) {
								return {
									name: completion,
									full: cmdLine.substr(0, autoCompleteArg.begin) + completion + cmdLine.substr(autoCompleteArg.end)
								};
							});
					rtn.index = autoCompleteArg.begin;
				} else if(autoCompleteArgIndex == -1) {
					var cmdSplit = cmdName ? cmdName.split('/') : [];
					rtn = terminal.getPath(terminal.fs.getFile(cmdSplit.slice(0, cmdSplit.length - 1).join('/'), terminal.currentDir))
						.filter(function(file) {
							return file.executable && ( cmdName ? file.name.substr(0, cmdSplit[cmdSplit.length - 1].length) == cmdSplit[cmdSplit.length - 1] : true );
						}).map(function(file) {
							return {
								name: ( cmdSplit.length > 1 ? terminal.fs.pathTo(file) : file.name ),
								full: ( autoCompleteCMD ? cmdLine.substr(0, autoCompleteCMD.begin) : '' ) +
									( cmdSplit.length > 1 ? terminal.fs.pathTo(file) : file.name ) +
									( cmdName ? cmdLine.substr(cmdName.end) : '' )
							};
						});
				} else {
					rtn = [];
				}

				rtn.index = autoCompleteArg ? autoCompleteArg.begin : ( autoCompleteCMD ? autoCompleteCMD.begin : 0 );
			} else {
				var cmdSplit = cmdName ? cmdName.split('/') : [];
				rtn = terminal.getPath(terminal.fs.getFile(cmdSplit.slice(0, cmdSplit.length - 1).join('/'), terminal.currentDir))
					.filter(function(file) {
						return file.executable && ( cmdName ? file.name.substr(0, cmdSplit[cmdSplit.length - 1].length) == cmdSplit[cmdSplit.length - 1] : true );
					}).map(function(file) {
						return {
							name: ( cmdSplit.length > 1 ? terminal.fs.pathTo(file) : file.name ),
							full: ( autoCompleteCMD ? cmdLine.substr(0, autoCompleteCMD.begin) : '' ) +
								( cmdSplit.length > 1 ? terminal.fs.pathTo(file) : file.name ) +
								( cmdName ? cmdLine.substr(cmdName.end) : '' )
						};
					});
				rtn.index = autoCompleteCMD ? autoCompleteCMD.begin : 0;
			}

			return rtn;
		};

		AutoCompleter.prototype.parse = function parse(cmdLine, parser) {
			var errMatch;

			try {
				return (parser || this.autoCompleteCmdParser).parse(cmdLine, undefined, function(cmd) { return cmd; }, {
					checkCmd: false,
					checkStr: false,
					checkArgs: false
				});
			} catch(e) {
				if(errMatch = /Unclosed quotation at\: (\d*|end) type\: ("|')/.exec(e)) {
					if(errMatch[1] == 'end') {
						return this.parse(cmdLine + errMatch[2]);
					}
				} else {
					console.log('Unknown error:', e, e.stack, e.message);
				}
			}
		};

		AutoCompleter.prototype.positionFromCursorPos = function positionFromCursorPos(value, cursor) {
			var parsed = ( typeof(value) == 'object' && typeof(value.length) != 'undefined' ? value : this.parse(value, this.findPosCmdParser) ), args;

			for(var i = 0; i < parsed.length; i++) {
				if(parsed[i].begin <= cursor && parsed[i].end >= cursor) {
					args = parsed[i].args;

					for(var e = 0; e < args.length; e++) {
						if(args[e].begin <= cursor && args[e].end >= cursor) {
							return [i, e - 1, (cursor - 1) - args[e].begin];
						}
					}
				}
			}
		};

		AutoCompleter.prototype.isValid = function isValid(cmdLine) {

		};

		return AutoCompleter;
	})();
});
<|endoftext|>


<commit_before>var _ = require('lodash');

module.exports = {

  bucket: [],

  population: [],

  populate: function(population, length) {

    this.population = population;
    this.bucket = [];

    _.each(population, _.bind(function(item, index) {

      // Because the population is in order by fitness, we can use the index
      // as a divisor which gives more bucket slots for earlier items.
      var bucketSlots = Math.round(length / (index + 2));

      _.times(bucketSlots, _.bind(function() {
        this.bucket.push(index);
      }, this));
    }, this));
  },

  getChildFromBucket: function() {
    var mateIndex = _.sample(this.bucket);
    return this.population[mateIndex];
  },

  getChildrenFromSelection: function(population, length) {
    this.populate(population, length);
    return this.getChildren(length);
  },

  getChildrenFromPopulation: function(population) {
    this.populate(population, population.length);
    return this.getChildren(population.length);
  },

  getChildren: function(populationSize) {
    var children = [];

    _.times(populationSize, _.bind(function() {
      children.push(this.getChildFromBucket());
    }, this));

    return children;
  }
};
<commit_msg>Selected networks will all have equal fitness, so are selected as such.<commit_after>var _ = require('lodash');

module.exports = {

  bucket: [],

  population: [],

  populateByRank: function(population, length) {

    this.population = population;
    this.bucket = [];

    _.each(population, _.bind(function(item, index) {

      // Because the population is in order by fitness, we can use the index
      // as a divisor which gives more bucket slots for earlier items.
      var bucketSlots = Math.round(length / (index + 2));

      _.times(bucketSlots, _.bind(function() {
        this.bucket.push(index);
      }, this));
    }, this));
  },

  populateEqually: function(population) {
    this.population = population;
    this.bucket = [];

    _.each(population, _.bind(function(item, index) {
      this.bucket.push(index);
    }, this));
  },

  getChildFromBucket: function() {
    var mateIndex = _.sample(this.bucket);
    return this.population[mateIndex];
  },

  getChildrenFromSelection: function(population, length) {
    this.populateEqually(population, length);
    return this.getChildren(length);
  },

  getChildrenFromPopulation: function(population) {
    this.populateByRank(population, population.length);
    return this.getChildren(population.length);
  },

  getChildren: function(populationSize) {
    var children = [];

    _.times(populationSize, _.bind(function() {
      children.push(this.getChildFromBucket());
    }, this));

    return children;
  }
};
<|endoftext|>


<commit_before>/*globals require, nodeRequire, process, console*/
/**
 * Created by Zsolt on 5/16/2014.
 *
 * THIS IS A THROW AWAY CODE AND IMPLEMENTATION.
 *
 * TEMPORARY CODE AND IMPLEMENTATION.
 *
 */

// eb.executorClient.createJob('1092dd2b135af5d164b9d157b5360391246064db', function (err, res) { console.log(require('util').inspect(res)); })
// eb.executorClient.getInfoByStatus('CREATED', function(err, res) { console.log("xxx " + require('util').inspect(res)); })

define(['logManager',
        'blob/BlobClient',
        'blob/BlobMetadata',
        'fs',
        'util',
        'events',
        'path',
        'child_process',
        'minimatch',
        'executor/ExecutorClient',
        'executor/WorkerInfo',
        'superagent'
    ],
    function (logManager, BlobClient, BlobMetadata, fs, util, events, path, child_process, minimatch, ExecutorClient, WorkerInfo, superagent) {

        // FIXME: test for exe existance
        // FIXME: detect arch and use different exe and args
        var UNZIP_EXE = "c:\\Program Files\\7-Zip\\7z.exe";
        var UNZIP_ARGS = ["x", "-y"];

        var walk = function(dir, done) {
        var results = [];
        fs.readdir(dir, function(err, list) {
            if (err) return done(err);
            var i = 0;
            (function next() {
                var file = list[i++];
                if (!file) return done(null, results);
                file = dir + '/' + file;
                fs.stat(file, function(err, stat) {
                    if (stat && stat.isDirectory()) {
                        walk(file, function(err, res) {
                            results = results.concat(res);
                            next();
                        });
                    } else {
                        results.push(file);
                        next();
                    }
                });
            })();
        });
    };

    var deleteFolderRecursive = function(path) {
        if( fs.existsSync(path) ) {
            fs.readdirSync(path).forEach(function(file,index){
                var curPath = path + "/" + file;
                if(fs.lstatSync(curPath).isDirectory()) { // recurse
                    deleteFolderRecursive(curPath);
                } else { // delete file
                    try {
                        fs.unlinkSync(curPath);
                    } catch (err) {
                        logger.error('Could not delete executor-temp file, err:' + err);
                    }
                }
            });
            try {
                fs.rmdirSync(path);
            } catch (err) {
                logger.error('Could not delete executor-temp directory, err:' + err);
            }
        }
    };
    //here you can define global variables for your middleware
    var logger = // logManager.create('REST-External-Executor'); //how to define your own logger which will use the global settings
        function() { };
    logger.prototype.error = function(x) { console.log(x); };
    logger.prototype.debug = logger.prototype.error;
    logger = new logger();

    var ExecutorWorker = function (parameters) {
        this.blobClient = new BlobClient({server: parameters.server, serverPort: parameters.serverPort, httpsecure: parameters.httpsecure });

        this.executorClient = new ExecutorClient({server: parameters.server, serverPort: parameters.serverPort, httpsecure: parameters.httpsecure });
        this.jobList = {};

        this.sourceFilename = 'source.zip';
        this.resultFilename = 'execution_results';
        this.executorConfigFilename = 'executor_config.json';

        this.workingDirectory = 'executor-temp';

        if (!fs.existsSync(this.workingDirectory)) {
            fs.mkdirSync(this.workingDirectory);
        }
        this.maxProcesses = parameters.maxProcesses || 1;
        this.clientRequest = new WorkerInfo.ClientRequest({ clientId: null });
        this.clientRequest.availableProcesses = this.maxProcesses;
    };
    util.inherits(ExecutorWorker, events.EventEmitter);

    ExecutorWorker.prototype.startJob = function (jobInfo) {
        var self = this;
        this.emit('jobUpdate', jobInfo);

        // TODO: create job
        // TODO: what if job is already running?

        // get metadata for hash
        self.blobClient.getMetadata(jobInfo.hash, function (err, metadata) {
            if (err) {
                logger.error(err);
                jobInfo.status = 'FAILED_TO_GET_SOURCE_METADATA';
                self.sendJobUpdate(jobInfo);
                return;
            }

            if (metadata.contentType !== BlobMetadata.CONTENT_TYPES.COMPLEX) {
                jobInfo.status = 'FAILED_SOURCE_IS_NOT_COMPLEX';
                self.sendJobUpdate(jobInfo);
                return;
            }

            // download artifacts
            self.blobClient.getObject(jobInfo.hash, function (err, content) {
                if (err) {
                    logger.error('Failed obtaining job source content, err: ' + err.toString());
                    jobInfo.status = 'FAILED_SOURCE_COULD_NOT_BE_OBTAINED';
                    self.sendJobUpdate(jobInfo);
                    return;
                }

                var jobDir = path.normalize(path.join(self.workingDirectory, jobInfo.hash));

                if (!fs.existsSync(jobDir)) {
                    fs.mkdirSync(jobDir);
                }

                var zipPath = path.join(jobDir, self.sourceFilename);

                //content = new Uint8Array(content);
                content = new Buffer(new Uint8Array(content));
                fs.writeFile(zipPath, content, function (err) {
                    if (err) {
                        logger.error('Failed creating source zip-file, err: ' + err.toString());
                        jobInfo.status = 'FAILED_CREATING_SOURCE_ZIP';
                        self.sendJobUpdate(jobInfo);
                        return;
                    }

                    // unzip downloaded file

                    var args = [path.basename(zipPath)];
                    args.unshift.apply(args, UNZIP_ARGS);
                    var child = child_process.execFile(UNZIP_EXE, args, {cwd: jobDir},
                        function (err, stdout, stderr) {
                        if (err) {
                            logger.error(err);
                            jobInfo.status = 'FAILED_UNZIP';
                            self.sendJobUpdate(jobInfo);
                            return;
                        }

                        // delete downloaded file
                        fs.unlinkSync(zipPath);

                        var exec = child_process.exec;

                        jobInfo.startTime = new Date().toISOString();

                        // get cmd file dynamically from the this.executorConfigFilename file
                        fs.readFile(path.join(jobDir, self.executorConfigFilename), 'utf8', function (err, data) {
                            if (err) {
                                logger.error('Could not read ' + self.executorConfigFilename + ' err:' + err);
                                jobInfo.status = 'FAILED_EXECUTOR_CONFIG';
                                self.sendJobUpdate(jobInfo);
                                return;
                            }

                            var executorConfig = JSON.parse(data);
                            var cmd = executorConfig.cmd;

                            logger.debug('working directory: ' + jobDir + ' executing: ' + cmd);

                            var child = exec(cmd, {cwd: jobDir},
                                function (error, stdout, stderr) {

                                    jobInfo.finishTime = new Date().toISOString();

                                    logger.debug('stdout: ' + stdout);

                                    if (stderr) {
                                        logger.error('stderr: ' + stderr);
                                    }

                                    if (error !== null) {
                                        logger.error('exec error: ' + error);
                                        jobInfo.status = 'FAILED';
                                    }

                                    // TODO: save stderr and stdout to files.

                                    self.saveJobResults(jobInfo, jobDir, executorConfig);
                                });
                        });
                    });

                });
            });
        });
    };

    ExecutorWorker.prototype.saveJobResults = function (jobInfo, directory, executorConfig) {
        var self = this,
            i,
            jointArtifact = self.blobClient.createArtifact('jobInfo_resultSuperSetHash'),
            resultsArtifacts = [],
            afterWalk,
            archiveFile,
            afterAllFilesArchived,
            addObjectHashesAndSaveArtifact;
        jobInfo.resultHashes = {};

        for (i = 0; i < executorConfig.resultArtifacts.length; i += 1) {
            resultsArtifacts.push(
                {
                    name: executorConfig.resultArtifacts[i].name,
                    artifact: self.blobClient.createArtifact(executorConfig.resultArtifacts[i].name),
                    patterns: executorConfig.resultArtifacts[i].resultPatterns instanceof Array ?
                        executorConfig.resultArtifacts[i].resultPatterns : [],
                    files: {}
                }
            );
        }

        afterWalk = function (filesToArchive) {
            var counter,
                pendingStatus,
                i,
                counterCallback = function (err) {
                    if (err) {
                        pendingStatus = err;
                    }
                    counter -= 1;
                    if (counter <= 0) {
                        if (pendingStatus) {
                            jobInfo.status = pendingStatus;
                        } else {
                            afterAllFilesArchived();
                        }

                    }
                };
            counter = filesToArchive.length;
            if (filesToArchive.length === 0) {
                logger.info('There was no files to archive..');
                counterCallback(null);
            }
            for (i = 0; i < filesToArchive.length; i += 1) {
                archiveFile(filesToArchive[i].filename, filesToArchive[i].filePath, counterCallback);
            }
        };

        archiveFile = function (filename, filePath, callback) {
            // FIXME: get the blob client to stream
            //var stream = fs.createReadStream(results[i]);
            fs.readFile(filePath, function (err, data) {
                jointArtifact.addFileAsSoftLink(filename, data, function (err, hash) {
                    var j;
                    if (err) {
                        logger.error('Failed to archive as "' + filename + '" from "' + filePath + '", err: ' + err);
                        callback('FAILED_TO_ARCHIVE_FILE');
                    } else {
                        // Add the file-hash to the results artifacts containing the filename.
                        //console.log('Filename added : ' + filename);
                        for (j = 0; j < resultsArtifacts.length; j += 1) {
                            if (resultsArtifacts[j].files[filename] === true) {
                                resultsArtifacts[j].files[filename] = hash;
                                //console.log('Replaced! filename: "' + filename + '", artifact "' + resultsArtifacts[j].name
                                //    + '" with hash: ' + hash);
                            }
                        }
                        callback(null);
                    }
                });
            });
        };

        afterAllFilesArchived = function () {
            jointArtifact.save(function (err, resultHash) {
                var counter,
                    pendingStatus,
                    i,
                    counterCallback;
                if (err) {
                    logger.error(err);
                    jobInfo.status = 'FAILED_TO_SAVE_JOINT_ARTIFACT';
                    self.sendJobUpdate(jobInfo);
                } else {
                    counterCallback = function (err) {
                        if (err) {
                            pendingStatus = err;
                        }
                        counter -= 1;
                        if (counter <= 0) {
                            if (pendingStatus) {
                                jobInfo.status = pendingStatus;
                            } else {
                                jobInfo.status = 'SUCCESS';
                            }
                            self.sendJobUpdate(jobInfo);
                        }
                    };
                    counter = resultsArtifacts.length;
                    if (counter === 0) {
                        counterCallback(null);
                    }
                    // FIXME: This is synchronous
                    deleteFolderRecursive(directory);
                    jobInfo.resultSuperSetHash = resultHash;
                    for (i = 0; i < resultsArtifacts.length; i += 1) {
                        addObjectHashesAndSaveArtifact(resultsArtifacts[i], counterCallback);
                    }
                }
            });
        };

        addObjectHashesAndSaveArtifact = function (resultArtifact, callback) {
            resultArtifact.artifact.addMetadataHashes(resultArtifact.files, function (err, hashes) {
                if (err) {
                    logger.error(err);
                    return callback('FAILED_TO_ADD_OBJECT_HASHES');
                }
                resultArtifact.artifact.save(function (err, resultHash) {
                    if (err) {
                        logger.error(err);
                        return callback('FAILED_TO_SAVE_ARTIFACT');
                    }
                    jobInfo.resultHashes[resultArtifact.name] = resultHash;
                    callback(null);
                });
            });
        };

        walk(directory, function (err, results) {
            var i, j, a,
                filesToArchive = [],
                archive,
                filename,
                matched;
            //console.log('Walking the walk..');
            for (i = 0; i < results.length; i += 1) {
                filename = path.relative(directory, results[i]).replace(/\\/g,'/');
                archive = false;
                for (a = 0; a < resultsArtifacts.length; a += 1) {
                    if (resultsArtifacts[a].patterns.length === 0) {
                        //console.log('Matched! filename: "' + filename + '", artifact "' + resultsArtifacts[a].name + '"');
                        resultsArtifacts[a].files[filename] = true;
                        archive = true;
                    } else {
                        for (j = 0; j < resultsArtifacts[a].patterns.length; j += 1) {
                            matched = minimatch(filename, resultsArtifacts[a].patterns[j]);
                            if (matched) {
                                //console.log('Matched! filename: "' + filename + '", artifact "' + resultsArtifacts[a].name + '"');
                                resultsArtifacts[a].files[filename] = true;
                                archive = true;
                                break;
                            }
                        }
                    }
                }
                if (archive) {
                    filesToArchive.push({ filename: filename, filePath: results[i]});
                }
            }
            afterWalk(filesToArchive);
        });
    };

    ExecutorWorker.prototype.sendJobUpdate = function(jobInfo) {
        this.executorClient.updateJob(jobInfo, function (err) {
            if (err) {
                console.log(err); // TODO
            }
        });
        this.emit('jobUpdate', jobInfo);
    };

    ExecutorWorker.prototype.cancelJob = function () {

    };

    ExecutorWorker.prototype.checkForUnzipExe = function() {
        this.checkForUnzipExe = function() { };
        fs.exists(UNZIP_EXE, function (exists) {
            if (exists) {
            } else {
                alert("Unzip exe \"" + UNZIP_EXE + "\" does not exist. Please install it.");
            }
        });
    };

    ExecutorWorker.prototype.queryWorkerAPI = function (callback) {
        var self = this;
        self.checkForUnzipExe();

        var _queryWorkerAPI = function() {

            superagent.post(self.executorClient.executorUrl + 'worker')
                //.set('Content-Type', 'application/json')
                //oReq.timeout = 25 * 1000;
                .send(self.clientRequest)
                .end(function (err, res) {
                    if (err) {
                        callback(err);
                        return;
                    }
                    if (res.status > 399) {
                        callback('Server returned ' + res.status);
                    } else {
                        var response = JSON.parse(res.text);
                        console.log(res.text)
                        var jobsToStart = response.jobsToStart;
                        for (var i = 0; i < jobsToStart.length; i++) {
                            self.executorClient.getInfo(jobsToStart[i], function (err, info) {
                                if (err) {
                                    // TODO
                                }
                                self.jobList[info.hash] = info;
                                self.startJob(info);
                            });
                        }

                        callback(null, response);
                    }

                });
        };
        if (self.clientRequest.clientId) {
            _queryWorkerAPI();
        } else {
            var child = child_process.execFile("hostname", [], {}, function (err, stdout, stderr) {
                self.clientRequest.clientId = stdout.trim() || "unknown";
                _queryWorkerAPI();
            });
        }
    };

    return ExecutorWorker;
});
<commit_msg>Add process id to executor_worker clientId<commit_after>/*globals require, nodeRequire, process, console*/
/**
 * Created by Zsolt on 5/16/2014.
 *
 * THIS IS A THROW AWAY CODE AND IMPLEMENTATION.
 *
 * TEMPORARY CODE AND IMPLEMENTATION.
 *
 */

// eb.executorClient.createJob('1092dd2b135af5d164b9d157b5360391246064db', function (err, res) { console.log(require('util').inspect(res)); })
// eb.executorClient.getInfoByStatus('CREATED', function(err, res) { console.log("xxx " + require('util').inspect(res)); })

define(['logManager',
        'blob/BlobClient',
        'blob/BlobMetadata',
        'fs',
        'util',
        'events',
        'path',
        'child_process',
        'minimatch',
        'executor/ExecutorClient',
        'executor/WorkerInfo',
        'superagent'
    ],
    function (logManager, BlobClient, BlobMetadata, fs, util, events, path, child_process, minimatch, ExecutorClient, WorkerInfo, superagent) {

        // FIXME: test for exe existance
        // FIXME: detect arch and use different exe and args
        var UNZIP_EXE = "c:\\Program Files\\7-Zip\\7z.exe";
        var UNZIP_ARGS = ["x", "-y"];

        var walk = function(dir, done) {
        var results = [];
        fs.readdir(dir, function(err, list) {
            if (err) return done(err);
            var i = 0;
            (function next() {
                var file = list[i++];
                if (!file) return done(null, results);
                file = dir + '/' + file;
                fs.stat(file, function(err, stat) {
                    if (stat && stat.isDirectory()) {
                        walk(file, function(err, res) {
                            results = results.concat(res);
                            next();
                        });
                    } else {
                        results.push(file);
                        next();
                    }
                });
            })();
        });
    };

    var deleteFolderRecursive = function(path) {
        if( fs.existsSync(path) ) {
            fs.readdirSync(path).forEach(function(file,index){
                var curPath = path + "/" + file;
                if(fs.lstatSync(curPath).isDirectory()) { // recurse
                    deleteFolderRecursive(curPath);
                } else { // delete file
                    try {
                        fs.unlinkSync(curPath);
                    } catch (err) {
                        logger.error('Could not delete executor-temp file, err:' + err);
                    }
                }
            });
            try {
                fs.rmdirSync(path);
            } catch (err) {
                logger.error('Could not delete executor-temp directory, err:' + err);
            }
        }
    };
    //here you can define global variables for your middleware
    var logger = // logManager.create('REST-External-Executor'); //how to define your own logger which will use the global settings
        function() { };
    logger.prototype.error = function(x) { console.log(x); };
    logger.prototype.debug = logger.prototype.error;
    logger = new logger();

    var ExecutorWorker = function (parameters) {
        this.blobClient = new BlobClient({server: parameters.server, serverPort: parameters.serverPort, httpsecure: parameters.httpsecure });

        this.executorClient = new ExecutorClient({server: parameters.server, serverPort: parameters.serverPort, httpsecure: parameters.httpsecure });
        this.jobList = {};

        this.sourceFilename = 'source.zip';
        this.resultFilename = 'execution_results';
        this.executorConfigFilename = 'executor_config.json';

        this.workingDirectory = 'executor-temp';

        if (!fs.existsSync(this.workingDirectory)) {
            fs.mkdirSync(this.workingDirectory);
        }
        this.maxProcesses = parameters.maxProcesses || 1;
        this.clientRequest = new WorkerInfo.ClientRequest({ clientId: null });
        this.clientRequest.availableProcesses = this.maxProcesses;
    };
    util.inherits(ExecutorWorker, events.EventEmitter);

    ExecutorWorker.prototype.startJob = function (jobInfo) {
        var self = this;
        this.emit('jobUpdate', jobInfo);

        // TODO: create job
        // TODO: what if job is already running?

        // get metadata for hash
        self.blobClient.getMetadata(jobInfo.hash, function (err, metadata) {
            if (err) {
                logger.error(err);
                jobInfo.status = 'FAILED_TO_GET_SOURCE_METADATA';
                self.sendJobUpdate(jobInfo);
                return;
            }

            if (metadata.contentType !== BlobMetadata.CONTENT_TYPES.COMPLEX) {
                jobInfo.status = 'FAILED_SOURCE_IS_NOT_COMPLEX';
                self.sendJobUpdate(jobInfo);
                return;
            }

            // download artifacts
            self.blobClient.getObject(jobInfo.hash, function (err, content) {
                if (err) {
                    logger.error('Failed obtaining job source content, err: ' + err.toString());
                    jobInfo.status = 'FAILED_SOURCE_COULD_NOT_BE_OBTAINED';
                    self.sendJobUpdate(jobInfo);
                    return;
                }

                var jobDir = path.normalize(path.join(self.workingDirectory, jobInfo.hash));

                if (!fs.existsSync(jobDir)) {
                    fs.mkdirSync(jobDir);
                }

                var zipPath = path.join(jobDir, self.sourceFilename);

                //content = new Uint8Array(content);
                content = new Buffer(new Uint8Array(content));
                fs.writeFile(zipPath, content, function (err) {
                    if (err) {
                        logger.error('Failed creating source zip-file, err: ' + err.toString());
                        jobInfo.status = 'FAILED_CREATING_SOURCE_ZIP';
                        self.sendJobUpdate(jobInfo);
                        return;
                    }

                    // unzip downloaded file

                    var args = [path.basename(zipPath)];
                    args.unshift.apply(args, UNZIP_ARGS);
                    var child = child_process.execFile(UNZIP_EXE, args, {cwd: jobDir},
                        function (err, stdout, stderr) {
                        if (err) {
                            logger.error(err);
                            jobInfo.status = 'FAILED_UNZIP';
                            self.sendJobUpdate(jobInfo);
                            return;
                        }

                        // delete downloaded file
                        fs.unlinkSync(zipPath);

                        var exec = child_process.exec;

                        jobInfo.startTime = new Date().toISOString();

                        // get cmd file dynamically from the this.executorConfigFilename file
                        fs.readFile(path.join(jobDir, self.executorConfigFilename), 'utf8', function (err, data) {
                            if (err) {
                                logger.error('Could not read ' + self.executorConfigFilename + ' err:' + err);
                                jobInfo.status = 'FAILED_EXECUTOR_CONFIG';
                                self.sendJobUpdate(jobInfo);
                                return;
                            }

                            var executorConfig = JSON.parse(data);
                            var cmd = executorConfig.cmd;

                            logger.debug('working directory: ' + jobDir + ' executing: ' + cmd);

                            var child = exec(cmd, {cwd: jobDir},
                                function (error, stdout, stderr) {

                                    jobInfo.finishTime = new Date().toISOString();

                                    logger.debug('stdout: ' + stdout);

                                    if (stderr) {
                                        logger.error('stderr: ' + stderr);
                                    }

                                    if (error !== null) {
                                        logger.error('exec error: ' + error);
                                        jobInfo.status = 'FAILED';
                                    }

                                    // TODO: save stderr and stdout to files.

                                    self.saveJobResults(jobInfo, jobDir, executorConfig);
                                });
                        });
                    });

                });
            });
        });
    };

    ExecutorWorker.prototype.saveJobResults = function (jobInfo, directory, executorConfig) {
        var self = this,
            i,
            jointArtifact = self.blobClient.createArtifact('jobInfo_resultSuperSetHash'),
            resultsArtifacts = [],
            afterWalk,
            archiveFile,
            afterAllFilesArchived,
            addObjectHashesAndSaveArtifact;
        jobInfo.resultHashes = {};

        for (i = 0; i < executorConfig.resultArtifacts.length; i += 1) {
            resultsArtifacts.push(
                {
                    name: executorConfig.resultArtifacts[i].name,
                    artifact: self.blobClient.createArtifact(executorConfig.resultArtifacts[i].name),
                    patterns: executorConfig.resultArtifacts[i].resultPatterns instanceof Array ?
                        executorConfig.resultArtifacts[i].resultPatterns : [],
                    files: {}
                }
            );
        }

        afterWalk = function (filesToArchive) {
            var counter,
                pendingStatus,
                i,
                counterCallback = function (err) {
                    if (err) {
                        pendingStatus = err;
                    }
                    counter -= 1;
                    if (counter <= 0) {
                        if (pendingStatus) {
                            jobInfo.status = pendingStatus;
                        } else {
                            afterAllFilesArchived();
                        }

                    }
                };
            counter = filesToArchive.length;
            if (filesToArchive.length === 0) {
                logger.info('There was no files to archive..');
                counterCallback(null);
            }
            for (i = 0; i < filesToArchive.length; i += 1) {
                archiveFile(filesToArchive[i].filename, filesToArchive[i].filePath, counterCallback);
            }
        };

        archiveFile = function (filename, filePath, callback) {
            // FIXME: get the blob client to stream
            //var stream = fs.createReadStream(results[i]);
            fs.readFile(filePath, function (err, data) {
                jointArtifact.addFileAsSoftLink(filename, data, function (err, hash) {
                    var j;
                    if (err) {
                        logger.error('Failed to archive as "' + filename + '" from "' + filePath + '", err: ' + err);
                        callback('FAILED_TO_ARCHIVE_FILE');
                    } else {
                        // Add the file-hash to the results artifacts containing the filename.
                        //console.log('Filename added : ' + filename);
                        for (j = 0; j < resultsArtifacts.length; j += 1) {
                            if (resultsArtifacts[j].files[filename] === true) {
                                resultsArtifacts[j].files[filename] = hash;
                                //console.log('Replaced! filename: "' + filename + '", artifact "' + resultsArtifacts[j].name
                                //    + '" with hash: ' + hash);
                            }
                        }
                        callback(null);
                    }
                });
            });
        };

        afterAllFilesArchived = function () {
            jointArtifact.save(function (err, resultHash) {
                var counter,
                    pendingStatus,
                    i,
                    counterCallback;
                if (err) {
                    logger.error(err);
                    jobInfo.status = 'FAILED_TO_SAVE_JOINT_ARTIFACT';
                    self.sendJobUpdate(jobInfo);
                } else {
                    counterCallback = function (err) {
                        if (err) {
                            pendingStatus = err;
                        }
                        counter -= 1;
                        if (counter <= 0) {
                            if (pendingStatus) {
                                jobInfo.status = pendingStatus;
                            } else {
                                jobInfo.status = 'SUCCESS';
                            }
                            self.sendJobUpdate(jobInfo);
                        }
                    };
                    counter = resultsArtifacts.length;
                    if (counter === 0) {
                        counterCallback(null);
                    }
                    // FIXME: This is synchronous
                    deleteFolderRecursive(directory);
                    jobInfo.resultSuperSetHash = resultHash;
                    for (i = 0; i < resultsArtifacts.length; i += 1) {
                        addObjectHashesAndSaveArtifact(resultsArtifacts[i], counterCallback);
                    }
                }
            });
        };

        addObjectHashesAndSaveArtifact = function (resultArtifact, callback) {
            resultArtifact.artifact.addMetadataHashes(resultArtifact.files, function (err, hashes) {
                if (err) {
                    logger.error(err);
                    return callback('FAILED_TO_ADD_OBJECT_HASHES');
                }
                resultArtifact.artifact.save(function (err, resultHash) {
                    if (err) {
                        logger.error(err);
                        return callback('FAILED_TO_SAVE_ARTIFACT');
                    }
                    jobInfo.resultHashes[resultArtifact.name] = resultHash;
                    callback(null);
                });
            });
        };

        walk(directory, function (err, results) {
            var i, j, a,
                filesToArchive = [],
                archive,
                filename,
                matched;
            //console.log('Walking the walk..');
            for (i = 0; i < results.length; i += 1) {
                filename = path.relative(directory, results[i]).replace(/\\/g,'/');
                archive = false;
                for (a = 0; a < resultsArtifacts.length; a += 1) {
                    if (resultsArtifacts[a].patterns.length === 0) {
                        //console.log('Matched! filename: "' + filename + '", artifact "' + resultsArtifacts[a].name + '"');
                        resultsArtifacts[a].files[filename] = true;
                        archive = true;
                    } else {
                        for (j = 0; j < resultsArtifacts[a].patterns.length; j += 1) {
                            matched = minimatch(filename, resultsArtifacts[a].patterns[j]);
                            if (matched) {
                                //console.log('Matched! filename: "' + filename + '", artifact "' + resultsArtifacts[a].name + '"');
                                resultsArtifacts[a].files[filename] = true;
                                archive = true;
                                break;
                            }
                        }
                    }
                }
                if (archive) {
                    filesToArchive.push({ filename: filename, filePath: results[i]});
                }
            }
            afterWalk(filesToArchive);
        });
    };

    ExecutorWorker.prototype.sendJobUpdate = function(jobInfo) {
        this.executorClient.updateJob(jobInfo, function (err) {
            if (err) {
                console.log(err); // TODO
            }
        });
        this.emit('jobUpdate', jobInfo);
    };

    ExecutorWorker.prototype.cancelJob = function () {

    };

    ExecutorWorker.prototype.checkForUnzipExe = function() {
        this.checkForUnzipExe = function() { };
        fs.exists(UNZIP_EXE, function (exists) {
            if (exists) {
            } else {
                alert("Unzip exe \"" + UNZIP_EXE + "\" does not exist. Please install it.");
            }
        });
    };

    ExecutorWorker.prototype.queryWorkerAPI = function (callback) {
        var self = this;
        self.checkForUnzipExe();

        var _queryWorkerAPI = function() {

            superagent.post(self.executorClient.executorUrl + 'worker')
                //.set('Content-Type', 'application/json')
                //oReq.timeout = 25 * 1000;
                .send(self.clientRequest)
                .end(function (err, res) {
                    if (err) {
                        callback(err);
                        return;
                    }
                    if (res.status > 399) {
                        callback('Server returned ' + res.status);
                    } else {
                        var response = JSON.parse(res.text);
                        console.log(res.text)
                        var jobsToStart = response.jobsToStart;
                        for (var i = 0; i < jobsToStart.length; i++) {
                            self.executorClient.getInfo(jobsToStart[i], function (err, info) {
                                if (err) {
                                    // TODO
                                }
                                self.jobList[info.hash] = info;
                                self.startJob(info);
                            });
                        }

                        callback(null, response);
                    }

                });
        };
        if (self.clientRequest.clientId) {
            _queryWorkerAPI();
        } else {
            var child = child_process.execFile("hostname", [], {}, function (err, stdout, stderr) {
                self.clientRequest.clientId = (stdout.trim() || "unknown") + "_" + process.pid;
                _queryWorkerAPI();
            });
        }
    };

    return ExecutorWorker;
});
<|endoftext|>


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

    var DEFAULT_FEE_AMOUNT = '0.001';

    function WavesWalletListController($scope, $interval, events, applicationContext,
                                       apiService, transactionLoadingService) {
        var walletList = this;
        var refreshPromise;
        var refreshDelay = 10 * 1000;

        function sendCommandEvent(event, currency) {
            var assetWallet = findWalletByCurrency(currency);
            var wavesWallet = findWalletByCurrency(Currency.WAV);

            $scope.$broadcast(event, {
                assetBalance: assetWallet.balance,
                wavesBalance: wavesWallet.balance
            });
        }

        function findWalletByCurrency(currency) {
            return _.find(walletList.wallets, function (w) {
                return w.balance.currency === currency;
            });
        }

        walletList.wallets = [
            {
                balance: new Money(0, Currency.USD)
            },
            {
                balance: new Money(0, Currency.EUR)
            },
            {
                balance: new Money(0, Currency.BTC)
            },
            {
                balance: new Money(0, Currency.WAV)
            },
            {
                balance: new Money(0, Currency.CNY)
            }
        ];
        walletList.transactions = [];
        walletList.send = send;
        walletList.withdraw = withdraw;
        walletList.deposit = deposit;

        loadDataFromBackend();
        patchCurrencyIdsForTestnet();

        $scope.$on('$destroy', function () {
            if (angular.isDefined(refreshPromise)) {
                $interval.cancel(refreshPromise);
                refreshPromise = undefined;
            }
        });

        function send (currency) {
            sendCommandEvent(events.WALLET_SEND, currency);
        }

        function withdraw (currency) {
            sendCommandEvent(events.WALLET_WITHDRAW, currency);
        }

        function deposit (currency) {
            sendCommandEvent(events.WALLET_DEPOSIT, currency);
        }

        function loadDataFromBackend() {
            refreshWallets();
            refreshTransactions();

            refreshPromise = $interval(function() {
                refreshWallets();
                refreshTransactions();
            }, refreshDelay);
        }

        function refreshWallets() {
            apiService.address.balance(applicationContext.account.address)
                .then(function (response) {
                    var wavesWallet = findWalletByCurrency(Currency.WAV);
                    wavesWallet.balance = Money.fromCoins(response.balance, Currency.WAV);
                });

            apiService.assets.balance(applicationContext.account.address).then(function (response) {
                _.forEach(response.balances, function (assetBalance) {
                    var id = assetBalance.assetId;

                    // adding asset details to cache
                    applicationContext.cache.assets.put(assetBalance.issueTransaction);
                    applicationContext.cache.assets.update(id, assetBalance.balance,
                        assetBalance.reissuable, assetBalance.quantity);
                });

                _.forEach(walletList.wallets, function (wallet) {
                    var asset = applicationContext.cache.assets[wallet.balance.currency.id];
                    if (asset) {
                        wallet.balance = asset.balance;
                    }
                });
            });
        }

        function refreshTransactions() {
            var txArray;
            transactionLoadingService.loadTransactions(applicationContext.account.address)
                .then(function (transactions) {
                    txArray = transactions;

                    return transactionLoadingService.refreshAssetCache(applicationContext.cache.assets, transactions);
                })
                .then(function () {
                    walletList.transactions = txArray;
                });
        }

        /* AssetId substitution for testnet only.
           Mainnet version uses default asset identifiers.
         */
        function patchCurrencyIdsForTestnet() {
            if ($scope.isTestnet()) {
                Currency.EUR.id = '8zEZuJcKPQmFuYgVe5ZMpxgiPLu5zBhjA6xgdGomQDaP';
                Currency.USD.id = '2aSqCbvCTgvCpwkGsk4mea4tCLG4Zgp69aQDhHNvRUZv';
                Currency.CNY.id = 'D2MNuUyA38pSKoV7F7vpS15Uhw9nw5qfbrGUfCLRNuRo';
                Currency.BTC.id = 'J3gwJZHJBtK9994EXhmEzdHX5dj7bToRuVf7fvJ3GgBq';
            }
        }
    }

    WavesWalletListController.$inject = ['$scope', '$interval', 'wallet.events',
        'applicationContext', 'apiService', 'transactionLoadingService'];

    angular
        .module('app.wallet')
        .controller('walletListController', WavesWalletListController);
})();
<commit_msg>Updated testnet currency identifiers. Again.<commit_after>(function () {
    'use strict';

    var DEFAULT_FEE_AMOUNT = '0.001';

    function WavesWalletListController($scope, $interval, events, applicationContext,
                                       apiService, transactionLoadingService) {
        var walletList = this;
        var refreshPromise;
        var refreshDelay = 10 * 1000;

        function sendCommandEvent(event, currency) {
            var assetWallet = findWalletByCurrency(currency);
            var wavesWallet = findWalletByCurrency(Currency.WAV);

            $scope.$broadcast(event, {
                assetBalance: assetWallet.balance,
                wavesBalance: wavesWallet.balance
            });
        }

        function findWalletByCurrency(currency) {
            return _.find(walletList.wallets, function (w) {
                return w.balance.currency === currency;
            });
        }

        walletList.wallets = [
            {
                balance: new Money(0, Currency.USD)
            },
            {
                balance: new Money(0, Currency.EUR)
            },
            {
                balance: new Money(0, Currency.BTC)
            },
            {
                balance: new Money(0, Currency.WAV)
            },
            {
                balance: new Money(0, Currency.CNY)
            }
        ];
        walletList.transactions = [];
        walletList.send = send;
        walletList.withdraw = withdraw;
        walletList.deposit = deposit;

        loadDataFromBackend();
        patchCurrencyIdsForTestnet();

        $scope.$on('$destroy', function () {
            if (angular.isDefined(refreshPromise)) {
                $interval.cancel(refreshPromise);
                refreshPromise = undefined;
            }
        });

        function send (currency) {
            sendCommandEvent(events.WALLET_SEND, currency);
        }

        function withdraw (currency) {
            sendCommandEvent(events.WALLET_WITHDRAW, currency);
        }

        function deposit (currency) {
            sendCommandEvent(events.WALLET_DEPOSIT, currency);
        }

        function loadDataFromBackend() {
            refreshWallets();
            refreshTransactions();

            refreshPromise = $interval(function() {
                refreshWallets();
                refreshTransactions();
            }, refreshDelay);
        }

        function refreshWallets() {
            apiService.address.balance(applicationContext.account.address)
                .then(function (response) {
                    var wavesWallet = findWalletByCurrency(Currency.WAV);
                    wavesWallet.balance = Money.fromCoins(response.balance, Currency.WAV);
                });

            apiService.assets.balance(applicationContext.account.address).then(function (response) {
                _.forEach(response.balances, function (assetBalance) {
                    var id = assetBalance.assetId;

                    // adding asset details to cache
                    applicationContext.cache.assets.put(assetBalance.issueTransaction);
                    applicationContext.cache.assets.update(id, assetBalance.balance,
                        assetBalance.reissuable, assetBalance.quantity);
                });

                _.forEach(walletList.wallets, function (wallet) {
                    var asset = applicationContext.cache.assets[wallet.balance.currency.id];
                    if (asset) {
                        wallet.balance = asset.balance;
                    }
                });
            });
        }

        function refreshTransactions() {
            var txArray;
            transactionLoadingService.loadTransactions(applicationContext.account.address)
                .then(function (transactions) {
                    txArray = transactions;

                    return transactionLoadingService.refreshAssetCache(applicationContext.cache.assets, transactions);
                })
                .then(function () {
                    walletList.transactions = txArray;
                });
        }

        /* AssetId substitution for testnet only.
           Mainnet version uses default asset identifiers.
         */
        function patchCurrencyIdsForTestnet() {
            if ($scope.isTestnet()) {
                Currency.EUR.id = '2xnE3EdpqXtFgCP156qt1AbyjpqdZ5jGjWo3CwTawcux';
                Currency.USD.id = 'HyFJ3rrq5m7FxdkWtQXkZrDat1F7LjVVGfpSkUuEXQHj';
                Currency.CNY.id = '6pmDivReTLikwYqQtJTv6dTcE59knriaodB3AK8T9cF8';
                Currency.BTC.id = 'Fmg13HEHJHuZYbtJq8Da8wifJENq8uBxDuWoP9pVe2Qe';
            }
        }
    }

    WavesWalletListController.$inject = ['$scope', '$interval', 'wallet.events',
        'applicationContext', 'apiService', 'transactionLoadingService'];

    angular
        .module('app.wallet')
        .controller('walletListController', WavesWalletListController);
})();
<|endoftext|>


<commit_before>import {Icon} from './Icon';
import * as DomUtil from '../../dom/DomUtil';

/*
 * @miniclass Icon.Default (Icon)
 * @aka L.Icon.Default
 * @section
 *
 * A trivial subclass of `Icon`, represents the icon to use in `Marker`s when
 * no icon is specified. Points to the blue marker image distributed with Leaflet
 * releases.
 *
 * In order to customize the default icon, just change the properties of `L.Icon.Default.prototype.options`
 * (which is a set of `Icon options`).
 *
 * If you want to _completely_ replace the default icon, override the
 * `L.Marker.prototype.options.icon` with your own icon instead.
 */

export var IconDefault = Icon.extend({

	options: {
		iconUrl:       'marker-icon.png',
		iconRetinaUrl: 'marker-icon-2x.png',
		shadowUrl:     'marker-shadow.png',
		iconSize:    [25, 41],
		iconAnchor:  [12, 41],
		popupAnchor: [1, -34],
		tooltipAnchor: [16, -28],
		shadowSize:  [41, 41]
	},

	_getIconUrl: function (name) {
		if (!IconDefault.imagePath) {	// Deprecated, backwards-compatibility only
			IconDefault.imagePath = this._detectIconPath();
		}

		// @option imagePath: String
		// `Icon.Default` will try to auto-detect the absolute location of the
		// blue icon images. If you are placing these images in a non-standard
		// way, set this option to point to the right absolute path.
		return (this.options.imagePath || IconDefault.imagePath) + Icon.prototype._getIconUrl.call(this, name);
	},

	_detectIconPath: function () {
		var el = DomUtil.create('div',  'leaflet-default-icon-path', document.body);
		var path = DomUtil.getStyle(el, 'background-image') ||
		           DomUtil.getStyle(el, 'backgroundImage');	// IE8

		document.body.removeChild(el);

		return path.indexOf('url') === 0 ?
			path.replace(/^url\([\"\']?/, '').replace(/marker-icon\.png[\"\']?\)$/, '') : '';
	}
});
<commit_msg>Fixes #5534 by adding a check for null. (#5535)<commit_after>import {Icon} from './Icon';
import * as DomUtil from '../../dom/DomUtil';

/*
 * @miniclass Icon.Default (Icon)
 * @aka L.Icon.Default
 * @section
 *
 * A trivial subclass of `Icon`, represents the icon to use in `Marker`s when
 * no icon is specified. Points to the blue marker image distributed with Leaflet
 * releases.
 *
 * In order to customize the default icon, just change the properties of `L.Icon.Default.prototype.options`
 * (which is a set of `Icon options`).
 *
 * If you want to _completely_ replace the default icon, override the
 * `L.Marker.prototype.options.icon` with your own icon instead.
 */

export var IconDefault = Icon.extend({

	options: {
		iconUrl:       'marker-icon.png',
		iconRetinaUrl: 'marker-icon-2x.png',
		shadowUrl:     'marker-shadow.png',
		iconSize:    [25, 41],
		iconAnchor:  [12, 41],
		popupAnchor: [1, -34],
		tooltipAnchor: [16, -28],
		shadowSize:  [41, 41]
	},

	_getIconUrl: function (name) {
		if (!IconDefault.imagePath) {	// Deprecated, backwards-compatibility only
			IconDefault.imagePath = this._detectIconPath();
		}

		// @option imagePath: String
		// `Icon.Default` will try to auto-detect the absolute location of the
		// blue icon images. If you are placing these images in a non-standard
		// way, set this option to point to the right absolute path.
		return (this.options.imagePath || IconDefault.imagePath) + Icon.prototype._getIconUrl.call(this, name);
	},

	_detectIconPath: function () {
		var el = DomUtil.create('div',  'leaflet-default-icon-path', document.body);
		var path = DomUtil.getStyle(el, 'background-image') ||
		           DomUtil.getStyle(el, 'backgroundImage');	// IE8

		document.body.removeChild(el);

		if (path === null || path.indexOf('url') !== 0) {
			path = '';
		} else {
			path.replace(/^url\([\"\']?/, '').replace(/marker-icon\.png[\"\']?\)$/, '');
		}

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