<commit_before>(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var jacks = (function() {
	var plugins = {};
	var globalUses = [];
	var exports = {};
	var serializers = require("./serializers");
	var parsers = require("./parsers");
	var listeners = {};

	function getXHR() {
	  if (window.XMLHttpRequest) {
	    return new XMLHttpRequest;
	  } else {
	    try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch(e) {}
	    try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(e) {}
	    try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(e) {}
	    try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch(e) {}
	  }
	  return false;
	};
	/**
	 * Serialize body with chosen type
	 * @param {Object} body
	 * @return String
	 */
	function serialize(body, type) {
		var serializer = serializers[type];
		if (serializer == null) {
			throw "No serializer found for type " + type;
		}
		return serializer(body);
	}

	/**
	 * ProcessUrl with query parameters
	 * @param {String} url
	 * @return String
	 */
	function processUrl(url, query) {
		var token,
			actualUrl = url;
		if (actualUrl.indexOf("?") > 0) {
			token = "&";
		} else {
			token = "?";
		}
		if (query != null) {
			for (param in query) {
				actualUrl += token + param + "=" + encodeURIComponent(query[param]);
				token = "&";
			}
		}
		return actualUrl;
	}

	/**
	 * Object JacksResponse
	 */
	function JacksResponse(xhr, jacksRequest) {
		this.url = jacksRequest.url;
		this.status = xhr.status;
		this.statusText = xhr.statusText;
		this.responseText = xhr.responseText;
		var contentType = xhr.getResponseHeader("Content-Type");
		if (parsers[contentType]){
			this.response = parsers[contentType](xhr.responseText);
		} else {
			xhr.response = xhr.responseText;
		}
		this.headers = xhr.getAllResponseHeaders();
	}

	function JacksError(xhr, jacksRequest) {
		this.type = xhr.type;
		this.url = jacksRequest.url;
	}

	/**
	 * Request object with all request elements
	 * @param {String} requestType
	 * @param {String} url
	 */
	function JacksRequest(requestType, url) {
		/** timeout handler */
		var timeoutHandler = null;
		/** Request headers */
		var headers = {};
		/** Body, only for post/put */
		var body = null;
		/** Query parameters, to append on url */
		var query = null;
		/**
		 * request type
		 */
		this.requestType = requestType;
		/**
		 * url
		 */
		this.url = url;
		var that = this;

		/**
		 * Add one or more headers. To add one, send param and value. To add more, send an key/value object.
		 * @param name - name of the header or key/value object
		 * @param value - value of the header. Ignored if name is an object
		 * @returns this or the headers if first param is undefined
		 */
		this.header = function(name, value) {
			if (name === undefined) {
				return headers;
			}
			headers[name] = value;
			return this;
		};

		/**
		 * Add one or more body. To add one, send param and value. To add more, send an key/value object.
		 * @param name - name of the body or key/value object
		 * @param value - value of the body. Ignored if name is an object
		 * @returns this or the body if first param is undefined
		 */
		this.body = function(value) {
			if (name === undefined) {
				return body;
			}
			body = value;
			return this;
		};

		/**
		 * Add one or more query parameters. To add one, send param and value. To add more, send an key/value object.
		 * @param name - name of the query parameter or key/value object
		 * @param value - value of the query parameter. Ignored if name is an object
		 * @returns this or the query parameters if first param is undefined
		 */
		this.query = function(name, value) {
			if (name === undefined) {
				return query;
			}
			query = query || {};
			if (typeof name === "string") {
				query[name] = value;
				var queryTemp = {};
				queryTemp[name] = value;
				that.url = processUrl(that.url, queryTemp);
			} else if (typeof name === "object") {
				for (var attr in name) {
					query[attr] = name[attr];
					that.url = processUrl(that.url, name);
				}
			}
			return this;
		};

		/**
		 * executes a plugin
		 * @param {Function} pluginFn
		 */
		this.use = function(pluginNameOrFn) {
			if (typeof pluginNameOrFn == "string") {
				if (plugins[pluginNameOrFn] == null) {
					throw "Plugin " + globalUses[i] + " not found";
				}
				plugins[pluginNameOrFn](this);
			} else if (typeof pluginNameOrFn === "function") {
				pluginNameOrFn(this);
			}
			return this;
		};

		/**
		 * Sends the request
		 * @param {Function} callback
		 * @param {Function} error
		 */
		this.send = function(callback, error) {
			var xhr = getXHR();
			this.xhr = xhr;
	  		// state change
			xhr.onreadystatechange = function(){
				if (xhr.readyState != 4) return;

				stopTimeout();
				// IE9 bug fix (status read if request aborted results in error...)
				var status;
   				try { status = xhr.status } catch(e) { status = 0; }

   				if (status === 0) {
   					// if request is aborted or timed out, then we launch error.
   					if (that.aborted) {
   						return error({type:"abort", url: that.url}, that);
   					} else if (that.timedout) {
   						return error({type:"timeout", url: that.url}, that);
   					}
   					// else error, ignore statechange
   					return;
   				}
				callback(new JacksResponse(xhr, jacksRequest));
			};
			xhr.onerror = function(e) {
				error(new JacksError(e, that), that);
			}
			xhr.open(requestType, that.url);
			emit("open");
			for (var header in headers) {
				xhr.setRequestHeader(header, headers[header]);
			}

			var bodySerialized = null;
			if (body != null && typeof body === "object") {
				bodySerialized = serialize(body, headers["Content-Type"])
			} else {
				bodySerialized = body;
			}

			xhr.send(bodySerialized);
			emit("send");
			return this;
		};

		/**
		 * Abord a request
		 */
		this.abort = function() {
			this.aborted = true;
			emit("abort");
			this.xhr.abort();
			return this;
		};

		/**
		 * Define a timeout on the request
		 */
		this.timeout = function(delay) {
			setTimeout(function() {
				emit("timeout");
				this.timedout = true;
				this.xhr.abort();
			}, delay);
			return this;
		};

		/**
		 * Register to an event on the request.
		 */
		this.on = function(eventName, fn) {
			listeners[eventName] = listeners[eventName] || [];
			listeners[eventName].push(fn);
			return this;
		};

		// Exec plugins
		for (var i = 0 ; i < globalUses.length ; i++) {
			this.use(globalUses[i]);
		}

		/**
		 * Emit event
		 * @param {String} eventName
		 * @param {Object} data
		 */
		function emit(eventName, data) {
			var eventListeners = listeners[eventName];
			if (eventListeners) {
				for (var i = 0 ; i < eventListeners.length ; i++) {
					eventListeners[i](data);
				}
			}
		}

		/**
		 * stops the current timeout if exists
		 */
		function stopTimeout() {
			if (timeoutHandler) {
				clearTimeout(timeoutHandler);
				timeoutHandler = null;
			}
		}
	}

	exports.get = function(url) {
		return new JacksRequest("GET", url);
	}
	exports.post = function(url) {
		return new JacksRequest("POST", url);
	}
	exports.put = function(url) {
		return new JacksRequest("PUT", url);
	}
	exports.options = function(url) {
		return new JacksRequest("OPTIONS", url);
	}
	exports.head = function(url) {
		return new JacksRequest("HEAD", url);
	}
	exports["delete"] = function(url) {
		return new JacksRequest("DELETE", url);
	}
	exports.plugin = function(name, pluginObject) {
		plugins[name] = pluginObject;
		return this;
	}
	exports.use = function(pluginNameOrFn) {
		globalUses.push(pluginNameOrFn);
		return this;
	}
	exports.parser = function(type, parserFn) {
		parsers[type] = parserFn;
		return this;
	}
	exports.serializer = function(type, serializerFn) {
		serializers[type] = serializerFn;
		return this;
	}
	return exports;
})();

window.jacks = jacks;
},{"./parsers":2,"./serializers":3}],2:[function(require,module,exports){
module.exports = {
	"application/json": function(data) {
		return JSON.parse(data);
	}
};
},{}],3:[function(require,module,exports){
module.exports = {
		"application/json": function(data) {
			return JSON.stringify(data);
		},
		"application/x-www-form-urlencoded": function(data) {
			var arr = [];
			for (var attr in data) {
				arr.push(encodeURIComponent(attr) + '=' + encodeURIComponent(data[attr]));
			}
			return arr.join('&');
		}
	};

},{}]},{},[1]);
<commit_msg>Bug when creating JacksResponse<commit_after>(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var jacks = (function() {
	var plugins = {};
	var globalUses = [];
	var exports = {};
	var serializers = require("./serializers");
	var parsers = require("./parsers");
	var listeners = {};

	function getXHR() {
	  if (window.XMLHttpRequest) {
	    return new XMLHttpRequest();
	  } else {
	    try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch(e) {}
	    try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(e) {}
	    try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(e) {}
	    try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch(e) {}
	  }
	  return false;
	}
	/**
	 * Serialize body with chosen type
	 * @param {Object} body
	 * @return String
	 */
	function serialize(body, type) {
		var serializer = serializers[type];
		if (serializer == null) {
			throw "No serializer found for type " + type;
		}
		return serializer(body);
	}

	/**
	 * ProcessUrl with query parameters
	 * @param {String} url
	 * @return String
	 */
	function processUrl(url, query) {
		var token,
			actualUrl = url;
		if (actualUrl.indexOf("?") > 0) {
			token = "&";
		} else {
			token = "?";
		}
		if (query != null) {
			for (param in query) {
				actualUrl += token + param + "=" + encodeURIComponent(query[param]);
				token = "&";
			}
		}
		return actualUrl;
	}

	/**
	 * Object JacksResponse
	 */
	function JacksResponse(xhr, jacksRequest) {
		this.url = jacksRequest.url;
		this.status = xhr.status;
		this.statusText = xhr.statusText;
		this.responseText = xhr.responseText;
		var contentType = xhr.getResponseHeader("Content-Type");
		if (parsers[contentType]){
			this.response = parsers[contentType](xhr.responseText);
		} else {
			xhr.response = xhr.responseText;
		}
		this.headers = xhr.getAllResponseHeaders();
	}

	function JacksError(xhr, jacksRequest) {
		this.type = xhr.type;
		this.url = jacksRequest.url;
	}

	/**
	 * Request object with all request elements
	 * @param {String} requestType
	 * @param {String} url
	 */
	function JacksRequest(requestType, url) {
		/** timeout handler */
		var timeoutHandler = null;
		/** Request headers */
		var headers = {};
		/** Body, only for post/put */
		var body = null;
		/** Query parameters, to append on url */
		var query = null;
		/**
		 * request type
		 */
		this.requestType = requestType;
		/**
		 * url
		 */
		this.url = url;
		var that = this;

		/**
		 * Add one or more headers. To add one, send param and value. To add more, send an key/value object.
		 * @param name - name of the header or key/value object
		 * @param value - value of the header. Ignored if name is an object
		 * @returns this or the headers if first param is undefined
		 */
		this.header = function(name, value) {
			if (name === undefined) {
				return headers;
			}
			headers[name] = value;
			return this;
		};

		/**
		 * Add one or more body. To add one, send param and value. To add more, send an key/value object.
		 * @param name - name of the body or key/value object
		 * @param value - value of the body. Ignored if name is an object
		 * @returns this or the body if first param is undefined
		 */
		this.body = function(value) {
			if (name === undefined) {
				return body;
			}
			body = value;
			return this;
		};

		/**
		 * Add one or more query parameters. To add one, send param and value. To add more, send an key/value object.
		 * @param name - name of the query parameter or key/value object
		 * @param value - value of the query parameter. Ignored if name is an object
		 * @returns this or the query parameters if first param is undefined
		 */
		this.query = function(name, value) {
			if (name === undefined) {
				return query;
			}
			query = query || {};
			if (typeof name === "string") {
				query[name] = value;
				var queryTemp = {};
				queryTemp[name] = value;
				that.url = processUrl(that.url, queryTemp);
			} else if (typeof name === "object") {
				for (var attr in name) {
					query[attr] = name[attr];
					that.url = processUrl(that.url, name);
				}
			}
			return this;
		};

		/**
		 * executes a plugin
		 * @param {Function} pluginFn
		 */
		this.use = function(pluginNameOrFn) {
			if (typeof pluginNameOrFn == "string") {
				if (plugins[pluginNameOrFn] == null) {
					throw "Plugin " + globalUses[i] + " not found";
				}
				plugins[pluginNameOrFn](this);
			} else if (typeof pluginNameOrFn === "function") {
				pluginNameOrFn(this);
			}
			return this;
		};

		/**
		 * Sends the request
		 * @param {Function} callback
		 * @param {Function} error
		 */
		this.send = function(callback, error) {
			var xhr = getXHR();
			this.xhr = xhr;
	  		// state change
			xhr.onreadystatechange = function(){
				if (xhr.readyState != 4) return;

				stopTimeout();
				// IE9 bug fix (status read if request aborted results in error...)
				var status;
   				try { status = xhr.status; } catch(e) { status = 0; }

   				if (status === 0) {
   					// if request is aborted or timed out, then we launch error.
   					if (that.aborted) {
   						return error({type:"abort", url: that.url}, that);
   					} else if (that.timedout) {
   						return error({type:"timeout", url: that.url}, that);
   					}
   					// else error, ignore statechange
   					return;
   				}
				callback(new JacksResponse(xhr, that));
			};
			xhr.onerror = function(e) {
				error(new JacksError(e, that), that);
			};
			xhr.open(requestType, that.url);
			emit("open");
			for (var header in headers) {
				xhr.setRequestHeader(header, headers[header]);
			}

			var bodySerialized = null;
			if (body != null && typeof body === "object") {
				bodySerialized = serialize(body, headers["Content-Type"]);
			} else {
				bodySerialized = body;
			}

			xhr.send(bodySerialized);
			emit("send");
			return this;
		};

		/**
		 * Abord a request
		 */
		this.abort = function() {
			this.aborted = true;
			emit("abort");
			this.xhr.abort();
			return this;
		};

		/**
		 * Define a timeout on the request
		 */
		this.timeout = function(delay) {
			setTimeout(function() {
				emit("timeout");
				this.timedout = true;
				this.xhr.abort();
			}, delay);
			return this;
		};

		/**
		 * Register to an event on the request.
		 */
		this.on = function(eventName, fn) {
			listeners[eventName] = listeners[eventName] || [];
			listeners[eventName].push(fn);
			return this;
		};

		// Exec plugins
		for (var i = 0 ; i < globalUses.length ; i++) {
			this.use(globalUses[i]);
		}

		/**
		 * Emit event
		 * @param {String} eventName
		 * @param {Object} data
		 */
		function emit(eventName, data) {
			var eventListeners = listeners[eventName];
			if (eventListeners) {
				for (var i = 0 ; i < eventListeners.length ; i++) {
					eventListeners[i](data);
				}
			}
		}

		/**
		 * stops the current timeout if exists
		 */
		function stopTimeout() {
			if (timeoutHandler) {
				clearTimeout(timeoutHandler);
				timeoutHandler = null;
			}
		}
	}

	exports.get = function(url) {
		return new JacksRequest("GET", url);
	};
	exports.post = function(url) {
		return new JacksRequest("POST", url);
	};
	exports.put = function(url) {
		return new JacksRequest("PUT", url);
	};
	exports.options = function(url) {
		return new JacksRequest("OPTIONS", url);
	};
	exports.head = function(url) {
		return new JacksRequest("HEAD", url);
	};
	exports["delete"] = function(url) {
		return new JacksRequest("DELETE", url);
	};
	exports.plugin = function(name, pluginObject) {
		plugins[name] = pluginObject;
		return this;
	};
	exports.use = function(pluginNameOrFn) {
		globalUses.push(pluginNameOrFn);
		return this;
	};
	exports.parser = function(type, parserFn) {
		parsers[type] = parserFn;
		return this;
	};
	exports.serializer = function(type, serializerFn) {
		serializers[type] = serializerFn;
		return this;
	};
	return exports;
})();

window.jacks = jacks;
},{"./parsers":2,"./serializers":3}],2:[function(require,module,exports){
module.exports = {
	"application/json": function(data) {
		return JSON.parse(data);
	}
};
},{}],3:[function(require,module,exports){
module.exports = {
		"application/json": function(data) {
			return JSON.stringify(data);
		},
		"application/x-www-form-urlencoded": function(data) {
			var arr = [];
			for (var attr in data) {
				arr.push(encodeURIComponent(attr) + '=' + encodeURIComponent(data[attr]));
			}
			return arr.join('&');
		}
	};

},{}]},{},[1]);
<|endoftext|>


