<commit_before>(function($) {

    $.fn.extend({
        donetyping: function(callback,timeout){
            timeout = timeout || 1e3; // 1 second default timeout
            var timeoutReference,
                doneTyping = function(el){
                    if (!timeoutReference) return;
                    timeoutReference = null;
                    callback.call(el);
                };
            return this.each(function(i,el){
                var $el = $(el);
                // Chrome Fix (Use keyup over keypress to detect backspace)
                // thank you @palerdot
                $el.is(':input') && $el.on('keyup keypress',function(e){
                    // This catches the backspace button in chrome, but also prevents
                    // the event from triggering too premptively. Without this line,
                    // using tab/shift+tab will make the focused element fire the callback.
                    if (e.type=='keyup' && e.keyCode!=8) return;

                    // Check if timeout has been set. If it has, "reset" the clock and
                    // start over again.
                    if (timeoutReference) clearTimeout(timeoutReference);
                    timeoutReference = setTimeout(function(){
                        // if we made it here, our timeout has elapsed. Fire the
                        // callback
                        doneTyping(el);
                    }, timeout);
                }).on('blur',function(){
                    // If we can, fire the event since we're leaving the field
                    doneTyping(el);
                });
            });
        }
    });

    /** Carousel **/
    $('.registration-prev, .register').hide();

    $('#carousel-register').carousel({
        interval: false,
        wrap: false
    });

    checkRequired($('#carousel-register .item.active'));

    $('#carousel-register').on('slid.bs.carousel', function(e) {
        $('.registration-next').addClass('disabled');
        checkRequired($('#carousel-register .item.active'));

        if (e.direction == 'right' && false !== $('#register').parsley().validate('block' + $('.item.active').index())) {
            $('.registration-next').removeClass('disabled');
        }
    });

    function checkRequired(obj) {

        var idx = $('.item.active').index();

        if (idx > 0) {
            $('.registration-prev').show();
        } else {
            $('.registration-prev').hide();
        }

        if (idx == 6) {
            $('.registration-next').hide();
            $('.register').show();
        } else {
            $('.register').hide();
            $('.registration-next').show();
        }

        if (obj.find('div.is-required').length === 0) {
            $('.registration-next').removeClass('disabled');
            return;
        }

        obj.find('input, select').donetyping(function(e) {
            var requiredFieldsComplete = false;

            if (false !== $('#register').parsley().validate('block' + idx)) {
                requiredFieldsComplete = true;
            }

            if (requiredFieldsComplete) {
                $('.registration-next').removeClass('disabled');
            } else {
                $('.registration-next').addClass('disabled');
            }
        }, 400);

    }

    // Make avatars selectable
    $('.selectable').selectable({
        selected: function( event, ui ) {
            var fileName = $(ui.selected).find('img').attr('src');
            $('#avatar').val(fileName);
            $('.registration-next').removeClass('disabled');
        }
    });

})(jQuery);<commit_msg>timeout to 1 second<commit_after>(function($) {

    $.fn.extend({
        donetyping: function(callback,timeout){
            timeout = timeout || 1e3; // 1 second default timeout
            var timeoutReference,
                doneTyping = function(el){
                    if (!timeoutReference) return;
                    timeoutReference = null;
                    callback.call(el);
                };
            return this.each(function(i,el){
                var $el = $(el);
                // Chrome Fix (Use keyup over keypress to detect backspace)
                // thank you @palerdot
                $el.is(':input') && $el.on('keyup keypress',function(e){
                    // This catches the backspace button in chrome, but also prevents
                    // the event from triggering too premptively. Without this line,
                    // using tab/shift+tab will make the focused element fire the callback.
                    if (e.type=='keyup' && e.keyCode!=8) return;

                    // Check if timeout has been set. If it has, "reset" the clock and
                    // start over again.
                    if (timeoutReference) clearTimeout(timeoutReference);
                    timeoutReference = setTimeout(function(){
                        // if we made it here, our timeout has elapsed. Fire the
                        // callback
                        doneTyping(el);
                    }, timeout);
                }).on('blur',function(){
                    // If we can, fire the event since we're leaving the field
                    doneTyping(el);
                });
            });
        }
    });

    /** Carousel **/
    $('.registration-prev, .register').hide();

    $('#carousel-register').carousel({
        interval: false,
        wrap: false
    });

    checkRequired($('#carousel-register .item.active'));

    $('#carousel-register').on('slid.bs.carousel', function(e) {
        $('.registration-next').addClass('disabled');
        checkRequired($('#carousel-register .item.active'));

        if (e.direction == 'right' && false !== $('#register').parsley().validate('block' + $('.item.active').index())) {
            $('.registration-next').removeClass('disabled');
        }
    });

    function checkRequired(obj) {

        var idx = $('.item.active').index();

        if (idx > 0) {
            $('.registration-prev').show();
        } else {
            $('.registration-prev').hide();
        }

        if (idx == 6) {
            $('.registration-next').hide();
            $('.register').show();
        } else {
            $('.register').hide();
            $('.registration-next').show();
        }

        if (obj.find('div.is-required').length === 0) {
            $('.registration-next').removeClass('disabled');
            return;
        }

        obj.find('input, select').donetyping(function(e) {
            var requiredFieldsComplete = false;

            if (false !== $('#register').parsley().validate('block' + idx)) {
                requiredFieldsComplete = true;
            }

            if (requiredFieldsComplete) {
                $('.registration-next').removeClass('disabled');
            } else {
                $('.registration-next').addClass('disabled');
            }
        }, 1000);

    }

    // Make avatars selectable
    $('.selectable').selectable({
        selected: function( event, ui ) {
            var fileName = $(ui.selected).find('img').attr('src');
            $('#avatar').val(fileName);
            $('.registration-next').removeClass('disabled');
        }
    });

})(jQuery);<|endoftext|>


<commit_before>import * as patchSteps from './lib/patch-steps-es6.js';

