<commit_before>(function($){
    $.cForm = function(element, options){
        var base = this;

        // Access to jQuery and DOM versions of element
        base.$element = $(element);
        base.element = element;

        // Add a reverse reference to the DOM object
        base.$element.data("cForm", base);

        base.init = function(){
            base.options = $.extend({},$.cForm.defaultOptions, options);

            // elements which will be styled
            var filter = ['input', 'textarea', 'select', 'button'];

            // initialize a array for radio groups
        	base.radioGroupArray = [];

            // check if the called element a wrapper or a form-element
            // invoce the corresponding functions
            if(base.$element.is(filter.join())){
            	var tag = base.tagName(base.$element);

            	if(tag === 'input') 	base.handleInput(base.$element);
            	if(tag === 'select') 	base.handleSelect(base.$element);
            	if(tag === 'button') 	base.handleButton(base.$element);
            	if(tag === 'textarea') 	base.handleTextarea(base.$element);
            } else {
            	base.$element.find('input').each(function(){
            		base.handleInput($(this));
            	});
            	base.$element.find('select').each(function(){
            		base.handleSelect($(this));
            	});
            	base.$element.find('button').each(function(){
            		base.handleButton($(this));
            	});
            	base.$element.find('textarea').each(function(){
            		base.handleTextarea($(this));
            	});
            }
        };

		/**
		 * handles the BUTTON conversion
		 *
		 * @param  {object} $node jQuery-Element // BUTTON
		 */
        base.handleButton = function($node) {
        	var template = $.cForm.defaultOptions.templates['button'];
        	$node.wrap(template);
        };

		/**
		 * handles the TEXTAREA conversion
		 *
		 * @param  {object} $node jQuery-Element // TEXTAREA
		 */
        base.handleTextarea = function($node) {
        	var template = $.cForm.defaultOptions.templates['textarea'];
        	$node.wrap(template);
        };

		/**
		 * handles the INPUT conversion
		 *
		 * @param  {object} $node jQuery-Element // INPUT
		 */
        base.handleInput = function($node){
        	var type = $node.attr('type'),
        		name = $node.attr('name'),
        		value = $node.attr('value'),
        		checked = $node.attr('checked'),
        		template = '',
        		$html = $();

        	// check for input type
            if (typeof type === typeof undefined && type === false) {
				console.log('Error: Missing type-Attribute on input!');
				return false;
			}
			if (typeof name === typeof undefined && name === false) {
				name = '';
			}
			if (typeof value === typeof undefined && value === false) {
				value = '';
			}
			if (typeof checked === typeof undefined && checked === false) {
				checked = '';
			}

			template = $.cForm.defaultOptions.templates[type];

			switch(type) {
			    case 'password':
			    case 'text':
			    	$node.wrap(template);
			        break;
			    case 'file':
					$html = $(template.replace('{{name}}',name));

			    	// when the cForm file button gets clicked
			    	// trigger the original file button
					$html.bind('click',
						{
							$node: $node
						},
						function (event) {
							var $node = event.data.$node;
								$node.trigger('click');
						}
					);

					// when the original file input gets changed (gets a file)
					// update the cForm file input as well
					$node.bind(
						'change',
						{
							$html: $html
						},
						function (event) {
							var filename = $(this).val().split('\\').pop(),
								$html = event.data.$html;

							$html.addClass('filled')
								.find('.cform-filename')
									.text(filename);
						}
					);
			    	break;
			    case 'checkbox':
			    	$html = $(template.replace('{{name}}',name).replace('{{value}}',value));

			    	if(checked || checked === 'checked'){
			    		$html.addClass('checked')
			    			.data('checked', true);
			    	}

			    	// when the cForm checkbox gets clicked, change its style/values
			    	// change the original checkbox as well
			    	$html.bind(
			    		'click',
			    		{
			    			$origin: $node
			    		},
			    		function(event){
			    			var $node = $(this),
			    				$origin = event.data.$origin,
			    				checked = $node.data('checked');

			    			if(checked){
			    				$origin.prop('checked', false);
			    				$node.removeClass('checked')
			    					.data('checked', false);
			    			}else{
			    				$origin.prop('checked', true);
			    				$node.addClass('checked')
			    					.data('checked', true);
			    			}
			    		}
			    	);

			    	// when the original checkbox gets changed via js or other means
			    	// update the cForm checkbox as well
			    	$node.bind(
			    		'change',
			    		{
			    			$mirror: $html
			    		},
			    		function(event){
			    			var $node = $(this),
			    				$mirror = event.data.$mirror;

			    			if($node.prop('checked')){
			    				$mirror.addClass('checked')
			    					.data('checked', true);
			    			}else{
								$mirror.removeClass('checked')
			    					.data('checked', false);
			    			}
			    		}
			    	);
			        break;
			    case 'radio':
			    	if(base.radioGroupArray.indexOf(name) > -1){
			    		break;
			    	}
			    	base.radioGroupArray.push(name);
			    	var $mirrors = $();

			    	$nodes = base.$element.find('input[type="radio"][name="' + name + '"]');
			    	$nodes.each(function(){
			    		var $node = $(this),
			    			value = $node.val(),
							checked = $node.attr('checked'),
							$html = $();

			    		$html = $(template.replace('{{name}}', name).replace('{{value}}', value));

						checked && $html.addClass('checked').data('checked', 'true');

						$mirrors = $mirrors.add($html);
						$node.addClass('hidden').after($html);
			    	});

					$mirrors.bind(
						'click',
						{
							$mirrors: $mirrors,
							$origins: $nodes
						},
						function(event){
							var $node = $(this),
								$mirrors = event.data.$mirrors,
								$origins = event.data.$origins,
								value = $node.data('value');

							if($node.data('checked')) return true;

							$mirrors.removeClass('checked')
								.data('checked', false);
							$node.addClass('checked')
								.data('checked', true);
							$origins.prop('checked', true)
								.filter('[value="' + value + '"]')
								.prop('checked', true);
						}
					);

					$nodes.bind(
						'change',
						{
							$mirrors: $mirrors,
							$origins: $nodes
						},
						function(event){
							var $node = $(this),
								$mirrors = event.data.$mirrors,
								$origins = event.data.$origins,
								value = $node.val();

							if($node.data('checked')) return true;

							$mirrors.removeClass('checked')
								.data('checked', false)
								.filter('[data-value="' + value + '"]')
									.data('checked', true)
									.addClass('checked');
						}
					);
			        break;
			    case 'submit':
			    	$node.wrap(template);
			        break;
			    default:
					console.log('Error: No matching was found - You will be forever alone!');
			}

			base.addToDom($node, $html);
        };

       	/**
		 * handles the SELECT conversion
		 *
		 * @param  {object} $node jQuery-Element // SELECT
		 */
        base.handleSelect = function($node){
        	var name = $node.attr('name'),
        		value = $node.attr('value'),
        		multiple = $node.attr('multiple'),
        		$subnodes = $node.find('option'),
        		$selected = $subnodes.filter(':selected'),
        		template = '',
        		$options = $(),
        		$html = $();

			if (typeof name === typeof undefined && name === false) {
				name = '';
			}
			if (typeof value === typeof undefined && value === false) {
				value = '';
			}
			if (typeof multiple === typeof undefined || multiple === false) {
				multiple = false;
				template = $.cForm.defaultOptions.templates['select'];
				$html = $(template.replace('{{name}}', name)
							.replace('{{text}}', $selected.html()));
			}else{
				multiple = true;
				template = $.cForm.defaultOptions.templates['multiselect'];
				$html = $(template.replace('{{name}}', name));
			}

			// create and populate the option list
			$subnodes.each(function(index){
				var $node = $(this),
					cssclass = $node.prop('selected')?'selected':'',
					template = $.cForm.defaultOptions.templates['option'];

				template = template.replace('{{value}}', $node.val())
								.replace('{{text}}', $node.html());

				$options = $options.add($(template).addClass(cssclass));
			});

			// when a cForm select-option gets clicked, change its style/values
			// change the original select/option as well
			$options.bind(
				'click',
				{
					$origin: $node,
					$mirror: $html,
					$options: $options,
					multiple: multiple
				},
				function (event) {
					var $node = $(this),
						$origin = event.data.$origin,
						$mirror = event.data.$mirror,
						$options = event.data.$options,
						multiple = event.data.multiple,
						value = $node.data('value'),
						text = $node.html();

					if(!multiple){
						$options.not($node).removeClass('selected');
						$node.addClass('selected');

						$origin.val(value);

						$mirror.data('value', value)
							.find('.cform-control')
								.html(text);
					}else{
						var value_array = [];
						if($node.hasClass('selected')){
							value_array = $origin.val();
							value_array.splice(value_array.indexOf(value), 1);

							$origin.val(value_array);
							$mirror.data('value', value_array);
							$node.removeClass('selected');
						}else{
							value_array = $origin.val()?$origin.val():[];
							value_array.push(value);

							$origin.val(value_array);
							$mirror.data('value', value_array);
							$node.addClass('selected');
						}
					}
				}
			);

			// when the original select gets changed via js or other means
			// update the cForm select/options as well
			$node.bind(
				'change',
				{
					$origin: $node,
					$mirror: $html,
					$options: $options,
					multiple: multiple
				},
				function(event){
					var $node = $(this),
						value = $node.val(),
						text = $node.find('option[value="' + value + '"]').html(),
						$origin = event.data.$origin,
						$mirror = event.data.$mirror,
						$options = event.data.$options,
						multiple = event.data.multiple;

					if(!multiple){
						$mirror.data('value', value)
							.find('.cform-control')
								.html(text);

						$options.removeClass('selected')
							.filter('[data-value="' + value + '"]')
							.addClass('selected');
					}else{
						var value_array = $origin.val()?$origin.val():[],
							i = 0;
						$mirror.data('value', value_array);

						$options.removeClass('selected');

						for(i = 0; i < value_array.length; i++){
							$options.filter('[data-value="' + value_array[i] + '"]')
								.addClass('selected')
						};
					}
				}
			)

			// adds the option-list-html to the cForm element
			$html.find('ul').append($options);

			base.addToDom($node, $html);
        };

        /**
         * adds an jQuery-Element to the DOM
         * and hides the connected element
         *
         * @param {object} $node jQuery-Element (original)
         * @param {object} $html Query-Element (cForm)
         */
        base.addToDom = function($node, $html) {
			$node.addClass('cform-hidden').after($html);
        };

        /* *** HELPER *** */

		/**
		 * return the tag name of an html-tag (in lower-case)
		 *
		 * @param  {string} $element html-tag as string
		 * @return {string}          name of the html-tag
		 */
        base.tagName = function($element) {
  			return $element.prop("tagName").toLowerCase();
		};

        /* *** RUN THE PLUGIN *** */

        base.init();
    };

    $.cForm.defaultOptions = {
    	templates:		{	// html templates for the differnet form fields
    		text:      		'

',
    		textarea:      	'

',
    		password:   	'

',
    		file:   		'
\

choose file
\

 here
\

',
    		checkbox:		'
\

\

',
    		radio:			'
\

\

',
    		select: 		'
\

{{text}}
\

\

',
    		multiselect: '
\

\

',
    		option: 		'
{{text}}
',
    		button: 		'

',
    		submit: 		'

',
    	}
    };

    $.fn.cForm = function(options){
        return this.each(function(){
            (new $.cForm(this, options));
        });
    };

})(jQuery);<commit_msg>ADD some comments<commit_after>(function($){
    $.cForm = function(element, options){
        var base = this;

        // Access to jQuery and DOM versions of element
        base.$element = $(element);
        base.element = element;

        // Add a reverse reference to the DOM object
        base.$element.data("cForm", base);

        base.init = function(){
            base.options = $.extend({},$.cForm.defaultOptions, options);

            // elements which will be styled
            var filter = ['input', 'textarea', 'select', 'button'];

            // initialize a array for radio groups
        	base.radioGroupArray = [];

            // check if the called element a wrapper or a form-element
            // invoce the corresponding functions
            if(base.$element.is(filter.join())){
            	var tag = base.tagName(base.$element);

            	if(tag === 'input') 	base.handleInput(base.$element);
            	if(tag === 'select') 	base.handleSelect(base.$element);
            	if(tag === 'button') 	base.handleButton(base.$element);
            	if(tag === 'textarea') 	base.handleTextarea(base.$element);
            } else {
            	base.$element.find('input').each(function(){
            		base.handleInput($(this));
            	});
            	base.$element.find('select').each(function(){
            		base.handleSelect($(this));
            	});
            	base.$element.find('button').each(function(){
            		base.handleButton($(this));
            	});
            	base.$element.find('textarea').each(function(){
            		base.handleTextarea($(this));
            	});
            }
        };

		/**
		 * handles the BUTTON conversion
		 *
		 * @param  {object} $node jQuery-Element // BUTTON
		 */
        base.handleButton = function($node) {
        	var template = $.cForm.defaultOptions.templates['button'];
        	$node.wrap(template);
        };

		/**
		 * handles the TEXTAREA conversion
		 *
		 * @param  {object} $node jQuery-Element // TEXTAREA
		 */
        base.handleTextarea = function($node) {
        	var template = $.cForm.defaultOptions.templates['textarea'];
        	$node.wrap(template);
        };

		/**
		 * handles the INPUT conversion
		 *
		 * @param  {object} $node jQuery-Element // INPUT
		 */
        base.handleInput = function($node){
        	var type = $node.attr('type'),
        		name = $node.attr('name'),
        		value = $node.attr('value'),
        		checked = $node.attr('checked'),
        		template = '',
        		$html = $();

        	// check for input type
            if (typeof type === typeof undefined && type === false) {
				console.log('Error: Missing type-Attribute on input!');
				return false;
			}
			if (typeof name === typeof undefined && name === false) {
				name = '';
			}
			if (typeof value === typeof undefined && value === false) {
				value = '';
			}
			if (typeof checked === typeof undefined && checked === false) {
				checked = '';
			}

			template = $.cForm.defaultOptions.templates[type];

			switch(type) {
			    case 'password':
			    case 'text':
			    	$node.wrap(template);
			        break;
			    case 'file':
					$html = $(template.replace('{{name}}',name));

			    	// when the cForm file button gets clicked
			    	// trigger the original file button
					$html.bind('click',
						{
							$node: $node
						},
						function (event) {
							var $node = event.data.$node;
								$node.trigger('click');
						}
					);

					// when the original file input gets changed (gets a file)
					// update the cForm file input as well
					$node.bind(
						'change',
						{
							$html: $html
						},
						function (event) {
							var filename = $(this).val().split('\\').pop(),
								$html = event.data.$html;

							$html.addClass('filled')
								.find('.cform-filename')
									.text(filename);
						}
					);
			    	break;
			    case 'checkbox':
			    	$html = $(template.replace('{{name}}',name).replace('{{value}}',value));

			    	if(checked || checked === 'checked'){
			    		$html.addClass('checked')
			    			.data('checked', true);
			    	}

			    	// when the cForm checkbox gets clicked, change its style/values
			    	// change the original checkbox as well
			    	$html.bind(
			    		'click',
			    		{
			    			$origin: $node
			    		},
			    		function(event){
			    			var $node = $(this),
			    				$origin = event.data.$origin,
			    				checked = $node.data('checked');

			    			if(checked){
			    				$origin.prop('checked', false);
			    				$node.removeClass('checked')
			    					.data('checked', false);
			    			}else{
			    				$origin.prop('checked', true);
			    				$node.addClass('checked')
			    					.data('checked', true);
			    			}
			    		}
			    	);

			    	// when the original checkbox gets changed via js or other means
			    	// update the cForm checkbox as well
			    	$node.bind(
			    		'change',
			    		{
			    			$mirror: $html
			    		},
			    		function(event){
			    			var $node = $(this),
			    				$mirror = event.data.$mirror;

			    			if($node.prop('checked')){
			    				$mirror.addClass('checked')
			    					.data('checked', true);
			    			}else{
								$mirror.removeClass('checked')
			    					.data('checked', false);
			    			}
			    		}
			    	);
			        break;
			    case 'radio':
			    	// for each radio group (= same name)
			    	// we want do this just once!
			    	if(base.radioGroupArray.indexOf(name) > -1){
			    		break;
			    	}
			    	base.radioGroupArray.push(name);
			    	var $mirrors = $();

			    	// get all radios with the same name and iterate
			    	// create html and insert, also hide the original
			    	$nodes = base.$element.find('input[type="radio"][name="' + name + '"]');
			    	$nodes.each(function(){
			    		var $node = $(this),
			    			value = $node.val(),
							checked = $node.attr('checked'),
							$html = $();

			    		$html = $(template.replace('{{name}}', name).replace('{{value}}', value));

						checked && $html.addClass('checked').data('checked', 'true');

						$mirrors = $mirrors.add($html);
						$node.addClass('hidden').after($html);
			    	});

			    	// when a cForm radio gets clicked, change its style/values
			    	// change the original radio as well
					$mirrors.bind(
						'click',
						{
							$mirrors: $mirrors,
							$origins: $nodes
						},
						function(event){
							var $node = $(this),
								$mirrors = event.data.$mirrors,
								$origins = event.data.$origins,
								value = $node.data('value');

							if($node.data('checked')) return true;

							$mirrors.removeClass('checked')
								.data('checked', false);
							$node.addClass('checked')
								.data('checked', true);
							$origins.prop('checked', true)
								.filter('[value="' + value + '"]')
								.prop('checked', true);
						}
					);

			    	// when the original radio group gets changed via js or other means
			    	// update the cForm radio group as well
					$nodes.bind(
						'change',
						{
							$mirrors: $mirrors,
							$origins: $nodes
						},
						function(event){
							var $node = $(this),
								$mirrors = event.data.$mirrors,
								$origins = event.data.$origins,
								value = $node.val();

							if($node.data('checked')) return true;

							$mirrors.removeClass('checked')
								.data('checked', false)
								.filter('[data-value="' + value + '"]')
									.data('checked', true)
									.addClass('checked');
						}
					);
			        break;
			    case 'submit':
			    	$node.wrap(template);
			        break;
			    default:
					console.log('Error: No matching was found - You will be forever alone!');
			}

			base.addToDom($node, $html);
        };

       	/**
		 * handles the SELECT conversion
		 *
		 * @param  {object} $node jQuery-Element // SELECT
		 */
        base.handleSelect = function($node){
        	var name = $node.attr('name'),
        		value = $node.attr('value'),
        		multiple = $node.attr('multiple'),
        		$subnodes = $node.find('option'),
        		$selected = $subnodes.filter(':selected'),
        		template = '',
        		$options = $(),
        		$html = $();

			if (typeof name === typeof undefined && name === false) {
				name = '';
			}
			if (typeof value === typeof undefined && value === false) {
				value = '';
			}
			if (typeof multiple === typeof undefined || multiple === false) {
				multiple = false;
				template = $.cForm.defaultOptions.templates['select'];
				$html = $(template.replace('{{name}}', name)
							.replace('{{text}}', $selected.html()));
			}else{
				multiple = true;
				template = $.cForm.defaultOptions.templates['multiselect'];
				$html = $(template.replace('{{name}}', name));
			}

			// create and populate the option list
			$subnodes.each(function(index){
				var $node = $(this),
					cssclass = $node.prop('selected')?'selected':'',
					template = $.cForm.defaultOptions.templates['option'];

				template = template.replace('{{value}}', $node.val())
								.replace('{{text}}', $node.html());

				$options = $options.add($(template).addClass(cssclass));
			});

			// when a cForm select-option gets clicked, change its style/values
			// change the original select/option as well
			$options.bind(
				'click',
				{
					$origin: $node,
					$mirror: $html,
					$options: $options,
					multiple: multiple
				},
				function (event) {
					var $node = $(this),
						$origin = event.data.$origin,
						$mirror = event.data.$mirror,
						$options = event.data.$options,
						multiple = event.data.multiple,
						value = $node.data('value'),
						text = $node.html();

					if(!multiple){
						$options.not($node).removeClass('selected');
						$node.addClass('selected');

						$origin.val(value);

						$mirror.data('value', value)
							.find('.cform-control')
								.html(text);
					}else{
						var value_array = [];
						if($node.hasClass('selected')){
							value_array = $origin.val();
							value_array.splice(value_array.indexOf(value), 1);

							$origin.val(value_array);
							$mirror.data('value', value_array);
							$node.removeClass('selected');
						}else{
							value_array = $origin.val()?$origin.val():[];
							value_array.push(value);

							$origin.val(value_array);
							$mirror.data('value', value_array);
							$node.addClass('selected');
						}
					}
				}
			);

			// when the original select gets changed via js or other means
			// update the cForm select/options as well
			$node.bind(
				'change',
				{
					$origin: $node,
					$mirror: $html,
					$options: $options,
					multiple: multiple
				},
				function(event){
					var $node = $(this),
						value = $node.val(),
						text = $node.find('option[value="' + value + '"]').html(),
						$origin = event.data.$origin,
						$mirror = event.data.$mirror,
						$options = event.data.$options,
						multiple = event.data.multiple;

					if(!multiple){
						$mirror.data('value', value)
							.find('.cform-control')
								.html(text);

						$options.removeClass('selected')
							.filter('[data-value="' + value + '"]')
							.addClass('selected');
					}else{
						var value_array = $origin.val()?$origin.val():[],
							i = 0;
						$mirror.data('value', value_array);

						$options.removeClass('selected');

						for(i = 0; i < value_array.length; i++){
							$options.filter('[data-value="' + value_array[i] + '"]')
								.addClass('selected')
						};
					}
				}
			)

			// adds the option-list-html to the cForm element
			$html.find('ul').append($options);

			base.addToDom($node, $html);
        };

        /**
         * adds an jQuery-Element to the DOM
         * and hides the connected element
         *
         * @param {object} $node jQuery-Element (original)
         * @param {object} $html Query-Element (cForm)
         */
        base.addToDom = function($node, $html) {
			$node.addClass('cform-hidden').after($html);
        };

        /* *** HELPER *** */

		/**
		 * return the tag name of an html-tag (in lower-case)
		 *
		 * @param  {string} $element html-tag as string
		 * @return {string}          name of the html-tag
		 */
        base.tagName = function($element) {
  			return $element.prop("tagName").toLowerCase();
		};

        /* *** RUN THE PLUGIN *** */

        base.init();
    };

    $.cForm.defaultOptions = {
    	templates:		{	// html templates for the differnet form fields
    		text:      		'

',
    		textarea:      	'

',
    		password:   	'

',
    		file:   		'
\

choose file
\

 here
\

',
    		checkbox:		'
\

\

',
    		radio:			'
\

\

',
    		select: 		'
\

{{text}}
\

\

',
    		multiselect: '
\

\

',
    		option: 		'
{{text}}
',
    		button: 		'

',
    		submit: 		'

',
    	}
    };

    $.fn.cForm = function(options){
        return this.each(function(){
            (new $.cForm(this, options));
        });
    };

})(jQuery);<|endoftext|>