<commit_before>angular.module('scharwerk')
.factory('stages', ['$http', function($http){
  var s = {
    graphs: {}
  };

  s.getStats = function() {
    return $http.get('/stats/tasks.json').success(function(data){
      angular.forEach(data, function(stage, key) {
        s.graphs[key] =
        [{
          label: 'Завершено',
          suffix: '%',
          value: 100 * stage.free / stage.total,
          color: '#FFC107',
          colorComplement: '#FFFFFF'
        }];
      });
    });
  };

  return s;
}])

<commit_msg>fix progress number<commit_after>angular.module('scharwerk')
.factory('stages', ['$http', function($http){
  var s = {
    graphs: {}
  };

  s.getStats = function() {
    return $http.get('/stats/tasks.json').success(function(data){
      angular.forEach(data, function(stage, key) {
        s.graphs[key] =
        [{
          label: 'Завершено',
          suffix: '%',
          value: Math.round(100 - 100 * stage.free / stage.total),
          color: '#FFC107',
          colorComplement: '#FFFFFF'
        }];
      });
    });
  };

  return s;
}])

<|endoftext|>


<commit_before>/*
   +----------------------------------------------------------------------+
   |                            HEP Random                                |
   |                       --- RandBreitWigner ---                        |
   |                            Module File                               |
   +----------------------------------------------------------------------+

   Module defining methods for shooting numbers according to the
   Breit-Wigner distribution algorithms (plain or mean^2).
   Default values are set: mean=1, gamma=.2, cut=1.
   Plain algorithm is used for shootArray() and fireArray().

   +----------------------------------------------------------------------+
   | C++                                                                  |
   +----------------------------------------------------------------------+

   Gabriele Cosmo - Created: 5th September 1995
                  - Added methods to shoot arrays: 28th July 1997
   J.Marraffino   - Added default arguments as attributes and
                    operator() with arguments: 16th Feb 1998
   M Fischler      - put and get to/from streams 12/10/04

   +----------------------------------------------------------------------+
   | JavaScript                                                           |
   +----------------------------------------------------------------------+

   F. Quinonez - Created 2015-10-30

*/