(() => {
	const igroot = window.IG_ROOT || '';

	/** @type {typeof import("fs")} */
	const fs = (!window.fs && window.require) ? require('fs') : window.fs;

	class SimplifyResources {
		constructor() {
			/** @type {{handler: (xhr: any, url: string) => void), filter?: string, beforeCall?: boolean}[]} */
			this.handlers = [];

			this._hookAjax();
			this._hookHttpRequest();
			this._hookImages();
		}

		/**
		 * Generates patches for specified mod and prints them into the console
		 * @param {string|Mod} mod
		 */
		async generatePatches(mod){
			if (mod.constructor === String){
				return this.generatePatches(window.simplify.getMod(mod));
			}

			const baseDir = mod.baseDirectory.substr(7);
			const assets = window.simplify.getAssets(mod);
			for (const asset of assets) {
				if(asset.endsWith('.patch')) {
					continue;
				}

				const original = asset.substr(baseDir.length + 7);
				const patch = await this.generatePatch(original, asset);
				console.log('File: ' + asset + '.patch');
				console.log(JSON.stringify(patch));
			}
		}

		/**
		 * Generates patches for a pair of given objects or files.
		 * @param {object} target
		 * @param {object|array} patch
		 * @param {string} modbase
		 * @return {Promise<any>} result
		 */
		async _applyPatch(target, patch, modbase) {
			await patchSteps.patch(target, patch, async (fromGame, url) => {
				if (fromGame) {
					// Import (game file)
					return await this.loadJSONPatched(igroot + url);
				} else {
					// Include (mod file)
					return await this.loadJSON(modbase + url);
				}
			});
		}

		/**
		 * Generates patches for a pair of given objects or files.
		 * @param {string|object} original
		 * @param {string|object} modified
		 * @return {Promise<array>} result
		 */
		async generatePatch(original, modified) {
			if(original.constructor === String)
				original = await this.loadJSON(original);

			if(modified.constructor === String)
				modified = await this.loadJSON(modified);

			return patchSteps.diff(original, modified);
		}

		/**
		 *
		 * @param {(xhr: any, url: string) => void} handler
		 * @param {string=} filter
		 * @param {boolean=} beforeCall
		 */
		registerHandler(handler, filter, beforeCall){
			this.handlers.push({handler, filter, beforeCall});
		}

		/**
		 *
		 * @param {string} path
		 * @param {(string) => void} [callback] deprecated, use returned promise instead
		 * @param {(string) => void} [errorCb] deprecated, use returned promise instead
		 * @returns {Promise<string>}
		 */
		loadFile(path, callback, errorCb) {
			const result = new Promise((resolve, reject) => {
				path = this._stripAssets(path);

				if(window.require) {
					fs.readFile('assets/' + path, 'utf8', (err, data) => {
						if (err) {
							return reject(err);
						}

						resolve(data);
					});
				} else {
					const req = new XMLHttpRequest();
					req.open('GET', path, true);
					req.onreadystatechange = function(){
						if(req.readyState === 4 && req.status >= 200 && req.status < 300) {
							resolve(req.responseText);
						}
					};
					req.onerror = err => reject(err);
					req.send();
				}
			});

			if (callback || errorCb) {
				result
					.then(callback)
					.catch(errorCb);
			}

			return result;
		}

		/**
		 *
		 * @param {string} path
		 * @param {(any) => void} [callback] deprecated, use returned promise instead
		 * @param {(any) => void} [errorCb] deprecated, use returned promise instead
		 * @returns {Promise<any>}
		 */
		loadJSON(path, callback, errorCb) {
			const result = new Promise((resolve, reject) => {
				this.loadFile(path)
					.then(data => resolve(JSON.parse(data)))
					.catch(err => reject(err));
			});

			if (callback || errorCb) {
				result
					.then(callback)
					.catch(errorCb);
			}

			return result;
		}

		/**
		 * Loads a file and patches it as necessary.
		 *
		 * @param {string} path
		 * @returns {Promise<string>}
		 */
		async loadFilePatched(path) {
			// Detect if this would be patched, which implies it's a JSON file.
			const patches = this._getRelevantPatchDetails(path);
			if (patches.length > 0) {
				// It would. loadJSONPatched - with original path for equivalent functionality.
				return JSON.stringify(await this.loadJSONPatched(path));
			}
			return await this.loadFile(this._applyAssetOverrides(path));
		}

		/**
		 * Parses a JSON file, potentially patching it.
		 *
		 * @param {string} path
		 * @returns {Promise<any>}
		 */
		loadJSONPatched(path) {
			// To avoid reimplementing the code that was already implemented.
			return new Promise((resolve, reject) => {
				$.ajax({
					dataType: 'json',
					url: path,
					success: (val) => {
						resolve(val);
					},
					error: reject
				});
			});
		}

		/**
		 * Given an igroot-prefixed string, returns the path with asset replacements applied.
		 * This only changes the path, not the contents at it, so it doesn't apply JSON patches.
		 *
		 * @param {string} oldpath
		 * @returns {string} newpath
		 */
		_applyAssetOverrides(path) {
			if (!path.startsWith(igroot))
				return;
			const fullreplace = this._getAllAssets(path.substr(igroot.length));

			if(fullreplace && fullreplace.length > 0){
				if(fullreplace.length > 1)
					console.warn('Conflict between \'' + fullreplace.join('\', \'') + '\' found. Taking \'' + fullreplace[0] + '\'');

				//console.log("Replacing '" + settings.url + "' with '" + fullreplace[0]  + "'");

				if (fullreplace[0].indexOf('assets') === 0) {
					return igroot + fullreplace[0].substr(7);
				} else {
					return igroot + fullreplace[0];
				}
			}
			return path;
		}

		/**
		 * Given an igroot-prefixed string, returns an array of the relevant patch files.
		 *
		 * @param {string} oldpath
		 * @returns {Array<{mod: Mod, path: string}>} patches
		 */
		_getRelevantPatchDetails(path) {
			return this._getAllAssetDetails(path.substr(igroot.length) + '.patch');
		}

		async _hookAjax() {
			$.ajaxSetup({
				beforeSend: async (_, settings) => {
					if (settings.url.constructor !== String) {
						return console.log(settings);
					}

					// Apply asset overrides.
					const originalUrl = settings.url;
					settings.url = this._applyAssetOverrides(settings.url);

					// Run request pre handlers
					this._callHandlers(settings, true);

					let successArgs;
					try {
						successArgs = await this._handleAjaxPatching(originalUrl, this._waitForAjax(settings));
					} catch (e) {
						settings.error.apply(settings.context, e);
						return;
					}

					// Done, run final handlers
					this._callHandlers(settings, false);

					settings.success.apply(settings.context, successArgs);
				}
			});
		}

		/**
		 *
		 * @param {object} settings
		 * @param {boolean} beforeCall
		 */
		_callHandlers(settings, beforeCall) {
			/** @type {string} */
			const url = settings.url.substr(igroot.length);
			for (const entry of this.handlers) {
				if(entry.beforeCall == beforeCall && (!entry.filter || url.match(entry.filter))) {
					entry.handler(settings, url);
				}
			}
		}

		/**
		 *
		 * @param {object} settings
		 * @returns {Promise<any[]>}
		 */
		_waitForAjax(settings) {
			const success = settings.success;
			const error = settings.error;

			return new Promise((resolve, reject) => {
				settings.success = (...sArgs) => {
					this._restoreSettings(settings, success, error);
					resolve(sArgs);
				};
				settings.error = (...err) => {
					this._restoreSettings(settings, success, error);
					reject(err);
				};
			});
		}

		/**
		 *
		 * @param {object} settings
		 * @param {Function} success
		 * @param {Function} error
		 */
		_restoreSettings(settings, success, error) {
			settings.success = success;
			settings.error = error;
		}

		/*
		 * Given a promise for when an AJAX request finishes, setup patching.
		 * Returns a promise for the value given by the AJAX request.
		 *
		 * @param {object} settings
		 * @returns {Promise<any>}
		 */
		async _handleAjaxPatching(url, promise){

			// To simplify the timeline, assume patching is always going on.
			// If any patches are actually *present*, the file must be JSON.
			const patches = this._getRelevantPatchDetails(url);

			// It is assumed that a patch's index in here is the patch's normal index + 1.
			// The same applies to the resulting value table later.
			const promises = [];

			// Load all resources needed
			promises.push(promise);
			for (const patch of patches)
				promises.push(this.loadJSON(patch.path));

			// Done making the parallel requests
			const values = await this._awaitAll(promises);
			if (values[0].status !== 'resolved') {
				throw values[0].value;
			}

			const successArgs = values[0].value;
			for (let i = 0; i < patches.length; i++) {
				if (values[i + 1].status !== 'resolved') {
					console.error(`Could not load patch '${patches[i].path}' for '${url}': `, values[i + 1].value);
					continue;
				}

				await this._applyPatch(successArgs[0], values[i + 1].value, patches[i].mod.baseDirectory);
			}
			return successArgs;
		}

		/**
		 * Awaits all Promises given but does not fail on rejects.
		 * @param {Promise<any>[]} promises
		 * @returns {Promise<{status: 'resolved' | 'rejected', value: any}[]>}
		 */
		_awaitAll(promises) {
			return Promise.all(promises.map(p => p
				.then(value => ({status: 'resolved', value: value}))
				.catch(err => ({status: 'rejected', value: err}))
			));
		}

		_hookHttpRequest() {
			const instance = this;
			const original = XMLHttpRequest.prototype.open;
			XMLHttpRequest.prototype.open = function(_, url) {
				arguments[1] = instance._applyAssetOverrides(url) || url;
				return original.apply(this, arguments);
			};
		}

		_hookImages() {
			const instance = this;
			const original = window.Image;
			window.Image = class Image extends original {
				set src(url) {
					const fullreplace = instance._getAllAssets(url.substr(igroot.length));

					if(fullreplace && fullreplace.length > 0){
						if(fullreplace.length > 1) {
							console.warn('Conflict between \'' + fullreplace.join('\', \'') + '\' found. Taking \'' + fullreplace[0] + '\'');
						}

						//console.log('Replacing \'' + url + '\' with \'' + fullreplace[0]  + '\'');

						if (fullreplace[0].indexOf('assets') === 0) {
							url = igroot + fullreplace[0].substr(7);
						} else {
							url = igroot + fullreplace[0];
						}
					}

					super.src = url;
				}
			};
		}

		/**
		 *
		 * @param {string} path
		 */
		_stripAssets(path){
			return path.indexOf('assets/') == 0 ? path.substr(7) : path;
		}

		/**
		 * Gets all assets with the given path.
		 *
		 * @param {string} name
		 * @returns {string[]}
		 */
		_getAllAssets(name){
			const result = [];

			for (const mod of window.activeMods) {
				const asset = mod.getAsset(name);
				if(asset) {
					result.push(asset);
				}
			}

			return result;
		}

		/**
		 * Gets all assets with the given path. Extended version.
		 * Notes on the new return value layout:
		 * mod: Mod
		 * path: string
		 * data: Reserved for use by recipients, must not be present (must be undefined)
		 *
		 * @param {string} name
		 * @returns {Array<{mod: Mod, path: string}>}
		 */
		_getAllAssetDetails(name){
			const result = [];

			for (const mod of window.activeMods) {
				const asset = mod.getAsset(name);
				if(asset) {
					result.push({
						mod: mod,
						path: asset
					});
				}
			}

			return result;
		}
	}

	window.simplifyResources = new SimplifyResources();
})();
<commit_msg>Loader returns data and path of data. Patch Method gets the patch file path.<commit_after>import * as patchSteps from './lib/patch-steps-es6.js';