<commit_before>angular.module('webui.services.rpc.helpers', [
  'webui.services.deps', 'webui.services.rpc', 'webui.services.alerts'
])
.factory('$rpchelpers', ['$_', '$rpc', '$alerts', function(_, rpc, alerts) {
  var miscellaneous = {version: '', enabledFeatures: []};
  rpc.once('getVersion', [], function(data) { miscellaneous = data[0]});
  return {
    isFeatureEnabled: function(feature) {
      return miscellaneous.enabledFeatures.indexOf(feature) != -1;
    },
    getAria2Version: function() {
      return miscellaneous.version;
    },
    addUris: function(uris, settings, cb) {
      _.each(uris, function(uri) {
        uri_parsed = [];
        // parse options passed in the URIs. E.g. http://ex1.com/f1.jpg --out=image.jpg --check-integrity
        _.each(uri, function(uri_element) {
          if (uri_element.startsWith('--')) {
            uri_options = uri_element.split(/--|=(.*)/);
            if (uri_options.length > 2) {
              settings[uri_options[2]] = uri_options[3] || 'true';
            }
          }
          else {
            uri_parsed.push(uri_element);
          }
        });
        // passing true to batch all the addUri calls
        rpc.once('addUri', [uri_parsed, settings], cb, true);
      });

      // now dispatch all addUri syscalls
      rpc.forceUpdate();
    },
    addTorrents: function(txts, settings, cb) {
      _.each(txts, function(txt) {
        // passing true to batch all the addUri calls
        rpc.once('addTorrent', [txt, [], settings], cb, true);
      });

      // now dispatch all addUri syscalls
      rpc.forceUpdate();
    },
    addMetalinks: function(txts, settings, cb) {
      _.each(txts, function(txt) {
        // passing true to batch all the addUri calls
        rpc.once('addMetalink', [txt, settings], cb, true);
      });

      // now dispatch all addUri syscalls
      rpc.forceUpdate();
    }
  };
}]);
<commit_msg>fixed addUris settings bug<commit_after>angular.module('webui.services.rpc.helpers', [
  'webui.services.deps', 'webui.services.rpc', 'webui.services.alerts'
])
.factory('$rpchelpers', ['$_', '$rpc', '$alerts', function(_, rpc, alerts) {
  var miscellaneous = {version: '', enabledFeatures: []};
  rpc.once('getVersion', [], function(data) { miscellaneous = data[0]});
  return {
    isFeatureEnabled: function(feature) {
      return miscellaneous.enabledFeatures.indexOf(feature) != -1;
    },
    getAria2Version: function() {
      return miscellaneous.version;
    },
    addUris: function(uris, settings, cb) {
      _.each(uris, function(uri) {
        uri_parsed = [];
        // parse options passed in the URIs. E.g. http://ex1.com/f1.jpg --out=image.jpg --check-integrity
        var uriSettings = _.cloneDeep(settings);
        _.each(uri, function(uri_element) {
          if (uri_element.startsWith('--')) {
            uri_options = uri_element.split(/--|=(.*)/);
            if (uri_options.length > 2) {
              uriSettings[uri_options[2]] = uri_options[3] || 'true';
            }
          }
          else {
            uri_parsed.push(uri_element);
          }
        });
        // passing true to batch all the addUri calls
        rpc.once('addUri', [uri_parsed, uriSettings], cb, true);
      });

      // now dispatch all addUri syscalls
      rpc.forceUpdate();
    },
    addTorrents: function(txts, settings, cb) {
      _.each(txts, function(txt) {
        // passing true to batch all the addUri calls
        rpc.once('addTorrent', [txt, [], settings], cb, true);
      });

      // now dispatch all addUri syscalls
      rpc.forceUpdate();
    },
    addMetalinks: function(txts, settings, cb) {
      _.each(txts, function(txt) {
        // passing true to batch all the addUri calls
        rpc.once('addMetalink', [txt, settings], cb, true);
      });

      // now dispatch all addUri syscalls
      rpc.forceUpdate();
    }
  };
}]);
<|endoftext|>