define( [
  '../BBT/Generation/Random/JamesRandom',
], function( JamesRandom ){
  "use strict";

  function RandBreitWigner( args ){
    this.fmean = args.mean || 1.0;
    this.fgamma = args.gamma || 0.2;
    this.fcut = args.cut || undefined;
    this.fengine = args.engine || Object.create( JamesRandom() );
  }

  RandBreitWigner.Shoot = function( args ){
    var smean = args.mean || 1.0;
    var sgamma = args.gamma || 0.2;
    var scut = args.cut || undefined;
    var sengine = args.engine || Object.create( JamesRandom() );

    if( sgamma == 0 ) return smean;

    var rval, displ;
    rval  = 2.0 * sengine.Flat() - 1.0;

    if( scut === undefined ){
      // Without cut
      displ = 0.5 * sgamma * Math.tan( rval * Math.Pi * 0.5 );
    } else {
      // With cut
      var val;
      val = Math.atan( 2.0 * scut / sgamma );
      displ = 0.5 * gamma * Math.tan( rval * rval );
    }
    return ( smean + displ );
  };

  RandBreitWigner.ShootArray = function( args ){
    var ssize = args.size || 1;
    // var svect = args.vect;

    var argsShoot = { mean: args.mean, gamma: args.gamma, cut: args.cut, engine: args.engine };

    for( var i = 0; i < ssize; ++i ){
      args.vect.push( RandBreitWigner.Shoot( argsShoot ) );
    }

  };

  // Tweak CLHEP C++ that used the RandFlat::shoot static method.
  // Now this distribution has its own Shoot static function.
  RandBreitWigner.ShootFlat = function( args ){
    var sa = args.a || 0;
    var sb = args.b || 1;
    var swidth = args.width || ( args.b - args.a );
    var sengine = args.engine || Object.create( JamesRandom() );
    return ( swidth * sengine.Flat() + sa );
  };

  RandBreitWigner.ShootM2 = function( args ){
    var sengine = args.engine || Object.create( JamesRandom() );
    var smean = args.mean || 1.0;
    var sgamma = args.gamma || 0.2;
    var scut = args.cut || undefined;

    var val, rval, displ;
    if( sgamma == 0.0 ) return smean;

    if( scut === undefined ){
      // Without cut
      val = Math.atan( -smean / sgamma );
      rval = RandBreitWigner.ShootFlat( {  a: val, b: Math.PI / 2, engine: sengine  } );
      displ = sgamma * Math.tan( rval );
      return Math.sqrt( Math.pow( smean, 2 ) + smean * displ );
    } else {
      // With cut
      var lower, upper, tmp;

      tmp = Math.max( 0.0, smean - scut );
      lower = Math.atan( ( tmp * tmp - Math.pow( smean, 2) ) / ( smean * sgamma ) );

      upper = Math.atan( ( Math.pow( smean + scut, 2 ) - Math.pow( smean, 2 ) ) / ( smean * sgamma ) );

      rval = RandBreitWigner.ShootFlat( { a: lower, b: upper, engine: sengine } );

      displ = sgamma * Math.tan( rval );

      return Math.sqrt( Math.max( 0.0, Math.pow( smean, 2 ) + smean * displ ) );
    }
  };

  RandBreitWigner.prototype = {
    constructor: RandBreitWigner,

    Fire: function(){
      if( this.fgamma == 0 ) return this.fmean;
      var rval, displ;
      rval  = 2.0 * this.fengine.Flat() - 1.0;

      if( this.fcut === undefined ){
        // Without cut
        displ = 0.5 * this.fgamma * Math.tan( rval * Math.Pi * 0.5 );
      } else {
        // With cut
        var val;
        val = Math.atan( 2.0 * this.fcut / this.fgamma );
        displ = 0.5 * gamma * Math.tan( rval * rval );
      }
      return ( this.fmean + displ );
    },

    FireM2: function(){
      var val, rval, displ;
      if( this.fgamma == 0.0 ) return this.fmean;

      if( this.fcut === undefined ){
        // Without cut
        val = Math.atan( -this.fmean / this.fgamma );
        rval = RandBreitWigner.ShootFlat( {  a: val, b: Math.PI / 2, engine: this.fengine  } );
        displ = this.fgamma * Math.tan( rval );
        return Math.sqrt( Math.pow( this.fmean, 2 ) + this.fmean * displ );
      } else {
        // With cut
        var lower, upper, tmp;

        tmp = Math.max( 0.0, this.fmean - this.fcut );
        lower = Math.atan( ( tmp * tmp - Math.pow( this.fmean, 2) ) / ( this.fmean * this.fgamma ) );

        upper = Math.atan( ( Math.pow( this.fmean + this.fcut, 2 ) - Math.pow( this.fmean, 2 ) ) / ( this.fmean * this.fgamma ) );

        rval = RandBreitWigner.ShootFlat( { a: lower, b: upper, engine: this.fengine } );

        displ = this.fgamma * Math.tan( rval );

        return Math.sqrt( Math.max( 0.0, Math.pow( this.fmean, 2 ) + this.fmean * displ ) );
      }
    },

    FireArray: function( /* size of vect */ size, /* Array */ vect ){
      for( var i = 0; i < size; ++i ){
        vect.push( this.Fire() );
      }
    }
  } // end prototype

  return RandBreitWigner;
});
<commit_msg>Few corrections<commit_after>/*
   +----------------------------------------------------------------------+
   |                            HEP Random                                |
   |                       --- RandBreitWigner ---                        |
   |                            Module File                               |
   +----------------------------------------------------------------------+

   Module defining methods for shooting numbers according to the
   Breit-Wigner distribution algorithms (plain or mean^2).
   Default values are set: mean=1, gamma=.2, cut=1.
   Plain algorithm is used for shootArray() and fireArray().

   +----------------------------------------------------------------------+
   | C++                                                                  |
   +----------------------------------------------------------------------+

   Gabriele Cosmo - Created: 5th September 1995
                  - Added methods to shoot arrays: 28th July 1997
   J.Marraffino   - Added default arguments as attributes and
                    operator() with arguments: 16th Feb 1998
   M Fischler      - put and get to/from streams 12/10/04

   +----------------------------------------------------------------------+
   | JavaScript                                                           |
   +----------------------------------------------------------------------+

   F. Quinonez - Created 2015-10-30

*/

define( [
  '../Random/JamesRandom',
], function( JamesRandom ){
  "use strict";

  function RandBreitWigner( args ){
    this.fmean = args.mean || 1.0;
    this.fgamma = args.gamma || 0.2;
    this.fcut = args.cut || undefined;
    this.fengine = args.engine || Object.create( JamesRandom({}) );
  }

  RandBreitWigner.Shoot = function( args ){
    var smean = args.mean || 1.0;
    var sgamma = args.gamma || 0.2;
    var scut = args.cut || undefined;
    var sengine = args.engine || Object.create( JamesRandom({}) );

    if( sgamma == 0 ) return smean;

    var rval, displ;
    rval  = 2.0 * sengine.Flat() - 1.0;

    if( scut === undefined ){
      // Without cut
      displ = 0.5 * sgamma * Math.tan( rval * Math.Pi * 0.5 );
    } else {
      // With cut
      var val;
      val = Math.atan( 2.0 * scut / sgamma );
      displ = 0.5 * gamma * Math.tan( rval * rval );
    }
    return ( smean + displ );
  };

  RandBreitWigner.ShootArray = function( args ){
    var ssize = args.size || 1;
    // var svect = args.vect;

    var argsShoot = { mean: args.mean, gamma: args.gamma, cut: args.cut, engine: args.engine };

    for( var i = 0; i < ssize; ++i ){
      args.vect.push( RandBreitWigner.Shoot( argsShoot ) );
    }

  };

  // Tweak CLHEP C++ that used the RandFlat::shoot static method.
  // Now this distribution has its own Shoot static function.
  RandBreitWigner.ShootFlat = function( args ){
    var sa = args.a || 0;
    var sb = args.b || 1;
    var swidth = args.width || ( args.b - args.a );
    var sengine = args.engine || Object.create( JamesRandom({}) );
    return ( swidth * sengine.Flat() + sa );
  };

  RandBreitWigner.ShootM2 = function( args ){
    var sengine = args.engine || Object.create( JamesRandom({}) );
    var smean = args.mean || 1.0;
    var sgamma = args.gamma || 0.2;
    var scut = args.cut || undefined;

    var val, rval, displ;
    if( sgamma == 0.0 ) return smean;

    if( scut === undefined ){
      // Without cut
      val = Math.atan( -smean / sgamma );
      rval = RandBreitWigner.ShootFlat( {  a: val, b: Math.PI / 2, engine: sengine  } );
      displ = sgamma * Math.tan( rval );
      return Math.sqrt( Math.pow( smean, 2 ) + smean * displ );
    } else {
      // With cut
      var lower, upper, tmp;

      tmp = Math.max( 0.0, smean - scut );
      lower = Math.atan( ( tmp * tmp - Math.pow( smean, 2) ) / ( smean * sgamma ) );

      upper = Math.atan( ( Math.pow( smean + scut, 2 ) - Math.pow( smean, 2 ) ) / ( smean * sgamma ) );

      rval = RandBreitWigner.ShootFlat( { a: lower, b: upper, engine: sengine } );

      displ = sgamma * Math.tan( rval );

      return Math.sqrt( Math.max( 0.0, Math.pow( smean, 2 ) + smean * displ ) );
    }
  };

  RandBreitWigner.prototype = {
    constructor: RandBreitWigner,

    Fire: function(){
      if( this.fgamma == 0 ) return this.fmean;
      var rval, displ;
      rval  = 2.0 * this.fengine.Flat() - 1.0;

      if( this.fcut === undefined ){
        // Without cut
        displ = 0.5 * this.fgamma * Math.tan( rval * Math.Pi * 0.5 );
      } else {
        // With cut
        var val;
        val = Math.atan( 2.0 * this.fcut / this.fgamma );
        displ = 0.5 * gamma * Math.tan( rval * rval );
      }
      return ( this.fmean + displ );
    },

    FireM2: function(){
      var val, rval, displ;
      if( this.fgamma == 0.0 ) return this.fmean;

      if( this.fcut === undefined ){
        // Without cut
        val = Math.atan( -this.fmean / this.fgamma );
        rval = RandBreitWigner.ShootFlat( {  a: val, b: Math.PI / 2, engine: this.fengine  } );
        displ = this.fgamma * Math.tan( rval );
        return Math.sqrt( Math.pow( this.fmean, 2 ) + this.fmean * displ );
      } else {
        // With cut
        var lower, upper, tmp;

        tmp = Math.max( 0.0, this.fmean - this.fcut );
        lower = Math.atan( ( tmp * tmp - Math.pow( this.fmean, 2) ) / ( this.fmean * this.fgamma ) );

        upper = Math.atan( ( Math.pow( this.fmean + this.fcut, 2 ) - Math.pow( this.fmean, 2 ) ) / ( this.fmean * this.fgamma ) );

        rval = RandBreitWigner.ShootFlat( { a: lower, b: upper, engine: this.fengine } );

        displ = this.fgamma * Math.tan( rval );

        return Math.sqrt( Math.max( 0.0, Math.pow( this.fmean, 2 ) + this.fmean * displ ) );
      }
    },

    FireArray: function( /* size of vect */ size, /* Array */ vect ){
      for( var i = 0; i < size; ++i ){
        vect.push( this.Fire() );
      }
    }
  } // end prototype

  return RandBreitWigner;
});
<|endoftext|>


<commit_before>var PT = PT || {};

/// Input type defaults
PT.defaultControls = {
  inputText: {
    label: "Text",
    input_type: "string"
  },

  inputLocation: {
    label: "Location",
    input_type: "location"
  },

  inputImage: {
    label: "Image",
    input_type: "image",
  }
};