(() => {
	const igroot = window.IG_ROOT || '';

	/** @type {typeof import("fs")} */
	const fs = (!window.fs && window.require) ? require('fs') : window.fs;

	class SimplifyResources {
		constructor() {
			/** @type {{handler: (xhr: any, url: string) => void), filter?: string, beforeCall?: boolean}[]} */
			this.handlers = [];

			this._hookAjax();
			this._hookHttpRequest();
			this._hookImages();
		}

		/**
		 * Generates patches for specified mod and prints them into the console
		 * @param {string|Mod} mod
		 */
		async generatePatches(mod){
			if (mod.constructor === String){
				return this.generatePatches(window.simplify.getMod(mod));
			}

			const baseDir = mod.baseDirectory.substr(7);
			const assets = window.simplify.getAssets(mod);
			for (const asset of assets) {
				if(asset.endsWith('.patch')) {
					continue;
				}

				const original = asset.substr(baseDir.length + 7);
				const patch = await this.generatePatch(original, asset);
				console.log('File: ' + asset + '.patch');
				console.log(JSON.stringify(patch));
			}
		}

		/**
		 * Generates patches for a pair of given objects or files.
		 * @param {object} target
		 * @param {object|array} patch
		 * @param {string} modbase
		 * @return {Promise<any>} result
		 */
		async _applyPatch(target, patch, modbase, patchPath) {
			await patchSteps.patch(target, patch, async (fromGame, url) => {
				if (fromGame) {
					// Import (game file)
					return {
						path: igroot + url,
						data: await this.loadJSONPatched(igroot + url)
					};
				} else {
					// Include (mod file)
					return {
						path: modbase + url,
						data: await this.loadJSON(modbase + url)
					};
				}
			}, patchPath);
		}

		/**
		 * Generates patches for a pair of given objects or files.
		 * @param {string|object} original
		 * @param {string|object} modified
		 * @return {Promise<array>} result
		 */
		async generatePatch(original, modified) {
			if(original.constructor === String)
				original = await this.loadJSON(original);

			if(modified.constructor === String)
				modified = await this.loadJSON(modified);

			return patchSteps.diff(original, modified);
		}

		/**
		 *
		 * @param {(xhr: any, url: string) => void} handler
		 * @param {string=} filter
		 * @param {boolean=} beforeCall
		 */
		registerHandler(handler, filter, beforeCall){
			this.handlers.push({handler, filter, beforeCall});
		}

		/**
		 *
		 * @param {string} path
		 * @param {(string) => void} [callback] deprecated, use returned promise instead
		 * @param {(string) => void} [errorCb] deprecated, use returned promise instead
		 * @returns {Promise<string>}
		 */
		loadFile(path, callback, errorCb) {
			const result = new Promise((resolve, reject) => {
				path = this._stripAssets(path);

				if(window.require) {
					fs.readFile('assets/' + path, 'utf8', (err, data) => {
						if (err) {
							return reject(err);
						}

						resolve(data);
					});
				} else {
					const req = new XMLHttpRequest();
					req.open('GET', path, true);
					req.onreadystatechange = function(){
						if(req.readyState === 4 && req.status >= 200 && req.status < 300) {
							resolve(req.responseText);
						}
					};
					req.onerror = err => reject(err);
					req.send();
				}
			});

			if (callback || errorCb) {
				result
					.then(callback)
					.catch(errorCb);
			}

			return result;
		}

		/**
		 *
		 * @param {string} path
		 * @param {(any) => void} [callback] deprecated, use returned promise instead
		 * @param {(any) => void} [errorCb] deprecated, use returned promise instead
		 * @returns {Promise<any>}
		 */
		loadJSON(path, callback, errorCb) {
			const result = new Promise((resolve, reject) => {
				this.loadFile(path)
					.then(data => resolve(JSON.parse(data)))
					.catch(err => reject(err));
			});

			if (callback || errorCb) {
				result
					.then(callback)
					.catch(errorCb);
			}

			return result;
		}

		/**
		 * Loads a file and patches it as necessary.
		 *
		 * @param {string} path
		 * @returns {Promise<string>}
		 */
		async loadFilePatched(path) {
			// Detect if this would be patched, which implies it's a JSON file.
			const patches = this._getRelevantPatchDetails(path);
			if (patches.length > 0) {
				// It would. loadJSONPatched - with original path for equivalent functionality.
				return JSON.stringify(await this.loadJSONPatched(path));
			}
			return await this.loadFile(this._applyAssetOverrides(path));
		}

		/**
		 * Parses a JSON file, potentially patching it.
		 *
		 * @param {string} path
		 * @returns {Promise<any>}
		 */
		loadJSONPatched(path) {
			// To avoid reimplementing the code that was already implemented.
			return new Promise((resolve, reject) => {
				$.ajax({
					dataType: 'json',
					url: path,
					success: (val) => {
						resolve(val);
					},
					error: reject
				});
			});
		}

		/**
		 * Given an igroot-prefixed string, returns the path with asset replacements applied.
		 * This only changes the path, not the contents at it, so it doesn't apply JSON patches.
		 *
		 * @param {string} oldpath
		 * @returns {string} newpath
		 */
		_applyAssetOverrides(path) {
			if (!path.startsWith(igroot))
				return;
			const fullreplace = this._getAllAssets(path.substr(igroot.length));

			if(fullreplace && fullreplace.length > 0){
				if(fullreplace.length > 1)
					console.warn('Conflict between \'' + fullreplace.join('\', \'') + '\' found. Taking \'' + fullreplace[0] + '\'');

				//console.log("Replacing '" + settings.url + "' with '" + fullreplace[0]  + "'");

				if (fullreplace[0].indexOf('assets') === 0) {
					return igroot + fullreplace[0].substr(7);
				} else {
					return igroot + fullreplace[0];
				}
			}
			return path;
		}

		/**
		 * Given an igroot-prefixed string, returns an array of the relevant patch files.
		 *
		 * @param {string} oldpath
		 * @returns {Array<{mod: Mod, path: string}>} patches
		 */
		_getRelevantPatchDetails(path) {
			return this._getAllAssetDetails(path.substr(igroot.length) + '.patch');
		}

		async _hookAjax() {
			$.ajaxSetup({
				beforeSend: async (_, settings) => {
					if (settings.url.constructor !== String) {
						return console.log(settings);
					}

					// Apply asset overrides.
					const originalUrl = settings.url;
					settings.url = this._applyAssetOverrides(settings.url);

					// Run request pre handlers
					this._callHandlers(settings, true);

					let successArgs;
					try {
						successArgs = await this._handleAjaxPatching(originalUrl, this._waitForAjax(settings));
					} catch (e) {
						debugger;
						settings.error.apply(settings.context, e);
						return;
					}

					// Done, run final handlers
					this._callHandlers(settings, false);

					settings.success.apply(settings.context, successArgs);
				}
			});
		}

		/**
		 *
		 * @param {object} settings
		 * @param {boolean} beforeCall
		 */
		_callHandlers(settings, beforeCall) {
			/** @type {string} */
			const url = settings.url.substr(igroot.length);
			for (const entry of this.handlers) {
				if(entry.beforeCall == beforeCall && (!entry.filter || url.match(entry.filter))) {
					entry.handler(settings, url);
				}
			}
		}

		/**
		 *
		 * @param {object} settings
		 * @returns {Promise<any[]>}
		 */
		_waitForAjax(settings) {
			const success = settings.success;
			const error = settings.error;

			return new Promise((resolve, reject) => {
				settings.success = (...sArgs) => {
					this._restoreSettings(settings, success, error);
					resolve(sArgs);
				};
				settings.error = (...err) => {
					this._restoreSettings(settings, success, error);
					reject(err);
				};
			});
		}

		/**
		 *
		 * @param {object} settings
		 * @param {Function} success
		 * @param {Function} error
		 */
		_restoreSettings(settings, success, error) {
			settings.success = success;
			settings.error = error;
		}

		/*
		 * Given a promise for when an AJAX request finishes, setup patching.
		 * Returns a promise for the value given by the AJAX request.
		 *
		 * @param {object} settings
		 * @returns {Promise<any>}
		 */
		async _handleAjaxPatching(url, promise){

			// To simplify the timeline, assume patching is always going on.
			// If any patches are actually *present*, the file must be JSON.
			const patches = this._getRelevantPatchDetails(url);

			// It is assumed that a patch's index in here is the patch's normal index + 1.
			// The same applies to the resulting value table later.
			const promises = [];

			// Load all resources needed
			promises.push(promise);
			for (const patch of patches)
				promises.push(this.loadJSON(patch.path));

			// Done making the parallel requests
			const values = await this._awaitAll(promises);
			if (values[0].status !== 'resolved') {
				throw values[0].value;
			}

			const successArgs = values[0].value;
			for (let i = 0; i < patches.length; i++) {
				if (values[i + 1].status !== 'resolved') {
					console.error(`Could not load patch '${patches[i].path}' for '${url}': `, values[i + 1].value);
					continue;
				}

				await this._applyPatch(successArgs[0], values[i + 1].value, patches[i].mod.baseDirectory, patches[i].path);
			}
			return successArgs;
		}

		/**
		 * Awaits all Promises given but does not fail on rejects.
		 * @param {Promise<any>[]} promises
		 * @returns {Promise<{status: 'resolved' | 'rejected', value: any}[]>}
		 */
		_awaitAll(promises) {
			return Promise.all(promises.map(p => p
				.then(value => ({status: 'resolved', value: value}))
				.catch(err => ({status: 'rejected', value: err}))
			));
		}

		_hookHttpRequest() {
			const instance = this;
			const original = XMLHttpRequest.prototype.open;
			XMLHttpRequest.prototype.open = function(_, url) {
				arguments[1] = instance._applyAssetOverrides(url) || url;
				return original.apply(this, arguments);
			};
		}

		_hookImages() {
			const instance = this;
			const original = window.Image;
			window.Image = class Image extends original {
				set src(url) {
					const fullreplace = instance._getAllAssets(url.substr(igroot.length));

					if(fullreplace && fullreplace.length > 0){
						if(fullreplace.length > 1) {
							console.warn('Conflict between \'' + fullreplace.join('\', \'') + '\' found. Taking \'' + fullreplace[0] + '\'');
						}

						//console.log('Replacing \'' + url + '\' with \'' + fullreplace[0]  + '\'');

						if (fullreplace[0].indexOf('assets') === 0) {
							url = igroot + fullreplace[0].substr(7);
						} else {
							url = igroot + fullreplace[0];
						}
					}

					super.src = url;
				}
			};
		}

		/**
		 *
		 * @param {string} path
		 */
		_stripAssets(path){
			return path.indexOf('assets/') == 0 ? path.substr(7) : path;
		}

		/**
		 * Gets all assets with the given path.
		 *
		 * @param {string} name
		 * @returns {string[]}
		 */
		_getAllAssets(name){
			const result = [];

			for (const mod of window.activeMods) {
				const asset = mod.getAsset(name);
				if(asset) {
					result.push(asset);
				}
			}

			return result;
		}

		/**
		 * Gets all assets with the given path. Extended version.
		 * Notes on the new return value layout:
		 * mod: Mod
		 * path: string
		 * data: Reserved for use by recipients, must not be present (must be undefined)
		 *
		 * @param {string} name
		 * @returns {Array<{mod: Mod, path: string}>}
		 */
		_getAllAssetDetails(name){
			const result = [];

			for (const mod of window.activeMods) {
				const asset = mod.getAsset(name);
				if(asset) {
					result.push({
						mod: mod,
						path: asset
					});
				}
			}

			return result;
		}
	}

	window.simplifyResources = new SimplifyResources();
})();
<|endoftext|>


<commit_before>'use strict';

var D3 = require('d3');
var $ = require('jquery');
var Cookie = require('../lib/cookie');
var Template = require('../lib/template');
var Parser = require('../lib/parser');
var Chart = require('../lib/chart');
var Util = require('../lib/util');

//  Specific Charts
function drawPanchayatPerformance(internals) {
    var limit = Util.discreteLimits(internals);
    internals.data.discrete.forEach(function(region, p_index) {
        if ($('#d_' + region.region_code).length !== 0) {
            var d_step_lines = (internals.discrete_compare_lines !== '') ? [internals.discrete_compare_lines] : internals.stepCols;
            var isCumu = (internals.discrete_compare_lines === '') ? true : false;
            var d_data = Parser.lines({
                data: region.data,
                past_n_days: internals.past_n_days,
                col: d_step_lines,
                isCumulative: isCumu
            });
            Chart.small({
                data: d_data,
                title: region.region_name,
                target: '#d_' + region.region_code,
                legend_target: '.region_legend',
                labels: internals.labels,
                max_y: limit.max_y,
                min_x: limit.min_x,
                max_x: limit.max_x,
            });
        }
    });
}

// Load JSON
exports.init = function() {
    var internals = {
        past_n_days: '',
        discrete_compare_lines: '',
        groupBy: 'TA',
        labels: [
            'Muster roll closure to muster roll entry',
            'Muster roll entry to wage list generation',
            'Wage list generation to wage list sign',
            'Wage list sign to FTO generation',
            'FTO generation to first signature',
            'First signature to second signature',
            'Second signature to processed by bank',
        ],
        stepCols: [1, 2, 3, 4, 5, 6, 7]
    };
    D3.json('/performance/discrete/data?region_code=' + Cookie.read('active_region'))
        .on('progress', function() {
            console.info('progress', D3.event.loaded);
        })
        .get(function(error, data) {
            // Set Canvas
            D3.select('#loading').remove();
            D3.select('#dashboard').classed('u-hidden', false);
            D3.select('#region_name').text(data.region_name);
            internals.data = data;
            internals.role = data.config.role;

            if (internals.role === 'district') {
                Template.discrete(internals.data.discrete);
            } else if (internals.role === 'block') {
                Template.sortedDiscrete(internals.data.employees[internals.groupBy], internals);
            }
            drawPanchayatPerformance(internals);

        });
};
<commit_msg>Add time period control to discrete performance<commit_after>'use strict';

var D3 = require('d3');
var $ = require('jquery');
var Cookie = require('../lib/cookie');
var Template = require('../lib/template');
var Parser = require('../lib/parser');
var Chart = require('../lib/chart');
var Util = require('../lib/util');

