<commit_before>'use strict';

import Fragmenter from '../model/Fragmenter'
import Component from './Component'
import AnnotationComponent from './AnnotationComponent'
import InlineNodeComponent from './InlineNodeComponent'

/**
  Renders an anotated text. Used internally by {@link ui/TextPropertyComponent}.

  @class
  @component
  @extends ui/Component

  @prop {String[]} path The property to be rendered.
*/

function AnnotatedTextComponent() {
  AnnotatedTextComponent.super.apply(this, arguments);
}

AnnotatedTextComponent.Prototype = function() {

  // TODO: this component should listen on changes to the property
  // Otherwise will not be updated.
  // Note that in contrast, TextPropertyComponents get updated by Surface.

  /**
    Node render implementation. Use model/Fragmenter for rendering of annotations.

    @return {VirtualNode} VirtualNode created using ui/Component
   */
  this.render = function($$) {
    var el = this._renderContent($$)
      .addClass('sc-annotated-text')
      .css({
        whiteSpace: "pre-wrap"
      });
    return el;
  };

  this.getText = function() {
    return this.getDocument().get(this.props.path) || '';
  };

  this.getAnnotations = function() {
    return this.getDocument().getIndex('annotations').get(this.props.path);
  };

  this._renderContent = function($$) {
    var text = this.getText();
    var annotations = this.getAnnotations();
    var el = $$(this.props.tagName || 'span');
    if (annotations && annotations.length > 0) {
      var fragmenter = new Fragmenter({
        onText: this._renderTextNode.bind(this),
        onEnter: this._renderFragment.bind(this, $$),
        onExit: this._finishFragment.bind(this)
      });
      fragmenter.start(el, text, annotations);
    } else {
      el.append(text);
    }
    return el;
  };

  this._renderTextNode = function(context, text) {
    if (text && text.length > 0) {
      context.append(text);
    }
  };

  this._renderFragment = function($$, fragment) {
    var doc = this.getDocument();
    var componentRegistry = this.getComponentRegistry();
    var node = fragment.node;
    if (node.type === "container-annotation-fragment") {
      return $$(AnnotationComponent, { doc: doc, node: node })
        .addClass("se-annotation-fragment")
        .addClass(node.anno.getTypeNames().join(' ').replace(/_/g, "-"));
    } else if (node.type === "container-annotation-anchor") {
      return $$(AnnotationComponent, { doc: doc, node: node })
        .addClass("se-anchor")
        .addClass(node.anno.getTypeNames().join(' ').replace(/_/g, "-"))
        .addClass(node.isStart?"start-anchor":"end-anchor");
    }
    var ComponentClass = componentRegistry.get(node.type) || AnnotationComponent;
    if (node.constructor.isInline &&
        // opt-out for custom implementations
        !ComponentClass.isCustom &&
        // also no extra wrapping if the node is already an inline node
        !ComponentClass.prototype._isInlineNodeComponent) {
      ComponentClass = InlineNodeComponent;
    }
    var el = $$(ComponentClass, { doc: doc, node: node });
    return el;
  };

  this._finishFragment = function(fragment, context, parentContext) {
    parentContext.append(context);
  };

  /**
    Gets document instance.

    @return {Document} The document instance
   */
  this.getDocument = function() {
    return this.props.doc || this.context.doc;
  };

  this.getComponentRegistry = function() {
    return this.props.componentRegistry || this.context.componentRegistry;
  };

};

Component.extend(AnnotatedTextComponent);

export default AnnotatedTextComponent;
<commit_msg>ES6 AnnotatedTextComponent.<commit_after>import Fragmenter from '../model/Fragmenter'
import Component from './Component'
import AnnotationComponent from './AnnotationComponent'
import InlineNodeComponent from './InlineNodeComponent'

/**
  Renders an anotated text. Used internally by {@link ui/TextPropertyComponent}.

  @class
  @component
  @extends ui/Component

  @prop {String[]} path The property to be rendered.
*/

class AnnotatedTextComponent extends Component {

  // TODO: this component should listen on changes to the property
  // Otherwise will not be updated.
  // Note that in contrast, TextPropertyComponents get updated by Surface.

  /**
    Node render implementation. Use model/Fragmenter for rendering of annotations.

    @return {VirtualNode} VirtualNode created using ui/Component
   */
  render($$) {
    let el = this._renderContent($$)
      .addClass('sc-annotated-text')
      .css({
        whiteSpace: "pre-wrap"
      })

    return el
  }

  getText() {
    return this.getDocument().get(this.props.path) || ''
  }

  getAnnotations() {
    return this.getDocument().getIndex('annotations').get(this.props.path)
  }

  _renderContent($$) {
    let text = this.getText();
    let annotations = this.getAnnotations()
    let el = $$(this.props.tagName || 'span')
    if (annotations && annotations.length > 0) {
      let fragmenter = new Fragmenter({
        onText: this._renderTextNode.bind(this),
        onEnter: this._renderFragment.bind(this, $$),
        onExit: this._finishFragment.bind(this)
      });
      fragmenter.start(el, text, annotations)
    } else {
      el.append(text)
    }
    return el
  }

  _renderTextNode(context, text) {
    if (text && text.length > 0) {
      context.append(text)
    }
  }

  _renderFragment($$, fragment) {
    let doc = this.getDocument()
    let componentRegistry = this.getComponentRegistry()
    let node = fragment.node
    if (node.type === "container-annotation-fragment") {
      return $$(AnnotationComponent, { doc: doc, node: node })
        .addClass("se-annotation-fragment")
        .addClass(node.anno.getTypeNames().join(' ').replace(/_/g, "-"));
    } else if (node.type === "container-annotation-anchor") {
      return $$(AnnotationComponent, { doc: doc, node: node })
        .addClass("se-anchor")
        .addClass(node.anno.getTypeNames().join(' ').replace(/_/g, "-"))
        .addClass(node.isStart?"start-anchor":"end-anchor")
    }
    let ComponentClass = componentRegistry.get(node.type) || AnnotationComponent
    if (node.constructor.isInline &&
        // opt-out for custom implementations
        !ComponentClass.isCustom &&
        // also no extra wrapping if the node is already an inline node
        !ComponentClass.prototype._isInlineNodeComponent) {
      ComponentClass = InlineNodeComponent
    }
    let el = $$(ComponentClass, { doc: doc, node: node })
    return el
  }

  _finishFragment(fragment, context, parentContext) {
    parentContext.append(context)
  }

  /**
    Gets document instance.

    @return {Document} The document instance
   */
  getDocument() {
    return this.props.doc || this.context.doc
  }

  getComponentRegistry() {
    return this.props.componentRegistry || this.context.componentRegistry
  }

}

export default AnnotatedTextComponent
<|endoftext|>


<commit_before>/*
 * jQuery UI Autocomplete @VERSION
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Autocomplete
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.widget.js
 *	jquery.ui.position.js
 *	jquery.ui.menu.js
 */