<commit_before>function index(res, req) {
	console.log("Request handler 'welcome' was called.");
	var data = {};
	data.hello = "hello";
	data.pageTitle = '<script>alert(1)</script>';
	data._CSSLinks = ['home', 'pages/main'];
	this.render(res, req, 'welcome.html', data);
}

exports.index = index;<commit_msg>add new controller<commit_after>function index(res, req) {
	console.log("Request handler 'welcome' was called.");
	var data = {};
	data.hello = "hello";
	data.pageTitle = '<script>alert(1)</script>';
	data._CSSLinks = ['home', 'pages/main'];
	this.render(res, req, 'welcome.html', data);
}
function h(res, req) {
	console.log(this)
	console.log("Request handler 'welcome' was called.");
	var data = {};
	data.hello = "hello";
	data.pageTitle = '<script>alert(1)</script>';
	data._CSSLinks = ['home', 'pages/main'];
	this.render(res, req, 'welcome.html', data);
}

exports.index = index;
exports.h = h;<|endoftext|>


<commit_before>var simulateMouseEvent;

simulateMouseEvent = function(elm, type, button, other) {
  var evt, key, properties, val;
  if (type == null) {
    type = 'click';
  }
  if (button == null) {
    button = 0;
  }
  if (other == null) {
    other = {};
  }
  properties = {
    type: 'click',
    canBubble: true,
    cancelable: true,
    view: window,
    detail: 0,
    screenX: 0,
    screenY: 0,
    clientX: 0,
    clientY: 0,
    ctrlKey: false,
    altKey: false,
    shiftKey: false,
    metaKey: false,
    button: 0,
    relatedTarget: null
  };
  other.type = type;
  other.button = (function() {
    switch (button) {
      case 'left':
        return 0;
      case 'middle':
        return 1;
      case 'right':
        return 2;
      default:
        return button;
    }
  })();
  for (key in other) {
    val = other[key];
    properties[key] = val;
  }
  evt = document.createEvent('MouseEvents');
  evt.initMouseEvent(properties.type, properties.canBubble, properties.cancelable, properties.view, properties.detail, properties.screenX, properties.screenY, properties.clientX, properties.clientY, properties.ctrlKey, properties.altKey, properties.shiftKey, properties.metaKey, properties.button, properties.relatedTarget);
  return elm.dispatchEvent(evt);
};
<commit_msg>Removed obsolete directory<commit_after><|endoftext|>


<commit_before>const poplar = require('poplar')
const userAPI = new poplar.ApiBuilder('test2')
const userModel = require('../../../models/user/user')
const userEntity = require('../../../models/user/user_entity')

/**
 * not supported:
* { arg: 'body', type: ['object'], description: '文章内容（图文混排）' }
* { arg: 'str', type: [['string']], description: '文章内容（图文混排）' }
*/
userAPI.define('getindex', {
  description: 'test api index action',
  accepts: [
    { arg: 'name', type: 'string', description: '名称' },
    { arg: 'index', type: 'number', description: '索引', default: 1, required: true },
    { arg: 'images', type: ['string'], description: '图片数组', validates: { required: true } },
  ],
  notes: { schema: userModel.schema , entity: userEntity },
  http: { path: '', verb: 'get' }
}, function (params, cb) {
  cb(null, "hello world")
})

userAPI.define('postindex', {
  description: 'test api index action',
  accepts: [
    { arg: 'name', type: 'string', description: '名称', required: true },
    { arg: 'index', type: 'number', description: '索引', default: 1, required: true },
    { arg: 'images', type: ['string'], description: '图片数组', validates: { required: true } },
  ],
  http: { path: '', verb: 'post' }
}, function (params, cb) {
  cb(null, "hello world")
})

userAPI.define('foorbar', {
  description: 'test path templating action',
  accepts: [
    { arg: 'bar', type: 'string', description: 'barbar', required: true }
  ],
  http: { path: 'foo/:bar', verb: 'get' }
}, function (params, cb) {
  cb(null, "hello world")
})

userAPI.define('deleteuser', {
  description: 'test path templating action',
  accepts: [
    { arg: 'id', type: 'string', description: 'user id', required: true }
  ],
  http: { path: 'user/:id', verb: 'delete' }
}, function (params, cb) {
  cb(null, "hello world")
})

userAPI.define('patchuser', {
  description: 'test path templating action',
  accepts: [
    { arg: 'id', type: 'string', description: 'user id', required: true },
    { arg: 'name', type: 'string', description: 'user name' },
    { arg: 'email', type: 'string', description: 'user email', required: true },
  ],
  http: { path: 'user/:id', verb: 'patch' }
}, function (params, cb) {
  cb(null, "hello world")
})

// userAPI.
module.exports = userAPI<commit_msg>remove useless test case<commit_after><|endoftext|>