//  Specific Charts
function drawPanchayatPerformance(internals) {
    var limit = Util.discreteLimits(internals);
    internals.data.discrete.forEach(function(region, p_index) {
        if ($('#d_' + region.region_code).length !== 0) {
            var d_step_lines = (internals.discrete_compare_lines !== '') ? [internals.discrete_compare_lines] : internals.stepCols;
            var isCumu = (internals.discrete_compare_lines === '') ? true : false;
            var d_data = Parser.lines({
                data: region.data,
                past_n_days: internals.past_n_days,
                col: d_step_lines,
                isCumulative: isCumu
            });
            Chart.small({
                data: d_data,
                title: region.region_name,
                target: '#d_' + region.region_code,
                legend_target: '.region_legend',
                labels: internals.labels,
                max_y: limit.max_y,
                min_x: limit.min_x,
                max_x: limit.max_x,
            });
        }
    });
}

// Load JSON
exports.init = function() {
    var internals = {
        past_n_days: '',
        discrete_compare_lines: '',
        groupBy: 'TA',
        labels: [
            'Muster roll closure to muster roll entry',
            'Muster roll entry to wage list generation',
            'Wage list generation to wage list sign',
            'Wage list sign to FTO generation',
            'FTO generation to first signature',
            'First signature to second signature',
            'Second signature to processed by bank',
        ],
        stepCols: [1, 2, 3, 4, 5, 6, 7]
    };
    D3.json('/performance/discrete/data?region_code=' + Cookie.read('active_region'))
        .on('progress', function() {
            console.info('progress', D3.event.loaded);
        })
        .get(function(error, data) {
            // Set Canvas
            D3.select('#loading').remove();
            D3.select('#dashboard').classed('u-hidden', false);
            D3.select('#region_name').text(data.region_name);
            internals.data = data;
            internals.role = data.config.role;

            if (internals.role === 'district') {
                Template.discrete(internals.data.discrete);
            } else if (internals.role === 'block') {
                Template.sortedDiscrete(internals.data.employees[internals.groupBy], internals);
            }
            drawPanchayatPerformance(internals);

        });

    // Time period Selection
    D3.selectAll('#modify-time-period-controls').on('change', function() {
        internals.past_n_days = D3.event.target.value;
        drawPanchayatPerformance(internals);

        // Update employee stats based on time controls
        if (internals.role === 'block') {
            var p_past_n_days;
            if (internals.past_n_days === '') {
                p_past_n_days = 'all';
            } else {
                p_past_n_days = internals.past_n_days - 1;
            }
            internals.data.employees[internals.groupBy].forEach(function(d) {
                D3.select('#p_stat_step_avg' + d.mobile).text(d['step1_avg_' + p_past_n_days] || '');
                D3.select('#p_stat_tot_trans' + d.mobile).text(d['tot_trans_' + p_past_n_days] || '');
            });
        }

    });

};
<|endoftext|>


<commit_before>// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
var DEBUG = true;

// At this point, libs with most common functions are loaded
// Options are ready but not loaded

// Debug print function for the main, will be overwriten in modules
var dbg = function(str) {
	utils.dbg("main", str);
};

// Firefox hacks to simulate chrome APIs
if($.browser.mozilla) {
	var chrome = {
		extension: {
			getURL: function(str) {
				return self.options[str];
			}
		}
	};
}

$(document).trigger("gksi_started");
dbg("[Init] Loading general funcs");
// Only DOM modifying functions are here