/// Input constructor
PT.Input = function(){
  var self = this;

  self.id = ko.observable("");
  self.survey_id = PT.survey.id;
  self.label = ko.observable("");
  self.input_type = ko.observable();
  self.required = ko.observable(false);
  self.options = ko.observableArray([I18n.t("surveys.survey_builder.option_1")]);
  self.order = "";
  self.inEdit = ko.observable(true);

  self.validate = function(){
    var inputEl = $("#input" + self.id());
    var messages = inputEl.find(".messages");
    messages.empty();

    if(!self.label()) {
      messages.append(I18n.t("defaults.validations.question_blank"));
      inputEl.addClass('invalid');
    } else if(self.input_type() == "select" || self.input_type() == "select1"){
      if (self.options().length == 0){
        messages.append(PT.validations.no_options);
        inputEl.addClass('invalid');
      } else {
      inputEl.removeClass('invalid');
      }
    } else {
      inputEl.removeClass('invalid');
    }
  };

  self.save = function(self, event){
    $.ajax({
      url: Routes.survey_inputs_path(PT.survey.id),
      type: "POST",
      contentType: "application/json",
      dataType: "json",
      data: ko.toJSON(self)
    })
    .done(function(response) {
      console.log(response);
      self.inEdit(false);
      self.options(response.options);

      if(self.id() === ""){
        self.id(response.id);
      }
      self.validate();
      PT.checkErrors();
    });
  };

  self.map = function(data){
    self.id = ko.observable(data.id);
    self.survey_id = data.survey_id;
    self.label = ko.observable(data.label);
    self.input_type = ko.observable(data.input_type);
    self.required = ko.observable(data.required);
    self.options = ko.observableArray(data.options);
    self.order = data.order;
    self.inEdit = ko.observable(false);
  };

  self.edit = function(){
    PT.survey.saveInputs();
    self.inEdit(true);
    PT.selectedInput(self);
  };

  self.addOption = function(input, event){
    self.options.push("");
    $(event.target).parents().find(".options").find(".option").last().find("input").focus();
  };

  self.deleteOption = function(option, event){
    self.options.remove(option);
  };

  self.copy = function(input, event) {
    $.ajax({
      url: Routes.clone_input_path(self.id()),
      type: 'POST',
      dataType: 'json'
    })
    .done(function(response) {
      var newInput = new PT.Input();
      newInput.map(response);
      PT.survey.inputs.push(newInput);
      newInput.validate();
    });
  };

  self.applyType = function(){
    if(self.input_type() == "yes_no"){
      self.options([I18n.t("defaults.yes_option"), I18n.t("defaults.no_option")]);
      self.input_type("select1");
    }
  };
};

/// Survey Constructor
PT.SurveyModel = function(){
  var self = this;

  self.id = "";
  self.title = ko.observable();
  self.campaign_id = "";
  self.inputs = ko.observableArray([]);

  self.addInput = function(event){
    event.stopPropagation();
    self.saveInputs();

    var input = new PT.Input();
    var type = PT.defaultControls[$(event.currentTarget).attr("rel")];
    var index;

    if(type){
      input.input_type(type["input_type"]);
    }

    if($(event.target).hasClass("drag-insert")){
      index = $(event.target).index();
      $(event.target).remove();
    } else {
      index = self.inputs().length;
    }

    self.inputs.splice(index, 0, input);
    PT.selectedInput(input);
    if($(".selected").length > 0) {
      $(".selected").find("input")[0].focus();
    }
  };

  self.saveInputs = function(){
    var unsaved = self.inputs().filter(function(input) { return input.inEdit() === true ;});
    unsaved.forEach(function(input){input.save(input); });
  };

  self.removeInput = function(){
    var confirmed = window.confirm(I18n.t("surveys.survey_builder.confirm_input_delete"));
    if(confirmed){
      self.inputs.remove(this);
      if(this.id()){
        $.ajax({
          url: Routes.survey_input_path(PT.survey.id, this.id()),
          type: "DELETE",
          contentType: "application/json",
          dataType: "json"
        })
        .done(function(response){
          console.log(response);
        });
      }
    }

    self.inputs().length < 1 ? PT.selectedInput("") : PT.selectedInput(_.last(PT.survey.inputs()));
  };

  /// Update order of all inputs
  self.saveOrder = function(){
    self.saveInputs();

    $.ajax({
      url: Routes.save_order_path(PT.survey.id),
      type: "PUT",
      contentType: "application/json",
      dataType: "json",
      data: ko.toJSON(self)
    })
    .done(function(data){
      window.location.pathname = I18n.currentLocale() + Routes[data.redirect_path](self.campaign_id);
    });

  };

  self.populateInputs = function(data){
    data.forEach(function(input){
      var newInput = new PT.Input();
      newInput.map(input);
      self.inputs.push(newInput);
    });

    self.inputs.sort(function(a,b){return a.order - b.order;});
    PT.selectedInput = ko.observable(self.inputs()[0]);
  };
};

PT.getSurvey = function(id){
  $.getJSON(Routes.survey_path(id), null, function(response, textStatus) {
    PT.survey = new PT.SurveyModel();

    PT.survey.id = response.id;
    PT.survey.title(response.title);
    PT.survey.campaign_id = response.campaign_id;
    PT.survey.populateInputs(response.inputs);
    ko.applyBindings(PT.survey);

    PT.survey.inputs().forEach(function(input){
      input.validate();
    });
    PT.checkErrors();

    $(document).on("click", ".tool-button", PT.survey.addInput);
  });
};

PT.updateTitle = function(){
  PT.survey.title($("#survey-title-input").val());

  $.ajax({
    url: Routes.survey_path(PT.survey.id),
    type: "PUT",
    contentType: "application/json",
    dataType: "json",
    data: ko.toJSON(PT.survey)
  })
  .done(function(response) {
    $("#survey-title-modal").modal('hide');
    $(".campaign-title").html(PT.survey.title());
  })
}

PT.flashMessage = function(message, element){
  $("#message").remove();
  element.after(HandlebarsTemplates["flash_message"]({text: message})).fadeIn();
  $("#message").delay(2000).fadeOut();
};

PT.checkErrors = function(){
  if($("#survey-body").find(".invalid").length > 0){
    $("#error-check").addClass("alert-danger");
    $("#error-check p").html(I18n.t("defaults.validations.has_error"));
  } else {
    $("#error-check").removeClass("alert-danger");
    $("#error-check p").html(I18n.t("defaults.validations.no_errors"));
  }
};
<commit_msg>Focus input when new response option added in builder<commit_after>var PT = PT || {};

/// Input type defaults
PT.defaultControls = {
  inputText: {
    label: "Text",
    input_type: "string"
  },

  inputLocation: {
    label: "Location",
    input_type: "location"
  },

  inputImage: {
    label: "Image",
    input_type: "image",
  }
};

/// Input constructor
PT.Input = function(){
  var self = this;

  self.id = ko.observable("");
  self.survey_id = PT.survey.id;
  self.label = ko.observable("");
  self.input_type = ko.observable();
  self.required = ko.observable(false);
  self.options = ko.observableArray([I18n.t("surveys.survey_builder.option_1")]);
  self.order = "";
  self.inEdit = ko.observable(true);

  self.validate = function(){
    var inputEl = $("#input" + self.id());
    var messages = inputEl.find(".messages");
    messages.empty();

    if(!self.label()) {
      messages.append(I18n.t("defaults.validations.question_blank"));
      inputEl.addClass('invalid');
    } else if(self.input_type() == "select" || self.input_type() == "select1"){
      if (self.options().length == 0){
        messages.append(PT.validations.no_options);
        inputEl.addClass('invalid');
      } else {
      inputEl.removeClass('invalid');
      }
    } else {
      inputEl.removeClass('invalid');
    }
  };

  self.save = function(self, event){
    $.ajax({
      url: Routes.survey_inputs_path(PT.survey.id),
      type: "POST",
      contentType: "application/json",
      dataType: "json",
      data: ko.toJSON(self)
    })
    .done(function(response) {
      console.log(response);
      self.inEdit(false);
      self.options(response.options);

      if(self.id() === ""){
        self.id(response.id);
      }
      self.validate();
      PT.checkErrors();
    });
  };

  self.map = function(data){
    self.id = ko.observable(data.id);
    self.survey_id = data.survey_id;
    self.label = ko.observable(data.label);
    self.input_type = ko.observable(data.input_type);
    self.required = ko.observable(data.required);
    self.options = ko.observableArray(data.options);
    self.order = data.order;
    self.inEdit = ko.observable(false);
  };

  self.edit = function(){
    PT.survey.saveInputs();
    self.inEdit(true);
    PT.selectedInput(self);
  };

  self.addOption = function(input, event){
    self.options.push("");
    $(event.target).parents().find(".options").first().find(".option.edit").last().find("input").focus();
  };

  self.deleteOption = function(option, event){
    self.options.remove(option);
  };

  self.copy = function(input, event) {
    $.ajax({
      url: Routes.clone_input_path(self.id()),
      type: 'POST',
      dataType: 'json'
    })
    .done(function(response) {
      var newInput = new PT.Input();
      newInput.map(response);
      PT.survey.inputs.push(newInput);
      newInput.validate();
    });
  };

  self.applyType = function(){
    if(self.input_type() == "yes_no"){
      self.options([I18n.t("defaults.yes_option"), I18n.t("defaults.no_option")]);
      self.input_type("select1");
    }
  };
};

/// Survey Constructor
PT.SurveyModel = function(){
  var self = this;

  self.id = "";
  self.title = ko.observable();
  self.campaign_id = "";
  self.inputs = ko.observableArray([]);

  self.addInput = function(event){
    event.stopPropagation();
    self.saveInputs();

    var input = new PT.Input();
    var type = PT.defaultControls[$(event.currentTarget).attr("rel")];
    var index;

    if(type){
      input.input_type(type["input_type"]);
    }

    if($(event.target).hasClass("drag-insert")){
      index = $(event.target).index();
      $(event.target).remove();
    } else {
      index = self.inputs().length;
    }

    self.inputs.splice(index, 0, input);
    PT.selectedInput(input);
    if($(".selected").length > 0) {
      $(".selected").find("input")[0].focus();
    }
  };

  self.saveInputs = function(){
    var unsaved = self.inputs().filter(function(input) { return input.inEdit() === true ;});
    unsaved.forEach(function(input){input.save(input); });
  };

  self.removeInput = function(){
    var confirmed = window.confirm(I18n.t("surveys.survey_builder.confirm_input_delete"));
    if(confirmed){
      self.inputs.remove(this);
      if(this.id()){
        $.ajax({
          url: Routes.survey_input_path(PT.survey.id, this.id()),
          type: "DELETE",
          contentType: "application/json",
          dataType: "json"
        })
        .done(function(response){
          console.log(response);
        });
      }
    }

    self.inputs().length < 1 ? PT.selectedInput("") : PT.selectedInput(_.last(PT.survey.inputs()));
  };

  /// Update order of all inputs
  self.saveOrder = function(){
    self.saveInputs();

    $.ajax({
      url: Routes.save_order_path(PT.survey.id),
      type: "PUT",
      contentType: "application/json",
      dataType: "json",
      data: ko.toJSON(self)
    })
    .done(function(data){
      window.location.pathname = I18n.currentLocale() + Routes[data.redirect_path](self.campaign_id);
    });

  };

  self.populateInputs = function(data){
    data.forEach(function(input){
      var newInput = new PT.Input();
      newInput.map(input);
      self.inputs.push(newInput);
    });

    self.inputs.sort(function(a,b){return a.order - b.order;});
    PT.selectedInput = ko.observable(self.inputs()[0]);
  };
};