<commit_before>UI.once('init', function(){
	var UI = this
	  , messages = new MessageList()
	  , newline = Util.Text.newlineMatcher
	  , last_line = null
	  , msgs = [];

	// Clicking on username appends @username to the input
	$('#message_list').click(function(e){
		var name = $(e.target).data('data-uname');
		if(name){
			var input = $('#message'),
			val = input.val().trim();
			val += ' @' + name.split(' ')[0];
			val = val.trim() + ' ';
			input.val(val).focus();
			input.get(0).selectionStart =
			input.get(0).selectionEnd = val.length;
		}
	})

	function prepareMessageElement(el, data){
		var text = '' + data.msg, first;
		text
			.split(newline)
			.forEach(function(line){
				var wrap = $('
');
				first = first || wrap;
				//todo check for user element that enables or disables profanity
				line = Util.Text.wordFilter(line);
				el.append(linkifyAndInsert(wrap, line));
			});

		el.addClass('msg');

		first.append(timestamp(data));
		return el;
	}

	function linkifyAndInsert(el, text){
		if(Util.Text.linkifyTest(text)){
			//escape <,> so we don't include any nasty html tags
			text = text.replace(/</g, '<').replace(/>/g,'>');
			el.html(Util.Text.linkify(text));
		}
		else
			el.text(text);
		return el;
	}

	function timestamp(data){
		if(!data.t) return;

		var ts = $('
'),
		    date = new Date(data.t),
		    time = Util.date(date) + " " + Util.time(date);

		ts.addClass('ts');
		ts.text(time);
		return ts;
	}

	function pruneOldMessages(){
		var num_to_remove = msgs.length - WOMPT.messages.max_shown;

		if(num_to_remove <=0) return;

		for(var i=0; i < num_to_remove; i++){
			var msg = msgs[i], next = msgs[i+1];
			if(msg.from.id == next.from.id){
				next.nick.text(next.from.name);
				next.nick.css('color', UI.Colors.forUser(next.from.id));
				next.nick.addClass('name');
				next.line.addClass('first');
			}
			msg.line.remove();
		}

		msgs.splice(0,num_to_remove);
	}

	function firstMessageInGroup(msg){
		msg.nick.text(msg.from.name);
		if(msg.from.id != 'system'){
			msg.nick.css('color', UI.Colors.forUser(msg.from.id));
			msg.nick.data('data-uname', msg.from.name);
		}
		msg.nick.addClass('name');
		msg.line.addClass('first');
	}

	UI.Messages = {
		list:messages,

		actions:{
			message: function(data){
				UI.emit('before_append', data);
				UI.Messages.appendWithoutEvents(data);
				UI.emit('after_append', data);
				UI.emit('user_message', data);
			},

			batch: function(msg){
				UI.emit('before_append', msg.messages);
				UI.muteEvents(function(){
					$.each(msg.messages, function(i,m){
						if(m.action == 'message'){
							UI.Messages.appendWithoutEvents(m);
							UI.emit('user_message', m);
						} else
							UI.Messages.newMessage(m);
					});
				});
				UI.emit('after_append', msg.messages);
			}
		},

		newMessage: function(msg){
			var action = UI.Messages.actions[msg.action];
			if(action) action(msg);
		},

		appendWithoutEvents: function(data){
			var same_person = last_line && (last_line.from.id == data.from.id),
				line = $('
'),
				nick = $(''),
				msg_container  = $('');

			if(data.from.id == 'system'){
				line.addClass('system');
				msg_container.attr('colspan', 2);
				line.append(msg_container);
			}else
				line.append(nick, msg_container);

			line.addClass('line');
			prepareMessageElement(msg_container, data);

			if(Util.Text.mentionMatcher(data.msg)){
				line.addClass('mention');
			}

			data.line = line;
			data.nick = nick;
			last_line = data;

			if(!same_person) firstMessageInGroup(data);

			$('#message_list').append(line);
			msgs.push(data);
			pruneOldMessages();
			return line;
		},

		system: function(msg){
			UI.emit('before_append', msg);
			var line = UI.Messages.appendWithoutEvents({from:{id:'system'}, msg:msg, t:Util.ts()});
			UI.emit('after_append', msg);
			UI.emit('system_message', msg);
			return line;
		}
	}
});
<commit_msg>Improve message escaping<commit_after>UI.once('init', function(){
	var UI = this
	  , messages = new MessageList()
	  , newline = Util.Text.newlineMatcher
	  , last_line = null
	  , msgs = [];

	// Clicking on username appends @username to the input
	$('#message_list').click(function(e){
		var name = $(e.target).data('data-uname');
		if(name){
			var input = $('#message'),
			val = input.val().trim();
			val += ' @' + name.split(' ')[0];
			val = val.trim() + ' ';
			input.val(val).focus();
			input.get(0).selectionStart =
			input.get(0).selectionEnd = val.length;
		}
	})

	function prepareMessageElement(el, data){
		var text = '' + data.msg, first;
		text
			.split(newline)
			.forEach(function(line){
				var wrap = $('
');
				first = first || wrap;
				//todo check for user element that enables or disables profanity
				line = Util.Text.wordFilter(line);
				el.append(linkifyAndInsert(wrap, line));
			});

		el.addClass('msg');

		first.append(timestamp(data));
		return el;
	}

	function linkifyAndInsert(el, text){
		if(Util.Text.linkifyTest(text)){
			//escape [<, >, ', ", &] so we don't include any nasty html tags
			text = text
          .replace(/'/g, ''')
          .replace(/"/g, '"')
          .replace(/&/g, '&')
          .replace(/</g, '<')
          .replace(/>/g,'>');
			el.html(Util.Text.linkify(text));
		}
		else
			el.text(text);
		return el;
	}

	function timestamp(data){
		if(!data.t) return;

		var ts = $('
'),
		    date = new Date(data.t),
		    time = Util.date(date) + " " + Util.time(date);

		ts.addClass('ts');
		ts.text(time);
		return ts;
	}

	function pruneOldMessages(){
		var num_to_remove = msgs.length - WOMPT.messages.max_shown;

		if(num_to_remove <=0) return;

		for(var i=0; i < num_to_remove; i++){
			var msg = msgs[i], next = msgs[i+1];
			if(msg.from.id == next.from.id){
				next.nick.text(next.from.name);
				next.nick.css('color', UI.Colors.forUser(next.from.id));
				next.nick.addClass('name');
				next.line.addClass('first');
			}
			msg.line.remove();
		}

		msgs.splice(0,num_to_remove);
	}

	function firstMessageInGroup(msg){
		msg.nick.text(msg.from.name);
		if(msg.from.id != 'system'){
			msg.nick.css('color', UI.Colors.forUser(msg.from.id));
			msg.nick.data('data-uname', msg.from.name);
		}
		msg.nick.addClass('name');
		msg.line.addClass('first');
	}

	UI.Messages = {
		list:messages,

		actions:{
			message: function(data){
				UI.emit('before_append', data);
				UI.Messages.appendWithoutEvents(data);
				UI.emit('after_append', data);
				UI.emit('user_message', data);
			},

			batch: function(msg){
				UI.emit('before_append', msg.messages);
				UI.muteEvents(function(){
					$.each(msg.messages, function(i,m){
						if(m.action == 'message'){
							UI.Messages.appendWithoutEvents(m);
							UI.emit('user_message', m);
						} else
							UI.Messages.newMessage(m);
					});
				});
				UI.emit('after_append', msg.messages);
			}
		},

		newMessage: function(msg){
			var action = UI.Messages.actions[msg.action];
			if(action) action(msg);
		},

		appendWithoutEvents: function(data){
			var same_person = last_line && (last_line.from.id == data.from.id),
				line = $('
'),
				nick = $(''),
				msg_container  = $('');

			if(data.from.id == 'system'){
				line.addClass('system');
				msg_container.attr('colspan', 2);
				line.append(msg_container);
			}else
				line.append(nick, msg_container);

			line.addClass('line');
			prepareMessageElement(msg_container, data);

			if(Util.Text.mentionMatcher(data.msg)){
				line.addClass('mention');
			}

			data.line = line;
			data.nick = nick;
			last_line = data;

			if(!same_person) firstMessageInGroup(data);

			$('#message_list').append(line);
			msgs.push(data);
			pruneOldMessages();
			return line;
		},

		system: function(msg){
			UI.emit('before_append', msg);
			var line = UI.Messages.appendWithoutEvents({from:{id:'system'}, msg:msg, t:Util.ts()});
			UI.emit('after_append', msg);
			UI.emit('system_message', msg);
			return line;
		}
	}
});
<|endoftext|>


<commit_before>var camera, scene, renderer, width, height, clock, orbitControl, fpsStats, intersectedObject;
var objects = [];
var fans = [];
var raycaster = new THREE.Raycaster();
var mouse = new THREE.Vector2();

var hoverFanColor = 0xD88080;
var editFanColor = 0x00FF00;
var normalFanColor = 0xB20000;

init();
animate();

function init() {
	//Loads physijs files, creates scene etc.

	Physijs.scripts.worker = '/js/external/physijs_worker.js';
	Physijs.scripts.ammo = '/js/external/ammo.js';

	window.addEventListener( 'resize', onWindowResize, false);

	width = document.getElementById('simulationContainer').offsetWidth;
	height = document.getElementById('simulationContainer').offsetHeight;

	fpsStats = new Stats();
	fpsStats.setMode(0);

	fpsStats.domElement.style.position = 'absolute';
	fpsStats.domElement.style.right = '0px';
	fpsStats.domElement.style.top = '0px';

	document.getElementById("simulationContainer").appendChild(fpsStats.domElement);

	renderer = new THREE.WebGLRenderer ( { antialias: true});
	renderer.setSize(width, height);
	document.getElementById("simulationContainer").appendChild(renderer.domElement);

	scene = new Physijs.Scene;

	scene.setGravity(new THREE.Vector3( 0, 12, 0));

	createObjects(50);

	createCase();

	createFan("intake", new THREE.Vector3(0, 100, -450));
	createFan("exhaust", new THREE.Vector3(0, 700, 450));

	camera = new THREE.PerspectiveCamera(45, width/height, 0.1, 10000);

	camera.position.x = 800;
	camera.position.y = 800;
	camera.position.z = -800;

	scene.add(camera);

	orbitControl = new THREE.OrbitControls(camera, document.getElementById('simulationContainer'));
	//orbitControl.enablePan = false;
	orbitControl.constraint.minDistance = 600;
	orbitControl.constraint.maxDistance = 2200;
	clock = new THREE.Clock();

	var skyboxGeometry = new THREE.CubeGeometry(9000, 9000, 9000);
	var skyboxMaterial = new THREE.MeshBasicMaterial({ color: 0x262B30, side: THREE.BackSide });
	var skybox = new THREE.Mesh(skyboxGeometry, skyboxMaterial);

	scene.add(skybox);

	var topLight = new THREE.DirectionalLight(0xffffff, 1);
	topLight.position.set(0, 1, 0);

	var bottomLight = new THREE.DirectionalLight(0xffffff, 0.5);
	bottomLight.position.set(0, -1, 0);

	scene.add(topLight);
	scene.add(bottomLight);

	var pointLightA = new THREE.PointLight(0xffffff, 0.75);
	pointLightA.position.set(0, -100, -400);

	var pointLightB = new THREE.PointLight(0xffffff, 0.75);
	pointLightB.position.set(-600, 0, -800);

	scene.add(pointLightA);
	scene.add(pointLightB);

	scene.add(new THREE.AxisHelper(200));

	renderer.domElement.addEventListener( 'mousemove', handleMouseMove, false );
	renderer.domElement.addEventListener( 'mousedown', handleMouseClick, false );
}

function animate() {
	//Animates/simulates scene

	fpsStats.begin();

	scene.simulate(); //Run physics simulation

	requestAnimationFrame(animate);
	var delta = clock.getDelta();
	orbitControl.update(delta);

	renderer.render(scene, camera);

	fpsStats.end();
}

function createObjects(numToCreate) {
	//Creates numToCreate random physics objects to be used in the simulation
	for (var i=0; i < numToCreate; i++) {

		var object;

		var randNum = Math.random();
		var matColor;

		if (randNum < 0.34) {
			matColor = 0xD9216A;
		} else if (randNum > 0.34 && randNum < 0.67) {
			matColor = 0x18ABDB;
		} else {
			matColor = 0x18DB3F;
		}

		var sphereGeometry = new THREE.SphereGeometry(10, 16, 16);

		var sphereMaterial = Physijs.createMaterial(
          new THREE.MeshLambertMaterial({
            color: matColor
          }),
	      0.3, // friction
	      1 // restitution
        );

		object = new Physijs.SphereMesh(sphereGeometry, sphereMaterial);

		object.position.set((( Math.random() - 0.5 ) * 280), (( Math.random() - 0.25) * 200), (( Math.random() - 3.5 ) * 200));

		object.addEventListener( 'collision', handleCollision );

		scene.add(object);

		objects.push(object);
	}
}

function createCase() {
	//Creates a 3D model of a computer case

	var caseGroup = new THREE.Object3D(); //Empty container to store each case plane in

	var caseMaterial = Physijs.createMaterial(
      	new THREE.MeshLambertMaterial({
			color: 0x5F6E7D
		}),
      	0.3, // friction
      	0.1 // restitution
    );

	var transparentMaterial = new THREE.MeshBasicMaterial({
	    opacity: 0.2,
	    color: 0x5F6E7D,
	    transparent: true,
	    side: THREE.DoubleSide
	});

	var componentMaterial = new THREE.MeshLambertMaterial({
		color: 0xD5D3D0
	})

	var caseWidth = 350;
	var caseHeight = 800;
	var caseLength = 900;
	var caseThickness = 4;
	var fanHoleSize = 200;

	var caseBottomGeometry = new THREE.CubeGeometry(caseWidth, caseThickness, caseLength);
	var caseTopGeometry = new THREE.CubeGeometry(caseWidth, caseThickness, caseLength);
	var caseVisibleSideGeometry = new THREE.CubeGeometry(caseThickness, caseHeight, caseLength);
	var caseInvisibleSideGeometry = new THREE.CubeGeometry(caseThickness, caseHeight, caseLength);
	var caseBackGeometry = new THREE.CubeGeometry(caseWidth, caseHeight - fanHoleSize, caseThickness);
	var caseFrontGeometry = new THREE.CubeGeometry(caseWidth, caseHeight - fanHoleSize, caseThickness);

	var gpuGeometry = new THREE.CubeGeometry(caseWidth - 100, 25, 375);

	var caseBottomPlane = new Physijs.BoxMesh(caseBottomGeometry, caseMaterial, 0); //Gravity, 0 = weightless
	var caseTopPlane = new Physijs.BoxMesh(caseTopGeometry, caseMaterial, 0); //Gravity, 0 = weightless
	var caseVisibleSidePlane = new Physijs.BoxMesh(caseVisibleSideGeometry, caseMaterial, 0); //Gravity, 0 = weightless
	var caseInvisibleSidePlane = new Physijs.BoxMesh(caseInvisibleSideGeometry, transparentMaterial, 0); //Gravity, 0 = weightless
	var caseBackPlane = new Physijs.BoxMesh(caseBackGeometry, caseMaterial, 0); //Gravity, 0 = weightless
	var caseFrontPlane = new Physijs.BoxMesh(caseFrontGeometry, caseMaterial, 0); //Gravity, 0 = weightless

	var gpuPlane = new Physijs.BoxMesh(gpuGeometry, componentMaterial, 0); //Gravity, 0 = weightless

	caseBottomPlane.position.set(0, 0, 0);

	caseTopPlane.position.set(0, caseHeight, 0);

	caseVisibleSidePlane.position.set(-caseWidth/2, caseHeight/2, 0);

	caseInvisibleSidePlane.position.set(caseWidth/2, caseHeight/2, 0);

	caseBackPlane.position.set(0, caseHeight/2 - (fanHoleSize/2), caseLength/2);

	caseFrontPlane.position.set(0, caseHeight/2 + (fanHoleSize/2), -caseLength/2);

	gpuPlane.position.set(-45, caseHeight/2 - 100, 200);

	scene.add(caseBottomPlane);
	scene.add(caseTopPlane);
	scene.add(caseVisibleSidePlane);
	scene.add(caseInvisibleSidePlane);
	scene.add(caseBackPlane);
	scene.add(caseFrontPlane);
	scene.add(gpuPlane);
}

function createFan(paramMode, position) {
	/*A fan is made up a of a fanObject with two sub-objects, a fanAOEObject representing the are of effect for a fan
	and the fanPhysicalObject, which is the physical fan the user sees*/

	var fan = new Object();

	fan.mode = paramMode;

	//------------------------CREATE FAN AOE OBJECT-----------------------//
	var fanAOEMaterial = new THREE.MeshLambertMaterial({
		opacity: 0,
	    color: normalFanColor,
	    transparent: true,
	    side: THREE.DoubleSide
	})

	var fanAOEGeometry = new THREE.CubeGeometry(350, 175, 400);
	var fanAOEObject = new Physijs.BoxMesh(fanAOEGeometry, fanAOEMaterial, 0); //Gravity, 0 = weightless

	fanAOEObject.position.set(position.x, position.y, position.z);
	fanAOEObject._physijs.collision_flags = 4;	//Allows collision detection, but doesn't affect velocity etc. of object colliding with it

	scene.add(fanAOEObject);
	//------------------------CREATE FAN AOE OBJECT-----------------------//

	//------------------------CREATE FAN PHYSICAL OBJECT-----------------------//

	//TODO: Create actual fan physical object here and assign it as a property of fan

	var fanPhysicalMaterial = new THREE.MeshLambertMaterial ({
		color: normalFanColor,
		side: THREE.DoubleSide
	})

	var fanPhysicalGeometry = new THREE.CubeGeometry(350, 200, 50);
	var fanPhysicalObject = new Physijs.BoxMesh(fanPhysicalGeometry, fanPhysicalMaterial, 0); //Gravity, 0 = weightless

	fanPhysicalObject.position.set(position.x, position.y, position.z);
	fanPhysicalObject._physijs.collision_flags = 4;	//Allows collision detection, but doesn't affect velocity etc. of object colliding with it

	scene.add(fanPhysicalObject);

	//------------------------CREATE FAN PHYSICAL OBJECT-----------------------//

	fan.fanAOEObject = fanAOEObject;
	fan.fanPhysicalObject = fanPhysicalObject;
	fan.id = fanPhysicalObject.id;
	fan.editing = false;
	fan.AOEWireframe = new THREE.EdgesHelper(fanAOEObject, 0x90DAFF);

	fans.push(fan);

	//Add component controller for this fan
	document.getElementById('tabbedPaneContainer').insertAdjacentHTML('beforeend', '<component-Settings id="' + fan.id +'"></component-Settings>');
}

function handleCollision(collided_with, linearVelocity, angularVelocity) {
	//Event gets called when physics objects (spheres) collide with another object
	for (var i = 0; i < fans.length; i++) {
		if (collided_with.id === fans[i].fanAOEObject.id) {
			//Collided with fan
			if ( fans[i].mode === "intake" ) {
				var forceVector = new THREE.Vector3(0, 50000, 700000); 	//Force/Impulse is quantified by units pushing in a 3 axis directions. NOTE: A really big number is needed to produce any noticeable affect
			} else if (fans[i].mode === "exhaust" ) {
				var forceVector = new THREE.Vector3(0, 0, 1000000); 	//Force/Impulse is quantified by units pushing in a 3 axis directions. NOTE: A really big number is needed to produce any noticeable affect
			}
			this.applyCentralImpulse(forceVector);
		}
	}
}

function handleMouseMove(event) {
	//When a user hovers on a fan change fan color to hover state only if we are NOT editing that fan

	var touchFan = detectTouchingFan(event);

	if (touchFan) {
		//Only change to hover color when we are NOT editing the current fan
		if (touchFan.editing == false) {
			touchFan.fanPhysicalObject.material.color.setHex(hoverFanColor);
		}
	} else {
		for (var i = 0; i < fans.length; i++) {
			//Only set fans that we are NOT editing to normal fan color
			if (fans[i].editing == false) {
				fans[i].fanPhysicalObject.material.color.setHex(normalFanColor);
			}
		}
	}
}

function handleMouseClick(event) {
	//When a user clicks on a fan, open the component control panel section and change fan color

	var touchFan = detectTouchingFan(event);

	//For peace of mind, reset all fans to not editing when we click
	for (var i = 0; i < fans.length; i++) {
		fans[i].editing = false;
		fans[i].fanPhysicalObject.material.color.setHex(normalFanColor);
		scene.remove(fans[i].AOEWireframe);
		document.getElementById(fans[i].id).style.color = "black";
	}

	//If we clicked on a fan, do stuff here
	if (touchFan) {
		touchFan.fanPhysicalObject.material.color.setHex(editFanColor);
		touchFan.editing = true;
		scene.add(touchFan.AOEWireframe);
		document.getElementById(touchFan.id).style.color = "red";	//Placeholder. When user clicks on the fan it's component section will display
	}
}

function detectTouchingFan(event) {
	//Returns a fanObject if the mouse is touching one, else nothing is returned

	//Have to normalise these coords so that they are between -1 and 1
	mouse.x = ( ( (event.clientX - document.getElementById('tabbedPaneContainer').offsetWidth) / width ) * 2 - 1); //Have to minus the tabbedPaneContainer width because oftherwise it would be included in the normalising to get X in terms of the canvas
	mouse.y = - ( event.clientY / height ) * 2 + 1;

	raycaster.setFromCamera( mouse, camera );

	//Isolate the fanPhysicalObjects from the root fan objects
	var fanPhysicalObjects = [];
	for (var i = 0; i < fans.length; i++) {
		fanPhysicalObjects.push(fans[i].fanPhysicalObject);
	}

	var intersects = raycaster.intersectObjects( fanPhysicalObjects, true );

	//If we have touched a fanPhysicalObject, return the root fanObject it belongs to
	if ( intersects.length > 0 ) {;
		for (var i = 0; i < fans.length; i++) {
			if (fans[i].fanPhysicalObject.id == intersects[0].object.id) {
				return fans[i];
			}
		}
	} else {
		return null;
	}
}

function restartSim() {
	//Removes all existing physics objects from the scene, then generates new physics objects
	for (var i=0; i < objects.length; i++) {
		 if(objects[i] != null) {
			scene.remove(objects[i]);
		}
	}
	createObjects(50);
}

function onWindowResize(){
	//Dynamically resizes renderer and camera when window is resized

	width = document.getElementById('simulationContainer').offsetWidth;
	height = document.getElementById('simulationContainer').offsetHeight;

    camera.aspect = width / height;
    camera.updateProjectionMatrix();

    renderer.setSize( width, height );

}

//TODO:
// - Maybe use an eventListener for when $scope changes instead of checking every update frame -> better for perfomance<commit_msg>Fixed bug where hover state was applied to multiple fans<commit_after>var camera, scene, renderer, width, height, clock, orbitControl, fpsStats, intersectedObject;
var objects = [];
var fans = [];
var raycaster = new THREE.Raycaster();
var mouse = new THREE.Vector2();

var hoverFanColor = 0xD88080;
var editFanColor = 0x00FF00;
var normalFanColor = 0xB20000;

init();
animate();

function init() {
	//Loads physijs files, creates scene etc.

	Physijs.scripts.worker = '/js/external/physijs_worker.js';
	Physijs.scripts.ammo = '/js/external/ammo.js';

	window.addEventListener( 'resize', onWindowResize, false);

	width = document.getElementById('simulationContainer').offsetWidth;
	height = document.getElementById('simulationContainer').offsetHeight;

	fpsStats = new Stats();
	fpsStats.setMode(0);

	fpsStats.domElement.style.position = 'absolute';
	fpsStats.domElement.style.right = '0px';
	fpsStats.domElement.style.top = '0px';

	document.getElementById("simulationContainer").appendChild(fpsStats.domElement);

	renderer = new THREE.WebGLRenderer ( { antialias: true});
	renderer.setSize(width, height);
	document.getElementById("simulationContainer").appendChild(renderer.domElement);

	scene = new Physijs.Scene;

	scene.setGravity(new THREE.Vector3( 0, 12, 0));

	createObjects(50);

	createCase();

	createFan("intake", new THREE.Vector3(0, 100, -450));
	createFan("exhaust", new THREE.Vector3(0, 700, 450));

	camera = new THREE.PerspectiveCamera(45, width/height, 0.1, 10000);

	camera.position.x = 800;
	camera.position.y = 800;
	camera.position.z = -800;

	scene.add(camera);

	orbitControl = new THREE.OrbitControls(camera, document.getElementById('simulationContainer'));
	//orbitControl.enablePan = false;
	orbitControl.constraint.minDistance = 600;
	orbitControl.constraint.maxDistance = 2200;
	clock = new THREE.Clock();

	var skyboxGeometry = new THREE.CubeGeometry(9000, 9000, 9000);
	var skyboxMaterial = new THREE.MeshBasicMaterial({ color: 0x262B30, side: THREE.BackSide });
	var skybox = new THREE.Mesh(skyboxGeometry, skyboxMaterial);

	scene.add(skybox);

	var topLight = new THREE.DirectionalLight(0xffffff, 1);
	topLight.position.set(0, 1, 0);

	var bottomLight = new THREE.DirectionalLight(0xffffff, 0.5);
	bottomLight.position.set(0, -1, 0);

	scene.add(topLight);
	scene.add(bottomLight);

	var pointLightA = new THREE.PointLight(0xffffff, 0.75);
	pointLightA.position.set(0, -100, -400);

	var pointLightB = new THREE.PointLight(0xffffff, 0.75);
	pointLightB.position.set(-600, 0, -800);

	scene.add(pointLightA);
	scene.add(pointLightB);

	scene.add(new THREE.AxisHelper(200));

	renderer.domElement.addEventListener( 'mousemove', handleMouseMove, false );
	renderer.domElement.addEventListener( 'mousedown', handleMouseClick, false );
}

function animate() {
	//Animates/simulates scene

	fpsStats.begin();

	scene.simulate(); //Run physics simulation

	requestAnimationFrame(animate);
	var delta = clock.getDelta();
	orbitControl.update(delta);

	renderer.render(scene, camera);

	fpsStats.end();
}

function createObjects(numToCreate) {
	//Creates numToCreate random physics objects to be used in the simulation
	for (var i=0; i < numToCreate; i++) {

		var object;

		var randNum = Math.random();
		var matColor;

		if (randNum < 0.34) {
			matColor = 0xD9216A;
		} else if (randNum > 0.34 && randNum < 0.67) {
			matColor = 0x18ABDB;
		} else {
			matColor = 0x18DB3F;
		}

		var sphereGeometry = new THREE.SphereGeometry(10, 16, 16);

		var sphereMaterial = Physijs.createMaterial(
          new THREE.MeshLambertMaterial({
            color: matColor
          }),
	      0.3, // friction
	      1 // restitution
        );

		object = new Physijs.SphereMesh(sphereGeometry, sphereMaterial);

		object.position.set((( Math.random() - 0.5 ) * 280), (( Math.random() - 0.25) * 200), (( Math.random() - 3.5 ) * 200));

		object.addEventListener( 'collision', handleCollision );

		scene.add(object);

		objects.push(object);
	}
}

function createCase() {
	//Creates a 3D model of a computer case

	var caseGroup = new THREE.Object3D(); //Empty container to store each case plane in

	var caseMaterial = Physijs.createMaterial(
      	new THREE.MeshLambertMaterial({
			color: 0x5F6E7D
		}),
      	0.3, // friction
      	0.1 // restitution
    );

	var transparentMaterial = new THREE.MeshBasicMaterial({
	    opacity: 0.2,
	    color: 0x5F6E7D,
	    transparent: true,
	    side: THREE.DoubleSide
	});

	var componentMaterial = new THREE.MeshLambertMaterial({
		color: 0xD5D3D0
	})

	var caseWidth = 350;
	var caseHeight = 800;
	var caseLength = 900;
	var caseThickness = 4;
	var fanHoleSize = 200;

	var caseBottomGeometry = new THREE.CubeGeometry(caseWidth, caseThickness, caseLength);
	var caseTopGeometry = new THREE.CubeGeometry(caseWidth, caseThickness, caseLength);
	var caseVisibleSideGeometry = new THREE.CubeGeometry(caseThickness, caseHeight, caseLength);
	var caseInvisibleSideGeometry = new THREE.CubeGeometry(caseThickness, caseHeight, caseLength);
	var caseBackGeometry = new THREE.CubeGeometry(caseWidth, caseHeight - fanHoleSize, caseThickness);
	var caseFrontGeometry = new THREE.CubeGeometry(caseWidth, caseHeight - fanHoleSize, caseThickness);

	var gpuGeometry = new THREE.CubeGeometry(caseWidth - 100, 25, 375);

	var caseBottomPlane = new Physijs.BoxMesh(caseBottomGeometry, caseMaterial, 0); //Gravity, 0 = weightless
	var caseTopPlane = new Physijs.BoxMesh(caseTopGeometry, caseMaterial, 0); //Gravity, 0 = weightless
	var caseVisibleSidePlane = new Physijs.BoxMesh(caseVisibleSideGeometry, caseMaterial, 0); //Gravity, 0 = weightless
	var caseInvisibleSidePlane = new Physijs.BoxMesh(caseInvisibleSideGeometry, transparentMaterial, 0); //Gravity, 0 = weightless
	var caseBackPlane = new Physijs.BoxMesh(caseBackGeometry, caseMaterial, 0); //Gravity, 0 = weightless
	var caseFrontPlane = new Physijs.BoxMesh(caseFrontGeometry, caseMaterial, 0); //Gravity, 0 = weightless

	var gpuPlane = new Physijs.BoxMesh(gpuGeometry, componentMaterial, 0); //Gravity, 0 = weightless

	caseBottomPlane.position.set(0, 0, 0);

	caseTopPlane.position.set(0, caseHeight, 0);

	caseVisibleSidePlane.position.set(-caseWidth/2, caseHeight/2, 0);

	caseInvisibleSidePlane.position.set(caseWidth/2, caseHeight/2, 0);

	caseBackPlane.position.set(0, caseHeight/2 - (fanHoleSize/2), caseLength/2);

	caseFrontPlane.position.set(0, caseHeight/2 + (fanHoleSize/2), -caseLength/2);

	gpuPlane.position.set(-45, caseHeight/2 - 100, 200);

	scene.add(caseBottomPlane);
	scene.add(caseTopPlane);
	scene.add(caseVisibleSidePlane);
	scene.add(caseInvisibleSidePlane);
	scene.add(caseBackPlane);
	scene.add(caseFrontPlane);
	scene.add(gpuPlane);
}

function createFan(paramMode, position) {
	/*A fan is made up a of a fanObject with two sub-objects, a fanAOEObject representing the are of effect for a fan
	and the fanPhysicalObject, which is the physical fan the user sees*/

	var fan = new Object();

	fan.mode = paramMode;

	//------------------------CREATE FAN AOE OBJECT-----------------------//
	var fanAOEMaterial = new THREE.MeshLambertMaterial({
		opacity: 0,
	    color: normalFanColor,
	    transparent: true,
	    side: THREE.DoubleSide
	})

	var fanAOEGeometry = new THREE.CubeGeometry(350, 175, 400);
	var fanAOEObject = new Physijs.BoxMesh(fanAOEGeometry, fanAOEMaterial, 0); //Gravity, 0 = weightless

	fanAOEObject.position.set(position.x, position.y, position.z);
	fanAOEObject._physijs.collision_flags = 4;	//Allows collision detection, but doesn't affect velocity etc. of object colliding with it

	scene.add(fanAOEObject);
	//------------------------CREATE FAN AOE OBJECT-----------------------//

	//------------------------CREATE FAN PHYSICAL OBJECT-----------------------//

	//TODO: Create actual fan physical object here and assign it as a property of fan

	var fanPhysicalMaterial = new THREE.MeshLambertMaterial ({
		color: normalFanColor,
		side: THREE.DoubleSide
	})

	var fanPhysicalGeometry = new THREE.CubeGeometry(350, 200, 50);
	var fanPhysicalObject = new Physijs.BoxMesh(fanPhysicalGeometry, fanPhysicalMaterial, 0); //Gravity, 0 = weightless

	fanPhysicalObject.position.set(position.x, position.y, position.z);
	fanPhysicalObject._physijs.collision_flags = 4;	//Allows collision detection, but doesn't affect velocity etc. of object colliding with it

	scene.add(fanPhysicalObject);

	//------------------------CREATE FAN PHYSICAL OBJECT-----------------------//

	fan.fanAOEObject = fanAOEObject;
	fan.fanPhysicalObject = fanPhysicalObject;
	fan.id = fanPhysicalObject.id;
	fan.editing = false;
	fan.AOEWireframe = new THREE.EdgesHelper(fanAOEObject, 0x90DAFF);

	fans.push(fan);

	//Add component controller for this fan
	document.getElementById('tabbedPaneContainer').insertAdjacentHTML('beforeend', '<component-Settings id="' + fan.id +'"></component-Settings>');
}

function handleCollision(collided_with, linearVelocity, angularVelocity) {
	//Event gets called when physics objects (spheres) collide with another object
	for (var i = 0; i < fans.length; i++) {
		if (collided_with.id === fans[i].fanAOEObject.id) {
			//Collided with fan
			if ( fans[i].mode === "intake" ) {
				var forceVector = new THREE.Vector3(0, 50000, 700000); 	//Force/Impulse is quantified by units pushing in a 3 axis directions. NOTE: A really big number is needed to produce any noticeable affect
			} else if (fans[i].mode === "exhaust" ) {
				var forceVector = new THREE.Vector3(0, 0, 1000000); 	//Force/Impulse is quantified by units pushing in a 3 axis directions. NOTE: A really big number is needed to produce any noticeable affect
			}
			this.applyCentralImpulse(forceVector);
		}
	}
}

function handleMouseMove(event) {
	//When a user hovers on a fan change fan color to hover state only if we are NOT editing that fan

	var touchFan = detectTouchingFan(event);

	//For peace of mind, reset all fans not being edited to normal fan color
	for (var i = 0; i < fans.length; i++) {
		if (fans[i].editing == false) {
			fans[i].fanPhysicalObject.material.color.setHex(normalFanColor);
		}
	}

	if (touchFan) {
		//Only change to hover color when we are NOT editing the current fan
		if (touchFan.editing == false) {
			touchFan.fanPhysicalObject.material.color.setHex(hoverFanColor);
		}
	}
}

function handleMouseClick(event) {
	//When a user clicks on a fan, open the component control panel section and change fan color

	var touchFan = detectTouchingFan(event);

	//For peace of mind, reset all fans to not editing when we click
	for (var i = 0; i < fans.length; i++) {
		fans[i].editing = false;
		fans[i].fanPhysicalObject.material.color.setHex(normalFanColor);
		scene.remove(fans[i].AOEWireframe);
		document.getElementById(fans[i].id).style.color = "black";
	}

	//If we clicked on a fan, do stuff here
	if (touchFan) {
		touchFan.fanPhysicalObject.material.color.setHex(editFanColor);
		touchFan.editing = true;
		scene.add(touchFan.AOEWireframe);
		document.getElementById(touchFan.id).style.color = "red";	//Placeholder. When user clicks on the fan it's component section will display
	}
}

function detectTouchingFan(event) {
	//Returns a fanObject if the mouse is touching one, else nothing is returned

	//Have to normalise these coords so that they are between -1 and 1
	mouse.x = ( ( (event.clientX - document.getElementById('tabbedPaneContainer').offsetWidth) / width ) * 2 - 1); //Have to minus the tabbedPaneContainer width because oftherwise it would be included in the normalising to get X in terms of the canvas
	mouse.y = - ( event.clientY / height ) * 2 + 1;

	raycaster.setFromCamera( mouse, camera );

	//Isolate the fanPhysicalObjects from the root fan objects
	var fanPhysicalObjects = [];
	for (var i = 0; i < fans.length; i++) {
		fanPhysicalObjects.push(fans[i].fanPhysicalObject);
	}

	var intersects = raycaster.intersectObjects( fanPhysicalObjects, true );

	//If we have touched a fanPhysicalObject, return the root fanObject it belongs to
	if ( intersects.length > 0 ) {;
		for (var i = 0; i < fans.length; i++) {
			if (fans[i].fanPhysicalObject.id == intersects[0].object.id) {
				return fans[i];
			}
		}
	} else {
		return null;
	}
}

function restartSim() {
	//Removes all existing physics objects from the scene, then generates new physics objects
	for (var i=0; i < objects.length; i++) {
		 if(objects[i] != null) {
			scene.remove(objects[i]);
		}
	}
	createObjects(50);
}

function onWindowResize(){
	//Dynamically resizes renderer and camera when window is resized

	width = document.getElementById('simulationContainer').offsetWidth;
	height = document.getElementById('simulationContainer').offsetHeight;

    camera.aspect = width / height;
    camera.updateProjectionMatrix();

    renderer.setSize( width, height );

}

//TODO:
// - Maybe use an eventListener for when $scope changes instead of checking every update frame -> better for perfomance<|endoftext|>


<commit_before>/*
 *  Copyright 2014 TWO SIGMA OPEN SOURCE, LLC
 *
 *  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.
 */

var helper = require('./helper.js');

var config = {
  seleniumAddress: 'http://localhost:4444/wd/hub',
  framework: 'jasmine2',
  allScriptsTimeout: 100000,
  restartBrowserBetweenTests: false,
  jasmineNodeOpts: {
    defaultTimeoutInterval: 100000,
    print: function() {}
  },
  capabilities: {
    shardTestFiles: true,
    maxInstances: 3,
    browserName: 'firefox'
  },
  getMultiCapabilities: helper.getFirefoxProfile,
  onPrepare: function() {
    var SpecReporter = require('jasmine-spec-reporter');
    jasmine.getEnv().addReporter(new SpecReporter({
        displayStacktrace: 'specs'
    }));
  },
  specs: [
    'tests/tutorials/groovy_plotting/category-plot-tutorial.js',
    'tests/tutorials/groovy_plotting/charting-tutorial.js',
    'tests/tutorials/groovy_plotting/plot-features-tutorial.js',
    'tests/tutorials/groovy_plotting/heatmap-tutorial.js',
    'tests/tutorials/groovy_plotting/treemap-tutorial.js',
    'tests/tutorials/groovy_plotting/histogram-tutorial.js',
    'tests/tutorials/groovy_plotting/levelsOfDetail-tutorial.js',
    'tests/tutorials/groovy_plotting/plotActions-tutorial.js',
    'tests/tutorials/language_demos/sql-tutorial.js',
    'tests/tutorials/language_demos/java-tutorial.js',
    'tests/tutorials/language_demos/groovy-tutorial.js',
    'tests/tutorials/language_demos/clojure-tutorial.js',
    'tests/tutorials/language_demos/python-tutorial.js',
    'tests/tutorials/language_demos/jscript-tutorial.js',
    'tests/tutorials/language_demos/R-tutorial.js',
    'tests/tutorials/language_demos/nodejs-tutorial.js',
    'tests/tutorials/table_display/tableGroovy-tutorial.js',
    'tests/tutorials/standard_visual_api/d3js-tutorial.js',
    'tests/tutorials/standard_visual_api/p5js-tutorial.js',
    'tests/tutorials/automate/progress-reporting-tutorial.js',
    'tests/tutorials/automate/notebookControl-tutorial.js',
    'tests/tutorials/automate/notebook-reflection-tutorial.js',
    'tests/tutorials/automate/dashboard-tutorial.js',
    'tests/tables.js',
    'tests/tutorials/native_plotting/jscriptPlot-tutorial.js',
    'tests/tutorials/feature_overview/autotranslation-tutorial.js',
    'tests/tutorials/feature_overview/codeReuse-tutorial.js',
    'tests/tutorials/feature_overview/beakerObject-tutorial.js',
    'tests/tutorials/feature_overview/outputContainer-tutorial.js',
    'tests/tutorials/feature_overview/bigIntegerTables-tutorial.js',
    'tests/tutorials/feature_overview/text-tutorial.js',
    'tests/badToStringTest.js'
  ]
};

exports.config = config;
<commit_msg>disable test<commit_after>/*
 *  Copyright 2014 TWO SIGMA OPEN SOURCE, LLC
 *
 *  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.
 */

var helper = require('./helper.js');

var config = {
  seleniumAddress: 'http://localhost:4444/wd/hub',
  framework: 'jasmine2',
  allScriptsTimeout: 100000,
  restartBrowserBetweenTests: false,
  jasmineNodeOpts: {
    defaultTimeoutInterval: 100000,
    print: function() {}
  },
  capabilities: {
    shardTestFiles: true,
    maxInstances: 3,
    browserName: 'firefox'
  },
  getMultiCapabilities: helper.getFirefoxProfile,
  onPrepare: function() {
    var SpecReporter = require('jasmine-spec-reporter');
    jasmine.getEnv().addReporter(new SpecReporter({
        displayStacktrace: 'specs'
    }));
  },
  specs: [
    'tests/tutorials/groovy_plotting/category-plot-tutorial.js',
    'tests/tutorials/groovy_plotting/charting-tutorial.js',
    'tests/tutorials/groovy_plotting/plot-features-tutorial.js',
    'tests/tutorials/groovy_plotting/heatmap-tutorial.js',
    'tests/tutorials/groovy_plotting/treemap-tutorial.js',
    'tests/tutorials/groovy_plotting/histogram-tutorial.js',
    'tests/tutorials/groovy_plotting/levelsOfDetail-tutorial.js',
    'tests/tutorials/groovy_plotting/plotActions-tutorial.js',
    'tests/tutorials/language_demos/sql-tutorial.js',
    'tests/tutorials/language_demos/java-tutorial.js',
    'tests/tutorials/language_demos/groovy-tutorial.js',
    'tests/tutorials/language_demos/clojure-tutorial.js',
    'tests/tutorials/language_demos/python-tutorial.js',
    'tests/tutorials/language_demos/jscript-tutorial.js',
    'tests/tutorials/language_demos/R-tutorial.js',
    'tests/tutorials/language_demos/nodejs-tutorial.js',
    'tests/tutorials/table_display/tableGroovy-tutorial.js',
    'tests/tutorials/standard_visual_api/d3js-tutorial.js',
    'tests/tutorials/standard_visual_api/p5js-tutorial.js',
    'tests/tutorials/automate/progress-reporting-tutorial.js',
    'tests/tutorials/automate/notebookControl-tutorial.js',
    'tests/tutorials/automate/notebook-reflection-tutorial.js',
    'tests/tutorials/automate/dashboard-tutorial.js',
    'tests/tables.js',
    'tests/tutorials/native_plotting/jscriptPlot-tutorial.js',
    'tests/tutorials/feature_overview/autotranslation-tutorial.js',
    'tests/tutorials/feature_overview/codeReuse-tutorial.js',
    'tests/tutorials/feature_overview/beakerObject-tutorial.js',
    'tests/tutorials/feature_overview/outputContainer-tutorial.js',
    'tests/tutorials/feature_overview/bigIntegerTables-tutorial.js',
    'tests/tutorials/feature_overview/text-tutorial.js'
   // 'tests/badToStringTest.js'
  ]
};

exports.config = config;
<|endoftext|>


<commit_before>import { ComplexNumber } from './complex-numbers.js';

describe('Complex numbers', () => {
  test('Real part of a purely real number', () => {
    const expected = 1;
    const actual = new ComplexNumber(1, 0).real;

    expect(actual).toEqual(expected);
  });

  xtest('Real part of a purely imaginary number', () => {
    const expected = 0;
    const actual = new ComplexNumber(0, 1).real;

    expect(actual).toEqual(expected);
  });

  xtest('Real part of a number with real and imaginary part', () => {
    const expected = 1;
    const actual = new ComplexNumber(1, 2).real;

    expect(actual).toEqual(expected);
  });

  xtest('Imaginary part of a purely real number', () => {
    const expected = 0;
    const actual = new ComplexNumber(1, 0).imag;

    expect(actual).toEqual(expected);
  });

  xtest('Imaginary part of a purely imaginary number', () => {
    const expected = 1;
    const actual = new ComplexNumber(0, 1).imag;

    expect(actual).toEqual(expected);
  });

  xtest('Imaginary part of a number with real and imaginary part', () => {
    const expected = 2;
    const actual = new ComplexNumber(1, 2).imag;

    expect(actual).toEqual(expected);
  });

  xtest('Add purely real numbers', () => {
    const expected = new ComplexNumber(3, 0);
    const actual = new ComplexNumber(1, 0).add(new ComplexNumber(2, 0));

    expect(actual).toEqual(expected);
  });

  xtest('Add purely imaginary numbers', () => {
    const expected = new ComplexNumber(0, 3);
    const actual = new ComplexNumber(0, 1).add(new ComplexNumber(0, 2));

    expect(actual).toEqual(expected);
  });

  xtest('Add numbers with real and imaginary part', () => {
    const expected = new ComplexNumber(4, 6);
    const actual = new ComplexNumber(1, 2).add(new ComplexNumber(3, 4));

    expect(actual).toEqual(expected);
  });

  xtest('Subtract purely real numbers', () => {
    const expected = new ComplexNumber(-1, 0);
    const actual = new ComplexNumber(1, 0).sub(new ComplexNumber(2, 0));

    expect(actual).toEqual(expected);
  });

  xtest('Subtract purely imaginary numbers', () => {
    const expected = new ComplexNumber(0, -1);
    const actual = new ComplexNumber(0, 1).sub(new ComplexNumber(0, 2));

    expect(actual).toEqual(expected);
  });

  xtest('Subtract numbers with real and imaginary part', () => {
    const expected = new ComplexNumber(-2, -2);
    const actual = new ComplexNumber(1, 2).sub(new ComplexNumber(3, 4));

    expect(actual).toEqual(expected);
  });

  xtest('Multiply purely real numbers', () => {
    const expected = new ComplexNumber(2, 0);
    const actual = new ComplexNumber(1, 0).mul(new ComplexNumber(2, 0));

    expect(actual).toEqual(expected);
  });

  xtest('Multiply imaginary unit', () => {
    const expected = new ComplexNumber(-1, 0);
    const actual = new ComplexNumber(0, 1).mul(new ComplexNumber(0, 1));

    expect(actual).toEqual(expected);
  });

  xtest('Multiply purely imaginary numbers', () => {
    const expected = new ComplexNumber(-2, 0);
    const actual = new ComplexNumber(0, 1).mul(new ComplexNumber(0, 2));

    expect(actual).toEqual(expected);
  });

  xtest('Multiply numbers with real and imaginary part', () => {
    const expected = new ComplexNumber(-5, 10);
    const actual = new ComplexNumber(1, 2).mul(new ComplexNumber(3, 4));

    expect(actual).toEqual(expected);
  });

  xtest('Divide purely real numbers', () => {
    const expected = new ComplexNumber(0.5, 0);
    const actual = new ComplexNumber(1, 0).div(new ComplexNumber(2, 0));

    expect(actual).toEqual(expected);
  });

  xtest('Divide purely imaginary numbers', () => {
    const expected = new ComplexNumber(0.5, 0);
    const actual = new ComplexNumber(0, 1).div(new ComplexNumber(0, 2));

    expect(actual).toEqual(expected);
  });

  xtest('Divide numbers with real and imaginary part', () => {
    const expected = new ComplexNumber(0.44, 0.08);
    const actual = new ComplexNumber(1, 2).div(new ComplexNumber(3, 4));

    expect(actual).toEqual(expected);
  });

  xtest('Absolute value of a positive purely real number', () => {
    const expected = 5;
    const actual = new ComplexNumber(5, 0).abs;

    expect(actual).toEqual(expected);
  });

  xtest('Absolute value of a negative purely real number', () => {
    const expected = 5;
    const actual = new ComplexNumber(-5, 0).abs;

    expect(actual).toEqual(expected);
  });

  xtest('Absolute value of a purely imaginary number with positive imaginary part', () => {
    const expected = 5;
    const actual = new ComplexNumber(0, 5).abs;

    expect(actual).toEqual(expected);
  });

  xtest('Absolute value of a purely imaginary number with negative imaginary part', () => {
    const expected = 5;
    const actual = new ComplexNumber(0, -5).abs;

    expect(actual).toEqual(expected);
  });

  xtest('Absolute value of a number with real and imaginary part', () => {
    const expected = 5;
    const actual = new ComplexNumber(3, 4).abs;

    expect(actual).toEqual(expected);
  });

  xtest('Conjugate a purely real number', () => {
    const expected = new ComplexNumber(5, 0);
    const actual = new ComplexNumber(5, 0).conj;

    expect(actual).toEqual(expected);
  });

  xtest('Conjugate a purely imaginary number', () => {
    const expected = new ComplexNumber(0, -5);
    const actual = new ComplexNumber(0, 5).conj;

    expect(actual).toEqual(expected);
  });

  xtest('Conjugate a number with real and imaginary part', () => {
    const expected = new ComplexNumber(1, -1);
    const actual = new ComplexNumber(1, 1).conj;

    expect(actual).toEqual(expected);
  });

  xtest('Euler\'s identity/formula', () => {
    const expected = new ComplexNumber(-1, 0);
    const actual = new ComplexNumber(0, Math.PI).exp;

    expect(actual.real).toBeCloseTo(expected.real);
    expect(actual.imag).toBeCloseTo(expected.imag);
  });

  xtest('Exponential of 0', () => {
    const expected = new ComplexNumber(1, 0);
    const actual = new ComplexNumber(0, 0).exp;

    expect(actual.real).toBeCloseTo(expected.real);
    expect(actual.imag).toBeCloseTo(expected.imag);
  });

  xtest('Exponential of a purely real number', () => {
    const expected = new ComplexNumber(Math.E, 0);
    const actual = new ComplexNumber(1, 0).exp;

    expect(actual.real).toBeCloseTo(expected.real);
    expect(actual.imag).toBeCloseTo(expected.imag);
  });
});
<commit_msg>complex-numbers: update tests to v1.3.0 (#623)<commit_after>import { ComplexNumber } from './complex-numbers.js';

describe('Complex numbers', () => {
  test('Real part of a purely real number', () => {
    const expected = 1;
    const actual = new ComplexNumber(1, 0).real;

    expect(actual).toEqual(expected);
  });

  xtest('Real part of a purely imaginary number', () => {
    const expected = 0;
    const actual = new ComplexNumber(0, 1).real;

    expect(actual).toEqual(expected);
  });

  xtest('Real part of a number with real and imaginary part', () => {
    const expected = 1;
    const actual = new ComplexNumber(1, 2).real;

    expect(actual).toEqual(expected);
  });

  xtest('Imaginary part of a purely real number', () => {
    const expected = 0;
    const actual = new ComplexNumber(1, 0).imag;

    expect(actual).toEqual(expected);
  });

  xtest('Imaginary part of a purely imaginary number', () => {
    const expected = 1;
    const actual = new ComplexNumber(0, 1).imag;

    expect(actual).toEqual(expected);
  });

  xtest('Imaginary part of a number with real and imaginary part', () => {
    const expected = 2;
    const actual = new ComplexNumber(1, 2).imag;

    expect(actual).toEqual(expected);
  });

  xtest('Add purely real numbers', () => {
    const expected = new ComplexNumber(3, 0);
    const actual = new ComplexNumber(1, 0).add(new ComplexNumber(2, 0));

    expect(actual).toEqual(expected);
  });

  xtest('Add purely imaginary numbers', () => {
    const expected = new ComplexNumber(0, 3);
    const actual = new ComplexNumber(0, 1).add(new ComplexNumber(0, 2));

    expect(actual).toEqual(expected);
  });

  xtest('Add numbers with real and imaginary part', () => {
    const expected = new ComplexNumber(4, 6);
    const actual = new ComplexNumber(1, 2).add(new ComplexNumber(3, 4));

    expect(actual).toEqual(expected);
  });

  xtest('Subtract purely real numbers', () => {
    const expected = new ComplexNumber(-1, 0);
    const actual = new ComplexNumber(1, 0).sub(new ComplexNumber(2, 0));

    expect(actual).toEqual(expected);
  });

  xtest('Subtract purely imaginary numbers', () => {
    const expected = new ComplexNumber(0, -1);
    const actual = new ComplexNumber(0, 1).sub(new ComplexNumber(0, 2));

    expect(actual).toEqual(expected);
  });

  xtest('Subtract numbers with real and imaginary part', () => {
    const expected = new ComplexNumber(-2, -2);
    const actual = new ComplexNumber(1, 2).sub(new ComplexNumber(3, 4));

    expect(actual).toEqual(expected);
  });

  xtest('Multiply purely real numbers', () => {
    const expected = new ComplexNumber(2, 0);
    const actual = new ComplexNumber(1, 0).mul(new ComplexNumber(2, 0));

    expect(actual).toEqual(expected);
  });

  xtest('Multiply imaginary unit', () => {
    const expected = new ComplexNumber(-1, 0);
    const actual = new ComplexNumber(0, 1).mul(new ComplexNumber(0, 1));

    expect(actual).toEqual(expected);
  });

  xtest('Multiply purely imaginary numbers', () => {
    const expected = new ComplexNumber(-2, 0);
    const actual = new ComplexNumber(0, 1).mul(new ComplexNumber(0, 2));

    expect(actual).toEqual(expected);
  });

  xtest('Multiply numbers with real and imaginary part', () => {
    const expected = new ComplexNumber(-5, 10);
    const actual = new ComplexNumber(1, 2).mul(new ComplexNumber(3, 4));

    expect(actual).toEqual(expected);
  });

  xtest('Divide purely real numbers', () => {
    const expected = new ComplexNumber(0.5, 0);
    const actual = new ComplexNumber(1, 0).div(new ComplexNumber(2, 0));

    expect(actual).toEqual(expected);
  });

  xtest('Divide purely imaginary numbers', () => {
    const expected = new ComplexNumber(0.5, 0);
    const actual = new ComplexNumber(0, 1).div(new ComplexNumber(0, 2));

    expect(actual).toEqual(expected);
  });

  xtest('Divide numbers with real and imaginary part', () => {
    const expected = new ComplexNumber(0.44, 0.08);
    const actual = new ComplexNumber(1, 2).div(new ComplexNumber(3, 4));

    expect(actual).toEqual(expected);
  });

  xtest('Absolute value of a positive purely real number', () => {
    const expected = 5;
    const actual = new ComplexNumber(5, 0).abs;

    expect(actual).toEqual(expected);
  });

  xtest('Absolute value of a negative purely real number', () => {
    const expected = 5;
    const actual = new ComplexNumber(-5, 0).abs;

    expect(actual).toEqual(expected);
  });

  xtest('Absolute value of a purely imaginary number with positive imaginary part', () => {
    const expected = 5;
    const actual = new ComplexNumber(0, 5).abs;

    expect(actual).toEqual(expected);
  });

  xtest('Absolute value of a purely imaginary number with negative imaginary part', () => {
    const expected = 5;
    const actual = new ComplexNumber(0, -5).abs;

    expect(actual).toEqual(expected);
  });

  xtest('Absolute value of a number with real and imaginary part', () => {
    const expected = 5;
    const actual = new ComplexNumber(3, 4).abs;

    expect(actual).toEqual(expected);
  });

  xtest('Conjugate a purely real number', () => {
    const expected = new ComplexNumber(5, 0);
    const actual = new ComplexNumber(5, 0).conj;

    expect(actual).toEqual(expected);
  });

  xtest('Conjugate a purely imaginary number', () => {
    const expected = new ComplexNumber(0, -5);
    const actual = new ComplexNumber(0, 5).conj;

    expect(actual).toEqual(expected);
  });

  xtest('Conjugate a number with real and imaginary part', () => {
    const expected = new ComplexNumber(1, -1);
    const actual = new ComplexNumber(1, 1).conj;

    expect(actual).toEqual(expected);
  });

  xtest('Euler\'s identity/formula', () => {
    const expected = new ComplexNumber(-1, 0);
    const actual = new ComplexNumber(0, Math.PI).exp;

    expect(actual.real).toBeCloseTo(expected.real);
    expect(actual.imag).toBeCloseTo(expected.imag);
  });

  xtest('Exponential of 0', () => {
    const expected = new ComplexNumber(1, 0);
    const actual = new ComplexNumber(0, 0).exp;

    expect(actual.real).toBeCloseTo(expected.real);
    expect(actual.imag).toBeCloseTo(expected.imag);
  });

  xtest('Exponential of a purely real number', () => {
    const expected = new ComplexNumber(Math.E, 0);
    const actual = new ComplexNumber(1, 0).exp;

    expect(actual.real).toBeCloseTo(expected.real);
    expect(actual.imag).toBeCloseTo(expected.imag);
  });

  xtest('Exponential of a number with real and imaginary part', () => {
    const expected = new ComplexNumber(-2, 0);
    const actual = new ComplexNumber(Math.LN2, Math.PI).exp;

    expect(actual.real).toBeCloseTo(expected.real);
    expect(actual.imag).toBeCloseTo(expected.imag);
  });
});
<|endoftext|>


<commit_before>(function (exports) {
    "use strict";

    /*jshint curly:false */
    /*global d3 */

    exports.barchart = function () {

        var barchart, width, height, yAxisPadding, yAxisTicks,
            xScale, yScale, yInverseScale, xAxis, yAxis;

        width = 300;
        height = 300;

        xScale = d3.scale.ordinal();

        yAxisPadding = 25;
        yAxisTicks = height / 75;
        yScale = d3.scale.linear();
        yInverseScale = d3.scale.linear();

        yAxis = d3.svg.axis()
                  .scale(yInverseScale)
                  .orient("left")
                  .ticks(yAxisTicks)
                  .tickSize(6, 0);

        barchart = function (selection) {

            selection.each(function (data) {

                var labels, yMin, yMax, svg, enter, group;

             // Extract labels.
                labels = d3.keys(data);

             // Convert object to array.
                data = d3.keys(data).map(function (d) {
                    return [d, data[d]];
                });

             // Update padded x scale.
                xScale.domain(labels)
                      .rangeBands([yAxisPadding, width]);

             // Update padded y scale.
                yMin = d3.min(data, function (d) {
                    return d[1];
                });
                yMax = d3.max(data, function (d) {
                    return d[1];
                });
                yScale.domain([yMin, yMax])
                      .range([0, height]);
                yInverseScale.domain([yMin, yMax])
                             .range([height, 0]);

             // Select existing SVG elements.
                svg = d3.select(this)
                        .selectAll("svg")
                        .data([data]) // Trick to create only one svg element for each data set.

             // Create non-existing SVG elements.
                svg.enter()
                   .append("svg");

             // Update both existing and newly created SVG elements.
                svg.attr("width", width)
                   .attr("height", height);

             // Generate y axis.
                svg.append("g")
                   .attr("class", "axis")
                 // Add penalty of 1 so that axis and first bar do not collide.
                   .attr("transform", "translate(" + (yAxisPadding - 1) + ",0)")
                   .call(yAxis);

             // Generate bars.
                svg.append("g")
                   .selectAll("rect")
                   .data(data)
                   .enter()
                   .append("rect")
                   .attr("class", "bar")
                   .attr("width", function (d) {
                        return xScale.rangeBand();
                    })
                   .attr("height", function (d) {
                        return yScale(d[1]);
                    })
                   .attr("x", function (d) {
                        return xScale(d[0]);
                    })
                   .attr("y", function (d) {
                       return height - yScale(d[1]);
                    })
                   .append("title")
                   .text(function (d) {
                        return d[0];
                    });

            });

        };

        barchart.height = function (_) {
            if (!arguments.length) return height;
            height = _;
            return barchart;
        };

        barchart.width = function (_) {
            if (!arguments.length) return width;
            width = _;
            return barchart;
        };

        barchart.yAxisPadding = function (_) {
            if (!arguments.length) return yAxisPadding;
            yAxisPadding = _;
            return barchart;
        };

        barchart.yAxisTicks = function (_) {
            if (!arguments.length) return yAxisTicks;
            yAxisTicks = _;
            return barchart;
        };

        return barchart;

    };

}(window));
<commit_msg>Clean up code.<commit_after>(function (exports) {
    "use strict";

    /*jshint curly:false */
    /*global d3 */

    exports.barchart = function () {

        var barchart, width, height, xScale, yScale, yAxisPadding,
            yAxisTicks, yAxisScale, yAxis;

        width = 300;
        height = 300;

        xScale = d3.scale.ordinal();
        yScale = d3.scale.linear();

        yAxisPadding = 25;
        yAxisTicks = height / 75;
        yAxisScale = d3.scale.linear();
        yAxis = d3.svg.axis()
                  .scale(yAxisScale)
                  .orient("left")
                  .ticks(yAxisTicks)
                  .tickSize(6, 0);

        barchart = function (selection) {

            selection.each(function (data) {

                var labels, yMin, yMax, svg;

             // Extract labels.
                labels = d3.keys(data);

             // Convert object to array.
                data = d3.keys(data).map(function (d) {
                    return [d, data[d]];
                });

             // Update padded x scale.
                xScale.domain(labels)
                      .rangeBands([yAxisPadding, width]);

             // Update y scale.
                yMin = d3.min(data, function (d) {
                    return d[1];
                });
                yMax = d3.max(data, function (d) {
                    return d[1];
                });
                yScale.domain([yMin, yMax])
                      .range([0, height]);

             // Update inverted y scale for y axis.
                yAxisScale.domain([yMin, yMax])
                          .range([height, 0]);

             // Select existing SVG elements.
                svg = d3.select(this)
                        .selectAll("svg")
                        .data([data]) // Trick to create only one svg element for each data set.

             // Create non-existing SVG elements.
                svg.enter()
                   .append("svg");

             // Update both existing and newly created SVG elements.
                svg.attr("width", width)
                   .attr("height", height);

             // Generate y axis.
                svg.append("g")
                   .attr("class", "axis")
                 // Add penalty of 1 so that axis and first bar do not collide.
                   .attr("transform", "translate(" + (yAxisPadding - 1) + ",0)")
                   .call(yAxis);

             // Generate bars.
                svg.append("g")
                   .selectAll("rect")
                   .data(data)
                   .enter()
                   .append("rect")
                   .attr("class", "bar")
                   .attr("x", function (d) {
                        return xScale(d[0]);
                    })
                   .attr("y", function (d) {
                       return height - yScale(d[1]);
                    })
                   .attr("width", function (d) {
                        return xScale.rangeBand();
                    })
                   .attr("height", function (d) {
                        return yScale(d[1]);
                    })
                   .append("title")
                   .text(function (d) {
                        return d[0];
                    });

            });

        };

        barchart.height = function (_) {
            if (!arguments.length) return height;
            height = _;
            return barchart;
        };

        barchart.width = function (_) {
            if (!arguments.length) return width;
            width = _;
            return barchart;
        };

        barchart.yAxisPadding = function (_) {
            if (!arguments.length) return yAxisPadding;
            yAxisPadding = _;
            return barchart;
        };

        barchart.yAxisTicks = function (_) {
            if (!arguments.length) return yAxisTicks;
            yAxisTicks = _;
            return barchart;
        };

        return barchart;

    };

}(window));
<|endoftext|>


<commit_before>'use strict';

var async = require('async');
var azuresb = require('azure-sb');
var path = require('path');
var util = require('util');

var topics = require('./lib/topics');
var subscriptions = require('./lib/subscriptions');
var queues = require('./lib/queues');

var configDir = path.resolve(process.argv[2] || './');
var statsConfig = require(path.join(configDir, 'statsd'));

util.log('starting...');
util.log(`using config from ${configDir}`);

var azuresbServers = require(path.join(configDir, 'azure-sb.json')).map((c) => {
  var client = azuresb.createServiceBusService(`Endpoint=${c.endpoint};SharedAccessKeyName=${c.keyname};SharedAccessKey=${c.key}`);
  client.endpoint = c.endpoint;
  client.tags = c.tags;
  client.prefix = c.prefix;
  client.queues = c.queues;
  client.topics = c.topics;
  client.ignoredsubscriptions = c.ignoredsubscriptions;

  if(!client.queues && !client.topics){
    util.log(`[${c.endpoint}]: WARN queues = false, topics = false, not doing anything`);
  }

  return client;
});

azuresbServers.forEach((c) => {
  setInterval(() => {
    if(c.queues){
      queues(c, (err, qs) => {
        if(err){
          util.log(`[${c.endpoint}]: ${err.toString()}`);
          return;
        }
      });
    }

    if(c.topics){
      topics(c, (err, ts) => {
        if(err){
          util.log(`[${c.endpoint}]: ${err.toString()}`);
          return;
        }

        async.forEach(ts, (topic, done) => {
          subscriptions(topic, c, done);
        }, (err) => {
          if(err){
            util.log(`[${c.endpoint}]: ${err.toString()}`);
          }
        });
      });
    }
  }, (statsConfig.interval || 10) * 1000);
});
<commit_msg>Added the null validation when load the ignored subscriptions<commit_after>'use strict';

var async = require('async');
var azuresb = require('azure-sb');
var path = require('path');
var util = require('util');

var topics = require('./lib/topics');
var subscriptions = require('./lib/subscriptions');
var queues = require('./lib/queues');

var configDir = path.resolve(process.argv[2] || './');
var statsConfig = require(path.join(configDir, 'statsd'));

util.log('starting...');
util.log(`using config from ${configDir}`);

var azuresbServers = require(path.join(configDir, 'azure-sb.json')).map((c) => {
  var client = azuresb.createServiceBusService(`Endpoint=${c.endpoint};SharedAccessKeyName=${c.keyname};SharedAccessKey=${c.key}`);
  client.endpoint = c.endpoint;
  client.tags = c.tags;
  client.prefix = c.prefix;
  client.queues = c.queues;
  client.topics = c.topics;
  client.ignoredsubscriptions = c.ignoredsubscriptions || [];;

  if(!client.queues && !client.topics){
    util.log(`[${c.endpoint}]: WARN queues = false, topics = false, not doing anything`);
  }

  return client;
});

azuresbServers.forEach((c) => {
  setInterval(() => {
    if(c.queues){
      queues(c, (err, qs) => {
        if(err){
          util.log(`[${c.endpoint}]: ${err.toString()}`);
          return;
        }
      });
    }

    if(c.topics){
      topics(c, (err, ts) => {
        if(err){
          util.log(`[${c.endpoint}]: ${err.toString()}`);
          return;
        }

        async.forEach(ts, (topic, done) => {
          subscriptions(topic, c, done);
        }, (err) => {
          if(err){
            util.log(`[${c.endpoint}]: ${err.toString()}`);
          }
        });
      });
    }
  }, (statsConfig.interval || 10) * 1000);
});
<|endoftext|>