// Import a javascript file from the site if we need it elsewhere (jQ function doesn't seem to work as intended)
var appendNativeScript = function (jsFileName) {
	$("body").append($("


<commit_before>function showResults(response) {
    var resultMessage = JSON.parse(response.body);
    var status = resultMessage.status;

    makeResultsPanel();

    if (status === 'COMPILE_FAILED') {
        showCompilationError(resultMessage);
    } else if (status === 'PASSED' || status === 'TESTS_FAILED') {
        showTestResults(resultMessage);
    } else {
        $("#panel")
                .addClass("alert alert-warning")
                .text("Something happened: " + status);
    }
}

function makeResultsPanel() {
    var results = $("#results");
    results.html(
            $("
")
            .addClass("col-md-6"));
    results.append($("
")
            .attr("id", "panel"));

    var panel = $("#panel");
    panel.append(
            $("
")
            .attr("id", "panel-heading")
            .addClass("panel-heading"));
    panel.append(
            $("
")
            .attr("id", "panel-body")
            .addClass("panel-body"));

}

function showCompilationError(resultMessage) {
    //The standard out contains a lot of unnecessary data
    //All the useful rows start with [javac], but some of
    //the [javac] rows are still unnecessary.
    var lines = resultMessage.stdout.split("\n");
    lines = lines.filter(line => line.includes("[javac] "))
            .map(line => line.replace("[javac] ", ""))
            .slice(2, -1);

    $("#panel").addClass("panel panel-warning");
    $("#panel-heading")
            .text("Oh no! Your submission did not compile!");
    var panelBody = $("#panel-body");
    for (const line of lines) {
        panelBody.append(
                $("
")
                .text(line));
    }
}

function showTestResults(resultMessage) {
    if (resultMessage.success) {
        showSuccess();
    } else {
        showFailure(resultMessage);
    }
}

function showSuccess() {
    $("#panel").addClass("panel panel-success");
    $("#panel-heading").text("Task cleared!");
    $("#panel-body").text("Well done! Head onto the next task!");
}

function showFailure(resultMessage) {
    $("#panel").addClass("panel panel-danger");
    var panelHeading = $("#panel-heading");

    if (resultMessage.type === 'TEST') {
        panelHeading
                .text("Hey! You're supposed to make a test that doesn't pass!");
    } else {
        panelHeading
                .text("Uh oh! Your submission didn't pass the tests!");
    }

    for (i = 0; i < resultMessage.tests.length; i++) {
        showIndividualTestResult(resultMessage, i);
    }
}

function showIndividualTestResult(resultMessage, i) {
    var res = resultMessage.tests[i];
    //The name field is formatted like below,
    //TestClass testMethod
    var names = res.name.split(" ");
    var className = names[0];
    var testName = names[1];
    var errorMessage = res.errorMessage;
    var backtrace = res.backtrace;
    var testId = "test" + i;
    var traceId = "backtrace" + i;

    var test = $("#panel-body").append(
            $("
")
            .attr("id", testId));

    test.append($("
")
            .text(testName + " (" + className + ")"));

    passedDiv = test.append($("
"));
    if (res.passed) {
        passedDiv.text("Passed");
    } else {
        passedDiv.text("Failed");
    }

    if (errorMessage) {
        test.append($("
")
                .text("Error message :" + errorMessage));
    }

    if (backtrace.length > 0) {
        test.append($("
"));
        var trace = test.append(
                $("
")
                .attr("id", traceId)
                .text("Stack trace: "));

        for (j = 0; j < backtrace.length; j++) {
            trace.append(
                    $("
")
                    .text(backtrace[j]));
        }
    }

    //If this isn't the last test result, add some space
    //before the next one
    if (i !== resultMessage.tests.length-1) {
        test.append(
                $("
"));
        test.append(
                $("
"));
    }
}
<commit_msg>Made it so that the panel body isn't simply empty when no tests are ran.<commit_after>function showResults(response) {
    var resultMessage = JSON.parse(response.body);
    var status = resultMessage.status;

    makeResultsPanel();

    if (status === 'COMPILE_FAILED') {
        showCompilationError(resultMessage);
    } else if (status === 'PASSED' || status === 'TESTS_FAILED') {
        showTestResults(resultMessage);
    } else {
        $("#panel")
                .addClass("alert alert-warning")
                .text("Something happened: " + status);
    }
}

function makeResultsPanel() {
    var results = $("#results");
    results.html(
            $("
")
            .addClass("col-md-6"));
    results.append($("
")
            .attr("id", "panel"));

    var panel = $("#panel");
    panel.append(
            $("
")
            .attr("id", "panel-heading")
            .addClass("panel-heading"));
    panel.append(
            $("
")
            .attr("id", "panel-body")
            .addClass("panel-body"));

}

function showCompilationError(resultMessage) {
    //The standard out contains a lot of unnecessary data
    //All the useful rows start with [javac], but some of
    //the [javac] rows are still unnecessary.
    var lines = resultMessage.stdout.split("\n");
    lines = lines.filter(line => line.includes("[javac] "))
            .map(line => line.replace("[javac] ", ""))
            .slice(2, -1);

    $("#panel").addClass("panel panel-warning");
    $("#panel-heading")
            .text("Oh no! Your submission did not compile!");
    var panelBody = $("#panel-body");
    for (const line of lines) {
        panelBody.append(
                $("
")
                .text(line));
    }
}

function showTestResults(resultMessage) {
    if (resultMessage.success) {
        showSuccess();
    } else {
        showFailure(resultMessage);
    }
}

function showSuccess() {
    $("#panel").addClass("panel panel-success");
    $("#panel-heading").text("Task cleared!");
    $("#panel-body").text("Well done! Head onto the next task!");
}

function showFailure(resultMessage) {
    $("#panel").addClass("panel panel-danger");
    var panelHeading = $("#panel-heading");

    if (resultMessage.type === 'TEST') {
        panelHeading
                .text("Hey! You're supposed to make a test that doesn't pass!");
    } else {
        panelHeading
                .text("Uh oh! Your submission didn't pass the tests!");
    }

    if (resultMessage.tests.length > 0) {
        for (i = 0; i < resultMessage.tests.length; i++) {
            showIndividualTestResult(resultMessage, i);
        }
    } else {
        $("#panel-body").text("No tests were found.");
    }
}

function showIndividualTestResult(resultMessage, i) {
    var res = resultMessage.tests[i];
    //The name field is formatted like below,
    //TestClass testMethod
    var names = res.name.split(" ");
    var className = names[0];
    var testName = names[1];
    var errorMessage = res.errorMessage;
    var backtrace = res.backtrace;
    var testId = "test" + i;
    var traceId = "backtrace" + i;

    var test = $("#panel-body").append(
            $("
")
            .attr("id", testId));

    test.append($("
")
            .text(testName + " (" + className + ")"));

    passedDiv = test.append($("
"));
    if (res.passed) {
        passedDiv.text("Passed");
    } else {
        passedDiv.text("Failed");
    }

    if (errorMessage) {
        test.append($("
")
                .text("Error message :" + errorMessage));
    }

    if (backtrace.length > 0) {
        test.append($("
"));
        var trace = test.append(
                $("
")
                .attr("id", traceId)
                .text("Stack trace: "));

        for (j = 0; j < backtrace.length; j++) {
            trace.append(
                    $("
")
                    .text(backtrace[j]));
        }
    }

    //If this isn't the last test result, add some space
    //before the next one
    if (i !== resultMessage.tests.length - 1) {
        test.append(
                $("
"));
        test.append(
                $("
"));
    }
}
<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');
var actionUtil = require('sails/lib/hooks/blueprints/actionUtil');

/**
 * Policy to set necessary update data to body. Note that this policy will also remove some body items.
 *
 * @param   {Request}   request     Request object
 * @param   {Response}  response    Response object
 * @param   {Function}  next        Callback function
 */
module.exports = function activeNodeData(request, response, next) {
  sails.log.verbose(__filename + ':' + __line + ' [Policy.activeNodeData() called]');

  sails.config.kong_admin_url = request.headers['kong-admin-url'] || sails.config.kong_admin_url

  var c = actionUtil.parseCriteria(request)

  if(c.hasOwnProperty('or')){
    c['and'] = [{node_id : sails.config.kong_admin_url}]
  }else{
    c['node_id'] = sails.config.kong_admin_url
  }

  console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
  console.log(c)

  request.query.where = JSON.stringify(c)

  console.log(request.query)

  return  next()

};
<commit_msg>Fixes query issue<commit_after>'use strict';

var _ = require('lodash');
var actionUtil = require('sails/lib/hooks/blueprints/actionUtil');

/**
 * Policy to set necessary update data to body. Note that this policy will also remove some body items.
 *
 * @param   {Request}   request     Request object
 * @param   {Response}  response    Response object
 * @param   {Function}  next        Callback function
 */
module.exports = function activeNodeData(request, response, next) {
  sails.log.verbose(__filename + ':' + __line + ' [Policy.activeNodeData() called]');

  sails.config.kong_admin_url = request.headers['kong-admin-url'] || sails.config.kong_admin_url

  var c = actionUtil.parseCriteria(request)

  if(c.hasOwnProperty('or')){
    c['and'] = [{node_id : sails.config.kong_admin_url}]
  }else{
    c['node_id'] = sails.config.kong_admin_url
  }

  request.query.where = JSON.stringify(c)

  console.log(request.query)

  return  next()

};
<|endoftext|>


<commit_before>module.exports = function (r) {
    const path = require('path');
    const dbExec = require('./run');
    const db = require('./db')(r);
    const model = require('./model')(r);
    const getSingle = require('./get-single');

    return {
        get: get,
        create: create
    };

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

    function* get(projectID, directoryID) {
        if (directoryID == "top") {
            return topLevelDir(projectID);
        } else {
            return directoryByID(directoryID);
        }
    }

    function topLevelDir(projectID) {
        let rql = r.table('projects').getAll(projectID).
            eqJoin('name', r.table('datadirs'), {index: 'name'}).zip().
            eqJoin('id', r.table('project2datadir'), {index: 'datadir_id'}).zip().
            filter({'project_id': projectID}).
            merge(function (ddir) {
                return {
                    'files': r.table('datadir2datafile').
                        getAll(ddir('datadir_id'), {index: 'datadir_id'}).
                        eqJoin('datafile_id', r.table('datafiles')).
                        zip().
                        filter({current: true}).
                        coerceTo('array'),
                    'directories': r.table('datadirs').getAll(ddir('datadir_id'), {index: 'parent'}).coerceTo('array')
                }
            });
        return dbExec(rql).then(results => toDir(results[0]));
    }

    function directoryByID(directoryID) {
        let rql = r.table('project2datadir').getAll(directoryID, {index: 'datadir_id'}).
            eqJoin('datadir_id', r.table('datadirs')).
            zip().
            merge(function (ddir) {
                return {
                    'files': r.table('datadir2datafile').
                        getAll(ddir('datadir_id'), {index: 'datadir_id'}).
                        eqJoin('datafile_id', r.table('datafiles')).
                        zip().
                        filter({current: true}).
                        coerceTo('array'),
                    'directories': r.table('datadirs').getAll(ddir('datadir_id'), {index: 'parent'}).coerceTo('array')
                }
            });
        return dbExec(rql).then(results => toDir(results[0]));
    }

    function toDir(results) {
        let dir = {
            _type: 'directory',
            id: results.datadir_id,
            size: 0,
            name: path.basename(results.name),
            path: results.name,
            checksum: "",
            children: []
        };

        dir.children = results.files.map(f => {
            return {
                _type: 'file',
                size: f.size,
                name: f.name,
                mediatype: f.mediatype,
                checksum: f.checksum,
                id: f.id
            };
        });

        let childrenDirs = results.directories.map(d => {
            return {
                _type: 'directory',
                id: d.id,
                size: 0,
                name: path.basename(d.name),
                path: d.name,
                checksum: ""
            };
        });

        dir.children = dir.children.concat(childrenDirs);

        return dir;
    }

    // create will create a directory path. It will create all children in the path, skipping
    // any entries that exist. Starting paths can be specified in 3 different ways:
    // from_dir is an id => start creating directories starting from id
    // from_dir == '/' => start creating directories starting from project root
    // from_dir == /path/of/directories' => start creating directories from leaf (must be valid)
    function* create(projectID, projectName, dirArgs) {
        if (dirArgs.from_dir.startsWith('/')) {
            return yield createFromPath(projectID, projectName, dirArgs);
        } else {
            return yield createFromDirID(projectID, dirArgs);
        }
    }

    function* createFromDirID(projectID, dirArgs) {
        let startingDir = yield dirById(dirArgs.from_dir, projectID);
        if (!startingDir) {
            return {
                error: `directory id ${dirArgs.from_dir} not found`
            };
        }
        yield createDirs(projectID, startingDir, dirSegments(dirArgs.path));
        return {
            val: true
        };
    }

    function* dirByPath(projectID, dirPath) {
        let rql = r.table('datadirs').getAll(dirPath, {index: 'name'}).
            filter({project: projectID});
        let dirs = yield dbExec(rql);
        if (dirs.length) {
            return dirs[0];
        }
        return null;
    }

    function* dirById(dirID, projectID) {
        let dir = yield getSingle(r, 'datadirs', dirID);
        if (! dir) {
            return null;
        } else if (dir.project !== projectID) {
            return null;
        }
        return dir;
    }

    function* createFromPath(projectID, projectName, dirArgs) {
        let dirPath = dirArgs.from_dir === '/' ? projectName : projectName + dirArgs.from_dir;
        let startingDir = yield dirByPath(projectID, dirPath);
        if (!startingDir) {
            return {
                error: `invalid dir path ${dirArgs.from_dir}`
            }
        }

        yield createDirs(projectID, startingDir, dirSegments(dirArgs.path));
        return {
            val: []
        };
    }

    function dirSegments(from) {
        let cleaned = trimStartingSlashes(from);
        return cleaned.split('/');
    }

    function trimStartingSlashes(from) {
        while (from.charAt(0) === '/') {
            from = from.substr(1);
        }
        return from;
    }

    function* createDirs(projectID, startingDir, dirSegments) {
        let existing = true;
        let dirPath = startingDir.name;
        let dirEntry = startingDir;
        for (let pathEntry of dirSegments) {
            dirPath = dirPath + '/' + pathEntry;
            if (!existing) {
                // if we encountered an unknown dir then all dirs afterward are
                // unknown and can just be created.
                dirEntry = yield insertDir(projectID, dirEntry.id, dirEntry.owner, dirPath);
            } else {
                // Check if dir exists, if it does continue checking, if not
                // create it, set dirEntry to newly created (so we have a parent),
                // and set existing to false so that all subsequent loop iterations
                // will simply create the path.
                let newDirEntry = yield dirByPath(projectID, dirPath);
                if (!newDirEntry) {
                    existing = false;
                    dirEntry = yield insertDir(projectID, dirEntry.id, dirEntry.owner, dirPath);
                } else {
                    dirEntry = newDirEntry;
                }
            }
        }
    }

    function* insertDir(projectID, parentID, owner, dirPath) {
        let dir = new model.Directory(dirPath, owner, projectID, parentID);
        let newDir = yield db.insert('datadirs', dir);
        let proj2dir = new model.Project2DataDir(projectID, newDir.id);
        yield db.insert('project2datadir', proj2dir);
        return newDir;
    }
};<commit_msg>Add full path for a file. This makes it easier when downloading files.<commit_after>module.exports = function (r) {
    const path = require('path');
    const dbExec = require('./run');
    const db = require('./db')(r);
    const model = require('./model')(r);
    const getSingle = require('./get-single');

    return {
        get: get,
        create: create
    };

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

    function* get(projectID, directoryID) {
        if (directoryID == "top") {
            return topLevelDir(projectID);
        } else {
            return directoryByID(directoryID);
        }
    }

    function topLevelDir(projectID) {
        let rql = r.table('projects').getAll(projectID).
            eqJoin('name', r.table('datadirs'), {index: 'name'}).zip().
            eqJoin('id', r.table('project2datadir'), {index: 'datadir_id'}).zip().
            filter({'project_id': projectID}).
            merge(function (ddir) {
                return {
                    'files': r.table('datadir2datafile').
                        getAll(ddir('datadir_id'), {index: 'datadir_id'}).
                        eqJoin('datafile_id', r.table('datafiles')).
                        zip().
                        filter({current: true}).
                        coerceTo('array'),
                    'directories': r.table('datadirs').getAll(ddir('datadir_id'), {index: 'parent'}).coerceTo('array')
                }
            });
        return dbExec(rql).then(results => toDir(results[0]));
    }

    function directoryByID(directoryID) {
        let rql = r.table('project2datadir').getAll(directoryID, {index: 'datadir_id'}).
            eqJoin('datadir_id', r.table('datadirs')).
            zip().
            merge(function (ddir) {
                return {
                    'files': r.table('datadir2datafile').
                        getAll(ddir('datadir_id'), {index: 'datadir_id'}).
                        eqJoin('datafile_id', r.table('datafiles')).
                        zip().
                        filter({current: true}).
                        coerceTo('array'),
                    'directories': r.table('datadirs').getAll(ddir('datadir_id'), {index: 'parent'}).coerceTo('array')
                }
            });
        return dbExec(rql).then(results => toDir(results[0]));
    }

    function toDir(results) {
        let dir = {
            _type: 'directory',
            id: results.datadir_id,
            size: 0,
            name: path.basename(results.name),
            path: results.name,
            checksum: "",
            children: []
        };

        dir.children = results.files.map(f => {
            return {
                _type: 'file',
                size: f.size,
                name: f.name,
                path: path.join(dir.path, f.name),
                mediatype: f.mediatype,
                checksum: f.checksum,
                id: f.id
            };
        });

        let childrenDirs = results.directories.map(d => {
            return {
                _type: 'directory',
                id: d.id,
                size: 0,
                name: path.basename(d.name),
                path: d.name,
                checksum: ""
            };
        });

        dir.children = dir.children.concat(childrenDirs);

        return dir;
    }

    // create will create a directory path. It will create all children in the path, skipping
    // any entries that exist. Starting paths can be specified in 3 different ways:
    // from_dir is an id => start creating directories starting from id
    // from_dir == '/' => start creating directories starting from project root
    // from_dir == /path/of/directories' => start creating directories from leaf (must be valid)
    function* create(projectID, projectName, dirArgs) {
        if (dirArgs.from_dir.startsWith('/')) {
            return yield createFromPath(projectID, projectName, dirArgs);
        } else {
            return yield createFromDirID(projectID, dirArgs);
        }
    }

    function* createFromDirID(projectID, dirArgs) {
        let startingDir = yield dirById(dirArgs.from_dir, projectID);
        if (!startingDir) {
            return {
                error: `directory id ${dirArgs.from_dir} not found`
            };
        }
        yield createDirs(projectID, startingDir, dirSegments(dirArgs.path));
        return {
            val: true
        };
    }

    function* dirByPath(projectID, dirPath) {
        let rql = r.table('datadirs').getAll(dirPath, {index: 'name'}).
            filter({project: projectID});
        let dirs = yield dbExec(rql);
        if (dirs.length) {
            return dirs[0];
        }
        return null;
    }

    function* dirById(dirID, projectID) {
        let dir = yield getSingle(r, 'datadirs', dirID);
        if (! dir) {
            return null;
        } else if (dir.project !== projectID) {
            return null;
        }
        return dir;
    }

    function* createFromPath(projectID, projectName, dirArgs) {
        let dirPath = dirArgs.from_dir === '/' ? projectName : projectName + dirArgs.from_dir;
        let startingDir = yield dirByPath(projectID, dirPath);
        if (!startingDir) {
            return {
                error: `invalid dir path ${dirArgs.from_dir}`
            }
        }

        yield createDirs(projectID, startingDir, dirSegments(dirArgs.path));
        return {
            val: []
        };
    }

    function dirSegments(from) {
        let cleaned = trimStartingSlashes(from);
        return cleaned.split('/');
    }

    function trimStartingSlashes(from) {
        while (from.charAt(0) === '/') {
            from = from.substr(1);
        }
        return from;
    }

    function* createDirs(projectID, startingDir, dirSegments) {
        let existing = true;
        let dirPath = startingDir.name;
        let dirEntry = startingDir;
        for (let pathEntry of dirSegments) {
            dirPath = dirPath + '/' + pathEntry;
            if (!existing) {
                // if we encountered an unknown dir then all dirs afterward are
                // unknown and can just be created.
                dirEntry = yield insertDir(projectID, dirEntry.id, dirEntry.owner, dirPath);
            } else {
                // Check if dir exists, if it does continue checking, if not
                // create it, set dirEntry to newly created (so we have a parent),
                // and set existing to false so that all subsequent loop iterations
                // will simply create the path.
                let newDirEntry = yield dirByPath(projectID, dirPath);
                if (!newDirEntry) {
                    existing = false;
                    dirEntry = yield insertDir(projectID, dirEntry.id, dirEntry.owner, dirPath);
                } else {
                    dirEntry = newDirEntry;
                }
            }
        }
    }

    function* insertDir(projectID, parentID, owner, dirPath) {
        let dir = new model.Directory(dirPath, owner, projectID, parentID);
        let newDir = yield db.insert('datadirs', dir);
        let proj2dir = new model.Project2DataDir(projectID, newDir.id);
        yield db.insert('project2datadir', proj2dir);
        return newDir;
    }
};<|endoftext|>


<commit_before>import utils from '../../utils'
import Ajv from 'ajv'
const ajv = new Ajv({ allErrors: true })
ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-06.json'))
ajv.addSchema(require('./schemas/common_definitions.json'))
const Issue = utils.issues.Issue

/**
 * JSON
 *
 * Takes a JSON file as a string and a callback
 * as arguments. And callsback with any errors
 * it finds while validating against the BIDS
 * specification.
 */
export default function(file, jsonContentsDict, callback) {
  // primary flow --------------------------------------------------------------------
  let issues = []
  const potentialSidecars = utils.files.potentialLocations(file.relativePath)
  const mergedDictionary = utils.files.generateMergedSidecarDict(
    potentialSidecars,
    jsonContentsDict,
  )
  if (mergedDictionary) {
    issues = issues.concat(checkUnits(file, mergedDictionary))
    issues = issues.concat(compareSidecarProperties(file, mergedDictionary))
  }
  callback(issues, mergedDictionary)
}

// individual checks ---------------------------------------------------------------

function checkUnits(file, sidecar) {
  let issues = []
  const schema = selectSchema(file)
  issues = issues.concat(validateSchema(file, sidecar, schema))

  issues = issues.concat(
    checkSidecarUnits(file, sidecar, { field: 'RepetitionTime', min: 100 }, 2),
  )

  issues = issues.concat(
    checkSidecarUnits(file, sidecar, { field: 'EchoTime', min: 1 }, 3),
  )
  issues = issues.concat(
    checkSidecarUnits(file, sidecar, { field: 'EchoTime1', min: 1 }, 4),
  )
  issues = issues.concat(
    checkSidecarUnits(file, sidecar, { field: 'EchoTime2', min: 1 }, 4),
  )
  issues = issues.concat(
    checkSidecarUnits(file, sidecar, { field: 'TotalReadoutTime', min: 10 }, 5),
  )

  return issues
}

const compareSidecarProperties = (file, sidecar) => {
  const issues = []

  // check that EffectiveEchoSpacing < TotalReadoutTime
  if (
    sidecar.hasOwnProperty('TotalReadoutTime') &&
    sidecar.hasOwnProperty('EffectiveEchoSpacing') &&
    sidecar['TotalReadoutTime'] < sidecar['EffectiveEchoSpacing']
  ) {
    issues.push(
      new Issue({
        file: file,
        code: 93,
      }),
    )
  }
  return issues
}

const selectSchema = file => {
  let schema = null
  if (file.name) {
    if (file.name.endsWith('participants.json')) {
      schema = require('./schemas/data_dictionary.json')
    } else if (
      file.name.endsWith('bold.json') ||
      file.name.endsWith('sbref.json')
    ) {
      schema = require('./schemas/bold.json')
    } else if (file.name.endsWith('asl.json')) {
      schema = require('./schemas/asl.json')
    } else if (file.name.endsWith('pet.json')) {
      schema = require('./schemas/pet.json')
    } else if (file.relativePath === '/dataset_description.json') {
      schema = require('./schemas/dataset_description.json')
    } else if (file.name.endsWith('meg.json')) {
      schema = require('./schemas/meg.json')
    } else if (file.name.endsWith('ieeg.json')) {
      schema = require('./schemas/ieeg.json')
    } else if (file.name.endsWith('eeg.json')) {
      schema = require('./schemas/eeg.json')
    } else if (
      file.relativePath.includes('/meg/') &&
      file.name.endsWith('coordsystem.json')
    ) {
      schema = require('./schemas/coordsystem_meg.json')
    } else if (
      file.relativePath.includes('/ieeg/') &&
      file.name.endsWith('coordsystem.json')
    ) {
      schema = require('./schemas/coordsystem_ieeg.json')
    } else if (
      file.relativePath.includes('/eeg/') &&
      file.name.endsWith('coordsystem.json')
    ) {
      schema = require('./schemas/coordsystem_eeg.json')
    } else if (file.name.endsWith('genetic_info.json')) {
      schema = require('./schemas/genetic_info.json')
    } else if (
        file.name.endsWith('physio.json') ||
        file.name.endsWith('stim.json')
    ) {
      schema = require('./schemas/physio.json')
    } else if (file.name.endsWith('events.json')) {
      schema = require('./schemas/events.json')
    }
  }
  return schema
}

const validateSchema = (file, sidecar, schema) => {
  const issues = []
  if (schema) {
    const validate = ajv.compile(schema)
    const valid = validate(sidecar)
    if (!valid) {
      validate.errors.map(error =>
        issues.push(
          new Issue({
            file: file,
            code: 55,
            evidence: error.dataPath + ' ' + error.message,
          }),
        ),
      )
    }
  }
  return issues
}

const checkSidecarUnits = (file, sidecar, fieldObj, errCode) => {
  const issues = []
  const field = fieldObj.field
  const min = fieldObj.min
  if (sidecar.hasOwnProperty(field) && sidecar[field] > min) {
    issues.push(
      new Issue({
        code: errCode,
        file: file,
      }),
    )
  }
  return issues
}
<commit_msg>Add blood schema to json.js<commit_after>import utils from '../../utils'
import Ajv from 'ajv'
const ajv = new Ajv({ allErrors: true })
ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-06.json'))
ajv.addSchema(require('./schemas/common_definitions.json'))
const Issue = utils.issues.Issue

/**
 * JSON
 *
 * Takes a JSON file as a string and a callback
 * as arguments. And callsback with any errors
 * it finds while validating against the BIDS
 * specification.
 */
export default function(file, jsonContentsDict, callback) {
  // primary flow --------------------------------------------------------------------
  let issues = []
  const potentialSidecars = utils.files.potentialLocations(file.relativePath)
  const mergedDictionary = utils.files.generateMergedSidecarDict(
    potentialSidecars,
    jsonContentsDict,
  )
  if (mergedDictionary) {
    issues = issues.concat(checkUnits(file, mergedDictionary))
    issues = issues.concat(compareSidecarProperties(file, mergedDictionary))
  }
  callback(issues, mergedDictionary)
}

// individual checks ---------------------------------------------------------------

function checkUnits(file, sidecar) {
  let issues = []
  const schema = selectSchema(file)
  issues = issues.concat(validateSchema(file, sidecar, schema))

  issues = issues.concat(
    checkSidecarUnits(file, sidecar, { field: 'RepetitionTime', min: 100 }, 2),
  )

  issues = issues.concat(
    checkSidecarUnits(file, sidecar, { field: 'EchoTime', min: 1 }, 3),
  )
  issues = issues.concat(
    checkSidecarUnits(file, sidecar, { field: 'EchoTime1', min: 1 }, 4),
  )
  issues = issues.concat(
    checkSidecarUnits(file, sidecar, { field: 'EchoTime2', min: 1 }, 4),
  )
  issues = issues.concat(
    checkSidecarUnits(file, sidecar, { field: 'TotalReadoutTime', min: 10 }, 5),
  )

  return issues
}

const compareSidecarProperties = (file, sidecar) => {
  const issues = []

  // check that EffectiveEchoSpacing < TotalReadoutTime
  if (
    sidecar.hasOwnProperty('TotalReadoutTime') &&
    sidecar.hasOwnProperty('EffectiveEchoSpacing') &&
    sidecar['TotalReadoutTime'] < sidecar['EffectiveEchoSpacing']
  ) {
    issues.push(
      new Issue({
        file: file,
        code: 93,
      }),
    )
  }
  return issues
}

const selectSchema = file => {
  let schema = null
  if (file.name) {
    if (file.name.endsWith('participants.json')) {
      schema = require('./schemas/data_dictionary.json')
    } else if (
      file.name.endsWith('bold.json') ||
      file.name.endsWith('sbref.json')
    ) {
      schema = require('./schemas/bold.json')
    } else if (file.name.endsWith('asl.json')) {
      schema = require('./schemas/asl.json')
    } else if (file.name.endsWith('pet.json')) {
      schema = require('./schemas/pet.json')
    } else if (file.relativePath === '/dataset_description.json') {
      schema = require('./schemas/dataset_description.json')
    } else if (file.name.endsWith('meg.json')) {
      schema = require('./schemas/meg.json')
    } else if (file.name.endsWith('ieeg.json')) {
      schema = require('./schemas/ieeg.json')
    } else if (file.name.endsWith('eeg.json')) {
      schema = require('./schemas/eeg.json')
    } else if (
      file.relativePath.includes('/meg/') &&
      file.name.endsWith('coordsystem.json')
    ) {
      schema = require('./schemas/coordsystem_meg.json')
    } else if (
      file.relativePath.includes('/ieeg/') &&
      file.name.endsWith('coordsystem.json')
    ) {
      schema = require('./schemas/coordsystem_ieeg.json')
    } else if (
      file.relativePath.includes('/eeg/') &&
      file.name.endsWith('coordsystem.json')
    ) {
      schema = require('./schemas/coordsystem_eeg.json')
    } else if (
      file.relativePath.includes('/pet/') &&
      file.name.endsWith('blood.json')
    ) {
      schema = require('./schemas/pet_blood.json')
    } else if (file.name.endsWith('genetic_info.json')) {
      schema = require('./schemas/genetic_info.json')
    } else if (
        file.name.endsWith('physio.json') ||
        file.name.endsWith('stim.json')
    ) {
      schema = require('./schemas/physio.json')
    } else if (file.name.endsWith('events.json')) {
      schema = require('./schemas/events.json')
    }
  }
  return schema
}

const validateSchema = (file, sidecar, schema) => {
  const issues = []
  if (schema) {
    const validate = ajv.compile(schema)
    const valid = validate(sidecar)
    if (!valid) {
      validate.errors.map(error =>
        issues.push(
          new Issue({
            file: file,
            code: 55,
            evidence: error.dataPath + ' ' + error.message,
          }),
        ),
      )
    }
  }
  return issues
}

const checkSidecarUnits = (file, sidecar, fieldObj, errCode) => {
  const issues = []
  const field = fieldObj.field
  const min = fieldObj.min
  if (sidecar.hasOwnProperty(field) && sidecar[field] > min) {
    issues.push(
      new Issue({
        code: errCode,
        file: file,
      }),
    )
  }
  return issues
}
<|endoftext|>


<commit_before>$(function () {
    "use strict";
	//paths for local tests and server
	//var path='http://fs-moni.cloudapp.net:8080';
	var path='';

$(document).ready ( function(){
	var table = $('#table').DataTable();

		$.ajax({
            type: 'GET', // define the type of HTTP verb we want to use (POST for our form)
           // url: '/configuration/fs-node/conn-data', // the url where we want to POST
            url: path+'/configuration/fs-node/conn-data', // the url where we want to POST
            //url: 'http://10.5.50.249:8080/configuration/fs-node/conn-data',
			dataType: 'json', // what type of data do we expect back from the server
            contentType: "application/json",
            encode: true
        })
            // using the done promise callback
            .done(function (data) {
                // log data to the console so we can see
                //console.log("on success get connections json" + JSON.stringify(data));

					//table.clear().draw();
					if (data.payload.length > 0) {
						//var table = $('#table').DataTable();
						console.log("LENGTH:"+data.payload.length);
					    $("#tableRow").show();

                    $.each(data.payload, function (i, n) {
                         console.log("Sensor Index: " + i + ", Sensor Name: " + n.ip );

                        table.row.add([n.ip, n.port,'<button type="button" class="btn btn-danger remove">Delete</button>']).draw();

                    });
                }

               /*  $("#message").toggleClass('alert-info alert-success');
                $(jQuery.parseJSON(JSON.stringify(data))).each(function() {

                  //  console.log(this.ip + " - ---- -- " + this.port);
                    $('#table > tbody:last').append('
'+this.ip+'	' +
                        ''+this.port+'	' +
                        '<button type="button" class="btn btn-danger remove"' +
                        ' onclick ="delete_user($(this),\''+this.ip+'\')">Delete</button>
');
                }); */

            })
            // using the fail promise callback
            .fail(function(data) {
                // show any errors
                // best to remove for production
                console.log("on fail " + JSON.stringify(data));
				if(data.status===401){
					//alert(JSON.stringify(data));
					window.location = "index.html";
				}
            });

});

    //$(document).ready(function () {

        // process the form
        $('#eslConnForm').click(function (event) {
              // get the form data
            // there are many ways to get this data using jQuery (you can use the class or id also)
            var formData = {
                "ip": $('input[id=eslIPAddress]').val(),
                "port": parseInt($('input[id=eslPort]').val()),
                "password": $('input[id=eslPassword]').val()
            };

            console.log(JSON.stringify(formData));
            // process the form
            $.ajax({
                type: 'POST', // define the type of HTTP verb we want to use (POST for our form)

                url: path+'/configuration/fs-node/conn-data', // the url where we want to POST

               // url: '/configuration/fs-node/conn-data', // the url where we want to POST
                //url: 'http://10.5.50.249:8080/configuration/fs-node/conn-data', // the url where we want to POST
               	data: JSON.stringify(formData), // our data object
                dataType: 'json', // what type of data do we expect back from the server
                contentType: "application/json",
                encode: true
            })
                // using the done promise callback
                .done(function (data) {
                    // log data to the console so we can see
                    console.log("on success " + JSON.stringify(data));
                    // here we will handle errors and validation messages
                    if(data.status===200){
                        //this removes a class name
                        //$(".form-horizontal").remove();
                        //this replace text in a  class
                        $( ".inputRes" ).replaceWith( data.message);
                        //this changes the class
                        $("#message").toggleClass('alert-info alert-success');
                      //  $('#table > tbody:last').append('
'+formData.ip+'	'+formData.port+'	<button type="button" class="btn btn-danger remove" onclick ="delete_user($(this),\''+formData.ip+'\')">Delete</button>
');

						if($('#tableRow').css('display') == 'none') {
						var table = $('#table').DataTable();
						 $("#tableRow").show();
					    //table.clear().draw();
						  table.row.add([formData.ip, formData.port,'<button type="button"  class="btn btn-danger remove">Delete</button>']).draw();

						}
                    } else if(data.status===400){
                        //alert(data.message);
                        //this removes a class name
                        //$(".form-horizontal").remove();
                        //this replace text in a  class
                        $( ".inputRes" ).replaceWith( data.message);
                        //this changes the class
                        $("#message").toggleClass('alert-info alert-danger');

                    }

                })
                // using the fail promise callback
                .fail(function(data) {
                   // alert(data.message);
					// show any errors
                    // best to remove for production
                    console.log("on fail " + JSON.stringify(data));
                    $( ".inputRes" ).replaceWith( data.message );
                    $("#message").toggleClass('alert-info alert-danger');
					if(data.status===401){
					//alert(JSON.stringify(data));
					window.location = "index.html";
					}
                });

            // stop the form from submitting the normal way and refreshing the page
            event.preventDefault();
        });

   // });

$('#table tbody').on( 'click', 'button', function() {
   // alert("The paragraph was tbody.");
	var table = $('#table').DataTable();
	//get the ip to delete
	var data = table.row( $(this).parents('tr') ).data();
       // alert( data[0]);
	table.row( $(this).parents('tr') ).remove().draw();
	var info = table.page.info();
	var count = info.recordsTotal;
	if(count===0) {
		$("#tableRow").hide();
		delete_user(data[0])
	}
	//alert(info);
	//number of rows
	//alert(count);

} );

function delete_user(ip)
{

	console.log("TABLE::")
    var formData = {
        "ip": ip
    };
    $.ajax({
        type: 'DELETE', // define the type of HTTP verb we want to use (POST for our form)
        //url: '/configuration/fs-node/conn-data', // the url where we want to POST
        url: path+'/configuration/fs-node/conn-data', // the url where we want to POST
        //url: 'http://10.5.50.249:8080/configuration/fs-node/conn-data', // the url where we want to POST
        data: JSON.stringify(formData), // our data object
        dataType: 'json', // what type of data do we expect back from the server
        contentType: "application/json",
        encode: true
    })
        // using the done promise callback
        .done(function (data) {
            // log data to the console so we can see
            console.log("on success delete " + JSON.stringify(data));
           // row.closest('tr').remove();

        })
        // using the fail promise callback
        .fail(function(data) {
            // show any errors
            // best to remove for production
            console.log("on fail " + JSON.stringify(data));
			if(data.status===401){
					//alert(JSON.stringify(data));
					window.location = "index.html";
			}
        });

}

});<commit_msg>upload plugin<commit_after>$(function () {
    "use strict";
	//paths for local tests and server
	//var path='http://fs-moni.cloudapp.net:8080';
	var path='';

$(document).ready ( function(){
	var table = $('#table').DataTable();

		$.ajax({
            type: 'GET', // define the type of HTTP verb we want to use (POST for our form)
           // url: '/configuration/fs-node/conn-data', // the url where we want to POST
            url: path+'/configuration/fs-node/conn-data', // the url where we want to POST
            //url: 'http://10.5.50.249:8080/configuration/fs-node/conn-data',
			dataType: 'json', // what type of data do we expect back from the server
            contentType: "application/json",
            encode: true
        })
            // using the done promise callback
            .done(function (data) {
                // log data to the console so we can see
                //console.log("on success get connections json" + JSON.stringify(data));
				 console.log("LENGTH:"+data.payload.length);
					   console.log("payload:"+data.payload);

					//table.clear().draw();
					if (data.payload.length > 0) {
						//var table = $('#table').DataTable();
						 $("#tableRow").show();

                    $.each(data.payload, function (i, n) {
                         console.log("Sensor Index: " + i + ", Sensor Name: " + n.ip );

                        table.row.add([n.ip, n.port,'<button type="button" class="btn btn-danger remove">Delete</button>']).draw();

                    });
                }

               /*  $("#message").toggleClass('alert-info alert-success');
                $(jQuery.parseJSON(JSON.stringify(data))).each(function() {

                  //  console.log(this.ip + " - ---- -- " + this.port);
                    $('#table > tbody:last').append('
'+this.ip+'	' +
                        ''+this.port+'	' +
                        '<button type="button" class="btn btn-danger remove"' +
                        ' onclick ="delete_user($(this),\''+this.ip+'\')">Delete</button>
');
                }); */

            })
            // using the fail promise callback
            .fail(function(data) {
                // show any errors
                // best to remove for production
                console.log("on fail " + JSON.stringify(data));
				if(data.status===401){
					//alert(JSON.stringify(data));
					window.location = "index.html";
				}
            });

});

    //$(document).ready(function () {

        // process the form
        $('#eslConnForm').click(function (event) {
              // get the form data
            // there are many ways to get this data using jQuery (you can use the class or id also)
            var formData = {
                "ip": $('input[id=eslIPAddress]').val(),
                "port": parseInt($('input[id=eslPort]').val()),
                "password": $('input[id=eslPassword]').val()
            };

            console.log(JSON.stringify(formData));
            // process the form
            $.ajax({
                type: 'POST', // define the type of HTTP verb we want to use (POST for our form)

                url: path+'/configuration/fs-node/conn-data', // the url where we want to POST

               // url: '/configuration/fs-node/conn-data', // the url where we want to POST
                //url: 'http://10.5.50.249:8080/configuration/fs-node/conn-data', // the url where we want to POST
               	data: JSON.stringify(formData), // our data object
                dataType: 'json', // what type of data do we expect back from the server
                contentType: "application/json",
                encode: true
            })
                // using the done promise callback
                .done(function (data) {
                    // log data to the console so we can see
                    console.log("on success " + JSON.stringify(data));
                    // here we will handle errors and validation messages
                    if(data.status===200){
                        //this removes a class name
                        //$(".form-horizontal").remove();
                        //this replace text in a  class
                        $( ".inputRes" ).replaceWith( data.message);
                        //this changes the class
                        $("#message").toggleClass('alert-info alert-success');
                      //  $('#table > tbody:last').append('
'+formData.ip+'	'+formData.port+'	<button type="button" class="btn btn-danger remove" onclick ="delete_user($(this),\''+formData.ip+'\')">Delete</button>
');

						if($('#tableRow').css('display') == 'none') {
						var table = $('#table').DataTable();
						 $("#tableRow").show();
					    //table.clear().draw();
						  table.row.add([formData.ip, formData.port,'<button type="button"  class="btn btn-danger remove">Delete</button>']).draw();

						}
                    } else if(data.status===400){
                        //alert(data.message);
                        //this removes a class name
                        //$(".form-horizontal").remove();
                        //this replace text in a  class
                        $( ".inputRes" ).replaceWith( data.message);
                        //this changes the class
                        $("#message").toggleClass('alert-info alert-danger');

                    }

                })
                // using the fail promise callback
                .fail(function(data) {
                   // alert(data.message);
					// show any errors
                    // best to remove for production
                    console.log("on fail " + JSON.stringify(data));
                    $( ".inputRes" ).replaceWith( data.message );
                    $("#message").toggleClass('alert-info alert-danger');
					if(data.status===401){
					//alert(JSON.stringify(data));
					window.location = "index.html";
					}
                });

            // stop the form from submitting the normal way and refreshing the page
            event.preventDefault();
        });

   // });

$('#table tbody').on( 'click', 'button', function() {
   // alert("The paragraph was tbody.");
	var table = $('#table').DataTable();
	//get the ip to delete
	var data = table.row( $(this).parents('tr') ).data();
       // alert( data[0]);
	table.row( $(this).parents('tr') ).remove().draw();
	var info = table.page.info();
	var count = info.recordsTotal;
	if(count===0) {
		$("#tableRow").hide();
		delete_user(data[0])
	}
	//alert(info);
	//number of rows
	//alert(count);

} );

function delete_user(ip)
{

	console.log("TABLE::")
    var formData = {
        "ip": ip
    };
    $.ajax({
        type: 'DELETE', // define the type of HTTP verb we want to use (POST for our form)
        //url: '/configuration/fs-node/conn-data', // the url where we want to POST
        url: path+'/configuration/fs-node/conn-data', // the url where we want to POST
        //url: 'http://10.5.50.249:8080/configuration/fs-node/conn-data', // the url where we want to POST
        data: JSON.stringify(formData), // our data object
        dataType: 'json', // what type of data do we expect back from the server
        contentType: "application/json",
        encode: true
    })
        // using the done promise callback
        .done(function (data) {
            // log data to the console so we can see
            console.log("on success delete " + JSON.stringify(data));
           // row.closest('tr').remove();

        })
        // using the fail promise callback
        .fail(function(data) {
            // show any errors
            // best to remove for production
            console.log("on fail " + JSON.stringify(data));
			if(data.status===401){
					//alert(JSON.stringify(data));
					window.location = "index.html";
			}
        });

}

});<|endoftext|>


<commit_before>var dgram = require('dgram')
var util = require('util')

function Client (options) {
  var queue = {}, client, id

  var defaults = {
    host: '127.0.0.1',
    port: 2003,
    type: 'udp4',
    maxPacketSize: 4096,
    prefix: '',
    suffix: '',
    verbose: false,
    interval: 5000,
    callback: null
  }

  function init () {
    options = util._extend(defaults, options)

    createClient()

    id = setInterval(send, options.interval)

    return {
      add: add,
      put: put,
      close: close,
      options: options
    }
  }

  function createClient () {
    client = dgram.createSocket(options.type)

    client.on('close', function () {
      log('UDP socket closed')
    })

    client.on('error', function (err) {
      log('UDP socket error: '+ err)
    })

    log('Creating new Graphite UDP client')
  }

  function close () {
    client.close()
    clearInterval(id)
  }

  function put (name, value) {
    add(name, value, true)
  }

  function add (name, value, replace) {
    if (!name || isNaN(parseFloat(value)) || value === Infinity)
      return log('Skipping invalid name/value: '+ name +' '+ value)

    if (options.prefix)
      name = options.prefix +'.'+ name

    if (options.suffix)
      name = name +'.'+ options.suffix

    if (queue[name] === undefined || replace)
      queue[name] = { value: value }
    else
      queue[name].value += value

    queue[name].timestamp = String(Date.now()).substr(0, 10)

    log('Adding metric to queue: '+ name +' '+ value)
  }

  function sendPacket (metrics, count) {
    log('Sending '+ count +' metrics to '+ options.host +':'+ options.port)

    client.send(metrics, 0, metrics.length, options.port,
    options.host, function (err) {
      if (err)
        return log('Error sending metrics: '+ err)

      log('Metrics sent:'+ metrics.toString().replace(/^|\n/g, '\n\t'))

      if (options.callback)
        options.callback(err, metrics.toString())
    })
  }

  function send () {
    if (Object.keys(queue).length === 0)
      return // log('Queue is empty. Nothing to send')

    var buffer = '', count = 0, line

    for (var name in queue) {
      line = name +' '+ queue[name].value +' '+ queue[name].timestamp +'\n'

      if (line.length + buffer.length > options.maxPacketSize
      && buffer.length > 0) {
        sendPacket(new Buffer(buffer), count)
        buffer = line
        count = 1
      }
      else {
        buffer += line
        count += 1
      }
    }

    if (buffer.length > 0)
      sendPacket(new Buffer(buffer), count)

    queue = {}
  }

  function log (line) {
    if (options.verbose)
      console.log('[graphite-udp]', line)
  }

  return init()
}

module.exports = {
  createClient: function (options) {
    return new Client(options)
  }
}
<commit_msg>removing util._extend (deprecated)<commit_after>var dgram = require('dgram')

function Client (options) {
  var queue = {}, client, id

  var defaults = {
    host: '127.0.0.1',
    port: 2003,
    type: 'udp4',
    maxPacketSize: 4096,
    prefix: '',
    suffix: '',
    verbose: false,
    interval: 5000,
    callback: null
  }

  function init () {
    options = extend(defaults, options)

    createClient()

    id = setInterval(send, options.interval)

    return {
      add: add,
      put: put,
      close: close,
      options: options
    }
  }

  function createClient () {
    client = dgram.createSocket(options.type)

    client.on('close', function () {
      log('UDP socket closed')
    })

    client.on('error', function (err) {
      log('UDP socket error: '+ err)
    })

    log('Creating new Graphite UDP client')
  }

  function close () {
    client.close()
    clearInterval(id)
  }

  function put (name, value) {
    add(name, value, true)
  }

  function add (name, value, replace) {
    if (!name || isNaN(parseFloat(value)) || value === Infinity)
      return log('Skipping invalid name/value: '+ name +' '+ value)

    if (options.prefix)
      name = options.prefix +'.'+ name

    if (options.suffix)
      name = name +'.'+ options.suffix

    if (queue[name] === undefined || replace)
      queue[name] = { value: value }
    else
      queue[name].value += value

    queue[name].timestamp = String(Date.now()).substr(0, 10)

    log('Adding metric to queue: '+ name +' '+ value)
  }

  function sendPacket (metrics, count) {
    log('Sending '+ count +' metrics to '+ options.host +':'+ options.port)

    client.send(metrics, 0, metrics.length, options.port,
    options.host, function (err) {
      if (err)
        return log('Error sending metrics: '+ err)

      log('Metrics sent:'+ metrics.toString().replace(/^|\n/g, '\n\t'))

      if (options.callback)
        options.callback(err, metrics.toString())
    })
  }

  function send () {
    if (Object.keys(queue).length === 0)
      return // log('Queue is empty. Nothing to send')

    var buffer = '', count = 0, line

    for (var name in queue) {
      line = name +' '+ queue[name].value +' '+ queue[name].timestamp +'\n'

      if (line.length + buffer.length > options.maxPacketSize
      && buffer.length > 0) {
        sendPacket(new Buffer(buffer), count)
        buffer = line
        count = 1
      }
      else {
        buffer += line
        count += 1
      }
    }

    if (buffer.length > 0)
      sendPacket(new Buffer(buffer), count)

    queue = {}
  }

  function log (line) {
    if (options.verbose)
      console.log('[graphite-udp]', line)
  }

  function extend (origin, add) {
    for (var key in add)
      origin[key] = add[key]
    return origin
  }

  return init()
}

module.exports = {
  createClient: function (options) {
    return new Client(options)
  }
}
<|endoftext|>