(function( $, undefined ) {

// used to prevent race conditions with remote data sources
var requestIndex = 0;

$.widget( "ui.autocomplete", {
	defaultElement: "<input>",
	options: {
		appendTo: "body",
		autoFocus: false,
		delay: 300,
		minLength: 1,
		position: {
			my: "left top",
			at: "left bottom",
			collision: "none"
		},
		source: null,

		// callbacks
		change: null,
		close: null,
		focus: null,
		open: null,
		response: null,
		search: null,
		select: null
	},

	pending: 0,

	_create: function() {
		var self = this,
			doc = this.element[ 0 ].ownerDocument,
			suppressKeyPress;

		this.valueMethod = this.element[ this.element.is( "input" ) ? "val" : "text" ];

		this.element
			.addClass( "ui-autocomplete-input" )
			.attr( "autocomplete", "off" )
			// TODO verify these actually work as intended
			.attr({
				role: "textbox",
				"aria-autocomplete": "list",
				"aria-haspopup": "true"
			})
			.bind( "keydown.autocomplete", function( event ) {
				if ( self.options.disabled || self.element.attr( "readonly" ) ) {
                    suppressKeyPress = true;
					return;
				}

				suppressKeyPress = false;
				var keyCode = $.ui.keyCode;
				switch( event.keyCode ) {
				case keyCode.PAGE_UP:
                    suppressKeyPress = true;
					self._move( "previousPage", event );
					break;
				case keyCode.PAGE_DOWN:
                    suppressKeyPress = true;
					self._move( "nextPage", event );
					break;
				case keyCode.UP:
                    suppressKeyPress = true;
					self._move( "previous", event );
					// prevent moving cursor to beginning of text field in some browsers
					event.preventDefault();
					break;
				case keyCode.DOWN:
                    suppressKeyPress = true;
					self._move( "next", event );
					// prevent moving cursor to end of text field in some browsers
					event.preventDefault();
					break;
				case keyCode.ENTER:
				case keyCode.NUMPAD_ENTER:
					// when menu is open and has focus
					if ( self.menu.active ) {
						// #6055 - Opera still allows the keypress to occur
						// which causes forms to submit
						suppressKeyPress = true;
						event.preventDefault();
					}
					//passthrough - ENTER and TAB both select the current element
				case keyCode.TAB:
					if ( !self.menu.active ) {
						return;
					}
					self.menu.select( event );
					break;
				case keyCode.ESCAPE:
					self._value( self.term );
					self.close( event );
					break;
				default:
					// keypress is triggered before the input value is changed
					clearTimeout( self.searching );
					self.searching = setTimeout(function() {
						// only search if the value has changed
						if ( self.term != self._value() ) {
							self.selectedItem = null;
							self.search( null, event );
						}
					}, self.options.delay );
					break;
				}
			})
			.bind( "keypress.autocomplete", function( event ) {
				if ( suppressKeyPress ) {
					suppressKeyPress = false;
					event.preventDefault();
                    return;
				}

				var keyCode = $.ui.keyCode;
				switch( event.keyCode ) {
				case keyCode.PAGE_UP:
					self._move( "previousPage", event );
					break;
				case keyCode.PAGE_DOWN:
					self._move( "nextPage", event );
					break;
				case keyCode.UP:
					self._move( "previous", event );
					// prevent moving cursor to beginning of text field in some browsers
					event.preventDefault();
					break;
				case keyCode.DOWN:
					self._move( "next", event );
					// prevent moving cursor to end of text field in some browsers
					event.preventDefault();
					break;
                }
			})
			.bind( "focus.autocomplete", function() {
				if ( self.options.disabled ) {
					return;
				}

				self.selectedItem = null;
				self.previous = self._value();
			})
			.bind( "blur.autocomplete", function( event ) {
				if ( self.options.disabled ) {
					return;
				}

				clearTimeout( self.searching );
				// clicks on the menu (or a button to trigger a search) will cause a blur event
				self.closing = setTimeout(function() {
					self.close( event );
					self._change( event );
				}, 150 );
			});
		this._initSource();
		this.response = function() {
			return self._response.apply( self, arguments );
		};
		this.menu = $( "

" )
			.addClass( "ui-autocomplete" )
			.appendTo( $( this.options.appendTo || "body", doc )[0] )
			// prevent the close-on-blur in case of a "slow" click on the menu (long mousedown)
			.mousedown(function( event ) {
				// clicking on the scrollbar causes focus to shift to the body
				// but we can't detect a mouseup or a click immediately afterward
				// so we have to track the next mousedown and close the menu if
				// the user clicks somewhere outside of the autocomplete
				var menuElement = self.menu.element[ 0 ];
				if ( !$( event.target ).closest( ".ui-menu-item" ).length ) {
					setTimeout(function() {
						$( document ).one( 'mousedown', function( event ) {
							if ( event.target !== self.element[ 0 ] &&
								event.target !== menuElement &&
								!$.contains( menuElement, event.target ) ) {
								self.close();
							}
						});
					}, 1 );
				}

				// use another timeout to make sure the blur-event-handler on the input was already triggered
				setTimeout(function() {
					clearTimeout( self.closing );
				}, 13);
			})
			.menu({
				// custom key handling for now
				input: $(),
				focus: function( event, ui ) {
					var item = ui.item.data( "item.autocomplete" );
					if ( false !== self._trigger( "focus", event, { item: item } ) ) {
						// use value to match what will end up in the input, if it was a key event
						if ( /^key/.test(event.originalEvent.type) ) {
							self._value( item.value );
						}
					}
				},
				select: function( event, ui ) {
					var item = ui.item.data( "item.autocomplete" ),
						previous = self.previous;

					// only trigger when focus was lost (click on menu)
					if ( self.element[0] !== doc.activeElement ) {
						self.element.focus();
						self.previous = previous;
						// #6109 - IE triggers two focus events and the second
						// is asynchronous, so we need to reset the previous
						// term synchronously and asynchronously :-(
						setTimeout(function() {
							self.previous = previous;
							self.selectedItem = item;
						}, 1);
					}

					if ( false !== self._trigger( "select", event, { item: item } ) ) {
						self._value( item.value );
					}
					// reset the term after the select event
					// this allows custom select handling to work properly
					self.term = self._value();

					self.close( event );
					self.selectedItem = item;
				},
				blur: function( event, ui ) {
					// don't set the value of the text field if it's already correct
					// this prevents moving the cursor unnecessarily
					if ( self.menu.element.is(":visible") &&
						( self._value() !== self.term ) ) {
						self._value( self.term );
					}
				}
			})
			.zIndex( this.element.zIndex() + 1 )
			.hide()
			.data( "menu" );
		if ( $.fn.bgiframe ) {
			 this.menu.element.bgiframe();
		}
	},

	_destroy: function() {
		this.element
			.removeClass( "ui-autocomplete-input" )
			.removeAttr( "autocomplete" )
			.removeAttr( "role" )
			.removeAttr( "aria-autocomplete" )
			.removeAttr( "aria-haspopup" );
		this.menu.element.remove();
	},

	_setOption: function( key, value ) {
		this._super( "_setOption", key, value );
		if ( key === "source" ) {
			this._initSource();
		}
		if ( key === "appendTo" ) {
			this.menu.element.appendTo( $( value || "body", this.element[0].ownerDocument )[0] )
		}
		if ( key === "disabled" && value && this.xhr ) {
			this.xhr.abort();
		}
	},

	_initSource: function() {
		var self = this,
			array,
			url;
		if ( $.isArray(this.options.source) ) {
			array = this.options.source;
			this.source = function( request, response ) {
				response( $.ui.autocomplete.filter(array, request.term) );
			};
		} else if ( typeof this.options.source === "string" ) {
			url = this.options.source;
			this.source = function( request, response ) {
				if ( self.xhr ) {
					self.xhr.abort();
				}
				self.xhr = $.ajax({
					url: url,
					data: request,
					dataType: "json",
					autocompleteRequest: ++requestIndex,
					success: function( data, status ) {
						if ( this.autocompleteRequest === requestIndex ) {
							response( data );
						}
					},
					error: function() {
						if ( this.autocompleteRequest === requestIndex ) {
							response( [] );
						}
					}
				});
			};
		} else {
			this.source = this.options.source;
		}
	},

	search: function( value, event ) {
		value = value != null ? value : this._value();

		// always save the actual value, not the one passed as an argument
		this.term = this._value();

		if ( value.length < this.options.minLength ) {
			return this.close( event );
		}

		clearTimeout( this.closing );
		if ( this._trigger( "search", event ) === false ) {
			return;
		}

		return this._search( value );
	},

	_search: function( value ) {
		this.pending++;
		this.element.addClass( "ui-autocomplete-loading" );

		this.source( { term: value }, this.response );
	},

	_response: function( content ) {
		if ( content ) {
			content = this._normalize( content );
		}
		this._trigger( "response", null, { content: content } );
		if ( !this.options.disabled && content && content.length ) {
			this._suggest( content );
			this._trigger( "open" );
		} else {
			this.close();
		}
		this.pending--;
		if ( !this.pending ) {
			this.element.removeClass( "ui-autocomplete-loading" );
		}
	},

	close: function( event ) {
		clearTimeout( this.closing );
		if ( this.menu.element.is(":visible") ) {
			this.menu.element.hide();
			this.menu.blur();
			this._trigger( "close", event );
			this.menu.isNewMenu = true;
		}
	},

	_change: function( event ) {
		if ( this.previous !== this._value() ) {
			this._trigger( "change", event, { item: this.selectedItem } );
		}
	},

	_normalize: function( items ) {
		// assume all items have the right format when the first item is complete
		if ( items.length && items[0].label && items[0].value ) {
			return items;
		}
		return $.map( items, function(item) {
			if ( typeof item === "string" ) {
				return {
					label: item,
					value: item
				};
			}
			return $.extend({
				label: item.label || item.value,
				value: item.value || item.label
			}, item );
		});
	},

	_suggest: function( items ) {
		var ul = this.menu.element
			.empty()
			.zIndex( this.element.zIndex() + 1 );
		this._renderMenu( ul, items );
		// TODO refresh should check if the active item is still in the dom, removing the need for a manual blur
		this.menu.blur();
		this.menu.refresh();

		// size and position menu
		ul.show();
		this._resizeMenu();
		ul.position( $.extend({
			of: this.element
		}, this.options.position ));

		if ( this.options.autoFocus ) {
			this.menu.next( new $.Event("mouseover") );
		}
	},

	_resizeMenu: function() {
		var ul = this.menu.element;
		ul.outerWidth( Math.max(
			ul.width( "" ).outerWidth(),
			this.element.outerWidth()
		) );
	},

	_renderMenu: function( ul, items ) {
		var self = this;
		$.each( items, function( index, item ) {
			self._renderItem( ul, item );
		});
	},

	_renderItem: function( ul, item) {
		return $( "

" )
			.data( "item.autocomplete", item )
			.append( $( "" ).text( item.label ) )
			.appendTo( ul );
	},

	_move: function( direction, event ) {
		if ( !this.menu.element.is(":visible") ) {
			this.search( null, event );
			return;
		}
		if ( this.menu.first() && /^previous/.test(direction) ||
				this.menu.last() && /^next/.test(direction) ) {
			this._value( this.term );
			this.menu.blur();
			return;
		}
		this.menu[ direction ]( event );
	},

	widget: function() {
		return this.menu.element;
	},

	_value: function( value ) {
		return this.valueMethod.apply( this.element, arguments );
	}
});

$.extend( $.ui.autocomplete, {
	version: "@VERSION",
	escapeRegex: function( value ) {
		return value.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
	},
	filter: function(array, term) {
		var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
		return $.grep( array, function(value) {
			return matcher.test( value.label || value.value || value );
		});
	}
});

}( jQuery ));
<commit_msg>Autocomplete: Add comment to fix for #7269<commit_after>/*
 * jQuery UI Autocomplete @VERSION
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Autocomplete
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.widget.js
 *	jquery.ui.position.js
 *	jquery.ui.menu.js
 */
(function( $, undefined ) {

// used to prevent race conditions with remote data sources
var requestIndex = 0;

$.widget( "ui.autocomplete", {
	defaultElement: "<input>",
	options: {
		appendTo: "body",
		autoFocus: false,
		delay: 300,
		minLength: 1,
		position: {
			my: "left top",
			at: "left bottom",
			collision: "none"
		},
		source: null,

		// callbacks
		change: null,
		close: null,
		focus: null,
		open: null,
		response: null,
		search: null,
		select: null
	},

	pending: 0,

	_create: function() {
		var self = this,
			doc = this.element[ 0 ].ownerDocument,
			suppressKeyPress;

		this.valueMethod = this.element[ this.element.is( "input" ) ? "val" : "text" ];

		this.element
			.addClass( "ui-autocomplete-input" )
			.attr( "autocomplete", "off" )
			// TODO verify these actually work as intended
			.attr({
				role: "textbox",
				"aria-autocomplete": "list",
				"aria-haspopup": "true"
			})
			.bind( "keydown.autocomplete", function( event ) {
				if ( self.options.disabled || self.element.attr( "readonly" ) ) {
                    suppressKeyPress = true;
					return;
				}

				suppressKeyPress = false;
				var keyCode = $.ui.keyCode;
				switch( event.keyCode ) {
				case keyCode.PAGE_UP:
                    suppressKeyPress = true;
					self._move( "previousPage", event );
					break;
				case keyCode.PAGE_DOWN:
                    suppressKeyPress = true;
					self._move( "nextPage", event );
					break;
				case keyCode.UP:
                    suppressKeyPress = true;
					self._move( "previous", event );
					// prevent moving cursor to beginning of text field in some browsers
					event.preventDefault();
					break;
				case keyCode.DOWN:
                    suppressKeyPress = true;
					self._move( "next", event );
					// prevent moving cursor to end of text field in some browsers
					event.preventDefault();
					break;
				case keyCode.ENTER:
				case keyCode.NUMPAD_ENTER:
					// when menu is open and has focus
					if ( self.menu.active ) {
						// #6055 - Opera still allows the keypress to occur
						// which causes forms to submit
						suppressKeyPress = true;
						event.preventDefault();
					}
					//passthrough - ENTER and TAB both select the current element
				case keyCode.TAB:
					if ( !self.menu.active ) {
						return;
					}
					self.menu.select( event );
					break;
				case keyCode.ESCAPE:
					self._value( self.term );
					self.close( event );
					break;
				default:
					// keypress is triggered before the input value is changed
					clearTimeout( self.searching );
					self.searching = setTimeout(function() {
						// only search if the value has changed
						if ( self.term != self._value() ) {
							self.selectedItem = null;
							self.search( null, event );
						}
					}, self.options.delay );
					break;
				}
			})
			.bind( "keypress.autocomplete", function( event ) {
				if ( suppressKeyPress ) {
					suppressKeyPress = false;
					event.preventDefault();
                    return;
				}

				// replicate some key handlers to allow them to repeat in Firefox and Opera
				var keyCode = $.ui.keyCode;
				switch( event.keyCode ) {
				case keyCode.PAGE_UP:
					self._move( "previousPage", event );
					break;
				case keyCode.PAGE_DOWN:
					self._move( "nextPage", event );
					break;
				case keyCode.UP:
					self._move( "previous", event );
					// prevent moving cursor to beginning of text field in some browsers
					event.preventDefault();
					break;
				case keyCode.DOWN:
					self._move( "next", event );
					// prevent moving cursor to end of text field in some browsers
					event.preventDefault();
					break;
                }
			})
			.bind( "focus.autocomplete", function() {
				if ( self.options.disabled ) {
					return;
				}

				self.selectedItem = null;
				self.previous = self._value();
			})
			.bind( "blur.autocomplete", function( event ) {
				if ( self.options.disabled ) {
					return;
				}

				clearTimeout( self.searching );
				// clicks on the menu (or a button to trigger a search) will cause a blur event
				self.closing = setTimeout(function() {
					self.close( event );
					self._change( event );
				}, 150 );
			});
		this._initSource();
		this.response = function() {
			return self._response.apply( self, arguments );
		};
		this.menu = $( "

" )
			.addClass( "ui-autocomplete" )
			.appendTo( $( this.options.appendTo || "body", doc )[0] )
			// prevent the close-on-blur in case of a "slow" click on the menu (long mousedown)
			.mousedown(function( event ) {
				// clicking on the scrollbar causes focus to shift to the body
				// but we can't detect a mouseup or a click immediately afterward
				// so we have to track the next mousedown and close the menu if
				// the user clicks somewhere outside of the autocomplete
				var menuElement = self.menu.element[ 0 ];
				if ( !$( event.target ).closest( ".ui-menu-item" ).length ) {
					setTimeout(function() {
						$( document ).one( 'mousedown', function( event ) {
							if ( event.target !== self.element[ 0 ] &&
								event.target !== menuElement &&
								!$.contains( menuElement, event.target ) ) {
								self.close();
							}
						});
					}, 1 );
				}

				// use another timeout to make sure the blur-event-handler on the input was already triggered
				setTimeout(function() {
					clearTimeout( self.closing );
				}, 13);
			})
			.menu({
				// custom key handling for now
				input: $(),
				focus: function( event, ui ) {
					var item = ui.item.data( "item.autocomplete" );
					if ( false !== self._trigger( "focus", event, { item: item } ) ) {
						// use value to match what will end up in the input, if it was a key event
						if ( /^key/.test(event.originalEvent.type) ) {
							self._value( item.value );
						}
					}
				},
				select: function( event, ui ) {
					var item = ui.item.data( "item.autocomplete" ),
						previous = self.previous;

					// only trigger when focus was lost (click on menu)
					if ( self.element[0] !== doc.activeElement ) {
						self.element.focus();
						self.previous = previous;
						// #6109 - IE triggers two focus events and the second
						// is asynchronous, so we need to reset the previous
						// term synchronously and asynchronously :-(
						setTimeout(function() {
							self.previous = previous;
							self.selectedItem = item;
						}, 1);
					}

					if ( false !== self._trigger( "select", event, { item: item } ) ) {
						self._value( item.value );
					}
					// reset the term after the select event
					// this allows custom select handling to work properly
					self.term = self._value();

					self.close( event );
					self.selectedItem = item;
				},
				blur: function( event, ui ) {
					// don't set the value of the text field if it's already correct
					// this prevents moving the cursor unnecessarily
					if ( self.menu.element.is(":visible") &&
						( self._value() !== self.term ) ) {
						self._value( self.term );
					}
				}
			})
			.zIndex( this.element.zIndex() + 1 )
			.hide()
			.data( "menu" );
		if ( $.fn.bgiframe ) {
			 this.menu.element.bgiframe();
		}
	},

	_destroy: function() {
		this.element
			.removeClass( "ui-autocomplete-input" )
			.removeAttr( "autocomplete" )
			.removeAttr( "role" )
			.removeAttr( "aria-autocomplete" )
			.removeAttr( "aria-haspopup" );
		this.menu.element.remove();
	},

	_setOption: function( key, value ) {
		this._super( "_setOption", key, value );
		if ( key === "source" ) {
			this._initSource();
		}
		if ( key === "appendTo" ) {
			this.menu.element.appendTo( $( value || "body", this.element[0].ownerDocument )[0] )
		}
		if ( key === "disabled" && value && this.xhr ) {
			this.xhr.abort();
		}
	},

	_initSource: function() {
		var self = this,
			array,
			url;
		if ( $.isArray(this.options.source) ) {
			array = this.options.source;
			this.source = function( request, response ) {
				response( $.ui.autocomplete.filter(array, request.term) );
			};
		} else if ( typeof this.options.source === "string" ) {
			url = this.options.source;
			this.source = function( request, response ) {
				if ( self.xhr ) {
					self.xhr.abort();
				}
				self.xhr = $.ajax({
					url: url,
					data: request,
					dataType: "json",
					autocompleteRequest: ++requestIndex,
					success: function( data, status ) {
						if ( this.autocompleteRequest === requestIndex ) {
							response( data );
						}
					},
					error: function() {
						if ( this.autocompleteRequest === requestIndex ) {
							response( [] );
						}
					}
				});
			};
		} else {
			this.source = this.options.source;
		}
	},

	search: function( value, event ) {
		value = value != null ? value : this._value();

		// always save the actual value, not the one passed as an argument
		this.term = this._value();

		if ( value.length < this.options.minLength ) {
			return this.close( event );
		}

		clearTimeout( this.closing );
		if ( this._trigger( "search", event ) === false ) {
			return;
		}

		return this._search( value );
	},

	_search: function( value ) {
		this.pending++;
		this.element.addClass( "ui-autocomplete-loading" );

		this.source( { term: value }, this.response );
	},

	_response: function( content ) {
		if ( content ) {
			content = this._normalize( content );
		}
		this._trigger( "response", null, { content: content } );
		if ( !this.options.disabled && content && content.length ) {
			this._suggest( content );
			this._trigger( "open" );
		} else {
			this.close();
		}
		this.pending--;
		if ( !this.pending ) {
			this.element.removeClass( "ui-autocomplete-loading" );
		}
	},

	close: function( event ) {
		clearTimeout( this.closing );
		if ( this.menu.element.is(":visible") ) {
			this.menu.element.hide();
			this.menu.blur();
			this._trigger( "close", event );
			this.menu.isNewMenu = true;
		}
	},

	_change: function( event ) {
		if ( this.previous !== this._value() ) {
			this._trigger( "change", event, { item: this.selectedItem } );
		}
	},

	_normalize: function( items ) {
		// assume all items have the right format when the first item is complete
		if ( items.length && items[0].label && items[0].value ) {
			return items;
		}
		return $.map( items, function(item) {
			if ( typeof item === "string" ) {
				return {
					label: item,
					value: item
				};
			}
			return $.extend({
				label: item.label || item.value,
				value: item.value || item.label
			}, item );
		});
	},

	_suggest: function( items ) {
		var ul = this.menu.element
			.empty()
			.zIndex( this.element.zIndex() + 1 );
		this._renderMenu( ul, items );
		// TODO refresh should check if the active item is still in the dom, removing the need for a manual blur
		this.menu.blur();
		this.menu.refresh();

		// size and position menu
		ul.show();
		this._resizeMenu();
		ul.position( $.extend({
			of: this.element
		}, this.options.position ));

		if ( this.options.autoFocus ) {
			this.menu.next( new $.Event("mouseover") );
		}
	},

	_resizeMenu: function() {
		var ul = this.menu.element;
		ul.outerWidth( Math.max(
			ul.width( "" ).outerWidth(),
			this.element.outerWidth()
		) );
	},

	_renderMenu: function( ul, items ) {
		var self = this;
		$.each( items, function( index, item ) {
			self._renderItem( ul, item );
		});
	},

	_renderItem: function( ul, item) {
		return $( "

" )
			.data( "item.autocomplete", item )
			.append( $( "" ).text( item.label ) )
			.appendTo( ul );
	},

	_move: function( direction, event ) {
		if ( !this.menu.element.is(":visible") ) {
			this.search( null, event );
			return;
		}
		if ( this.menu.first() && /^previous/.test(direction) ||
				this.menu.last() && /^next/.test(direction) ) {
			this._value( this.term );
			this.menu.blur();
			return;
		}
		this.menu[ direction ]( event );
	},

	widget: function() {
		return this.menu.element;
	},

	_value: function( value ) {
		return this.valueMethod.apply( this.element, arguments );
	}
});

$.extend( $.ui.autocomplete, {
	version: "@VERSION",
	escapeRegex: function( value ) {
		return value.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
	},
	filter: function(array, term) {
		var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
		return $.grep( array, function(value) {
			return matcher.test( value.label || value.value || value );
		});
	}
});

}( jQuery ));
<|endoftext|>


<commit_before>export default function getEntityLink(entity) {
  return entity.id ? `/entities/${entity.id}` : null;
}
<commit_msg>Missing entity<commit_after>export default function getEntityLink(entity) {
  return (entity && entity.id) ? `/entities/${entity.id}` : null;
}
<|endoftext|>


<commit_before>export { Base };

import * as Pool from "../../util/Pool.js";
import * as Recyclable from "../../util/Recyclable.js";
import * as MultiLayerMap from "../../util/MultiLayerMap.js";
import * as FloatValue from "../../Unpacker/FloatValue.js";
import * as ValueDesc from "../../Unpacker/ValueDesc.js";
import * as NumberImage from "./NumberImage.js";

/**
 * Dynamically create random image data with specified channelCount, depthwise_AvgMax_Or_ChannelMultiplier, depthwiseFilterHeight,
 * depthwiseFilterWidth, depthwiseStridesPad. The same image data will be returned when same specification is requested. So that
 * the testing performance could be improved.
 */
class Base extends Recyclable.Root {

  /**
   * Used as default ImageSourceBag.Base provider for conforming to Recyclable interface.
   */
  static Pool = new Pool.Root( "ImageSourceBag.Base.Pool", Base, Base.setAsConstructor );

  /**
   */
  constructor() {
    super();
    Base.setAsConstructor_self.call( this );
  }

  /** @override */
  static setAsConstructor() {
    super.setAsConstructor();
    Base.setAsConstructor_self.call( this );
    return this;
  }

  /** @override */
  static setAsConstructor_self() {
    // Images indexed by [ originalHeight, originalWidth, channelCount, filterHeight, filterWidth, stridesPad ].

    if ( !this.images )
      this.images = new MultiLayerMap.Base();

    if ( !this.tensors )
      this.tensors = new MultiLayerMap.Base();
  }

  /** @override */
  disposeResources() {

    {
      for ( let tensor of this.tensors.values() ) {
        tensor.dispose();
      }
      this.tensors.clear();
    }

    {
      for ( let numberImage of this.images.values() ) {
        numberImage.disposeResources_and_recycleToPool();
      }
      this.images.clear();
    }

    super.disposeResources();
  }

  /** @override */
  clear() {
    for ( let channelShuffler of this.values() ) {
      channelShuffler.disposeResources_and_recycleToPool();
    }
    super.clear();
  }

  /**
   * If ( depthwiseFilterHeight == 1 ) and ( depthwiseFilterWidth == 1 ) and ( depthwiseStridesPad == 0 ), the original image will be
   * returned. The original image has the size ( originalHeight, originalWidth, channelCount ). Its value is generated randomly.
   *
   *
   * @param {number} originalHeight
   *   A positive integer which represents the returned image's original height.
   *
   * @param {number} originalWidth
   *   A positive integer which represents the returned image's original width.
   *
   * @param {number} channelCount
   *   A positive integer which represents the returned image's depth.
   *
   * @param {number} depthwise_AvgMax_Or_ChannelMultiplier
   *   An integer represents the returned image should be the original image processed by depthwise convolution filter of this kinds.
   * Its should be in the range of ValueDesc.AvgMax_Or_ChannelMultiplier.Singleton.range.
   *
   * @param {number} depthwiseFilterHeight
   *   An integer represents the returned image should be the original image processed by depthwise convolution filter of this height.
   * Its should be in the range of Block.Params.depthwiseFilterHeight.valueDesc.range.
   *
   * @param {number} depthwiseFilterWidth
   *   An integer represents the returned image should be the original image processed by depthwise convolution filter of this width.
   * Its should be in the range of Block.Params.depthwiseFilterWidth.valueDesc.range.
   *
   * @param {number} depthwiseStridesPad
   *   An integer represents the returned image should be the original image processed by depthwise convolution of this strides and pad.
   * Its should be in the range of ValueDesc.depthwiseStridesPad.Singleton.range.
   *
   * @return {NumberImage.Base}
   *   Return an image data with the specified specification.
   */
  getImage_by(
    originalHeight, originalWidth, channelCount,
    depthwise_AvgMax_Or_ChannelMultiplier = 0, depthwiseFilterHeight = 1, depthwiseFilterWidth = 1, depthwiseStridesPad = 0 ) {

    // 1. When no depthwise operation, the original image is returned directly (i.e. will not be shrinked).
    //
    // Because there is not depthwise operation, there is not possible to shrink.
    if ( depthwise_AvgMax_Or_ChannelMultiplier == ValueDesc.AvgMax_Or_ChannelMultiplier.Singleton.Ids.NONE ) {
      let originalImage = Base.internal_getImage_by.call( this, originalHeight, originalWidth, channelCount );
      return originalImage;
    }

    // 2. Otherwise, return image which is adjusted by depthwise operation.
    let image = Base.internal_getImage_by.call( this,
      originalHeight, originalWidth, channelCount, depthwiseFilterHeight, depthwiseFilterWidth, depthwiseStridesPad );

    return image;
  }

  /**
   *
   * @return {tf.tensor3d}
   *   Return a tensor with the specified specification.
   */
  getTensor3d_by(
    originalHeight, originalWidth, channelCount,
    depthwise_AvgMax_Or_ChannelMultiplier = 0, depthwiseFilterHeight = 1, depthwiseFilterWidth = 1, depthwiseStridesPad = 0 ) {

    // 1. When no depthwise operation, the original image's tensor is returned directly (i.e. will not be shrinked).
    //
    // Because there is not depthwise operation, there is not possible to shrink.
    if ( depthwise_AvgMax_Or_ChannelMultiplier == ValueDesc.AvgMax_Or_ChannelMultiplier.Singleton.Ids.NONE ) {
      let originalTensor = Base.internal_getTensor3d_by.call( this, originalHeight, originalWidth, channelCount );
      return originalTensor;
    }

    // 2. Otherwise, return image tensor which is adjusted by depthwise operation.
    let tensor = Base.internal_getTensor3d_by.call( this,
      originalHeight, originalWidth, channelCount, depthwiseFilterHeight, depthwiseFilterWidth, depthwiseStridesPad );
    return tensor;
  }

  /**
   * Similiar to this.getImage_by() but does not consider depthwise_AvgMax_Or_ChannelMultiplier.
   */
  static internal_getImage_by(
    originalHeight, originalWidth, channelCount, depthwiseFilterHeight = 1, depthwiseFilterWidth = 1, depthwiseStridesPad = 0 ) {

    return this.images.get_or_create_by_arguments1_etc( Base.image_createBy, this,
      originalHeight, originalWidth, channelCount, depthwiseFilterHeight, depthwiseFilterWidth, depthwiseStridesPad );
  }

  /** Called when the requested image has not yet existed. */
  static image_createBy(
    originalHeight, originalWidth, channelCount, depthwiseFilterHeight = 1, depthwiseFilterWidth = 1, depthwiseStridesPad = 0 ) {

    let image;

    // 1. The original image is requested.
    if ( ( depthwiseFilterHeight == 1 ) && ( depthwiseFilterWidth == 1 ) && ( depthwiseStridesPad == 0 ) ) {
      let randomOffsetMin = -200; // Just choosed randomly.
      let randomOffsetMax = +200;

      //!!! (2022/04/21 Remaked) Using Weights.Base.ValueBounds is more like real use case.
      //let bAutoBounds = true;  // Image pixel channel value bounds are inside the real generated value bounds.
      let bAutoBounds = false; // Image pixel channel value bounds are inside the default value bounds (i.e. Weights.Base.ValueBounds).
      image = NumberImage.Base.create_bySequenceRandom( originalHeight, originalWidth, channelCount, randomOffsetMin, randomOffsetMax );

    // 2. The shrinked image requested.
    } else {

      // Use original image to create shrinked image.
      let originalImage = Base.internal_getImage_by.call( this, originalHeight, originalWidth, channelCount );

      // Borrow the clone_byDepthwise() function to create an input image which is shrinked by specified filter size and strides and pad.
      image = originalImage.clone_byDepthwise_NonPassThrough(
        ValueDesc.AvgMax_Or_ChannelMultiplier.Singleton.Ids.MAX, // Max Pooling is faster and without filter weights.
        depthwiseFilterHeight, depthwiseFilterWidth,
        depthwiseStridesPad,
        null, false,  // depthwiseFiltersArray, bDepthwiseBias,
        null, ValueDesc.ActivationFunction.Singleton.Ids.NONE, // depthwiseBiasesArray, depthwiseActivationId,
        "", "ImageSourceBag.Base.internal_getImage_by()"
      );
    }

    return image;
  }

  /**
   * Similiar to this.getTensor3d_by() but does not consider depthwise_AvgMax_Or_ChannelMultiplier.
   */
  static internal_getTensor3d_by(
    originalHeight, originalWidth, channelCount, depthwiseFilterHeight = 1, depthwiseFilterWidth = 1, depthwiseStridesPad = 0 ) {

    return this.tensors.get_or_create_by_arguments1_etc( Base.tensor_createBy, this,
      originalHeight, originalWidth, channelCount, depthwiseFilterHeight, depthwiseFilterWidth, depthwiseStridesPad );
  }

  /** Called when the requested tensor has not yet existed. */
  static tensor_createBy(
    originalHeight, originalWidth, channelCount, depthwiseFilterHeight, depthwiseFilterWidth, depthwiseStridesPad ) {

    let image = Base.internal_getImage_by.call( this,
      originalHeight, originalWidth, channelCount, depthwiseFilterHeight, depthwiseFilterWidth, depthwiseStridesPad );

    let shape = [ image.height, image.width, image.depth ];
    let tensor = tf.tensor3d( image.dataArray, shape ); // Create new tensor of specified specification.
    return tensor;
  }

}
<commit_msg>Update ImageSourceBag.js<commit_after>export { Base };

import * as Pool from "../../util/Pool.js";
import * as Recyclable from "../../util/Recyclable.js";
import * as MultiLayerMap from "../../util/MultiLayerMap.js";
import * as FloatValue from "../../Unpacker/FloatValue.js";
import * as ValueDesc from "../../Unpacker/ValueDesc.js";
import * as NumberImage from "./NumberImage.js";

/**
 * Dynamically create random image data with specified channelCount, depthwise_AvgMax_Or_ChannelMultiplier, depthwiseFilterHeight,
 * depthwiseFilterWidth, depthwiseStridesPad. The same image data will be returned when same specification is requested. So that
 * the testing performance could be improved.
 */
class Base extends Recyclable.Root {

  /**
   * Used as default ImageSourceBag.Base provider for conforming to Recyclable interface.
   */
  static Pool = new Pool.Root( "ImageSourceBag.Base.Pool", Base, Base.setAsConstructor );

  /**
   */
  constructor() {
    super();
    Base.setAsConstructor_self.call( this );
  }

  /** @override */
  static setAsConstructor() {
    super.setAsConstructor();
    Base.setAsConstructor_self.call( this );
    return this;
  }

  /** @override */
  static setAsConstructor_self() {
    // Images indexed by [ originalHeight, originalWidth, channelCount, filterHeight, filterWidth, stridesPad ].

    if ( !this.images )
      this.images = new MultiLayerMap.Base();

    if ( !this.tensors )
      this.tensors = new MultiLayerMap.Base();
  }

  /** @override */
  disposeResources() {

    {
      for ( let tensor of this.tensors.values() ) {
        tensor.dispose();
      }
      this.tensors.clear();
    }

    {
      for ( let numberImage of this.images.values() ) {
        numberImage.disposeResources_and_recycleToPool();
      }
      this.images.clear();
    }

    super.disposeResources();
  }

  /** @override */
  clear() {
    for ( let channelShuffler of this.values() ) {
      channelShuffler.disposeResources_and_recycleToPool();
    }
    super.clear();
  }

  /**
   * If ( depthwiseFilterHeight == 1 ) and ( depthwiseFilterWidth == 1 ) and ( depthwiseStridesPad == 0 ), the original image will be
   * returned. The original image has the size ( originalHeight, originalWidth, channelCount ). Its value is generated randomly.
   *
   *
   * @param {number} originalHeight
   *   A positive integer which represents the returned image's original height.
   *
   * @param {number} originalWidth
   *   A positive integer which represents the returned image's original width.
   *
   * @param {number} channelCount
   *   A positive integer which represents the returned image's depth.
   *
   * @param {number} depthwise_AvgMax_Or_ChannelMultiplier
   *   An integer represents the returned image should be the original image processed by depthwise convolution filter of this kinds.
   * Its should be in the range of ValueDesc.AvgMax_Or_ChannelMultiplier.Singleton.range.
   *
   * @param {number} depthwiseFilterHeight
   *   An integer represents the returned image should be the original image processed by depthwise convolution filter of this height.
   * Its should be in the range of Block.Params.depthwiseFilterHeight.valueDesc.range.
   *
   * @param {number} depthwiseFilterWidth
   *   An integer represents the returned image should be the original image processed by depthwise convolution filter of this width.
   * Its should be in the range of Block.Params.depthwiseFilterWidth.valueDesc.range.
   *
   * @param {number} depthwiseStridesPad
   *   An integer represents the returned image should be the original image processed by depthwise convolution of this strides and pad.
   * Its should be in the range of ValueDesc.depthwiseStridesPad.Singleton.range.
   *
   * @return {NumberImage.Base}
   *   Return an image data with the specified specification.
   */
  getImage_by(
    originalHeight, originalWidth, channelCount,
    depthwise_AvgMax_Or_ChannelMultiplier = 0, depthwiseFilterHeight = 1, depthwiseFilterWidth = 1, depthwiseStridesPad = 0 ) {

    // 1. When no depthwise operation, the original image is returned directly (i.e. will not be shrinked).
    //
    // Because there is not depthwise operation, there is not possible to shrink.
    if ( depthwise_AvgMax_Or_ChannelMultiplier == ValueDesc.AvgMax_Or_ChannelMultiplier.Singleton.Ids.NONE ) {
      let originalImage = Base.internal_getImage_by.call( this, originalHeight, originalWidth, channelCount );
      return originalImage;
    }

    // 2. Otherwise, return image which is adjusted by depthwise operation.
    let image = Base.internal_getImage_by.call( this,
      originalHeight, originalWidth, channelCount, depthwiseFilterHeight, depthwiseFilterWidth, depthwiseStridesPad );

    return image;
  }

  /**
   *
   * @return {tf.tensor3d}
   *   Return a tensor with the specified specification.
   */
  getTensor3d_by(
    originalHeight, originalWidth, channelCount,
    depthwise_AvgMax_Or_ChannelMultiplier = 0, depthwiseFilterHeight = 1, depthwiseFilterWidth = 1, depthwiseStridesPad = 0 ) {

    // 1. When no depthwise operation, the original image's tensor is returned directly (i.e. will not be shrinked).
    //
    // Because there is not depthwise operation, there is not possible to shrink.
    if ( depthwise_AvgMax_Or_ChannelMultiplier == ValueDesc.AvgMax_Or_ChannelMultiplier.Singleton.Ids.NONE ) {
      let originalTensor = Base.internal_getTensor3d_by.call( this, originalHeight, originalWidth, channelCount );
      return originalTensor;
    }

    // 2. Otherwise, return image tensor which is adjusted by depthwise operation.
    let tensor = Base.internal_getTensor3d_by.call( this,
      originalHeight, originalWidth, channelCount, depthwiseFilterHeight, depthwiseFilterWidth, depthwiseStridesPad );
    return tensor;
  }

  /**
   * Similiar to this.getImage_by() but does not consider depthwise_AvgMax_Or_ChannelMultiplier.
   */
  static internal_getImage_by(
    originalHeight, originalWidth, channelCount, depthwiseFilterHeight = 1, depthwiseFilterWidth = 1, depthwiseStridesPad = 0 ) {

    return this.images.get_or_create_by_arguments1_etc( Base.image_createBy, this,
      originalHeight, originalWidth, channelCount, depthwiseFilterHeight, depthwiseFilterWidth, depthwiseStridesPad );
  }

  /** Called when the requested image has not yet existed. */
  static image_createBy(
    originalHeight, originalWidth, channelCount, depthwiseFilterHeight = 1, depthwiseFilterWidth = 1, depthwiseStridesPad = 0 ) {

    let image;

    // 1. The original image is requested.
    if ( ( depthwiseFilterHeight == 1 ) && ( depthwiseFilterWidth == 1 ) && ( depthwiseStridesPad == 0 ) ) {
      let randomOffsetMin = -200; // Just choosed randomly.
      let randomOffsetMax = +200;

      //!!! (2022/04/21 Remarked) Using Weights.Base.ValueBounds is more like real use case.
      let bAutoBounds = true;  // Image pixel channel value bounds are inside the real generated value bounds.
      //!!! (2022/07/13 Remarked) Using small ValueBounds may reduce floating-point accumulated error.
      //let bAutoBounds = false; // Image pixel channel value bounds are inside the default value bounds (i.e. Weights.Base.ValueBounds).
      image = NumberImage.Base.create_bySequenceRandom( originalHeight, originalWidth, channelCount, randomOffsetMin, randomOffsetMax,
        bAutoBounds );

    // 2. The shrinked image requested.
    } else {

      // Use original image to create shrinked image.
      let originalImage = Base.internal_getImage_by.call( this, originalHeight, originalWidth, channelCount );

      // Borrow the clone_byDepthwise() function to create an input image which is shrinked by specified filter size and strides and pad.
      image = originalImage.clone_byDepthwise_NonPassThrough(
        ValueDesc.AvgMax_Or_ChannelMultiplier.Singleton.Ids.MAX, // Max Pooling is faster and without filter weights.
        depthwiseFilterHeight, depthwiseFilterWidth,
        depthwiseStridesPad,
        null, false,  // depthwiseFiltersArray, bDepthwiseBias,
        null, ValueDesc.ActivationFunction.Singleton.Ids.NONE, // depthwiseBiasesArray, depthwiseActivationId,
        "", "ImageSourceBag.Base.internal_getImage_by()"
      );
    }

    return image;
  }

  /**
   * Similiar to this.getTensor3d_by() but does not consider depthwise_AvgMax_Or_ChannelMultiplier.
   */
  static internal_getTensor3d_by(
    originalHeight, originalWidth, channelCount, depthwiseFilterHeight = 1, depthwiseFilterWidth = 1, depthwiseStridesPad = 0 ) {

    return this.tensors.get_or_create_by_arguments1_etc( Base.tensor_createBy, this,
      originalHeight, originalWidth, channelCount, depthwiseFilterHeight, depthwiseFilterWidth, depthwiseStridesPad );
  }

  /** Called when the requested tensor has not yet existed. */
  static tensor_createBy(
    originalHeight, originalWidth, channelCount, depthwiseFilterHeight, depthwiseFilterWidth, depthwiseStridesPad ) {

    let image = Base.internal_getImage_by.call( this,
      originalHeight, originalWidth, channelCount, depthwiseFilterHeight, depthwiseFilterWidth, depthwiseStridesPad );

    let shape = [ image.height, image.width, image.depth ];
    let tensor = tf.tensor3d( image.dataArray, shape ); // Create new tensor of specified specification.
    return tensor;
  }

}
<|endoftext|>


<commit_before>var addContent = function(o, e, i) {
    var proto = document.getElementById('prototype');
    var newEl = proto.cloneNode(true);

    e.appendChild(newEl);

    //TODO: change class name for different difficulties
    //TODO: get part name from API and display ("Part #") if none is provided

    newEl.setAttribute('class', 'part easy');
    newEl.removeAttribute('id');

    newEl.querySelector('.partName').setAttribute('for', 'part-'+i);
    newEl.querySelector('.partNameCheck').setAttribute('id', 'part-'+i);

    newEl.querySelector('.score').innerText = o.difficulty.toFixed(3);
    newEl.querySelector('.numNotes').innerText = o.numNotes;
    newEl.querySelector('.numChords').innerText = o.numChords;
    newEl.querySelector('.numAccidentals').innerText = o.numAccidentals;
    newEl.querySelector('.numGraceNotes').innerText = o.numGraceNotes;
    newEl.querySelector('.numRests').innerText = o.numRests;
    newEl.querySelector('.keyChanges').innerText = o.keyChanges;
    newEl.querySelector('.timeChanges').innerText = o.timeChanges;
    var rangeString = o.range.minPitch + '-' + o.range.maxPitch;
    newEl.querySelector('.range').innerText = rangeString;
};

var addPart = function(part, index) {
    var container = document.getElementById('part_container');

    addContent(part, container, index);
};

chrome.tabs.getSelected(null, function(tab) {
    var xhr = new XMLHttpRequest(),
        encodedUrl = encodeURIComponent(tab.url);
    xhr.open('GET', 'https://music-api.herokuapp.com/api/get_difficulty_for_musescore_url?url=' + encodedUrl, true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            var score = JSON.parse(xhr.response);

            document.getElementById('title').innerText = score.title;

            score.parts.map(addPart);

            var pro = document.getElementById('prototype');
            document.getElementById('part_container').removeChild(pro);
        }
    };
    xhr.send();
});
<commit_msg>Make difficulty more user-friendly<commit_after>var addContent = function(o, e, i) {
    var proto = document.getElementById('prototype');
    var newEl = proto.cloneNode(true);

    e.appendChild(newEl);

    //TODO: change class name for different difficulties
    //TODO: get part name from API and display ("Part #") if none is provided
    var score = (o.difficulty * 100).toFixed(0);

    newEl.setAttribute('class', 'part easy');
    newEl.removeAttribute('id');

    newEl.querySelector('.partName').setAttribute('for', 'part-'+i);
    newEl.querySelector('.partNameCheck').setAttribute('id', 'part-'+i);

    newEl.querySelector('.score').innerText = (o.difficulty * 100).toFixed(0);
    newEl.querySelector('.numNotes').innerText = o.numNotes;
    newEl.querySelector('.numChords').innerText = o.numChords;
    newEl.querySelector('.numAccidentals').innerText = o.numAccidentals;
    newEl.querySelector('.numGraceNotes').innerText = o.numGraceNotes;
    newEl.querySelector('.numRests').innerText = o.numRests;
    newEl.querySelector('.keyChanges').innerText = o.keyChanges;
    newEl.querySelector('.timeChanges').innerText = o.timeChanges;
    var rangeString = o.range.minPitch + '-' + o.range.maxPitch;
    newEl.querySelector('.range').innerText = rangeString;
};

var addPart = function(part, index) {
    var container = document.getElementById('part_container');

    addContent(part, container, index);
};

chrome.tabs.getSelected(null, function(tab) {
    var xhr = new XMLHttpRequest(),
        encodedUrl = encodeURIComponent(tab.url);
    xhr.open('GET', 'https://music-api.herokuapp.com/api/get_difficulty_for_musescore_url?url=' + encodedUrl, true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            var score = JSON.parse(xhr.response);

            document.getElementById('title').innerText = score.title;

            score.parts.map(addPart);

            var pro = document.getElementById('prototype');
            document.getElementById('part_container').removeChild(pro);
        }
    };
    xhr.send();
});
<|endoftext|>


<commit_before>// Unserialize view string into array of objects

'use strict';

var stringify = JSON.stringify;

module.exports = function (view, type) {
	return view.split('\n').map(function (data) {
		var id = data.slice(data.indexOf('.') + 1)
		  , obj = type.getById(id);
		if (!obj) {
			throw new Error("Not object found for " + stringify(id) +
				" (full data: " + stringify(data) + ") by type: " + stringify(type.__id__));
		}
		return obj;
	});
};
<commit_msg>Fix handling of empty view<commit_after>// Unserialize view string into array of objects

'use strict';

var stringify = JSON.stringify;

module.exports = function (view, type) {
	if (!view) return [];
	return view.split('\n').map(function (data) {
		var id = data.slice(data.indexOf('.') + 1)
		  , obj = type.getById(id);
		if (!obj) {
			throw new Error("Not object found for " + stringify(id) +
				" (full data: " + stringify(data) + ") by type: " + stringify(type.__id__));
		}
		return obj;
	});
};
<|endoftext|>


<commit_before>/*global process:false*/
/*global module:true*/
/*global exports:true*/
"use strict";

var transform = require('jstransform').transform;
var typesSyntax = require('jstransform/visitors/type-syntax');
var visitors = require('./visitors');

/**
 * @typechecks
 * @param {string} source
 * @param {object?} options
 * @param {array?} excludes
 * @return {string}
 */
function transformAll(source, options, excludes) {
  excludes = excludes || [];

  // Stripping types needs to happen before the other transforms
  // unfortunately, due to bad interactions. For example,
  // es6-rest-param-visitors conflict with stripping rest param type
  // annotation
  source = transform(typesSyntax.visitorList, source, options).code;

  // The typechecker transform must run in a second pass in order to operate on
  // the entire source code -- so exclude it from the first pass
  var visitorsList = visitors.getAllVisitors(excludes.concat('typechecker'));
  source = transform(visitorsList, source, options);
  if (excludes.indexOf('typechecks') == -1 && /@typechecks/.test(source.code)) {
    source = transform(
      visitors.transformVisitors.typechecker,
      source.code,
      options
    );
  }
  return source;
}

function runCli(argv) {
  var options = {};
  for (var optName in argv) {
    if (optName === '_' || optName === '$0') {
      continue;
    }
    options[optName] = optimist.argv[optName];
  }

  if (options.help) {
    optimist.showHelp();
    process.exit(0);
  }

  var excludes = options.excludes;
  delete options.excludes;

  var source = '';
  process.stdin.resume();
  process.stdin.setEncoding('utf8');
  process.stdin.on('data', function (chunk) {
    source += chunk;
  });
  process.stdin.on('end', function () {
    try {
      source = transformAll(source, options, excludes);
    } catch (e) {
      console.error(e.stack);
      process.exit(1);
    }
    process.stdout.write(source.code);
  });
}

if (require.main === module) {
  var optimist = require('optimist');

  optimist = optimist
    .usage('Usage: $0 [options]')
    .default('exclude', [])
    .boolean('help').alias('h', 'help')
    .boolean('minify')
    .describe(
      'minify',
      'Best-effort minification of the output source (when possible)'
    )
    .describe(
      'exclude',
      'A list of transformNames to exclude'
    );

  runCli(optimist.argv);
} else {
  exports.transformAll = transformAll;
}
<commit_msg>Remove fbtransform/syntax.js<commit_after><|endoftext|>


<commit_before>module.exports = function(config){
  var opalPath;
  if(process.env.TRAVIS){
    python_version = process.env.TRAVIS_PYTHON_VERSION;
    opalPath = '/home/travis/virtualenv/python' + python_version + '/src/opal';
  }
  else{
    opalPath = '../../opal';
  }
  var karmaDefaults = require(opalPath + '/config/karma_defaults.js');
  var karmaDir = __dirname;
  var coverageFiles = [
    __dirname + '/../referral/static/js/referral/*.js',
    __dirname + '/../referral/static/js/referral/controllers/*.js'
  ];
  var includedFiles = [
      __dirname + '/../referral/static/js/referral/*.js',
      __dirname + '/../referral/static/js/referral/controllers/*.js',
      __dirname + '/../referral/static/js/test/*.js',
  ];

  var defaultConfig = karmaDefaults(karmaDir, coverageFiles, includedFiles);
  config.set(defaultConfig);
};
<commit_msg>Update karma.conf.js<commit_after>module.exports = function(config){
  var opalPath;
  if(process.env.TRAVIS){
    python_version = process.env.TRAVIS_PYTHON_VERSION;
    opalPath = '/home/travis/virtualenv/python' + python_version + '/src/opal';
  }
  else{
    opalPath = '../../opal';
  }
  var karmaDefaults = require(opalPath + '/config/karma_defaults.js');
  var karmaDir = __dirname + '/..';
  var coverageFiles = [
    __dirname + '/../referral/static/js/referral/*.js',
    __dirname + '/../referral/static/js/referral/controllers/*.js'
  ];
  var includedFiles = [
      __dirname + '/../referral/static/js/referral/*.js',
      __dirname + '/../referral/static/js/referral/controllers/*.js',
      __dirname + '/../referral/static/js/test/*.js',
  ];

  var defaultConfig = karmaDefaults(includedFiles, karmaDir, coverageFiles);
  config.set(defaultConfig);
};
<|endoftext|>


<commit_before>// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
'use strict';

require('./files.js');

const execSync = require('child_process').execSync;

const ROOT_DIR = `${__dirname}/..`;
const FOAM_DIR = `${ROOT_DIR}/node_modules/foam2`;

// Outputs ../node_modules/foam2-experimental/foam-bin.js
execSync(`node ${FOAM_DIR}/tools/build.js web`);

const basePath = `${ROOT_DIR}/test`;
const deps = [
  `${FOAM_DIR}/foam-bin.js`,
  `${FOAM_DIR}/test/helpers/generic_dao.js`,
  `${FOAM_DIR}/test/helpers/testcontext.js`,
];
const entries = global.WEB_IDL_DIFF_FILES.slice()
    .map(path => `${ROOT_DIR}/${path}`);
const helpers = [
  'any/**/*-helper*.js',
  'browser/**/*-helper*.js',
];
const units = [
  'any/**/*-test*.js',
  'browser/**/*-test*.js',
];
const integrations = [
  'any/**/*-integration*.js',
  'browser/**/*-integration*.js',
];
const reporters = ['progress'];
function configurator(config) {
  config.set({
    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath,

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: deps,

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters,

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR ||
    // config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // start these browsers
    // available browser launchers:
    // https://npmjs.org/browse/keyword/karma-launcher
    // If run in travisCI, use firefox, otherwise, use Chrome.
    browsers: process.env.TRAVIS ? ['Firefox'] : ['Chrome'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: true,

    // enable / disable watching file and executing tests whenever any file
    // changes
    autoWatch: false,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity,
  });
}

configurator.ROOT_DIR = ROOT_DIR;
configurator.FOAM_DIR = FOAM_DIR;
configurator.deps = deps;
configurator.entries = entries;
configurator.helpers = helpers;
configurator.units = units;
configurator.integrations = integrations;

module.exports = configurator;
<commit_msg>Set browserNoActivityTimeout in Karma to fix Travis CI<commit_after>// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
'use strict';

require('./files.js');

const execSync = require('child_process').execSync;

const ROOT_DIR = `${__dirname}/..`;
const FOAM_DIR = `${ROOT_DIR}/node_modules/foam2`;

// Outputs ../node_modules/foam2-experimental/foam-bin.js
execSync(`node ${FOAM_DIR}/tools/build.js web`);

const basePath = `${ROOT_DIR}/test`;
const deps = [
  `${FOAM_DIR}/foam-bin.js`,
  `${FOAM_DIR}/test/helpers/generic_dao.js`,
  `${FOAM_DIR}/test/helpers/testcontext.js`,
];
const entries = global.WEB_IDL_DIFF_FILES.slice()
    .map(path => `${ROOT_DIR}/${path}`);
const helpers = [
  'any/**/*-helper*.js',
  'browser/**/*-helper*.js',
];
const units = [
  'any/**/*-test*.js',
  'browser/**/*-test*.js',
];
const integrations = [
  'any/**/*-integration*.js',
  'browser/**/*-integration*.js',
];
const reporters = ['progress'];
function configurator(config) {
  config.set({
    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath,

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: deps,

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters,

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR ||
    // config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // start these browsers
    // available browser launchers:
    // https://npmjs.org/browse/keyword/karma-launcher
    // If run in Travise CI, use firefox, otherwise use Chrome.
    browsers: process.env.TRAVIS ? ['Firefox'] : ['Chrome'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: true,

    // enable / disable watching file and executing tests whenever any file
    // changes
    autoWatch: false,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity,

    // Prevent Travis CI from killing Karma before it's done.
    browserNoActivityTimeout: 150000,
  });
}

configurator.ROOT_DIR = ROOT_DIR;
configurator.FOAM_DIR = FOAM_DIR;
configurator.deps = deps;
configurator.entries = entries;
configurator.helpers = helpers;
configurator.units = units;
configurator.integrations = integrations;

module.exports = configurator;
<|endoftext|>


<commit_before>const path = require('path');
const webpackConfig = require('./webpack.karma.config');

// Karma configuration
module.exports = function(config, specificOptions) {
	config.set({

		// base path that will be used to resolve all patterns (eg. files, exclude)
		basePath: '',

		// frameworks to use
		// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
		frameworks: [
			'sinon-chai',
			'sinon',
			'chai-as-promised',
			'chai',
			'mocha'
		],

		// list of files / patterns to load in the browser
		files: [
			'../src/**/*__tests__*/**/*spec.browser.js',
			'../src/**/*__tests__*/**/*spec.server.js'
		],
		// list of files to exclude
		exclude: [],
		// preprocess matching files before serving them to the browser
		// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
		preprocessors: {
			'../src/**/*__tests__*/**/*spec.server.js': ['webpack', 'sourcemap'],
			'../src/**/*__tests__*/**/*spec.browser.js': ['webpack', 'sourcemap']
		},
		webpack: {
			module: webpackConfig.module
		},
		webpackMiddleware: {
			noInfo: true
		},
		// test results reporter to use
		// possible values: 'dots', 'progress'
		// available reporters: https://npmjs.org/browse/keyword/karma-reporter
		reporters: ['mocha', 'coverage'],
		// reporter options
		mochaReporter: {
			colors: {
				success: 'green',
				info: 'bgYellow',
				warning: 'cyan',
				error: 'bgRed'
			},
			divider: ''
		},
		coverageReporter: {
			reporters: [
				{ type: 'html', dir: 'coverage/' },
				{ type: 'text' }
			]
		},

		// enable / disable watching file and executing tests whenever any file changes
		autoWatch: true,
		browsers: ['Chrome'],

		customLaunchers: {
		Chrome_for_Travis_CI: {
				base: 'Chrome',
				flags: ['--no-sandbox']
			}
		},

		browserDisconnectTimeout: 10000,
		browserDisconnectTolerance: 2,

		// Concurrency level
		// how many browser should be started simultaneous
		concurrency: 4,
		// If browser does not capture in given timeout [ms], kill it
		captureTimeout: 100000,
		browserNoActivityTimeout: 30000,

		// enable / disable colors in the output (reporters and logs)
		colors: true,

		// level of logging
		// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
		logLevel: config.LOG_INFO,

		// enable / disable watching file and executing tests whenever any file changes
		autoWatch: false,

		// Continuous Integration mode
		// if true, Karma captures browsers, runs the tests and exits
		singleRun: true
	});

	if (process.env.TRAVIS) {

		// Use Chrome as default browser for Travis CI
		config.browsers = ['Chrome_for_Travis_CI'];
		// Used by Travis to push coveralls info corretly to example coveralls.io
		config.reporters = ['mocha', 'coverage', 'coveralls'];
		// Karma (with socket.io 1.x) buffers by 50 and 50 tests can take a long time on IEs;-)
		config.browserNoActivityTimeout = 120000;

		if (process.env.BROWSER_PROVIDER === 'saucelabs' || !process.env.BROWSER_PROVIDER) {
			// Allocating a browser can take pretty long (eg. if we are out of capacity and need to wait
			// for another build to finish) and so the `captureTimeout` typically kills
			// an in-queue-pending request, which makes no sense.
			config.captureTimeout = 0;
		}
	}
};
<commit_msg>added missing lcov  report<commit_after>const path = require('path');
const webpackConfig = require('./webpack.karma.config');

// Karma configuration
module.exports = function(config, specificOptions) {
	config.set({

		// base path that will be used to resolve all patterns (eg. files, exclude)
		basePath: '',

		// frameworks to use
		// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
		frameworks: [
			'sinon-chai',
			'sinon',
			'chai-as-promised',
			'chai',
			'mocha'
		],

		// list of files / patterns to load in the browser
		files: [
			'../src/**/*__tests__*/**/*spec.browser.js',
			'../src/**/*__tests__*/**/*spec.server.js'
		],
		// list of files to exclude
		exclude: [],
		// preprocess matching files before serving them to the browser
		// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
		preprocessors: {
			'../src/**/*__tests__*/**/*spec.server.js': ['webpack', 'sourcemap'],
			'../src/**/*__tests__*/**/*spec.browser.js': ['webpack', 'sourcemap']
		},
		webpack: {
			module: webpackConfig.module
		},
		webpackMiddleware: {
			noInfo: true
		},
		// test results reporter to use
		// possible values: 'dots', 'progress'
		// available reporters: https://npmjs.org/browse/keyword/karma-reporter
		reporters: ['mocha', 'coverage'],
		// reporter options
		mochaReporter: {
			colors: {
				success: 'green',
				info: 'bgYellow',
				warning: 'cyan',
				error: 'bgRed'
			},
			divider: ''
		},
		coverageReporter: {
			reporters: [{
				type: 'html',
				dir: '../coverage'
			}, {
				type: 'text',
				dir: '../coverage'
			}, {
				type: 'lcov',
				dir: '../coverage'
			}]
		},

		// enable / disable watching file and executing tests whenever any file changes
		autoWatch: true,
		browsers: ['Chrome'],

		customLaunchers: {
		Chrome_for_Travis_CI: {
				base: 'Chrome',
				flags: ['--no-sandbox']
			}
		},

		browserDisconnectTimeout: 10000,
		browserDisconnectTolerance: 2,

		// Concurrency level
		// how many browser should be started simultaneous
		concurrency: 4,
		// If browser does not capture in given timeout [ms], kill it
		captureTimeout: 100000,
		browserNoActivityTimeout: 30000,

		// enable / disable colors in the output (reporters and logs)
		colors: true,

		// level of logging
		// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
		logLevel: config.LOG_INFO,

		// enable / disable watching file and executing tests whenever any file changes
		autoWatch: false,

		// Continuous Integration mode
		// if true, Karma captures browsers, runs the tests and exits
		singleRun: true
	});

	if (process.env.TRAVIS) {

		// Use Chrome as default browser for Travis CI
		config.browsers = ['Chrome_for_Travis_CI'];
		// Used by Travis to push coveralls info corretly to example coveralls.io
		config.reporters = ['mocha', 'coverage', 'coveralls'];
		// Karma (with socket.io 1.x) buffers by 50 and 50 tests can take a long time on IEs;-)
		config.browserNoActivityTimeout = 120000;

		if (process.env.BROWSER_PROVIDER === 'saucelabs' || !process.env.BROWSER_PROVIDER) {
			// Allocating a browser can take pretty long (eg. if we are out of capacity and need to wait
			// for another build to finish) and so the `captureTimeout` typically kills
			// an in-queue-pending request, which makes no sense.
			config.captureTimeout = 0;
		}
	}
};
<|endoftext|>


<commit_before>'use strict';
// Listens to the microphone and prints something when it's loud.
// `npm run-script listen` to run this.

// I installed this manually rather than via package.json
let coreAudio = require('node-core-audio');

let engine = coreAudio.createNewAudioEngine();

let range = [];
for (let i = 0; i < 1024; i++) {
  range.push(i);
}

let zero = [range.map(x => 0)];
let soft = [range.map(x => 2)];
let loud = [range.map(x => 20)];

function round(num) {
  let answer = Math.round(num);
  // Avoid annoying-looking negative zero
  if (answer === 0) {
    answer = 0;
  }
  return answer;
}

function get(buffer, i) {
  return round(buffer[0][i] * 100);
}

// Input seems to be a 1x24 matrix of numbers.
let average = 0.0;
function processAudio(input) {
  let delta = Math.abs(get(input, 0) + get(input, 1) + get(input, 2)) / 3;
  average = 0.9 * average + 0.1 * delta;
  console.log(average);
}

while (true) {
  let sample = engine.read();
  processAudio(sample);
}
<commit_msg>better loudness-recog<commit_after>'use strict';
// Listens to the microphone and prints something when it's loud.
// `npm run-script listen` to run this.

// I installed this manually rather than via package.json
let coreAudio = require('node-core-audio');

let engine = coreAudio.createNewAudioEngine();

let range = [];
for (let i = 0; i < 1024; i++) {
  range.push(i);
}

let zero = [range.map(x => 0)];
let soft = [range.map(x => 2)];
let loud = [range.map(x => 20)];

function round(num) {
  let answer = Math.round(num);
  // Avoid annoying-looking negative zero
  if (answer === 0) {
    answer = 0;
  }
  return answer;
}

function get(buffer, i) {
  return round(buffer[0][i] * 100);
}

// Input seems to be a 1x24 matrix of numbers.
let average = 0.0;
let decay = 0.1;
let upperThreshold = 3.0;
let lowerThreshold = 2.0;
let active = false;
function processAudio(input) {
  let delta = Math.abs(get(input, 0) + get(input, 1) + get(input, 2)) / 3;
  average = (1 - decay) * average + decay * delta;
  if (average > upperThreshold) {
    active = true;
  } else if (active && average < lowerThreshold) {
    active = false;
  }

  console.log(active ? 'ON' : '--', '     ', average);
}

while (true) {
  let sample = engine.read();
  processAudio(sample);
}
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs'),
    path = require('path'),
    route = require('../../vendor/router');

module.exports = function (app) {
    /* Load All Routes */
    route.setApp(app);

    function recursiveRoutes(folderName) {
        var normalizedPath = path.join(__dirname, folderName);

        fs.readdirSync(normalizedPath).forEach(function (file) {
            var pathName = path.join(normalizedPath, file);
            var stat = fs.lstatSync(pathName);

            if (stat.isDirectory()) {
                recursiveRoutes(folderName + '/' + file);
            } else if (file.indexOf('.routes') >= 0) {
                var name = pathName.replace('.js', '').replace(/\\/g, '/');
                require(name)(app);
            }
        });
    }

    recursiveRoutes('./../../modules');

    app.get('/logout', function (req, res) {
        req.logout();
        res.redirect('/login');
    });
};
<commit_msg>update routes<commit_after>'use strict';

var fs = require('fs'),
    path = require('path'),
    root = path.dirname(require.main.filename),
    route = require(root + '/vendor/router');

module.exports = function (app) {
    /* Load All Routes */
    route.setApp(app);

    function recursiveRoutes(dir) {
        fs.readdirSync(dir).forEach(function (file) {
            var pathName = path.join(dir, file);
            var stat = fs.lstatSync(pathName);

            if (stat.isDirectory()) {
                recursiveRoutes(dir + '/' + file);
            } else if (file.indexOf('.routes') >= 0) {
                var name = pathName.replace('.js', '').replace(/\\/g, '/');
                require(name)(app);
            }
        });
    }

    recursiveRoutes(root + '/modules');

    app.get('/logout', function (req, res) {
        req.logout();
        res.redirect('/login');
    });
};
<|endoftext|>


<commit_before>/**
   Copyright 2011 Couchbase, Inc.

   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 MonitorServersSection = {
  init: function () {
    ServersSection.serversCell.subscribe(function() {
      renderTemplate('monitor_servers', {rows:ServersSection.active}, $i('monitor_servers_container'));
    });
    DAL.cells.bucketsListCell.subscribeValue(function (list) {
      var empty = (list && list.length === 0);
      $('#monitor_servers table a.node_name')
        [empty ? 'addClass' : 'removeClass']('disabled')
        .bind('click', !empty); // shut off clicking
    });
  },
  onEnter: function () {
  },
  navClick: function () {
    this.onLeave();
    this.onEnter();
  },
  onLeave: function () {
  }
};
<commit_msg>correctly render monitor servers<commit_after>/**
   Copyright 2011 Couchbase, Inc.

   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 MonitorServersSection = {
  init: function () {
    ServersSection.serversCell.subscribeValue(function(servers) {
      if (!servers) {
        return;
      }
      renderTemplate('monitor_servers', {rows:servers.active}, $i('monitor_servers_container'));
    });
    prepareTemplateForCell('monitor_servers', ServersSection.serversCell);
    DAL.cells.bucketsListCell.subscribeValue(function (list) {
      var empty = (list && list.length === 0);
      $('#monitor_servers table a.node_name')
        [empty ? 'addClass' : 'removeClass']('disabled')
        .bind('click', !empty); // shut off clicking
    });
  },
  onEnter: function () {
  },
  navClick: function () {
    this.onLeave();
    this.onEnter();
  },
  onLeave: function () {
  }
};
<|endoftext|>


<commit_before>var path = require('path');

var gulp  = require('gulp');
var watch = require('gulp-watch');

global.DEBUG    = false;
global.WATCHING = false;

global.P = {
  styl  : 'stylus/',
  jade  : 'jade/',

  css   : 'css/',
  php   : 'php/',
  py    : 'python/',
  html  : 'html/',
  js    : 'js/',

  img   : 'img/',
  font  : 'fonts/',

  dev   : './dev/',
  dist  : './dist/',
};

module.exports = function loader(dir, taskPaths) {
  var tasks = {};

  /**
   * Loading tasks
   */
  for(var i = 0, l = taskPaths.length; i < l; i++) {
    var taskPath = taskPaths[i],
        taskName = path.basename(taskPath, '.js');
    var spos = taskPath.indexOf('./');
    var rpath;

    if(spos == 0 || spos == 1) {
      rpath = path.normalize(dir + taskPath);
    } else {
      rpath = path.normalize(__dirname + '/lib/tasks/' + taskPath);
    }

    var task = tasks[taskName] = require(rpath);

    gulp.task(taskName + ':dev', task.dev);
    gulp.task(taskName + ':build', task.build);

    if(typeof task.watch == 'function') {
      gulp.task(taskName + ':watch', task.watch);
    }
  }

  /**
   * Additive tasks.
   */
  gulp.task('watch', function(){
    console.log('I\'m watching...');

    global.WATCHING = true;

    for(var i in tasks) {
      if(!tasks.hasOwnProperty(i)) continue;

      var task = tasks[i];

      if(task.watch) {
        if(typeof task.watch == 'function') {
          gulp.start(i + ':watch');
        } else {
          watch(task.watch, (function(taskName) {
            return function() {
              gulp.start(taskName + ':dev');
            };
          })(i));
        }
      }
    }
  });
};
<commit_msg>Small changes to the watch tasks mechanics.<commit_after>var path = require('path');

var gulp  = require('gulp');
var watch = require('gulp-watch');

global.DEBUG    = false;
global.WATCHING = false;

global.P = {
  styl  : 'stylus/',
  jade  : 'jade/',

  css   : 'css/',
  php   : 'php/',
  py    : 'python/',
  html  : 'html/',
  js    : 'js/',

  img   : 'img/',
  font  : 'fonts/',

  dev   : './dev/',
  dist  : './dist/',
};

module.exports = function loader(dir, taskPaths) {
  var tasks = {};

  /**
   * Loading tasks
   */
  for(var i = 0, l = taskPaths.length; i < l; i++) {
    var taskPath = taskPaths[i],
        taskName = path.basename(taskPath, '.js');
    var spos = taskPath.indexOf('./');
    var rpath;

    if(spos == 0 || spos == 1) {
      rpath = path.normalize(dir + taskPath);
    } else {
      rpath = path.normalize(__dirname + '/lib/tasks/' + taskPath);
    }

    var task = tasks[taskName] = require(rpath);

    gulp.task(taskName + ':dev', task.dev);
    gulp.task(taskName + ':build', task.build);

    if(typeof task.watch == 'function') {
      gulp.task(taskName + ':watch', task.watch);
    } else if(task.watch) {
      gulp.task(taskName + ':watch', (function(tN, wch) {
        return function() {
          return watch(wch, function() {
              gulp.start(tN + ':dev');
            });
        };
      })(taskName, task.watch));
    }
  }

  /**
   * Additive tasks.
   */
  gulp.task('watch', function(){
    console.log('I\'m watching...');

    global.WATCHING = true;

    for(var i in tasks) {
      if(!tasks.hasOwnProperty(i)) continue;

      var task = tasks[i];

      if(task.watch) {
        gulp.start(i + ':watch');
      }
    }
  });
};
<|endoftext|>


<commit_before>module.exports = {
  // Component specific configuration
  auth: {
    // Azure table for the client table
    clientTableName:                'Clients',

    // Publish references and schemas
    publishMetaData:                'true'
  },

  // Server configuration
  server: {
    // Public URL from which the server can be accessed (used for persona)
    publicUrl:                      'http://auth.taskcluster.net',

    // Run in development mode (logging and error handling)
    development:                    false,
  },

  // AWS SDK configuration for publication of schemas and references
  aws: {
    // Default AWS region, this is where the S3 bucket lives
    region:                         'us-west-2',

    // Lock API version to use the latest API from 2013, this is fuzzy locking,
    // but it does the trick...
    apiVersion:                     '2014-01-01'
  }
};
<commit_msg>Updating production config to use HTTPS from defaults<commit_after>module.exports = {
  // Component specific configuration
  auth: {
    // Azure table for the client table
    clientTableName:                'Clients',

    // Publish references and schemas
    publishMetaData:                'true'
  },

  // Server configuration
  server: {
    // Run in development mode (logging and error handling)
    development:                    false,
  },

  // AWS SDK configuration for publication of schemas and references
  aws: {
    // Default AWS region, this is where the S3 bucket lives
    region:                         'us-west-2',

    // Lock API version to use the latest API from 2013, this is fuzzy locking,
    // but it does the trick...
    apiVersion:                     '2014-01-01'
  }
};
<|endoftext|>