PT.getSurvey = function(id){
  $.getJSON(Routes.survey_path(id), null, function(response, textStatus) {
    PT.survey = new PT.SurveyModel();

    PT.survey.id = response.id;
    PT.survey.title(response.title);
    PT.survey.campaign_id = response.campaign_id;
    PT.survey.populateInputs(response.inputs);
    ko.applyBindings(PT.survey);

    PT.survey.inputs().forEach(function(input){
      input.validate();
    });
    PT.checkErrors();

    $(document).on("click", ".tool-button", PT.survey.addInput);
  });
};

PT.updateTitle = function(){
  PT.survey.title($("#survey-title-input").val());

  $.ajax({
    url: Routes.survey_path(PT.survey.id),
    type: "PUT",
    contentType: "application/json",
    dataType: "json",
    data: ko.toJSON(PT.survey)
  })
  .done(function(response) {
    $("#survey-title-modal").modal('hide');
    $(".campaign-title").html(PT.survey.title());
  })
}

PT.flashMessage = function(message, element){
  $("#message").remove();
  element.after(HandlebarsTemplates["flash_message"]({text: message})).fadeIn();
  $("#message").delay(2000).fadeOut();
};

PT.checkErrors = function(){
  if($("#survey-body").find(".invalid").length > 0){
    $("#error-check").addClass("alert-danger");
    $("#error-check p").html(I18n.t("defaults.validations.has_error"));
  } else {
    $("#error-check").removeClass("alert-danger");
    $("#error-check p").html(I18n.t("defaults.validations.no_errors"));
  }
};
<|endoftext|>


<commit_before>import { assert } from 'chai';
import { isMatch } from '../wildcard-matching';

describe('Wildcard Matching', () => {
  const testCases = [
    ['a', 'a', true],
    ['a', 'a*', true],
    ['aa', 'a*', true],
    ['aa', 'a', false],
    ['aa', 'aa', true],
    ['aa', '?*', true],
    ['ab', '?*', true],
    ['aab', 'c*a*b', false],
    ['aaaaaaba', 'a*******b', false],
  ];

  testCases.forEach((testCase, index) => {
    it(`should check wildcard matching using recursive solution ${index}`, () => {
      const [s, p, expected] = testCase;
      const actual = isMatch(s, p);
      assert.equal(actual, expected);
    });
  });
});
<commit_msg>fix(dp): Added testcase for wildcard matching dp solution<commit_after>import { assert } from 'chai';
import { isMatch, isMatchDP } from '../wildcard-matching';

describe('Wildcard Matching', () => {
  const testCases = [
    ['a', 'a', true],
    ['a', 'a*', true],
    ['aa', 'a*', true],
    ['aa', 'a', false],
    ['aa', 'aa', true],
    ['aa', '?*', true],
    ['ab', '?*', true],
    ['aab', 'c*a*b', false],
    ['aaaaaaba', 'a*******b', false],
  ];

  testCases.forEach((testCase, index) => {
    it(`should check wildcard matching using recursive solution ${index}`, () => {
      const [s, p, expected] = testCase;
      const actual = isMatch(s, p);
      assert.equal(actual, expected);
    });

    it(`should check wildcard matching using dynamic programming solution ${index}`, () => {
      const [s, p, expected] = testCase;
      const actual = isMatchDP(s, p);
      assert.equal(actual, expected);
    });
  });
});
<|endoftext|>


<commit_before>import {handleActions} from 'redux-actions';
import Chance from 'chance';
const chance = new Chance();

const ADD_ALERT = 'ADD_ALERT';
const REMOVE_ALERT = 'REMOVE_ALERT';

const buttons = {
  OK: {
    text: 'OK',
    value: true,
    className: 'rodal-confirm-btn',
  },
  CANCEL: {
    text: 'Cancel',
    value: false,
    className: 'rodal-cancel-btn',
  }
};

function addAlert({buttons, onResult, shouldShow = true, ...alertProps}) {
  if (!shouldShow) {
    if (onResult) onResult(true);
    return;
  }

  return (dispatch) => {
    const id = chance.guid();
    const onClose = (result) => {
      dispatch({type: REMOVE_ALERT, id});
      if (onResult) onResult(result);
    };

    const alert = {
      ...alertProps,
      id,
      onClose,
      buttons: Array.isArray(buttons) ? buttons : buttons(onClose)
    };
    dispatch({type: ADD_ALERT, alert});
  }
}

export function showCustomAlert({buttons, ...alertProps}) {
  return addAlert({
    ...alertProps,
    buttons: onClose => buttons.map(({value, ...props}) => ({...props, onClick: () => onClose(value)}))
  });
}

export function showAlert(alertProps) {
  return showCustomAlert({
    ...alertProps,
    showCloseButton: true,
    buttons: [buttons.OK]
  });
}

export function showConfirm(alertProps) {
  return showCustomAlert({
    ...alertProps,
    buttons: [buttons.OK, buttons.CANCEL]
  });
}

export default handleActions({
  [ADD_ALERT]: (alerts, {alert}) => alerts.concat(alert),
  [REMOVE_ALERT]: (alerts, {id}) => alerts.filter(alert => alert.id !== id)
}, []);
<commit_msg>fix redux error<commit_after>import {handleActions} from 'redux-actions';
import Chance from 'chance';
const chance = new Chance();

const ADD_ALERT = 'ADD_ALERT';
const REMOVE_ALERT = 'REMOVE_ALERT';

const buttons = {
  OK: {
    text: 'OK',
    value: true,
    className: 'rodal-confirm-btn',
  },
  CANCEL: {
    text: 'Cancel',
    value: false,
    className: 'rodal-cancel-btn',
  }
};

function addAlert({buttons, onResult, shouldShow = true, ...alertProps}) {
  return (dispatch) => {
    if (!shouldShow) {
      if (onResult) onResult(true);
      return;
    }

    const id = chance.guid();
    const onClose = (result) => {
      dispatch({type: REMOVE_ALERT, id});
      if (onResult) onResult(result);
    };

    const alert = {
      ...alertProps,
      id,
      onClose,
      buttons: Array.isArray(buttons) ? buttons : buttons(onClose)
    };
    dispatch({type: ADD_ALERT, alert});
  }
}

export function showCustomAlert({buttons, ...alertProps}) {
  return addAlert({
    ...alertProps,
    buttons: onClose => buttons.map(({value, ...props}) => ({...props, onClick: () => onClose(value)}))
  });
}

export function showAlert(alertProps) {
  return showCustomAlert({
    ...alertProps,
    showCloseButton: true,
    buttons: [buttons.OK]
  });
}

export function showConfirm(alertProps) {
  return showCustomAlert({
    ...alertProps,
    buttons: [buttons.OK, buttons.CANCEL]
  });
}

export default handleActions({
  [ADD_ALERT]: (alerts, {alert}) => alerts.concat(alert),
  [REMOVE_ALERT]: (alerts, {id}) => alerts.filter(alert => alert.id !== id)
}, []);
<|endoftext|>


<commit_before><commit_msg>jshint errors<commit_after><|endoftext|>


<commit_before>/* ------------------------------------------------------------------------- *
 * Copyright 2002-2022, OpenNebula Project, OpenNebula Systems               *
 *                                                                           *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may   *
 * not use this file except in compliance with the License. You may obtain   *
 * a copy of the License at                                                  *
 *                                                                           *
 * http://www.apache.org/licenses/LICENSE-2.0                                *
 *                                                                           *
 * Unless required by applicable law or agreed to in writing, software       *
 * distributed under the License is distributed on an "AS IS" BASIS,         *
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  *
 * See the License for the specific language governing permissions and       *
 * limitations under the License.                                            *
 * ------------------------------------------------------------------------- */
import { ReactElement, memo, useMemo } from 'react'
import PropTypes from 'prop-types'

import { User, Group, Lock } from 'iconoir-react'
import { Typography } from '@mui/material'

import Timer from 'client/components/Timer'
import { StatusChip } from 'client/components/Status'
import { rowStyles } from 'client/components/Tables/styles'
import Image from 'client/components/Image'

import { timeFromMilliseconds } from 'client/models/Helper'
import { isExternalURL } from 'client/utils'
import { VM, STATIC_FILES_URL } from 'client/constants'

const VmTemplateCard = memo(
  /**
   * @param {object} props - Props
   * @param {VM} props.template - Virtual machine resource
   * @param {object} props.rootProps - Props to root component
   * @returns {ReactElement} - Card
   */
  ({ template, rootProps }) => {
    const classes = rowStyles()
    const {
      ID,
      NAME,
      UNAME,
      GNAME,
      REGTIME,
      LOCK,
      VROUTER,
      LOGO = '',
    } = template

    const logoSource = useMemo(
      () => (isExternalURL(LOGO) ? LOGO : `${STATIC_FILES_URL}/${LOGO}`),
      [LOGO]
    )

    const time = timeFromMilliseconds(+REGTIME)

    return (
      <div {...rootProps} data-cy={`template-${ID}`}>

          <Image
            alt="logo"
            src={logoSource}
            imgProps={{ className: classes.image }}
          />

            <Typography component="span">{NAME}</Typography>

              {LOCK && <Lock />}
              {VROUTER && <StatusChip text={VROUTER} />}

              {`#${ID} registered `}
              <Timer initial={time} />

            <span title={`Owner: ${UNAME}`}>
              <User />
              {` ${UNAME}`}

            <span title={`Group: ${GNAME}`}>
              <Group />
              {` ${GNAME}`}

    )
  }
)

VmTemplateCard.propTypes = {
  template: PropTypes.object,
  rootProps: PropTypes.shape({
    className: PropTypes.string,
  }),
}

VmTemplateCard.displayName = 'VmTemplateCard'

export default VmTemplateCard
<commit_msg>B #5422: Show logos on Templates cards (#1940)<commit_after>/* ------------------------------------------------------------------------- *
 * Copyright 2002-2022, OpenNebula Project, OpenNebula Systems               *
 *                                                                           *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may   *
 * not use this file except in compliance with the License. You may obtain   *
 * a copy of the License at                                                  *
 *                                                                           *
 * http://www.apache.org/licenses/LICENSE-2.0                                *
 *                                                                           *
 * Unless required by applicable law or agreed to in writing, software       *
 * distributed under the License is distributed on an "AS IS" BASIS,         *
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  *
 * See the License for the specific language governing permissions and       *
 * limitations under the License.                                            *
 * ------------------------------------------------------------------------- */
import { ReactElement, memo, useMemo } from 'react'
import PropTypes from 'prop-types'

import { User, Group, Lock } from 'iconoir-react'
import { Typography } from '@mui/material'

import Timer from 'client/components/Timer'
import { StatusChip } from 'client/components/Status'
import { rowStyles } from 'client/components/Tables/styles'
import Image from 'client/components/Image'

import { timeFromMilliseconds } from 'client/models/Helper'
import { isExternalURL } from 'client/utils'
import { VM, STATIC_FILES_URL } from 'client/constants'

const VmTemplateCard = memo(
  /**
   * @param {object} props - Props
   * @param {VM} props.template - Virtual machine resource
   * @param {object} props.rootProps - Props to root component
   * @returns {ReactElement} - Card
   */
  ({ template, rootProps }) => {
    const classes = rowStyles()
    const {
      ID,
      NAME,
      UNAME,
      GNAME,
      REGTIME,
      LOCK,
      VROUTER,
      TEMPLATE: { LOGO = '' } = {},
    } = template

    const logoSource = useMemo(
      () => (isExternalURL(LOGO) ? LOGO : `${STATIC_FILES_URL}/${LOGO}`),
      [LOGO]
    )

    const time = timeFromMilliseconds(+REGTIME)

    return (
      <div {...rootProps} data-cy={`template-${ID}`}>

          <Image
            alt="logo"
            src={logoSource}
            imgProps={{ className: classes.image }}
          />

            <Typography component="span">{NAME}</Typography>

              {LOCK && <Lock />}
              {VROUTER && <StatusChip text={VROUTER} />}

              {`#${ID} registered `}
              <Timer initial={time} />

            <span title={`Owner: ${UNAME}`}>
              <User />
              {` ${UNAME}`}

            <span title={`Group: ${GNAME}`}>
              <Group />
              {` ${GNAME}`}

    )
  }
)

VmTemplateCard.propTypes = {
  template: PropTypes.object,
  rootProps: PropTypes.shape({
    className: PropTypes.string,
  }),
}

VmTemplateCard.displayName = 'VmTemplateCard'

export default VmTemplateCard
<|endoftext|>


<commit_before>function htmlentities (string, quote_style) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: nobbler
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Ratheous
    // -    depends on: get_html_translation_table
    // *     example 1: htmlentities('Kevin & van Zonneveld');
    // *     returns 1: 'Kevin & van Zonneveld'
    // *     example 2: htmlentities("foo'bar","ENT_QUOTES");
    // *     returns 2: 'foo'bar'
    var hash_map = {},
        symbol = '',
        tmp_str = '',
        entity = '';
    tmp_str = string.toString();

    if (false === (hash_map = this.get_html_translation_table('HTML_ENTITIES', quote_style))) {
        return false;
    }
    hash_map["'"] = ''';
    for (symbol in hash_map) {
        entity = hash_map[symbol];
        tmp_str = tmp_str.split(symbol).join(entity);
    }

    return tmp_str;
}
<commit_msg>Added support for double_encode param<commit_after>function htmlentities (string, quote_style, charset, double_encode) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: nobbler
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Ratheous
    // +   improved by: Rafał Kukawski (http://blog.kukawski.pl)
    // -    depends on: get_html_translation_table
    // *     example 1: htmlentities('Kevin & van Zonneveld');
    // *     returns 1: 'Kevin & van Zonneveld'
    // *     example 2: htmlentities("foo'bar","ENT_QUOTES");
    // *     returns 2: 'foo'bar'
    var hash_map = {},
        symbol = '',
        entity = '',
        self = this;
    string += '';
    double_encode = !!double_encode || double_encode == null;

    if (false === (hash_map = this.get_html_translation_table('HTML_ENTITIES', quote_style))) {
        return false;
    }
    hash_map["'"] = ''';

    if (double_encode) {
        for (symbol in hash_map) {
            entity = hash_map[symbol];
            string = string.split(symbol).join(entity);
        }
    } else {
        string = string.replace(/([\s\S]*?)(&(?:#\d+|#x[\da-f]+|[a-z][\da-z]*);|$)/g, function (ignore, text, entity) {
            return self.htmlentities(text, quote_style, charset) + entity;
        });
    }

    return string;
}
<|endoftext|>


<commit_before>var helper = require("../../helper");
var validator = require('dl-models').validator.master;
var validatorPurchasing = require('dl-models').validator.purchasing;
var UnitReceiptNoteManager = require("../../../src/managers/garment-purchasing/unit-receipt-note-manager");
var unitReceiptNoteManager = null;
var unitReceiptNote = require("../../data-util/garment-purchasing/unit-receipt-note-data-util");
var StorageManager = require("../../../src/managers/master/storage-manager");
var storageManager = null;
var storage = require("../../data-util/master/storage-data-util");
require("should");

before('#00. connect db', function (done) {
    helper.getDb()
        .then(db => {
            unitReceiptNoteManager = new UnitReceiptNoteManager(db, {
                username: 'unit-test'
            });
            done();
        })
        .catch(e => {
            done(e);
        })
});

var createdData;
it('#01. should success when create new data', function (done) {
    unitReceiptNote.getNewData()
        .then((data) => unitReceiptNoteManager.create(data))
        .then((id) => {
            id.should.be.Object();
            createdId = id;
            done();
        })
        .catch((e) => {
            done(e);
        });
});

it('#02. should error when create new data with same code', function (done) {
    var data = Object.assign({}, createdData);
    delete data._id;
    unitReceiptNoteManager.create(data)
        .then(id => {
            id.should.be.Object();
            done();
        })
        .catch(e => {
            try {
                done();
            }
            catch (ex) {
                done(ex);
            }
        })
});

it('#03. should error when create new blank data', function (done) {
    unitReceiptNoteManager.create({})
        .then(id => {
            id.should.be.Object();
            done();
        })
        .catch(e => {
            try {
                done();
            }
            catch (ex) {
                done(ex);
            }
        })
});

it("#04. should error when create new data with deliveredQuantity greater than deliveredQuantity on delivery order", function (done) {
    unitReceiptNote.getNewData()
        .then((data) => {
            data.items.map((item) => {
                item.deliveredQuantity = item.deliveredQuantity + 2;
            })
            return unitReceiptNoteManager.create(data)
        })
        .then(id => {
            id.should.be.Object();
            done();
        })
        .catch(e => {
            try {
                done();
            }
            catch (ex) {
                done(ex);
            }
        })
});

//validator useStorage

var storageData;
var storageDataId;
it('#05. should success when create new data', function (done) {
    storage.getNewData()
        .then((data) => storageManager.create(data))
        .then((id) => {
            storageManager.getSingleById(id)
            .then((data) => {
                storageData=data;

            });

                id.should.be.Object();
                storageDataId = id;
                done();
        })
        .catch((e) => {
            done(e);
        });
});

it("#06. should success when create new data when useStorage is true", function (done) {
     unitReceiptNote.getNewData()
        .then((data) => {
            data.storageId=storageDataId;
            data.unit=storageData.unit;
            data.useStorage=true;
            unitReceiptNoteManager.create(data)
            .then((id) => {
                id.should.be.Object();
                var createdId = id;
                done();
            })
        })
        .catch((e) => {
            done(e);
        });
});

it('#07. should error when create new data useStorage=true without storage', function (done) {
    unitReceiptNote.getNewData()
        .then(data => {
            data.useStorage=true;
            unitReceiptNoteManager.create(data)
                .then(id => {
                    done("should error when create new data useStorage=true without storage");
                })
                .catch(e => {
                    try {
                        e.errors.should.have.property('storage');
                        done();
                    }
                    catch (ex) {
                        done(ex);
                    }
                });
        })
        .catch(e => {
            done(e);
        });
});
<commit_msg>fixunitreceiptGarment<commit_after>var helper = require("../../helper");
var validator = require('dl-models').validator.master;
var validatorPurchasing = require('dl-models').validator.purchasing;
var UnitReceiptNoteManager = require("../../../src/managers/garment-purchasing/unit-receipt-note-manager");
var unitReceiptNoteManager = null;
var unitReceiptNote = require("../../data-util/garment-purchasing/unit-receipt-note-data-util");
var StorageManager = require("../../../src/managers/master/storage-manager");
var storageManager = null;
var storage = require("../../data-util/master/storage-data-util");
require("should");

before('#00. connect db', function (done) {
    helper.getDb()
        .then(db => {
            unitReceiptNoteManager = new UnitReceiptNoteManager(db, {
                username: 'unit-test'
            });
            done();
        })
        .catch(e => {
            done(e);
        })
});

var createdData;
it('#01. should success when create new data', function (done) {
    unitReceiptNote.getNewData()
        .then((data) => unitReceiptNoteManager.create(data))
        .then((id) => {
            id.should.be.Object();
            createdId = id;
            done();
        })
        .catch((e) => {
            done(e);
        });
});

it('#02. should error when create new data with same code', function (done) {
    var data = Object.assign({}, createdData);
    delete data._id;
    unitReceiptNoteManager.create(data)
        .then(id => {
            id.should.be.Object();
            done();
        })
        .catch(e => {
            try {
                done();
            }
            catch (ex) {
                done(ex);
            }
        })
});

it('#03. should error when create new blank data', function (done) {
    unitReceiptNoteManager.create({})
        .then(id => {
            id.should.be.Object();
            done();
        })
        .catch(e => {
            try {
                done();
            }
            catch (ex) {
                done(ex);
            }
        })
});

it("#04. should error when create new data with deliveredQuantity greater than deliveredQuantity on delivery order", function (done) {
    unitReceiptNote.getNewData()
        .then((data) => {
            data.items.map((item) => {
                item.deliveredQuantity = item.deliveredQuantity + 2;
            })
            return unitReceiptNoteManager.create(data)
        })
        .then(id => {
            id.should.be.Object();
            done();
        })
        .catch(e => {
            try {
                done();
            }
            catch (ex) {
                done(ex);
            }
        })
});

//validator useStorage

var storageData;
var storageDataId;
it('#05. should success when create new data storage', function (done) {
    storage.getNewData ()
        .then((data) => storageManager.create(data))
        .then((id) => {
            storageManager.getSingleById(id)
            .then((data) => {
                storageData=data;

            });

                id.should.be.Object();
                storageDataId = id;
                done();
        })
        .catch((e) => {
            done(e);
        });
});

it("#06. should success when create new data when useStorage is true", function (done) {
     unitReceiptNote.getNewData()
        .then((data) => {
            data.storageId=storageDataId;
            data.unit=storageData.unit;
            data.useStorage=true;
            unitReceiptNoteManager.create(data)
            .then((id) => {
                id.should.be.Object();
                var createdId = id;
                done();
            })
        })
        .catch((e) => {
            done(e);
        });
});

it('#07. should error when create new data useStorage=true without storage', function (done) {
    unitReceiptNote.getNewData()
        .then(data => {
            data.useStorage=true;
            unitReceiptNoteManager.create(data)
                .then(id => {
                    done("should error when create new data useStorage=true without storage");
                })
                .catch(e => {
                    try {
                        e.errors.should.have.property('storage');
                        done();
                    }
                    catch (ex) {
                        done(ex);
                    }
                });
        })
        .catch(e => {
            done(e);
        });
});
<|endoftext|>


<commit_before>/**
 * Creating a sidebar enables you to:
 - create an ordered group of docs
 - render a sidebar for each doc of that group
 - provide next/previous navigation

 The sidebars can be generated from the filesystem, or explicitly defined here.

 Create as many sidebars as you want.
 */

// @ts-check

/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */
const sidebars = {
  // By default, Docusaurus generates a sidebar from the docs folder structure
  // defaultSidebar: [{type: 'autogenerated', dirName: '.', }],
  aptosSidebar: [
    "index",
    {
      type: "html",
      value: "Start Aptos",
      className: "sidebar-title",
    },
    "whats-new-in-docs",
    {
      type: "category",
      label: "Learn Aptos Concepts",
      link: { type: "doc", id: "concepts/index" },
      collapsible: true,
      collapsed: true,
      items: [
        {
          type: "category",
          label: "Aptos White Paper",
          collapsible: true,
          collapsed: true,
          link: { type: "doc", id: "aptos-white-paper/index" },
          items: ["aptos-white-paper/in-korean"],
        },
        "concepts/accounts",
        "concepts/resources",
        "concepts/events",
        "concepts/txns-states",
        "concepts/gas-txn-fee",
        "concepts/blocks",
        "guides/basics-life-of-txn",
        "concepts/staking",
        "concepts/governance",
      ],
    },
    {
      type: "category",
      label: "Set Environment",
      link: { type: "doc", id: "guides/getting-started" },
      collapsible: true,
      collapsed: true,
      items: [
        "guides/use-aptos-explorer",
        "guides/install-petra-wallet",
        {
          type: "category",
          label: "Download Aptos CLI",
          link: { type: "doc", id: "cli-tools/aptos-cli-tool/install-aptos-cli" },
          collapsible: true,
          collapsed: true,
          items: ["cli-tools/build-aptos-cli", "cli-tools/aptos-cli-tool/use-aptos-cli"],
        },
        "cli-tools/install-move-prover",
      ],
    },
    {
      type: "html",
      value: "Build Apps",
      className: "sidebar-title",
    },
    {
      type: "category",
      label: "Standards",
      link: { type: "doc", id: "concepts/coin-and-token/index" },
      collapsible: true,
      collapsed: true,
      items: ["concepts/coin-and-token/aptos-coin", "concepts/coin-and-token/aptos-token"],
    },
    {
      type: "category",
      label: "Reading blockchain data",
      collapsible: true,
      collapsed: true,
      items: ["guides/system-integrators-guide", "guides/indexing"],
    },
    {
      type: "category",
      label: "Interact with Blockchain",
      link: { type: "doc", id: "guides/index" },
      collapsible: true,
      collapsed: true,
      items: [
        "guides/sign-a-transaction",
        "guides/resource-accounts",
        "guides/wallet-standard",
        "guides/handle-aptos-errors",
      ],
    },
    {
      type: "category",
      label: "Develop by Tutorial",
      link: { type: "doc", id: "tutorials/index" },
      collapsible: true,
      collapsed: true,
      items: [
        "tutorials/first-transaction",
        "tutorials/your-first-nft",
        "tutorials/first-dapp",
        "tutorials/first-coin",
      ],
    },
    {
      type: "category",
      label: "Develop Locally",
      collapsible: true,
      collapsed: true,
      items: [
        "guides/local-testnet-dev-flow",
        "nodes/local-testnet/run-a-local-testnet",
        "nodes/local-testnet/using-cli-to-run-a-local-testnet",
        "guides/running-a-local-multi-node-network",
      ],
    },
    {
      type: "html",
      value: "Reference",
      className: "sidebar-title",
    },
    "reference/glossary",
    "issues-and-workarounds",
    {
      type: "category",
      label: "API Reference",
      collapsible: true,
      collapsed: true,
      items: ["nodes/aptos-api-spec", "guides/try-out-api"],
    },
    {
      type: "category",
      label: "Move Reference",
      link: { type: "doc", id: "guides/move-guides/index" },
      collapsible: true,
      collapsed: true,
      items: [
        "guides/move-guides/move-on-aptos",
        "concepts/base-gas",
        "guides/interacting-with-the-blockchain",
        "tutorials/first-move-module",
        "guides/move-guides/upgrading-move-code",
      ],
    },
    {
      type: "category",
      label: "SDK Reference",
      collapsible: true,
      collapsed: true,
      link: { type: "doc", id: "sdks/index" },
      items: [
        {
          type: "category",
          label: "TypeScript SDK",
          link: { type: "doc", id: "sdks/ts-sdk/index" },
          collapsible: true,
          collapsed: true,
          items: ["sdks/ts-sdk/typescript-sdk", "sdks/ts-sdk/typescript-sdk-overview"],
        },
        "sdks/python-sdk",
        "sdks/rust-sdk",
      ],
    },
    {
      type: "html",
      value: "Run Nodes",
      className: "sidebar-title",
    },
    {
      type: "category",
      label: "Find Nodes",
      collapsible: true,
      collapsed: true,
      link: { type: "doc", id: "nodes/nodes-landing" },
      items: [
        "concepts/node-networks-sync",
        "nodes/aptos-deployments",
        "nodes/leaderboard-metrics",
        "nodes/node-health-checker/index",
        "nodes/node-health-checker/node-health-checker-faq",
      ],
    },
    /** Delete during clean up
    {
      type: "category",
      label: "AIT-3",
      link: { type: "doc", id: "nodes/ait/index" },
      collapsible: true,
      collapsed: true,
      items: [
        "nodes/ait/whats-new-in-ait3",
        "nodes/ait/steps-in-ait3",

      ],
    },  */
    {
      type: "category",
      label: "Install Validators",
      link: { type: "doc", id: "nodes/validator-node/index" },
      collapsible: true,
      collapsed: true,
      items: [
        "concepts/validator-nodes",
        {
          type: "category",
          label: "Owner",
          collapsible: true,
          collapsed: true,
          link: { type: "doc", id: "nodes/validator-node/owner/index" },
          items: [],
        },
        {
          type: "category",
          label: "Operator",
          collapsible: true,
          collapsed: true,
          link: { type: "doc", id: "nodes/validator-node/operator/index" },
          items: [
            "nodes/validator-node/operator/node-requirements",
            {
              type: "category",
              label: "Running Validator Node",
              collapsible: true,
              collapsed: true,
              link: { type: "doc", id: "nodes/validator-node/operator/running-validator-node/index" },
              items: [
                "nodes/validator-node/operator/running-validator-node/using-aws",
                "nodes/validator-node/operator/running-validator-node/using-azure",
                "nodes/validator-node/operator/running-validator-node/using-gcp",
                "nodes/validator-node/operator/running-validator-node/using-docker",
                "nodes/validator-node/operator/running-validator-node/using-source-code",
                "nodes/validator-node/operator/update-validator-node",
              ],
            },
            "nodes/validator-node/operator/node-liveness-criteria",
            "nodes/validator-node/operator/connect-to-aptos-network",
            "nodes/validator-node/operator/staking-pool-operations",
            "nodes/validator-node/operator/shutting-down-nodes",
          ],
        },
        {
          type: "category",
          label: "Voter",
          collapsible: true,
          collapsed: true,
          link: { type: "doc", id: "nodes/validator-node/voter/index" },
          items: [],
        },
      ],
    },
    {
      type: "category",
      label: "Install Fullnodes",
      link: { type: "doc", id: "nodes/full-node/index" },
      collapsible: true,
      collapsed: true,
      items: [
        "concepts/fullnodes",
        "nodes/full-node/fullnode-source-code-or-docker",
        "nodes/full-node/bootstrap-fullnode",
        "nodes/full-node/update-fullnode-with-new-releases",
        "nodes/full-node/network-identity-fullnode",
        "nodes/full-node/fullnode-network-connections",
        "nodes/full-node/run-a-fullnode-on-gcp",
        "nodes/indexer-fullnode",
      ],
    },
    {
      type: "category",
      label: "Configure Nodes",
      collapsible: true,
      collapsed: true,
      link: { type: "doc", id: "nodes/identity-and-configuration" },
      items: [
        "reference/telemetry",
        "guides/state-sync",
        "guides/data-pruning",
        {
          type: "category",
          label: "Node Files For Mainnet",
          collapsible: true,
          collapsed: true,
          link: { type: "doc", id: "nodes/node-files-all-networks/node-files" },
          items: [
            "nodes/node-files-all-networks/node-files-devnet",
            "nodes/node-files-all-networks/node-files-testnet",
          ],
        },
      ],
    },
  ],
};

module.exports = sidebars;
<commit_msg>Begin edits to updated navigation<commit_after>/**
 * Creating a sidebar enables you to:
 - create an ordered group of docs
 - render a sidebar for each doc of that group
 - provide next/previous navigation

 The sidebars can be generated from the filesystem, or explicitly defined here.

 Create as many sidebars as you want.
 */

// @ts-check

/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */
const sidebars = {
  // By default, Docusaurus generates a sidebar from the docs folder structure
  // defaultSidebar: [{type: 'autogenerated', dirName: '.', }],
  aptosSidebar: [
    "index",
    {
      type: "html",
      value: "Start Aptos",
      className: "sidebar-title",
    },
    "whats-new-in-docs",
    {
      type: "category",
      label: "Learn Aptos Concepts",
      link: { type: "doc", id: "concepts/index" },
      collapsible: true,
      collapsed: true,
      items: [
        {
          type: "category",
          label: "Aptos White Paper",
          collapsible: true,
          collapsed: true,
          link: { type: "doc", id: "aptos-white-paper/index" },
          items: ["aptos-white-paper/in-korean"],
        },
        "concepts/accounts",
        "concepts/resources",
        "concepts/events",
        "concepts/txns-states",
        "concepts/gas-txn-fee",
        "concepts/blocks",
        "guides/basics-life-of-txn",
        "concepts/staking",
        "concepts/governance",
      ],
    },
    {
      type: "category",
      label: "Set Environment",
      link: { type: "doc", id: "guides/getting-started" },
      collapsible: true,
      collapsed: true,
      items: [
        "guides/use-aptos-explorer",
        "guides/install-petra-wallet",
        {
          type: "category",
          label: "Download Aptos CLI",
          link: { type: "doc", id: "cli-tools/aptos-cli-tool/install-aptos-cli" },
          collapsible: true,
          collapsed: true,
          items: ["cli-tools/build-aptos-cli", "cli-tools/aptos-cli-tool/use-aptos-cli"],
        },
        "cli-tools/install-move-prover",
      ],
    },
    {
      type: "html",
      value: "Build Apps",
      className: "sidebar-title",
    },
    {
      type: "category",
      label: "Follow Standards",
      link: { type: "doc", id: "concepts/coin-and-token/index" },
      collapsible: true,
      collapsed: true,
      items: ["concepts/coin-and-token/aptos-coin", "concepts/coin-and-token/aptos-token"],
    },
    {
      type: "category",
      label: "Read Blockchain Data",
      collapsible: true,
      collapsed: true,
      items: ["guides/system-integrators-guide", "guides/indexing"],
    },
    {
      type: "category",
      label: "Interact with Blockchain",
      link: { type: "doc", id: "guides/index" },
      collapsible: true,
      collapsed: true,
      items: [
        "guides/sign-a-transaction",
        "guides/resource-accounts",
        "guides/wallet-standard",
        "guides/handle-aptos-errors",
      ],
    },
    {
      type: "category",
      label: "Develop by Tutorial",
      link: { type: "doc", id: "tutorials/index" },
      collapsible: true,
      collapsed: true,
      items: [
        "tutorials/first-transaction",
        "tutorials/your-first-nft",
        "tutorials/first-dapp",
        "tutorials/first-coin",
      ],
    },
    {
      type: "category",
      label: "Develop Locally",
      collapsible: true,
      collapsed: true,
      items: [
        "guides/local-testnet-dev-flow",
        "nodes/local-testnet/run-a-local-testnet",
        "nodes/local-testnet/using-cli-to-run-a-local-testnet",
        "guides/running-a-local-multi-node-network",
      ],
    },
    {
      type: "html",
      value: "Reference",
      className: "sidebar-title",
    },
    "reference/glossary",
    "issues-and-workarounds",
    {
      type: "category",
      label: "API Reference",
      collapsible: true,
      collapsed: true,
      items: ["nodes/aptos-api-spec", "guides/try-out-api"],
    },
    {
      type: "category",
      label: "Move Reference",
      link: { type: "doc", id: "guides/move-guides/index" },
      collapsible: true,
      collapsed: true,
      items: [
        "guides/move-guides/move-on-aptos",
        "concepts/base-gas",
        "guides/interacting-with-the-blockchain",
        "tutorials/first-move-module",
        "guides/move-guides/upgrading-move-code",
      ],
    },
    {
      type: "category",
      label: "SDK Reference",
      collapsible: true,
      collapsed: true,
      link: { type: "doc", id: "sdks/index" },
      items: [
        {
          type: "category",
          label: "TypeScript SDK",
          link: { type: "doc", id: "sdks/ts-sdk/index" },
          collapsible: true,
          collapsed: true,
          items: ["sdks/ts-sdk/typescript-sdk", "sdks/ts-sdk/typescript-sdk-overview"],
        },
        "sdks/python-sdk",
        "sdks/rust-sdk",
      ],
    },
    {
      type: "html",
      value: "Run Nodes",
      className: "sidebar-title",
    },
    {
      type: "category",
      label: "Find Nodes",
      collapsible: true,
      collapsed: true,
      link: { type: "doc", id: "nodes/nodes-landing" },
      items: [
        "concepts/node-networks-sync",
        "nodes/aptos-deployments",
        "nodes/leaderboard-metrics",
        "nodes/node-health-checker/index",
        "nodes/node-health-checker/node-health-checker-faq",
      ],
    },
    /** Delete during clean up
    {
      type: "category",
      label: "AIT-3",
      link: { type: "doc", id: "nodes/ait/index" },
      collapsible: true,
      collapsed: true,
      items: [
        "nodes/ait/whats-new-in-ait3",
        "nodes/ait/steps-in-ait3",

      ],
    },  */
    {
      type: "category",
      label: "Install Validators",
      link: { type: "doc", id: "nodes/validator-node/index" },
      collapsible: true,
      collapsed: true,
      items: [
        "concepts/validator-nodes",
        {
          type: "category",
          label: "Owner",
          collapsible: true,
          collapsed: true,
          link: { type: "doc", id: "nodes/validator-node/owner/index" },
          items: [],
        },
        {
          type: "category",
          label: "Operator",
          collapsible: true,
          collapsed: true,
          link: { type: "doc", id: "nodes/validator-node/operator/index" },
          items: [
            "nodes/validator-node/operator/node-requirements",
            {
              type: "category",
              label: "Running Validator Node",
              collapsible: true,
              collapsed: true,
              link: { type: "doc", id: "nodes/validator-node/operator/running-validator-node/index" },
              items: [
                "nodes/validator-node/operator/running-validator-node/using-aws",
                "nodes/validator-node/operator/running-validator-node/using-azure",
                "nodes/validator-node/operator/running-validator-node/using-gcp",
                "nodes/validator-node/operator/running-validator-node/using-docker",
                "nodes/validator-node/operator/running-validator-node/using-source-code",
                "nodes/validator-node/operator/update-validator-node",
              ],
            },
            "nodes/validator-node/operator/node-liveness-criteria",
            "nodes/validator-node/operator/connect-to-aptos-network",
            "nodes/validator-node/operator/staking-pool-operations",
            "nodes/validator-node/operator/shutting-down-nodes",
          ],
        },
        {
          type: "category",
          label: "Voter",
          collapsible: true,
          collapsed: true,
          link: { type: "doc", id: "nodes/validator-node/voter/index" },
          items: [],
        },
      ],
    },
    {
      type: "category",
      label: "Install Fullnodes",
      link: { type: "doc", id: "nodes/full-node/index" },
      collapsible: true,
      collapsed: true,
      items: [
        "concepts/fullnodes",
        "nodes/full-node/fullnode-source-code-or-docker",
        "nodes/full-node/bootstrap-fullnode",
        "nodes/full-node/update-fullnode-with-new-releases",
        "nodes/full-node/network-identity-fullnode",
        "nodes/full-node/fullnode-network-connections",
        "nodes/full-node/run-a-fullnode-on-gcp",
        "nodes/indexer-fullnode",
      ],
    },
    {
      type: "category",
      label: "Configure Nodes",
      collapsible: true,
      collapsed: true,
      link: { type: "doc", id: "nodes/identity-and-configuration" },
      items: [
        "reference/telemetry",
        "guides/state-sync",
        "guides/data-pruning",
        {
          type: "category",
          label: "Node Files For Mainnet",
          collapsible: true,
          collapsed: true,
          link: { type: "doc", id: "nodes/node-files-all-networks/node-files" },
          items: [
            "nodes/node-files-all-networks/node-files-devnet",
            "nodes/node-files-all-networks/node-files-testnet",
          ],
        },
      ],
    },
  ],
};

module.exports = sidebars;
<|endoftext|>


<commit_before>var navigator = window.navigator;
  var Context = window.AudioContext || window.webkitAudioContext;
  var context = new Context();

  // audio
  var mediaStream;
  var rec;

  navigator.getUserMedia = (
    navigator.getUserMedia ||
    navigator.webkitGetUserMedia ||
    navigator.mozGetUserMedia ||
    navigator.msGetUserMedia
  );

  function recorderStart() {
    navigator.getUserMedia({audio: true}, function(localMediaStream){
      mediaStream = localMediaStream;
      var mediaStreamSource = context.createMediaStreamSource(localMediaStream);
      playAll();
      rec = new Recorder(mediaStreamSource, {
        workerPath: '../recorderWorker.js'
      });

      rec.record();
    }, function(err){
      console.log('Not supported');
    });
  }

  function recorderStop() {
    mediaStream.stop();
    rec.stop();

    rec.exportWAV(function(e){
      rec.clear();

      var fd = new FormData();
      fd.append('fname', 'test.wav');
      fd.append('data', e);
      fd.append('project_id', gon.project_id);
      $.ajax({
        type: 'POST',
        url: '/tracks',
        data: fd,
        processData: false,
        contentType: false,
        dataType: "script",

        // a custom XHR request, to allow for track upload progress bars
        xhr: function() {
          var xhr = new window.XMLHttpRequest();
          xhr.upload.addEventListener("progress", function(evt){
            if (evt.lengthComputable) {
              // current progress is set here.
              var percentComplete = (evt.loaded / evt.total) * 100;

            }
          }, false);
        return xhr;
        }
      });

    });
  }<commit_msg>add js to output upload progress to page<commit_after>var navigator = window.navigator;
  var Context = window.AudioContext || window.webkitAudioContext;
  var context = new Context();

  // audio
  var mediaStream;
  var rec;

  navigator.getUserMedia = (
    navigator.getUserMedia ||
    navigator.webkitGetUserMedia ||
    navigator.mozGetUserMedia ||
    navigator.msGetUserMedia
  );

  function recorderStart() {
    navigator.getUserMedia({audio: true}, function(localMediaStream){
      mediaStream = localMediaStream;
      var mediaStreamSource = context.createMediaStreamSource(localMediaStream);
      playAll();
      rec = new Recorder(mediaStreamSource, {
        workerPath: '../recorderWorker.js'
      });

      rec.record();
    }, function(err){
      console.log('Not supported');
    });
  }

  function recorderStop() {
    mediaStream.stop();
    rec.stop();

    rec.exportWAV(function(e){
      rec.clear();

      var fd = new FormData();
      fd.append('fname', 'test.wav');
      fd.append('data', e);
      fd.append('project_id', gon.project_id);
      $.ajax({
        type: 'POST',
        url: '/tracks',
        data: fd,
        processData: false,
        contentType: false,
        dataType: "script",

        // a custom XHR request, to allow for track upload progress bars
        xhr: function() {
          var xhr = new window.XMLHttpRequest();
          xhr.upload.addEventListener("progress", function(e){
            if (e.lengthComputable) {
              // current progress is set to the page here.
              var percentComplete = (e.loaded / e.total) * 100;
              $('.progress-bar').attr('aria-valuenow', percentComplete);
              $('.progress-bar').css('width', percentComplete + '%');
              $('.progress-text').text(percentComplete);
            }
          }, false);
        return xhr;
        }
      });

    });
  }<|endoftext|>