<commit_before>/*!
 * js-logger - http://github.com/jonnyreeves/js-logger
 * Jonny Reeves, http://jonnyreeves.co.uk/
 * js-logger may be freely distributed under the MIT license.
 */

/*jshint sub:true*/
/*global console:true,define:true, module:true*/
(function (global) {
    "use strict";

	// Top level module for the global, static logger instance.
	var Logger = { };

	// For those that are at home that are keeping score.
	Logger.VERSION = "@VERSION@";

	// Function which handles all incoming log messages.
	var logHandler;

	// Map of ContextualLogger instances by name; used by Logger.get() to return the same named instance.
	var contextualLoggersByNameMap = {};

	// Polyfill for ES5's Function.bind.
	var bind = function(scope, func) {
		return function() {
			return func.apply(scope, arguments);
		};
	};

	// Super exciting object merger-matron 9000 adding another 100 bytes to your download.
	var merge = function () {
		var args = arguments, target = args[0], key, i;
		for (i = 1; i < args.length; i++) {
			for (key in args[i]) {
				if (!(key in target) && args[i].hasOwnProperty(key)) {
					target[key] = args[i][key];
				}
			}
		}
		return target;
	};

	// Helper to define a logging level object; helps with optimisation.
	var defineLogLevel = function(value, name) {
		return { value: value, name: name };
	};

	// Predefined logging levels.
	Logger.DEBUG = defineLogLevel(1, 'DEBUG');
	Logger.INFO = defineLogLevel(2, 'INFO');
	Logger.WARN = defineLogLevel(4, 'WARN');
	Logger.ERROR = defineLogLevel(8, 'ERROR');
	Logger.OFF = defineLogLevel(99, 'OFF');

	// Inner class which performs the bulk of the work; ContextualLogger instances can be configured independently
	// of each other.
	var ContextualLogger = function(defaultContext) {
		this.context = defaultContext;
		this.setLevel(defaultContext.filterLevel);
		this.log = this.info;  // Convenience alias.
	};

	ContextualLogger.prototype = {
		// Changes the current logging level for the logging instance.
		setLevel: function(newLevel) {
			// Ensure the supplied Level object looks valid.
			if (newLevel && "value" in newLevel) {
				this.context.filterLevel = newLevel;
			}
		},

		// Is the logger configured to output messages at the supplied level?
		enabledFor: function (lvl) {
			var filterLevel = this.context.filterLevel;
			return lvl.value >= filterLevel.value;
		},

		debug: function () {
			this.invoke(Logger.DEBUG, arguments);
		},

		info: function () {
			this.invoke(Logger.INFO, arguments);
		},

		warn: function () {
			this.invoke(Logger.WARN, arguments);
		},

		error: function () {
			this.invoke(Logger.ERROR, arguments);
		},

		// Invokes the logger callback if it's not being filtered.
		invoke: function (level, msgArgs) {
			if (logHandler && this.enabledFor(level)) {
				logHandler(msgArgs, merge({ level: level }, this.context));
			}
		}
	};

	// Protected instance which all calls to the to level `Logger` module will be routed through.
	var globalLogger = new ContextualLogger({ filterLevel: Logger.OFF });

	// Configure the global Logger instance.
	(function() {
		// Shortcut for optimisers.
		var L = Logger;

		L.enabledFor = bind(globalLogger, globalLogger.enabledFor);
		L.debug = bind(globalLogger, globalLogger.debug);
		L.info = bind(globalLogger, globalLogger.info);
		L.warn = bind(globalLogger, globalLogger.warn);
		L.error = bind(globalLogger, globalLogger.error);

		// Don't forget the convenience alias!
		L.log = L.info;
	}());

	// Set the global logging handler.  The supplied function should expect two arguments, the first being an arguments
	// object with the supplied log messages and the second being a context object which contains a hash of stateful
	// parameters which the logging function can consume.
	Logger.setHandler = function (func) {
		logHandler = func;
	};

	// Sets the global logging filter level which applies to *all* previously registered, and future Logger instances.
	// (note that named loggers (retrieved via `Logger.get`) can be configured independently if required).
	Logger.setLevel = function(level) {
		// Set the globalLogger's level.
		globalLogger.setLevel(level);

		// Apply this level to all registered contextual loggers.
		for (var key in contextualLoggersByNameMap) {
			if (contextualLoggersByNameMap.hasOwnProperty(key)) {
				contextualLoggersByNameMap[key].setLevel(level);
			}
		}
	};

	// Retrieve a ContextualLogger instance.  Note that named loggers automatically inherit the global logger's level,
	// default context and log handler.
	Logger.get = function (name) {
		// All logger instances are cached so they can be configured ahead of use.
		return contextualLoggersByNameMap[name] ||
			(contextualLoggersByNameMap[name] = new ContextualLogger(merge({ name: name }, globalLogger.context)));
	};

	// Configure and example a Default implementation which writes to the `window.console` (if present).
	Logger.useDefaults = function(defaultLevel) {
		// Check for the presence of a logger.
		if (!console) {
			console.log("no console");
			return;
		}

		Logger.setLevel(defaultLevel || Logger.DEBUG);
		Logger.setHandler(function(messages, context) {
			var hdlr = console.log;

			// Prepend the logger's name to the log message for easy identification.
			if (context.name) {
				messages[0] = "[" + context.name + "] " + messages[0];
			}

			// Delegate through to custom warn/error loggers if present on the console.
			if (context.level === Logger.WARN && console.warn) {
				hdlr = console.warn;
			} else if (context.level === Logger.ERROR && console.error) {
				hdlr = console.error;
			} else if (context.level === Logger.INFO && console.info) {
				hdlr = console.info;
			}

			// Support for IE8+ (and other, slightly more sane environments)
			Function.prototype.apply.call(hdlr, console, messages);
		});
	};

	// Export to popular environments boilerplate.
	if (typeof define === 'function' && define.amd) {
		define(Logger);
	}
	else if (typeof module !== 'undefined' && module.exports) {
		module.exports = Logger;
	}
	else {
		Logger._prevLogger = global.Logger;

		Logger.noConflict = function () {
			global.Logger = Logger._prevLogger;
			return Logger;
		};

		global.Logger = Logger;
    }
}(this));<commit_msg>Removed (utterly insane) debug statement.<commit_after>/*!
 * js-logger - http://github.com/jonnyreeves/js-logger
 * Jonny Reeves, http://jonnyreeves.co.uk/
 * js-logger may be freely distributed under the MIT license.
 */

/*jshint sub:true*/
/*global console:true,define:true, module:true*/
(function (global) {
    "use strict";

	// Top level module for the global, static logger instance.
	var Logger = { };

	// For those that are at home that are keeping score.
	Logger.VERSION = "@VERSION@";

	// Function which handles all incoming log messages.
	var logHandler;

	// Map of ContextualLogger instances by name; used by Logger.get() to return the same named instance.
	var contextualLoggersByNameMap = {};

	// Polyfill for ES5's Function.bind.
	var bind = function(scope, func) {
		return function() {
			return func.apply(scope, arguments);
		};
	};

	// Super exciting object merger-matron 9000 adding another 100 bytes to your download.
	var merge = function () {
		var args = arguments, target = args[0], key, i;
		for (i = 1; i < args.length; i++) {
			for (key in args[i]) {
				if (!(key in target) && args[i].hasOwnProperty(key)) {
					target[key] = args[i][key];
				}
			}
		}
		return target;
	};

	// Helper to define a logging level object; helps with optimisation.
	var defineLogLevel = function(value, name) {
		return { value: value, name: name };
	};

	// Predefined logging levels.
	Logger.DEBUG = defineLogLevel(1, 'DEBUG');
	Logger.INFO = defineLogLevel(2, 'INFO');
	Logger.WARN = defineLogLevel(4, 'WARN');
	Logger.ERROR = defineLogLevel(8, 'ERROR');
	Logger.OFF = defineLogLevel(99, 'OFF');

	// Inner class which performs the bulk of the work; ContextualLogger instances can be configured independently
	// of each other.
	var ContextualLogger = function(defaultContext) {
		this.context = defaultContext;
		this.setLevel(defaultContext.filterLevel);
		this.log = this.info;  // Convenience alias.
	};

	ContextualLogger.prototype = {
		// Changes the current logging level for the logging instance.
		setLevel: function(newLevel) {
			// Ensure the supplied Level object looks valid.
			if (newLevel && "value" in newLevel) {
				this.context.filterLevel = newLevel;
			}
		},

		// Is the logger configured to output messages at the supplied level?
		enabledFor: function (lvl) {
			var filterLevel = this.context.filterLevel;
			return lvl.value >= filterLevel.value;
		},

		debug: function () {
			this.invoke(Logger.DEBUG, arguments);
		},

		info: function () {
			this.invoke(Logger.INFO, arguments);
		},

		warn: function () {
			this.invoke(Logger.WARN, arguments);
		},

		error: function () {
			this.invoke(Logger.ERROR, arguments);
		},

		// Invokes the logger callback if it's not being filtered.
		invoke: function (level, msgArgs) {
			if (logHandler && this.enabledFor(level)) {
				logHandler(msgArgs, merge({ level: level }, this.context));
			}
		}
	};

	// Protected instance which all calls to the to level `Logger` module will be routed through.
	var globalLogger = new ContextualLogger({ filterLevel: Logger.OFF });

	// Configure the global Logger instance.
	(function() {
		// Shortcut for optimisers.
		var L = Logger;

		L.enabledFor = bind(globalLogger, globalLogger.enabledFor);
		L.debug = bind(globalLogger, globalLogger.debug);
		L.info = bind(globalLogger, globalLogger.info);
		L.warn = bind(globalLogger, globalLogger.warn);
		L.error = bind(globalLogger, globalLogger.error);

		// Don't forget the convenience alias!
		L.log = L.info;
	}());

	// Set the global logging handler.  The supplied function should expect two arguments, the first being an arguments
	// object with the supplied log messages and the second being a context object which contains a hash of stateful
	// parameters which the logging function can consume.
	Logger.setHandler = function (func) {
		logHandler = func;
	};

	// Sets the global logging filter level which applies to *all* previously registered, and future Logger instances.
	// (note that named loggers (retrieved via `Logger.get`) can be configured independently if required).
	Logger.setLevel = function(level) {
		// Set the globalLogger's level.
		globalLogger.setLevel(level);

		// Apply this level to all registered contextual loggers.
		for (var key in contextualLoggersByNameMap) {
			if (contextualLoggersByNameMap.hasOwnProperty(key)) {
				contextualLoggersByNameMap[key].setLevel(level);
			}
		}
	};

	// Retrieve a ContextualLogger instance.  Note that named loggers automatically inherit the global logger's level,
	// default context and log handler.
	Logger.get = function (name) {
		// All logger instances are cached so they can be configured ahead of use.
		return contextualLoggersByNameMap[name] ||
			(contextualLoggersByNameMap[name] = new ContextualLogger(merge({ name: name }, globalLogger.context)));
	};

	// Configure and example a Default implementation which writes to the `window.console` (if present).
	Logger.useDefaults = function(defaultLevel) {
		// Check for the presence of a logger.
		if (!console) {
			return;
		}

		Logger.setLevel(defaultLevel || Logger.DEBUG);
		Logger.setHandler(function(messages, context) {
			var hdlr = console.log;

			// Prepend the logger's name to the log message for easy identification.
			if (context.name) {
				messages[0] = "[" + context.name + "] " + messages[0];
			}

			// Delegate through to custom warn/error loggers if present on the console.
			if (context.level === Logger.WARN && console.warn) {
				hdlr = console.warn;
			} else if (context.level === Logger.ERROR && console.error) {
				hdlr = console.error;
			} else if (context.level === Logger.INFO && console.info) {
				hdlr = console.info;
			}

			// Support for IE8+ (and other, slightly more sane environments)
			Function.prototype.apply.call(hdlr, console, messages);
		});
	};

	// Export to popular environments boilerplate.
	if (typeof define === 'function' && define.amd) {
		define(Logger);
	}
	else if (typeof module !== 'undefined' && module.exports) {
		module.exports = Logger;
	}
	else {
		Logger._prevLogger = global.Logger;

		Logger.noConflict = function () {
			global.Logger = Logger._prevLogger;
			return Logger;
		};

		global.Logger = Logger;
    }
}(this));<|endoftext|>


<commit_before>import React                from 'react';
import PureRenderMixin      from 'react-addons-pure-render-mixin';
import { merge }            from 'timm';
import {
  COLORS,
  UNICODE,
  KEYS,
  NULL_STRING,
  getScrollbarWidth,
}                           from '../gral/constants';
import {
  bindAll,
  cancelEvent,
}                           from '../gral/helpers';
import { scrollIntoView }   from '../gral/visibility';
import {
  isDark,
  flexContainer,
  flexItem,
}                           from '../gral/styles';
import {
  registerShortcut,
  unregisterShortcut,
}                           from '../gral/keys';
import hoverable            from '../hocs/hoverable';

const LIST_SEPARATOR_KEY = '__SEPARATOR__';
const LIST_SEPARATOR = {
  value: LIST_SEPARATOR_KEY,
  label: LIST_SEPARATOR_KEY,
};

// ==========================================
// Component
// ==========================================
class BaseListPicker extends React.Component {
  static propTypes = {
    registerOuterRef:       React.PropTypes.func,
    items:                  React.PropTypes.array.isRequired,
    curValue:               React.PropTypes.string.isRequired,
    keyDown:                React.PropTypes.object,
    emptyText:              React.PropTypes.string,
    onChange:               React.PropTypes.func.isRequired,
    onClickItem:            React.PropTypes.func,
    fFocused:               React.PropTypes.bool,
    fFloating:              React.PropTypes.bool,
    style:                  React.PropTypes.object,
    styleItem:              React.PropTypes.object,
    twoStageStyle:          React.PropTypes.bool,
    accentColor:            React.PropTypes.string,
    // Hoverable HOC
    hovering:               React.PropTypes.any,
    onHoverStart:           React.PropTypes.func.isRequired,
    onHoverStop:            React.PropTypes.func.isRequired,
  };
  static defaultProps = {
    emptyText:              'Ø',
    accentColor:            COLORS.accent,
  };

  constructor(props) {
    super(props);
    this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this);
    bindAll(this, [
      'registerOuterRef',
      'renderItem',
      'onClickItem',
      'doClickItemByIndex',
    ]);
  }

  componentWillMount() { this.processKeyShortcuts(this.props); }
  componentWillReceiveProps(nextProps) {
    const { items, keyDown } = nextProps;
    if (items !== this.props.items) this.processKeyShortcuts(nextProps);
    if (keyDown && keyDown !== this.props.keyDown) this.doKeyDown(keyDown);
  }

  // For floating pickers, we need to wait until the float update cycle has finished.
  componentDidMount() {
    const fnScroll = () => this.scrollSelectedIntoView({ topAncestor: this.refOuter });
    if (this.props.fFloating) {
      setTimeout(fnScroll);
    } else {
      fnScroll();
    }
  }

  componentDidUpdate(prevProps) {
    const { curValue } = this.props;
    if (curValue != null && curValue !== prevProps.curValue) {
      this.scrollSelectedIntoView();
    }
  }

  componentWillUnmount() { this.unregisterShortcuts(); }

  // ==========================================
  // Render
  // ==========================================
  render() {
    const { style: baseStyle } = this.props;
    return (

        {this.renderContents()}

    );
  }

  renderContents() {
    const { items } = this.props;
    if (!items.length ||
        (items.length === 1 && items[0].value === '' && items[0].label === '')) {
      return
{this.props.emptyText}
;
    }
    this.refItems = [];
    return items.map(this.renderItem);
  }

  renderItem(item, idx) {
    const { value: itemValue, label } = item;
    if (label === LIST_SEPARATOR_KEY) {
      return (
        <div key={`separator_${idx}`} ref={c => { this.refItems[idx] = c; }}
          style={style.separator}
        />
      );
    }
    const {
      curValue,
      hovering, onHoverStart, onHoverStop,
      styleItem, twoStageStyle, accentColor,
    } = this.props;
    const styleProps = {
      hovering,
      fHovered: hovering === itemValue,
      fSelected: curValue === itemValue,
      twoStageStyle, accentColor,
    };
    const keyEl = this.renderKeys(idx);
    return (

 { this.refItems[idx] = c; }}
        id={itemValue}
        onMouseEnter={onHoverStart}
        onMouseLeave={onHoverStop}
        onMouseDown={cancelEvent}
        onMouseUp={this.onClickItem}
        style={merge(style.item(styleProps), styleItem)}
      >
        {label || UNICODE.nbsp}
        {keyEl ?
 : undefined}
        {keyEl}

    );
  }

  renderKeys(idx) {
    const shortcuts = this.keyShortcuts[idx].map(o => o.description).join(', ');
    if (!shortcuts) return null;
    return {shortcuts};
  }

  // ==========================================
  // Event handlers
  // ==========================================
  registerOuterRef(c) {
    this.refOuter = c;
    this.props.registerOuterRef && this.props.registerOuterRef(c);
  }

  onClickItem(ev) {
    const { onClickItem, onChange } = this.props;
    onChange(ev, ev.currentTarget.id);
    if (onClickItem) onClickItem(ev, ev.currentTarget.id);
  }

  doClickItemByIndex(idx) {
    const { items, onClickItem, onChange } = this.props;
    const value = items[idx].value;
    onChange(null, value);
    if (onClickItem) onClickItem(null, value);
  }

  // ==========================================
  // Helpers
  // ==========================================
  doKeyDown({ which, shiftKey, ctrlKey, altKey, metaKey }) {
    if (shiftKey || ctrlKey || altKey || metaKey) return;
    let idx;
    switch (which) {
      case KEYS.down:   this.selectMoveBy(+1); break;
      case KEYS.up:     this.selectMoveBy(-1); break;
      case KEYS.home:   this.selectMoveBy(+1, -1); break;
      case KEYS.end:    this.selectMoveBy(-1, this.props.items.length); break;
      case KEYS.return:
        if (this.props.onClickItem) {
          idx = this.getCurIdx();
          if (idx >= 0) this.props.onClickItem(null, this.props.items[idx].value);
        }
        break;
      case KEYS.del:
      case KEYS.backspace:
        this.props.onChange(null, NULL_STRING);
        break;
      default:
        break;
    }
  }

  selectMoveBy(delta, idx0) {
    const { items } = this.props;
    const len = items.length;
    let idx = idx0 != null ? idx0 : this.getCurIdx();
    if (idx < 0) idx = delta >= 0 ? -1 : len;
    let fFound = false;
    while (!fFound) {
      idx += delta;
      if (idx < 0 || idx > len - 1) break;
      fFound = (items[idx].label !== LIST_SEPARATOR_KEY);
    }
    if (fFound) this.selectMoveTo(idx);
  }

  selectMoveTo(idx) {
    const { items } = this.props;
    if (!items.length) return;
    const nextValue = items[idx].value;
    this.props.onChange(null, nextValue);
  }

  getCurIdx() {
    const { curValue, items } = this.props;
    return items.findIndex(item => item.value === curValue);
  }

  scrollSelectedIntoView(options) {
    const idx = this.getCurIdx();
    if (idx < 0) return;
    scrollIntoView(this.refItems[idx], options);
  }

  processKeyShortcuts(props) {
    this.keyShortcuts = props.items.map((item, idx) => {
      let keys = item.keys || [];
      if (!Array.isArray(keys)) keys = [keys];
      return keys.map(shortcut => registerShortcut(shortcut, () => {
        this.doClickItemByIndex(idx);
      }));
    });
  }

  unregisterShortcuts() {
    this.keyShortcuts.forEach(itemShortcuts =>
      itemShortcuts.forEach(unregisterShortcut));
  }
}

// ==========================================
// Styles
// ==========================================
const style = {
  outer: ({ fFocused }) => {
    const out = {
      paddingTop: 3,
      paddingBottom: 3,
      maxHeight: 'inherit',
      overflowY: 'auto',
      border: `1px solid ${COLORS.line}`,
    };
    if (fFocused) {
      out.boxShadow = COLORS.focusGlow;
      out.border = `1px solid ${COLORS.focus}`;
    }
    return out;
  },
  empty: {
    paddingTop: 3,
    paddingBottom: 3,
    color: COLORS.dim,
    paddingRight: 10 + getScrollbarWidth(),
    paddingLeft: 10,
    cursor: 'not-allowed',
  },
  item: ({ hovering, fHovered, fSelected, twoStageStyle, accentColor }) => {
    let border;
    let backgroundColor;
    if (twoStageStyle) {
      border = `1px solid ${fHovered || fSelected ? accentColor : 'transparent'}`;
      backgroundColor = fSelected ? accentColor : undefined;
    } else {
      const fHighlighted = fHovered || (fSelected && hovering == null);
      border = '1px solid transparent';
      backgroundColor = fHighlighted ? accentColor : undefined;
    }
    let color;
    if (backgroundColor) {
      color = COLORS[isDark(backgroundColor) ? 'lightText' : 'darkText'];
    }
    return flexContainer('row', {
      alignItems: 'baseline',
      backgroundColor, color, border,
      cursor: 'default',
      whiteSpace: 'nowrap',
      padding: `3px ${10 + getScrollbarWidth()}px 3px 10px`,
    });
  },
  separator: {
    borderTop: `1px solid ${COLORS.line}`,
    height: 1,
    marginTop: 3,
    marginBottom: 3,
    cursor: 'default',
  },
  shortcut: {
    marginLeft: 20,
  },
};

// ==========================================
// Public API
// ==========================================
const ListPicker = hoverable(BaseListPicker);

export {
  ListPicker,
  LIST_SEPARATOR,
};
<commit_msg>Prevent body to scroll when listPicker cannot scroll further<commit_after>import React                from 'react';
import ReactDOM             from 'react-dom';
import PureRenderMixin      from 'react-addons-pure-render-mixin';
import { merge }            from 'timm';
import {
  COLORS,
  UNICODE,
  KEYS,
  NULL_STRING,
  getScrollbarWidth,
}                           from '../gral/constants';
import {
  bindAll,
  cancelEvent,
}                           from '../gral/helpers';
import { scrollIntoView }   from '../gral/visibility';
import {
  isDark,
  flexContainer,
  flexItem,
}                           from '../gral/styles';
import {
  registerShortcut,
  unregisterShortcut,
}                           from '../gral/keys';
import hoverable            from '../hocs/hoverable';

const LIST_SEPARATOR_KEY = '__SEPARATOR__';
const LIST_SEPARATOR = {
  value: LIST_SEPARATOR_KEY,
  label: LIST_SEPARATOR_KEY,
};

// ==========================================
// Component
// ==========================================
class BaseListPicker extends React.Component {
  static propTypes = {
    registerOuterRef:       React.PropTypes.func,
    items:                  React.PropTypes.array.isRequired,
    curValue:               React.PropTypes.string.isRequired,
    keyDown:                React.PropTypes.object,
    emptyText:              React.PropTypes.string,
    onChange:               React.PropTypes.func.isRequired,
    onClickItem:            React.PropTypes.func,
    fFocused:               React.PropTypes.bool,
    fFloating:              React.PropTypes.bool,
    style:                  React.PropTypes.object,
    styleItem:              React.PropTypes.object,
    twoStageStyle:          React.PropTypes.bool,
    accentColor:            React.PropTypes.string,
    // Hoverable HOC
    hovering:               React.PropTypes.any,
    onHoverStart:           React.PropTypes.func.isRequired,
    onHoverStop:            React.PropTypes.func.isRequired,
  };
  static defaultProps = {
    emptyText:              'Ø',
    accentColor:            COLORS.accent,
  };

  constructor(props) {
    super(props);
    this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this);
    bindAll(this, [
      'registerOuterRef',
      'renderItem',
      'onWheel',
      'onClickItem',
      'doClickItemByIndex',
    ]);
  }

  componentWillMount() { this.processKeyShortcuts(this.props); }
  componentWillReceiveProps(nextProps) {
    const { items, keyDown } = nextProps;
    if (items !== this.props.items) this.processKeyShortcuts(nextProps);
    if (keyDown && keyDown !== this.props.keyDown) this.doKeyDown(keyDown);
  }

  // For floating pickers, we need to wait until the float update cycle has finished.
  componentDidMount() {
    const fnScroll = () => this.scrollSelectedIntoView({ topAncestor: this.refOuter });
    if (this.props.fFloating) {
      setTimeout(fnScroll);
    } else {
      fnScroll();
    }
  }

  componentDidUpdate(prevProps) {
    const { curValue } = this.props;
    if (curValue != null && curValue !== prevProps.curValue) {
      this.scrollSelectedIntoView();
    }
  }

  componentWillUnmount() { this.unregisterShortcuts(); }

  // ==========================================
  // Render
  // ==========================================
  render() {
    const { style: baseStyle } = this.props;
    return (

        {this.renderContents()}

    );
  }

  renderContents() {
    const { items } = this.props;
    if (!items.length ||
        (items.length === 1 && items[0].value === '' && items[0].label === '')) {
      return
{this.props.emptyText}
;
    }
    this.refItems = [];
    return items.map(this.renderItem);
  }

  renderItem(item, idx) {
    const { value: itemValue, label } = item;
    if (label === LIST_SEPARATOR_KEY) {
      return (
        <div key={`separator_${idx}`} ref={c => { this.refItems[idx] = c; }}
          style={style.separator}
        />
      );
    }
    const {
      curValue,
      hovering, onHoverStart, onHoverStop,
      styleItem, twoStageStyle, accentColor,
    } = this.props;
    const styleProps = {
      hovering,
      fHovered: hovering === itemValue,
      fSelected: curValue === itemValue,
      twoStageStyle, accentColor,
    };
    const keyEl = this.renderKeys(idx);
    return (

 { this.refItems[idx] = c; }}
        id={itemValue}
        onMouseEnter={onHoverStart}
        onMouseLeave={onHoverStop}
        onMouseDown={cancelEvent}
        onMouseUp={this.onClickItem}
        style={merge(style.item(styleProps), styleItem)}
      >
        {label || UNICODE.nbsp}
        {keyEl ?
 : undefined}
        {keyEl}

    );
  }

  renderKeys(idx) {
    const shortcuts = this.keyShortcuts[idx].map(o => o.description).join(', ');
    if (!shortcuts) return null;
    return {shortcuts};
  }

  // ==========================================
  // Event handlers
  // ==========================================
  registerOuterRef(c) {
    this.refOuter = c;
    this.props.registerOuterRef && this.props.registerOuterRef(c);
  }

  onWheel(ev) {
    const el = ReactDOM.findDOMNode(this);
    if (ev.nativeEvent.deltaY <= 0) {
      if (el.scrollTop <= 0) cancelEvent(ev);
    } else {
      if (el.scrollTop + el.clientHeight >= el.scrollHeight) cancelEvent(ev);
    }
  }

  onClickItem(ev) {
    const { onClickItem, onChange } = this.props;
    onChange(ev, ev.currentTarget.id);
    if (onClickItem) onClickItem(ev, ev.currentTarget.id);
  }

  doClickItemByIndex(idx) {
    const { items, onClickItem, onChange } = this.props;
    const value = items[idx].value;
    onChange(null, value);
    if (onClickItem) onClickItem(null, value);
  }

  // ==========================================
  // Helpers
  // ==========================================
  doKeyDown({ which, shiftKey, ctrlKey, altKey, metaKey }) {
    if (shiftKey || ctrlKey || altKey || metaKey) return;
    let idx;
    switch (which) {
      case KEYS.down:   this.selectMoveBy(+1); break;
      case KEYS.up:     this.selectMoveBy(-1); break;
      case KEYS.home:   this.selectMoveBy(+1, -1); break;
      case KEYS.end:    this.selectMoveBy(-1, this.props.items.length); break;
      case KEYS.return:
        if (this.props.onClickItem) {
          idx = this.getCurIdx();
          if (idx >= 0) this.props.onClickItem(null, this.props.items[idx].value);
        }
        break;
      case KEYS.del:
      case KEYS.backspace:
        this.props.onChange(null, NULL_STRING);
        break;
      default:
        break;
    }
  }

  selectMoveBy(delta, idx0) {
    const { items } = this.props;
    const len = items.length;
    let idx = idx0 != null ? idx0 : this.getCurIdx();
    if (idx < 0) idx = delta >= 0 ? -1 : len;
    let fFound = false;
    while (!fFound) {
      idx += delta;
      if (idx < 0 || idx > len - 1) break;
      fFound = (items[idx].label !== LIST_SEPARATOR_KEY);
    }
    if (fFound) this.selectMoveTo(idx);
  }

  selectMoveTo(idx) {
    const { items } = this.props;
    if (!items.length) return;
    const nextValue = items[idx].value;
    this.props.onChange(null, nextValue);
  }

  getCurIdx() {
    const { curValue, items } = this.props;
    return items.findIndex(item => item.value === curValue);
  }

  scrollSelectedIntoView(options) {
    const idx = this.getCurIdx();
    if (idx < 0) return;
    scrollIntoView(this.refItems[idx], options);
  }

  processKeyShortcuts(props) {
    this.keyShortcuts = props.items.map((item, idx) => {
      let keys = item.keys || [];
      if (!Array.isArray(keys)) keys = [keys];
      return keys.map(shortcut => registerShortcut(shortcut, () => {
        this.doClickItemByIndex(idx);
      }));
    });
  }

  unregisterShortcuts() {
    this.keyShortcuts.forEach(itemShortcuts =>
      itemShortcuts.forEach(unregisterShortcut));
  }
}

// ==========================================
// Styles
// ==========================================
const style = {
  outer: ({ fFocused }) => {
    const out = {
      paddingTop: 3,
      paddingBottom: 3,
      maxHeight: 'inherit',
      overflowY: 'auto',
      border: `1px solid ${COLORS.line}`,
    };
    if (fFocused) {
      out.boxShadow = COLORS.focusGlow;
      out.border = `1px solid ${COLORS.focus}`;
    }
    return out;
  },
  empty: {
    paddingTop: 3,
    paddingBottom: 3,
    color: COLORS.dim,
    paddingRight: 10 + getScrollbarWidth(),
    paddingLeft: 10,
    cursor: 'not-allowed',
  },
  item: ({ hovering, fHovered, fSelected, twoStageStyle, accentColor }) => {
    let border;
    let backgroundColor;
    if (twoStageStyle) {
      border = `1px solid ${fHovered || fSelected ? accentColor : 'transparent'}`;
      backgroundColor = fSelected ? accentColor : undefined;
    } else {
      const fHighlighted = fHovered || (fSelected && hovering == null);
      border = '1px solid transparent';
      backgroundColor = fHighlighted ? accentColor : undefined;
    }
    let color;
    if (backgroundColor) {
      color = COLORS[isDark(backgroundColor) ? 'lightText' : 'darkText'];
    }
    return flexContainer('row', {
      alignItems: 'baseline',
      backgroundColor, color, border,
      cursor: 'default',
      whiteSpace: 'nowrap',
      padding: `3px ${10 + getScrollbarWidth()}px 3px 10px`,
    });
  },
  separator: {
    borderTop: `1px solid ${COLORS.line}`,
    height: 1,
    marginTop: 3,
    marginBottom: 3,
    cursor: 'default',
  },
  shortcut: {
    marginLeft: 20,
  },
};

// ==========================================
// Public API
// ==========================================
const ListPicker = hoverable(BaseListPicker);

export {
  ListPicker,
  LIST_SEPARATOR,
};
<|endoftext|>


<commit_before>angular.module('materialscommons').component('mcSamplesTable', {
    template: `
    <md-table-container>

                Sample
                Description
                Composition
                Modified
                Last Transformation
                # Files
                # Processes

                    {{sample.name}}

                    {{sample.description}}

                    Unknown

                    {{sample.mtime | toDate}}

                    Last transformation

                        {{sample.files.length}}

                        {{sample.processes.length}}

    </md-table-container>
    `,
    bindings: {
        showSample: '&',
        showProcesses: '&',
        showFiles: '&',
        samples: '<',
        projectId: '<'
    }
});<commit_msg>Remove last transformation column.<commit_after>angular.module('materialscommons').component('mcSamplesTable', {
    template: `
    <md-table-container>

                Sample
                Description
                Composition
                Modified
                Last Transformation
                # Files
                # Processes

                    {{sample.name}}

                    {{sample.description}}

                    Unknown

                    {{sample.mtime | toDate}}

                        {{sample.files.length}}

                        {{sample.processes.length}}

    </md-table-container>
    `,
    bindings: {
        showSample: '&',
        showProcesses: '&',
        showFiles: '&',
        samples: '<',
        projectId: '<'
    }
});<|endoftext|>


<commit_before>class Fps {
	constructor(){
		// Select FPS div
		this.fpsContainer = document.getElementById("fps");

		// Timer for animation delta
		this.lastTime = 0;
		this.currentTime = 0;
		this.deltaTime = 0;

		// Initialize timer for FPS Calc
		this.startTime = Date.now();
		this.prevTime = this.startTime;

		// Set default fps values
		this.fpsValue = 0;
		this.fpsMin = Infinity;
		this.fpsMax = 0;
		this.framesFps = 0;
	}

	// TIMER FUNCTIONS
    timerBegin() {
    	this.preUpdate();

        this.startTime = Date.now();
    }

    timerEnd() {
        let time = Date.now();

        this.framesFps++;

        if (time > this.prevTime + 1000) {
            this.fpsValue = Math.round((this.framesFps * 1000) / (time - this.prevTime));
            this.fpsMin = Math.min(this.fpsMin, this.fpsValue);
            this.fpsMax = Math.max(this.fpsMax, this.fpsValue);
            this.fpsContainer.innerHTML = this.fpsValue + ' FPS (' + this.fpsMin + '-' + this.fpsMax + ')';
            this.prevTime = time;
            this.framesFps = 0;
        }

        this.postUpdate();
    }

    preUpdate(){
    	this.currentTime = Date.now();
    	this.deltaTime = (this.currentTime - this.lastTime) / 1000.0;
    }

    postUpdate(){
    	this.lastTime = this.currentTime;
    }

}

export default new Fps;<commit_msg>Fps changes<commit_after>class Fps {
	constructor(){
		// Select FPS div
		this.fpsContainer = document.getElementById("fps");

		// Timer for animation delta
		this.lastTime = 0;
		this.currentTime = 0;
		this.deltaTime = 0;

		// Initialize timer for FPS Calc
		this.startTime = Date.now();
		this.prevTime = this.startTime;

		// Set default fps values
		this.fpsValue = 0;
		this.fpsMin = Infinity;
		this.fpsMax = 0;
		this.framesFps = 0;

        this.showFps = false;
	}

	// TIMER FUNCTIONS
    timerBegin() {
    	this.preUpdate();
    }

    timerEnd() {

        if(this.showFps){
            let time = Date.now();

            this.framesFps++;

            if (time > this.prevTime + 1000) {
                this.fpsValue = Math.round((this.framesFps * 1000) / (time - this.prevTime));
                this.fpsMin = Math.min(this.fpsMin, this.fpsValue);
                this.fpsMax = Math.max(this.fpsMax, this.fpsValue);
                this.fpsContainer.innerHTML = this.fpsValue + ' FPS (' + this.fpsMin + '-' + this.fpsMax + ')';
                this.prevTime = time;
                this.framesFps = 0;
            }
        }

        this.postUpdate();
    }

    preUpdate(){
    	this.currentTime = Date.now();
    	this.deltaTime = (this.currentTime - this.lastTime) / 1000.0;
    }

    postUpdate(){
    	this.lastTime = this.currentTime;
    }

}

export default new Fps;<|endoftext|>


<commit_before>import Ember from 'ember';
import QUnit from 'qunit';

const get = Ember.get,
      set = Ember.set,
      map = Ember.EnumerableUtils.map,
      mockjax = Ember.$.mockjax,
      assert = QUnit.assert;

export default Ember.Object.extend({
  install: function() {
    var calls = get(this, 'calls');
    var expectations = get(this, 'expectations');

    mockjax(function(settings) {
      calls.pushObject({
        url: settings.url,
        data: settings.data});

      var match = expectations[settings.url];
      if (!match) {
        throw new Error('Unexpected ajax call to ' + settings.url);
      }

      assert.deepEqual(settings.data, match.data, 'Unexpected ajax request data');

      return match;
    });
  },

  reset: function() {
    mockjax.clear();
  },

  expect: function(url, data, responseData) {
    var expectations = get(this, 'expectations');
    var settings = {
      logging: false,
      data: data,
      responseText: responseData || {}
    };

    expectations[url] = settings;

    var continuation = {
      withStatusCode: function(statusCode) {
        settings.status = statusCode;
        return continuation;
      },
      withResponseText: function(responseText) {
        settings.responseText = responseText;
        return continuation;
      }
    };

    return continuation;
  },

  verifySingleAjaxCall: function() {
    assert.equal(get(this, 'calls').length, 1, 'number of ajax calls');
  },

  verifyAll: function() {
    var actual = map(get(this, 'calls'), function(i) {
      return { url: i.url, data: i.data };
    });

    var expectations = get(this, 'expectations');
    var expected = Ember.A();
    for (var k in expectations) {
      expected.pushObject({ url: k, data: expectations[k].data });
    }

    assert.deepEqual(actual, expected, 'expected ajax calls vs actual');
  },

  _init: Ember.on('init', function() {
    set(this, 'calls', Ember.A());
    set(this, 'expectations', {});
  })
});
<commit_msg>Set responseTime to 1 millisecond to make mockjax tests faster.<commit_after>import Ember from 'ember';
import QUnit from 'qunit';

const get = Ember.get,
      set = Ember.set,
      map = Ember.EnumerableUtils.map,
      mockjax = Ember.$.mockjax,
      assert = QUnit.assert;

export default Ember.Object.extend({
  install: function() {
    var calls = get(this, 'calls');
    var expectations = get(this, 'expectations');

    mockjax(function(settings) {
      calls.pushObject({
        url: settings.url,
        data: settings.data});

      var match = expectations[settings.url];
      if (!match) {
        throw new Error('Unexpected ajax call to ' + settings.url);
      }

      assert.deepEqual(settings.data, match.data, 'Unexpected ajax request data');

      return match;
    });
  },

  reset: function() {
    mockjax.clear();
  },

  expect: function(url, data, responseData) {
    var expectations = get(this, 'expectations');
    var settings = {
      logging: false,
      data: data,
      responseText: responseData || {},
      responseTime: 1
    };

    expectations[url] = settings;

    var continuation = {
      withStatusCode: function(statusCode) {
        settings.status = statusCode;
        return continuation;
      },
      withResponseText: function(responseText) {
        settings.responseText = responseText;
        return continuation;
      }
    };

    return continuation;
  },

  verifySingleAjaxCall: function() {
    assert.equal(get(this, 'calls').length, 1, 'number of ajax calls');
  },

  verifyAll: function() {
    var actual = map(get(this, 'calls'), function(i) {
      return { url: i.url, data: i.data };
    });

    var expectations = get(this, 'expectations');
    var expected = Ember.A();
    for (var k in expectations) {
      expected.pushObject({ url: k, data: expectations[k].data });
    }

    assert.deepEqual(actual, expected, 'expected ajax calls vs actual');
  },

  _init: Ember.on('init', function() {
    set(this, 'calls', Ember.A());
    set(this, 'expectations', {});
  })
});
<|endoftext|>


<commit_before><commit_msg>make searchTrials function more flexible...<commit_after><|endoftext|>


<commit_before>require('dotenv').config();
import './ai';
<commit_msg>try on .env<commit_after>try {
  require('dotenv').config();
} catch(e) {
  console.warn('No .env found, assuming ENV loaded manually');
}
import './ai';
<|endoftext|>


<commit_before>"use strict";

window.gswaSynth = function() {
	this._currId = 0;
	this._liveKeyPressed = {};
	this.data = {
		oscillators: {}
	};
};

gswaSynth.nativeTypes = [ "sine", "triangle", "sawtooth", "square" ];

gswaSynth.prototype = {
	setContext( ctx ) {
		this.stop();
		this.disconnect();
		this.ctx = ctx;
		Object.values( this.data.oscillators ).forEach( osc => {
			this._oscCreateMainNodes( osc, osc );
		} );
	},
	connect( nodeDest ) {
		this.connectedTo = nodeDest;
		Object.values( this.data.oscillators )
			.forEach( osc => osc._gain.connect( nodeDest ) );
	},
	disconnect() {
		this.connectedTo = null;
		Object.values( this.data.oscillators )
			.forEach( osc => osc._gain.disconnect() );
	},
	liveMidiKeyStart( midiKey ) {
		if ( !this._liveKeyPressed[ midiKey ] ) {
			var node, arrNodes = [];

			this._liveKeyPressed[ midiKey ] = arrNodes;
			Object.values( this.data.oscillators ).forEach( osc => {
				node = this._oscCreateNode( osc, midiKey );
				arrNodes.push( node );
				node._gainEnvNode.gain.setValueCurveAtTime( new Float32Array( [ 0, 1 ] ), 0, .012 ); // tmp
				node.start( 0 );
			} );
		}
	},
	liveMidiKeyStop( midiKey ) {
		var arrNodes = this._liveKeyPressed[ midiKey ],
			currTime = this.ctx.currentTime;

		if ( arrNodes ) {
			arrNodes.forEach( n => {
				n._gainEnvNode.gain.setValueCurveAtTime( new Float32Array( [ 1, 0 ] ), 0, .015 ); // tmp
				n.stop( currTime + .015 );
			} );
			delete this._liveKeyPressed[ midiKey ];
		}
	},
	liveKeyStopAll() {
		Object.keys( this._liveKeyPressed ).forEach( this.liveMidiKeyStop, this );
	},
	start( key, when, offset, duration ) {
		Object.values( this.data.oscillators ).forEach( osc => {
			var n = this._oscCreateNode( osc, key );

			n._when = when;
			n.start( when || 0 );
			if ( arguments.length > 3 ) {
				n._duration = duration;
				n._gainEnvNode.gain.setValueCurveAtTime( new Float32Array( [ 0, 1 ] ), when, .012 ); // tmp
				n._gainEnvNode.gain.setValueCurveAtTime( new Float32Array( [ 1, 0 ] ), when + duration, .015 ); // tmp
				n.stop( when + duration + .015 ); // tmp
			}
		} );
	},
	stop() {
		Object.values( this.data.oscillators ).forEach( osc => {
			Object.values( osc._nodeStack ).forEach( n => n.stop() );
		} );
	},
	change( obj ) {
		var oscs = this.data.oscillators;

		if ( obj.oscillators ) {
			Object.entries( obj.oscillators ).forEach( ( [ id, obj ] ) => {
				obj ? oscs[ id ]
					? this._oscUpdate( id, obj )
					: this._oscCreate( id, obj )
					: this._oscDelete( id );
			} );
			Object.values( this._liveKeyPressed ).forEach( keypressed => {
				keypressed.forEach( node => {
					if ( "type" in obj ) { this._nodeSetType( node, obj.type ); }
					if ( "detune" in obj ) { node.detune.value = obj.detune; }
				} );
			} );
		}
	},

	// private:
	_nodeSetType( node, type ) {
		if ( gswaSynth.nativeTypes.indexOf( type ) > -1 ) {
			node.type = type;
		} else {
			var wave = gswaPeriodicWaves[ type ];

			node.setPeriodicWave( this.ctx.createPeriodicWave( wave.real, wave.imag ) );
		}
	},
	_oscCreateNode( osc, key ) {
		var node = this.ctx.createOscillator(),
			gainEnvNode = this.ctx.createGain();

		this._nodeSetType( node, osc.type );
		node.detune.value = osc.detune;
		if ( !gswaSynth.midiKeyToHz[ key ] ) {
			lg(key, gswaSynth.midiKeyToHz[ key ])
		}
		node.frequency.value = gswaSynth.midiKeyToHz[ key ];
		node.onended = this._oscDeleteNode.bind( this, osc, this._currId );
		gainEnvNode.gain.value = 0;
		node.connect( gainEnvNode );
		gainEnvNode.connect( osc._pan );
		node._gainEnvNode = gainEnvNode;
		node._key = key;
		osc._nodeStack[ this._currId ] = node;
		++this._currId;
		++osc._nodeStackLength;
		return node;
	},
	_oscDeleteNode( osc, id ) {
		delete osc._nodeStack[ id ];
		--osc._nodeStackLength;
	},
	_oscCreate( id, obj ) {
		var newNode,
			oscs = this.data.oscillators,
			oscFirst = Object.values( oscs )[ 0 ],
			osc = Object.assign( {
				_nodeStack: {},
				_nodeStackLength: 0
			}, obj );

		this._oscCreateMainNodes( osc, obj );
		osc._gain.connect( this.connectedTo );
		oscs[ id ] = osc;
		if ( oscFirst && oscFirst._nodeStackLength > 0 ) {
			Object.values( oscFirst._nodeStack ).forEach( node => {
				newNode = this._oscCreateNode( osc, node._key );
				newNode._when = node._when;
				newNode.start( node._when );
				if ( typeof node._duration === "number" ) {
					newNode._duration = node._duration;
					newNode.stop( node._when + node._duration );
				} else {
					this._liveKeyPressed[ node._key ].push( newNode );
				}
			} );
		}
	},
	_oscUpdate( id, obj ) {
		var osc = this.data.oscillators[ id ];

		Object.assign( osc, obj );
		if ( "gain" in obj ) { osc._gain.gain.value = obj.gain; }
		if ( "pan" in obj ) { osc._pan.pan.value = obj.pan; }
		Object.values( osc._nodeStack ).forEach( node => {
			if ( "type" in obj ) { this._nodeSetType( node, obj.type ); }
			if ( "detune" in obj ) { node.detune.value = obj.detune; }
		} );
	},
	_oscDelete( id ) {
		var oscs = this.data.oscillators;

		Object.values( oscs[ id ]._nodeStack ).forEach( node => {
			node.stop();
		} );
		delete oscs[ id ];
	},
	_oscCreateMainNodes( osc, obj ) {
		osc._gain = this.ctx.createGain();
		osc._pan = this.ctx.createStereoPanner();
		osc._pan.pan.value = obj.pan;
		osc._gain.gain.value = obj.gain;
		osc._pan.connect( osc._gain );
	}
};

gswaSynth.midiKeyToHz = ( new Array( 12 ) ).concat( [
	//
	  // 27.5,
	  // 29.1353,
	  // 30.8677,

	//
	  32.7032, // C1 24
	  34.6479,
	  36.7081,
	  38.8909,
	  41.2035,
	  43.6536,
	  46.2493,
	  48.9995,
	  51.9130,
	  55,
	  58.2705,
	  61.7354,

	//
	  65.4064,
	  69.2957,
	  73.4162,
	  77.7817,
	  82.4069,
	  87.3071,
	  92.4986,
	  97.9989,
	 103.826,
	 110,
	 116.541,
	 123.471,

	//
	 130.813,
	 138.591,
	 146.832,
	 155.563,
	 164.814,
	 174.614,
	 184.997,
	 195.998,
	 207.652,
	 220,
	 233.082,
	 246.942,

	//
	 261.626,
	 277.183,
	 293.665,
	 311.127,
	 329.628,
	 349.228,
	 369.994,
	 391.995,
	 415.305,
	 440,
	 466.164,
	 493.883,

	//
	 523.251,
	 554.365,
	 587.33,
	 622.254,
	 659.255,
	 698.456,
	 739.989,
	 783.991,
	 830.609,
	 880,
	 932.328,
	 987.767,

	//
	1046.5,
	1108.73,
	1174.66,
	1244.51,
	1318.51,
	1396.91,
	1479.98,
	1567.98,
	1661.22,
	1760,
	1864.66,
	1975.53,

	//
	2093,
	2217.46,
	2349.32,
	2489.02,
	2637.02,
	2793.83,
	2959.96,
	3135.96,
	3322.44,
	3520,
	3729.31,
	3951.07,

	//
	4186.01,
] );
<commit_msg>gswaSynth: fix a temporary bug with liveMidiKeyStop()<commit_after>"use strict";

window.gswaSynth = function() {
	this._currId = 0;
	this._liveKeyPressed = {};
	this.data = {
		oscillators: {}
	};
};

gswaSynth.nativeTypes = [ "sine", "triangle", "sawtooth", "square" ];

gswaSynth.prototype = {
	setContext( ctx ) {
		this.stop();
		this.disconnect();
		this.ctx = ctx;
		Object.values( this.data.oscillators ).forEach( osc => {
			this._oscCreateMainNodes( osc, osc );
		} );
	},
	connect( nodeDest ) {
		this.connectedTo = nodeDest;
		Object.values( this.data.oscillators )
			.forEach( osc => osc._gain.connect( nodeDest ) );
	},
	disconnect() {
		this.connectedTo = null;
		Object.values( this.data.oscillators )
			.forEach( osc => osc._gain.disconnect() );
	},
	liveMidiKeyStart( midiKey ) {
		if ( !this._liveKeyPressed[ midiKey ] ) {
			var node, arrNodes = [],
				currTime = this.ctx.currentTime;

			this._liveKeyPressed[ midiKey ] = arrNodes;
			arrNodes._currTime = currTime;
			Object.values( this.data.oscillators ).forEach( osc => {
				node = this._oscCreateNode( osc, midiKey );
				arrNodes.push( node );
				node._gainEnvNode.gain.setValueCurveAtTime( new Float32Array( [ 0, 1 ] ), currTime, .012 ); // tmp
				node.start( currTime );
			} );
		}
	},
	liveMidiKeyStop( midiKey ) {
		var arrNodes = this._liveKeyPressed[ midiKey ],
			currTime = this.ctx.currentTime;

		if ( arrNodes ) {
			arrNodes.forEach( arrNodes._currTime + .0121 >= currTime // tmp
				? n => n.stop()
				: n => {
					// n._gainEnvNode.gain.cancelAndHoldAtTime( 0 ); // <-- do not work on Firefox yet..
					n._gainEnvNode.gain.setValueCurveAtTime( new Float32Array( [ 1, 0 ] ), currTime, .015 ); // tmp
					n.stop( currTime + .015 );
				} );
			delete this._liveKeyPressed[ midiKey ];
		}
	},
	liveKeyStopAll() {
		Object.keys( this._liveKeyPressed ).forEach( this.liveMidiKeyStop, this );
	},
	start( key, when, offset, duration ) {
		Object.values( this.data.oscillators ).forEach( osc => {
			var n = this._oscCreateNode( osc, key );

			n._when = when;
			n.start( when || 0 );
			if ( arguments.length > 3 ) {
				n._duration = duration;
				n._gainEnvNode.gain.setValueCurveAtTime( new Float32Array( [ 0, 1 ] ), when, .012 ); // tmp
				n._gainEnvNode.gain.setValueCurveAtTime( new Float32Array( [ 1, 0 ] ), when + duration, .015 ); // tmp
				n.stop( when + duration + .015 ); // tmp
			}
		} );
	},
	stop() {
		Object.values( this.data.oscillators ).forEach( osc => {
			Object.values( osc._nodeStack ).forEach( n => n.stop() );
		} );
	},
	change( obj ) {
		var oscs = this.data.oscillators;

		if ( obj.oscillators ) {
			Object.entries( obj.oscillators ).forEach( ( [ id, obj ] ) => {
				obj ? oscs[ id ]
					? this._oscUpdate( id, obj )
					: this._oscCreate( id, obj )
					: this._oscDelete( id );
			} );
			Object.values( this._liveKeyPressed ).forEach( keypressed => {
				keypressed.forEach( node => {
					if ( "type" in obj ) { this._nodeSetType( node, obj.type ); }
					if ( "detune" in obj ) { node.detune.value = obj.detune; }
				} );
			} );
		}
	},

	// private:
	_nodeSetType( node, type ) {
		if ( gswaSynth.nativeTypes.indexOf( type ) > -1 ) {
			node.type = type;
		} else {
			var wave = gswaPeriodicWaves[ type ];

			node.setPeriodicWave( this.ctx.createPeriodicWave( wave.real, wave.imag ) );
		}
	},
	_oscCreateNode( osc, key ) {
		var node = this.ctx.createOscillator(),
			gainEnvNode = this.ctx.createGain();

		this._nodeSetType( node, osc.type );
		node.detune.value = osc.detune;
		if ( !gswaSynth.midiKeyToHz[ key ] ) {
			lg(key, gswaSynth.midiKeyToHz[ key ])
		}
		node.frequency.value = gswaSynth.midiKeyToHz[ key ];
		node.onended = this._oscDeleteNode.bind( this, osc, this._currId );
		gainEnvNode.gain.value = 0;
		node.connect( gainEnvNode );
		gainEnvNode.connect( osc._pan );
		node._gainEnvNode = gainEnvNode;
		node._key = key;
		osc._nodeStack[ this._currId ] = node;
		++this._currId;
		++osc._nodeStackLength;
		return node;
	},
	_oscDeleteNode( osc, id ) {
		delete osc._nodeStack[ id ];
		--osc._nodeStackLength;
	},
	_oscCreate( id, obj ) {
		var newNode,
			oscs = this.data.oscillators,
			oscFirst = Object.values( oscs )[ 0 ],
			osc = Object.assign( {
				_nodeStack: {},
				_nodeStackLength: 0
			}, obj );

		this._oscCreateMainNodes( osc, obj );
		osc._gain.connect( this.connectedTo );
		oscs[ id ] = osc;
		if ( oscFirst && oscFirst._nodeStackLength > 0 ) {
			Object.values( oscFirst._nodeStack ).forEach( node => {
				newNode = this._oscCreateNode( osc, node._key );
				newNode._when = node._when;
				newNode.start( node._when );
				if ( typeof node._duration === "number" ) {
					newNode._duration = node._duration;
					newNode.stop( node._when + node._duration );
				} else {
					this._liveKeyPressed[ node._key ].push( newNode );
				}
			} );
		}
	},
	_oscUpdate( id, obj ) {
		var osc = this.data.oscillators[ id ];

		Object.assign( osc, obj );
		if ( "gain" in obj ) { osc._gain.gain.value = obj.gain; }
		if ( "pan" in obj ) { osc._pan.pan.value = obj.pan; }
		Object.values( osc._nodeStack ).forEach( node => {
			if ( "type" in obj ) { this._nodeSetType( node, obj.type ); }
			if ( "detune" in obj ) { node.detune.value = obj.detune; }
		} );
	},
	_oscDelete( id ) {
		var oscs = this.data.oscillators;

		Object.values( oscs[ id ]._nodeStack ).forEach( node => {
			node.stop();
		} );
		delete oscs[ id ];
	},
	_oscCreateMainNodes( osc, obj ) {
		osc._gain = this.ctx.createGain();
		osc._pan = this.ctx.createStereoPanner();
		osc._pan.pan.value = obj.pan;
		osc._gain.gain.value = obj.gain;
		osc._pan.connect( osc._gain );
	}
};

gswaSynth.midiKeyToHz = ( new Array( 12 ) ).concat( [
	//
	  // 27.5,
	  // 29.1353,
	  // 30.8677,

	//
	  32.7032, // C1 24
	  34.6479,
	  36.7081,
	  38.8909,
	  41.2035,
	  43.6536,
	  46.2493,
	  48.9995,
	  51.9130,
	  55,
	  58.2705,
	  61.7354,

	//
	  65.4064,
	  69.2957,
	  73.4162,
	  77.7817,
	  82.4069,
	  87.3071,
	  92.4986,
	  97.9989,
	 103.826,
	 110,
	 116.541,
	 123.471,

	//
	 130.813,
	 138.591,
	 146.832,
	 155.563,
	 164.814,
	 174.614,
	 184.997,
	 195.998,
	 207.652,
	 220,
	 233.082,
	 246.942,

	//
	 261.626,
	 277.183,
	 293.665,
	 311.127,
	 329.628,
	 349.228,
	 369.994,
	 391.995,
	 415.305,
	 440,
	 466.164,
	 493.883,

	//
	 523.251,
	 554.365,
	 587.33,
	 622.254,
	 659.255,
	 698.456,
	 739.989,
	 783.991,
	 830.609,
	 880,
	 932.328,
	 987.767,

	//
	1046.5,
	1108.73,
	1174.66,
	1244.51,
	1318.51,
	1396.91,
	1479.98,
	1567.98,
	1661.22,
	1760,
	1864.66,
	1975.53,

	//
	2093,
	2217.46,
	2349.32,
	2489.02,
	2637.02,
	2793.83,
	2959.96,
	3135.96,
	3322.44,
	3520,
	3729.31,
	3951.07,

	//
	4186.01,
] );
<|endoftext|>


<commit_before>(function($){
    $.fn.seAccordion = function(options) {
        var defaults = {
            header: 'h1',
            content: 'div',
            speed: 'slow',
            easing: 'swing',
            singleOpen: true,
            triggerEvent: 'click'
        };
        var params = $.extend(defaults, options);

        return this.each(function() {
            var obj = $(this),
                triggerEvent = 'touchstart click',
                slideOptions = {
                    duration: params.speed,
                    easing: params.easing
                }
                openContent = false;

            if(params.singleOpen === true)
                obj.children(params.content).first().addClass('opened');

            obj.children(params.header).css('cursor', 'pointer');
            obj.children(params.content + ':not(.opened)').css('display', 'none');

            if(params.triggerEvent === 'hover')
                triggerEvent = 'mouseover'

            obj.children(params.header).off().on(triggerEvent, function() {
                if(!$(this).next(params.content).hasClass('opened'))
                {
                    if(params.singleOpen === true)
                        obj.children(params.content + '.opened').stop().removeClass('opened').slideUp(slideOptions);

                    $(this).next(params.content).stop().addClass('opened').slideDown(slideOptions);
                }
                else
                {
                    if(params.singleOpen === true)
                        return;
                    else
                        $(this).next(params.content).stop().removeClass('opened').slideUp(slideOptions);
                }
            });
        });
    }
})(jQuery);
<commit_msg>Add missing semicolons<commit_after>(function($){
    $.fn.seAccordion = function(options) {
        var defaults = {
            header: 'h1',
            content: 'div',
            speed: 'slow',
            easing: 'swing',
            singleOpen: true,
            triggerEvent: 'click'
        };
        var params = $.extend(defaults, options);

        return this.each(function() {
            var obj = $(this),
                triggerEvent = 'touchstart click',
                slideOptions = {
                    duration: params.speed,
                    easing: params.easing
                },
                openContent = false;

            if(params.singleOpen === true)
                obj.children(params.content).first().addClass('opened');

            obj.children(params.header).css('cursor', 'pointer');
            obj.children(params.content + ':not(.opened)').css('display', 'none');

            if(params.triggerEvent === 'hover')
                triggerEvent = 'mouseover';

            obj.children(params.header).off().on(triggerEvent, function() {
                if(!$(this).next(params.content).hasClass('opened'))
                {
                    if(params.singleOpen === true)
                        obj.children(params.content + '.opened').stop().removeClass('opened').slideUp(slideOptions);

                    $(this).next(params.content).stop().addClass('opened').slideDown(slideOptions);
                }
                else
                {
                    if(params.singleOpen === true)
                        return;
                    else
                        $(this).next(params.content).stop().removeClass('opened').slideUp(slideOptions);
                }
            });
        });
    };
})(jQuery);
<|endoftext|>


<commit_before>var express = require('express');
var app = express();
var edge = require('edge');
var port = 12345;
var passport = require('passport');
var Strategy = require('passport-http').BasicStrategy;
var favicon = require('serve-favicon');
app.use(favicon(__dirname + '/favicon.ico'));
var db = require('./db');
var bodyParser = require('body-parser')
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// Add headers for Cross Origin XML HTTP REQUEST
app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:63342');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Pass to next layer of middleware
    next();
});
app.post('/', function (request, response) {

    var operation = request.body.action;
    var ID = request.body.ID;
    var NAME = request.body.NAME;
    //select
    if (operation == "ShowAllCompanies") {
       params = {
            connectionString: "Data Source=LIRON-PC\\SQLEXPRESS;Initial Catalog=myDataBase;Integrated Security=True",
            source: "SELECT * FROM companies"
        };
    }
    if (operation == "ShowCompanyById") {
        params = {
            connectionString: "Data Source=LIRON-PC\\SQLEXPRESS;Initial Catalog=myDataBase;Integrated Security=True",
            source: "SELECT * FROM companies where id='" +ID+"'"
        };
    }
    else if (operation == "ShowAllBrands") {
        params = {
            connectionString: "Data Source=LIRON-PC\\SQLEXPRESS;Initial Catalog=myDataBase;Integrated Security=True",
            source: "SELECT * FROM Brands"
        };
    }
    if (operation == "ShowBrandById") {
        params = {
            connectionString: "Data Source=LIRON-PC\\SQLEXPRESS;Initial Catalog=myDataBase;Integrated Security=True",
            source: "SELECT * FROM Brands where id='" + ID + "'"
        };
    }
    else if (operation == "ShowAllClients") {
        params = {
            connectionString: "Data Source=LIRON-PC\\SQLEXPRESS;Initial Catalog=myDataBase;Integrated Security=True",
            source: "SELECT * FROM clients"
        };
    }
    if (operation == "ShowAllInvoice") {
        params = {
            connectionString: "Data Source=LIRON-PC\\SQLEXPRESS;Initial Catalog=myDataBase;Integrated Security=True",
            source: "SELECT invoice.id, company_id,companies._name,serial_no,date,total_value FROM invoice,companies where invoice.company_id=companies.id"
        };
    }
    if (operation == "ShowInvoiceById") {
        params = {
            connectionString: "Data Source=LIRON-PC\\SQLEXPRESS;Initial Catalog=myDataBase;Integrated Security=True",
            source: "SELECT invoice.id, company_id,companies._name,serial_no,date,total_value FROM invoice,companies where invoice.company_id=companies.id and invoice.id='" + ID + "'"
        };
    }
    if (operation == "ShowAllParts") {
        params = {
            connectionString: "Data Source=LIRON-PC\\SQLEXPRESS;Initial Catalog=myDataBase;Integrated Security=True",
            source: "SELECT * FROM parts"
        };
    }
    if (operation == "ShowAllModel_Parts") {
        params = {
            connectionString: "Data Source=LIRON-PC\\SQLEXPRESS;Initial Catalog=myDataBase;Integrated Security=True",
            source: "SELECT model_parts.id,Brands._name,parts._name as part,models._name as model FROM model_parts,parts,models,brands where parts.id=part_id and model_id=models.id and Brand_id=Brands.id"
        };
    }
    if (operation == "ShowAllRepair_status") {
        params = {
            connectionString: "Data Source=LIRON-PC\\SQLEXPRESS;Initial Catalog=myDataBase;Integrated Security=True",
            source: "SELECT repair_status.id,repair_id,status._name as status,created_at,updated_at,user_id,users.firstname as userFirstName,users.lastname as userLastName,users.email as userEmail  FROM repair_status,users,status where status.id=status_id and user_id=users.id"
        };
    }
    //insert
    else if (operation == "AddCompany") {
        params = {
            connectionString: "Data Source=LIRON-PC\\SQLEXPRESS;Initial Catalog=myDataBase;Integrated Security=True",
            source: "INSERT INTO companies(id,_name) VALUES ('" + ID + "','" + NAME +"')"

        };
    }
    else if (operation == "AddBrand") {
        params = {
            connectionString: "Data Source=LIRON-PC\\SQLEXPRESS;Initial Catalog=myDataBase;Integrated Security=True",
            source: "INSERT INTO Brands(id,_name) VALUES ('" + ID + "','" + NAME + "')"

        };
    }
    //update
    else if (operation == "UpdateCompany") {
        params = {
            connectionString: "Data Source=LIRON-PC\\SQLEXPRESS;Initial Catalog=myDataBase;Integrated Security=True",
            source: "UPDATE companies SET _name = '" + NAME + "' WHERE id ='" + ID + "'"

        };
    }
    else if (operation == "UpdateBrand") {
        params = {
            connectionString: "Data Source=LIRON-PC\\SQLEXPRESS;Initial Catalog=myDataBase;Integrated Security=True",
            source: "UPDATE Brands SET _name = '" + NAME + "' WHERE id ='" + ID + "'"

        };
    }
    //delete
    else if (operation == "DeleteCompany") {
        params = {
            connectionString: "Data Source=LIRON-PC\\SQLEXPRESS;Initial Catalog=myDataBase;Integrated Security=True",
            source: "DELETE FROM companies WHERE id='" + ID + "'"

        };
    }
    else if (operation == "DeleteBrand") {
        params = {
            connectionString: "Data Source=LIRON-PC\\SQLEXPRESS;Initial Catalog=myDataBase;Integrated Security=True",
            source: "DELETE FROM Brands WHERE id='" + ID + "'"

        };
    }

    var getData = edge.func('sql', params);
    getData(null, function (error, result) {
        if (error) { console.log(error); return; }
        if (result) {
            console.log(result);
            var temp = JSON.stringify(result);
            response.send(temp);
        }
        else {
            console.log("No results");
        }
    });
});

passport.use(new Strategy(
    function(email, password, cb) {
        console.log('in strategy');
        db.users.findByUsername(email, function(err, user) {
            if (err) { return cb(err); }
            if (!user) { return cb(null, false); }
            if (user.password != password) { return cb(null, false); }
            return cb(null, user);
        });
    }));

app.use(express.static(__dirname + '/project'));

app.get('/',
    passport.authenticate('basic', { session: false }),
    function(request,response){
        response.json({ username: request.user.username, email: request.user.email });
    }
);

app.listen(12345);
console.log('Server running on port ' + port);<commit_msg>favicon caused bug<commit_after>var express = require('express');
var app = express();
var edge = require('edge');
var port = 12345;
var passport = require('passport');
var Strategy = require('passport-http').BasicStrategy;
var db = require('./db');
var bodyParser = require('body-parser')
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// Add headers for Cross Origin XML HTTP REQUEST
app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:63342');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Pass to next layer of middleware
    next();
});
app.post('/', function (request, response) {

    var operation = request.body.action;
    var ID = request.body.ID;
    var NAME = request.body.NAME;
    //select
    if (operation == "ShowAllCompanies") {
       params = {
            connectionString: "Data Source=LIRON-PC\\SQLEXPRESS;Initial Catalog=myDataBase;Integrated Security=True",
            source: "SELECT * FROM companies"
        };
    }
    if (operation == "ShowCompanyById") {
        params = {
            connectionString: "Data Source=LIRON-PC\\SQLEXPRESS;Initial Catalog=myDataBase;Integrated Security=True",
            source: "SELECT * FROM companies where id='" +ID+"'"
        };
    }
    else if (operation == "ShowAllBrands") {
        params = {
            connectionString: "Data Source=LIRON-PC\\SQLEXPRESS;Initial Catalog=myDataBase;Integrated Security=True",
            source: "SELECT * FROM Brands"
        };
    }
    if (operation == "ShowBrandById") {
        params = {
            connectionString: "Data Source=LIRON-PC\\SQLEXPRESS;Initial Catalog=myDataBase;Integrated Security=True",
            source: "SELECT * FROM Brands where id='" + ID + "'"
        };
    }
    else if (operation == "ShowAllClients") {
        params = {
            connectionString: "Data Source=LIRON-PC\\SQLEXPRESS;Initial Catalog=myDataBase;Integrated Security=True",
            source: "SELECT * FROM clients"
        };
    }
    if (operation == "ShowAllInvoice") {
        params = {
            connectionString: "Data Source=LIRON-PC\\SQLEXPRESS;Initial Catalog=myDataBase;Integrated Security=True",
            source: "SELECT invoice.id, company_id,companies._name,serial_no,date,total_value FROM invoice,companies where invoice.company_id=companies.id"
        };
    }
    if (operation == "ShowInvoiceById") {
        params = {
            connectionString: "Data Source=LIRON-PC\\SQLEXPRESS;Initial Catalog=myDataBase;Integrated Security=True",
            source: "SELECT invoice.id, company_id,companies._name,serial_no,date,total_value FROM invoice,companies where invoice.company_id=companies.id and invoice.id='" + ID + "'"
        };
    }
    if (operation == "ShowAllParts") {
        params = {
            connectionString: "Data Source=LIRON-PC\\SQLEXPRESS;Initial Catalog=myDataBase;Integrated Security=True",
            source: "SELECT * FROM parts"
        };
    }
    if (operation == "ShowAllModel_Parts") {
        params = {
            connectionString: "Data Source=LIRON-PC\\SQLEXPRESS;Initial Catalog=myDataBase;Integrated Security=True",
            source: "SELECT model_parts.id,Brands._name,parts._name as part,models._name as model FROM model_parts,parts,models,brands where parts.id=part_id and model_id=models.id and Brand_id=Brands.id"
        };
    }
    if (operation == "ShowAllRepair_status") {
        params = {
            connectionString: "Data Source=LIRON-PC\\SQLEXPRESS;Initial Catalog=myDataBase;Integrated Security=True",
            source: "SELECT repair_status.id,repair_id,status._name as status,created_at,updated_at,user_id,users.firstname as userFirstName,users.lastname as userLastName,users.email as userEmail  FROM repair_status,users,status where status.id=status_id and user_id=users.id"
        };
    }
    //insert
    else if (operation == "AddCompany") {
        params = {
            connectionString: "Data Source=LIRON-PC\\SQLEXPRESS;Initial Catalog=myDataBase;Integrated Security=True",
            source: "INSERT INTO companies(id,_name) VALUES ('" + ID + "','" + NAME +"')"

        };
    }
    else if (operation == "AddBrand") {
        params = {
            connectionString: "Data Source=LIRON-PC\\SQLEXPRESS;Initial Catalog=myDataBase;Integrated Security=True",
            source: "INSERT INTO Brands(id,_name) VALUES ('" + ID + "','" + NAME + "')"

        };
    }
    //update
    else if (operation == "UpdateCompany") {
        params = {
            connectionString: "Data Source=LIRON-PC\\SQLEXPRESS;Initial Catalog=myDataBase;Integrated Security=True",
            source: "UPDATE companies SET _name = '" + NAME + "' WHERE id ='" + ID + "'"

        };
    }
    else if (operation == "UpdateBrand") {
        params = {
            connectionString: "Data Source=LIRON-PC\\SQLEXPRESS;Initial Catalog=myDataBase;Integrated Security=True",
            source: "UPDATE Brands SET _name = '" + NAME + "' WHERE id ='" + ID + "'"

        };
    }
    //delete
    else if (operation == "DeleteCompany") {
        params = {
            connectionString: "Data Source=LIRON-PC\\SQLEXPRESS;Initial Catalog=myDataBase;Integrated Security=True",
            source: "DELETE FROM companies WHERE id='" + ID + "'"

        };
    }
    else if (operation == "DeleteBrand") {
        params = {
            connectionString: "Data Source=LIRON-PC\\SQLEXPRESS;Initial Catalog=myDataBase;Integrated Security=True",
            source: "DELETE FROM Brands WHERE id='" + ID + "'"

        };
    }

    var getData = edge.func('sql', params);
    getData(null, function (error, result) {
        if (error) { console.log(error); return; }
        if (result) {
            console.log(result);
            var temp = JSON.stringify(result);
            response.send(temp);
        }
        else {
            console.log("No results");
        }
    });
});

passport.use(new Strategy(
    function(email, password, cb) {
        console.log('in strategy');
        db.users.findByUsername(email, function(err, user) {
            if (err) { return cb(err); }
            if (!user) { return cb(null, false); }
            if (user.password != password) { return cb(null, false); }
            return cb(null, user);
        });
    }));

app.use(express.static(__dirname + '/project'));

app.get('/',
    passport.authenticate('basic', { session: false }),
    function(request,response){
        response.json({ username: request.user.username, email: request.user.email });
    }
);

app.listen(12345);
console.log('Server running on port ' + port);<|endoftext|>


<commit_before>function OnConfig($stateProvider, $locationProvider, $urlRouterProvider, $mdThemingProvider, $logProvider, AppSettings) {
    'ngInject';

    $mdThemingProvider.theme('default')
		.dark();

    $locationProvider.html5Mode(false);

    $stateProvider
	    .state('Home', {
	        url: '/',
	        controller: 'HomeCtrl as home',
	        templateUrl: 'home.html',
	        title: 'Home'
	    });

    $urlRouterProvider.otherwise('/');

    $logProvider.debugEnabled(AppSettings.debugEnabled)

}

export default OnConfig;<commit_msg>Blue is Better<commit_after>function OnConfig($stateProvider, $locationProvider, $urlRouterProvider, $mdThemingProvider, $logProvider, AppSettings) {
    'ngInject';

    $mdThemingProvider.theme('default')
    .accentPalette('blue')
		.dark();

    $locationProvider.html5Mode(false);

    $stateProvider
	    .state('Home', {
	        url: '/',
	        controller: 'HomeCtrl as home',
	        templateUrl: 'home.html',
	        title: 'Home'
	    });

    $urlRouterProvider.otherwise('/');

    $logProvider.debugEnabled(AppSettings.debugEnabled)

}

export default OnConfig;<|endoftext|>


<commit_before>/* eslint no-extend-native: 0 */

(function () {
  // Defining locale
  Date.shortMonths = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
  Date.longMonths = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
  Date.shortDays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
  Date.longDays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
  // Defining patterns
  var replaceChars = {
    // Day
    d: function () { var d = this.getDate(); return (d < 10 ? '0' : '') + d },
    D: function () { return Date.shortDays[this.getDay()] },
    j: function () { return this.getDate() },
    l: function () { return Date.longDays[this.getDay()] },
    N: function () { var N = this.getDay(); return (N === 0 ? 7 : N) },
    S: function () { var S = this.getDate(); return (S % 10 === 1 && S !== 11 ? 'st' : (S % 10 === 2 && S !== 12 ? 'nd' : (S % 10 === 3 && S !== 13 ? 'rd' : 'th'))) },
    w: function () { return this.getDay() },
    z: function () { var d = new Date(this.getFullYear(), 0, 1); return Math.ceil((this - d) / 86400000) },
    // Week
    W: function () {
      var target = new Date(this.valueOf())
      var dayNr = (this.getDay() + 6) % 7
      target.setDate(target.getDate() - dayNr + 3)
      var firstThursday = target.valueOf()
      target.setMonth(0, 1)
      if (target.getDay() !== 4) {
        target.setMonth(0, 1 + ((4 - target.getDay()) + 7) % 7)
      }
      var retVal = 1 + Math.ceil((firstThursday - target) / 604800000)

      return (retVal < 10 ? '0' + retVal : retVal)
    },
    // Month
    F: function () { return Date.longMonths[this.getMonth()] },
    m: function () { var m = this.getMonth(); return (m < 9 ? '0' : '') + (m + 1) },
    M: function () { return Date.shortMonths[this.getMonth()] },
    n: function () { return this.getMonth() + 1 },
    t: function () {
      var year = this.getFullYear()
      var nextMonth = this.getMonth() + 1
      if (nextMonth === 12) {
        year = year++
        nextMonth = 0
      }
      return new Date(year, nextMonth, 0).getDate()
    },
    // Year
    L: function () { var L = this.getFullYear(); return (L % 400 === 0 || (L % 100 !== 0 && L % 4 === 0)) },
    o: function () { var d = new Date(this.valueOf()); d.setDate(d.getDate() - ((this.getDay() + 6) % 7) + 3); return d.getFullYear() },
    Y: function () { return this.getFullYear() },
    y: function () { return ('' + this.getFullYear()).substr(2) },
    // Time
    a: function () { return this.getHours() < 12 ? 'am' : 'pm' },
    A: function () { return this.getHours() < 12 ? 'AM' : 'PM' },
    B: function () { return Math.floor((((this.getUTCHours() + 1) % 24) + this.getUTCMinutes() / 60 + this.getUTCSeconds() / 3600) * 1000 / 24) },
    g: function () { return this.getHours() % 12 || 12 },
    G: function () { return this.getHours() },
    h: function () { var h = this.getHours(); return ((h % 12 || 12) < 10 ? '0' : '') + (h % 12 || 12) },
    H: function () { var H = this.getHours(); return (H < 10 ? '0' : '') + H },
    i: function () { var i = this.getMinutes(); return (i < 10 ? '0' : '') + i },
    s: function () { var s = this.getSeconds(); return (s < 10 ? '0' : '') + s },
    v: function () { var v = this.getMilliseconds(); return (v < 10 ? '00' : (v < 100 ? '0' : '')) + v },
    // Timezone
    e: function () { return Intl.DateTimeFormat().resolvedOptions().timeZone },
    I: function () {
      var DST = null
      for (var i = 0; i < 12; ++i) {
        var d = new Date(this.getFullYear(), i, 1)
        var offset = d.getTimezoneOffset()

        if (DST === null) DST = offset
        else if (offset < DST) { DST = offset; break } else if (offset > DST) break
      }
      return (this.getTimezoneOffset() === DST) | 0
    },
    O: function () { var O = this.getTimezoneOffset(); return (-O < 0 ? '-' : '+') + (Math.abs(O / 60) < 10 ? '0' : '') + Math.floor(Math.abs(O / 60)) + (Math.abs(O % 60) === 0 ? '00' : ((Math.abs(O % 60) < 10 ? '0' : '')) + (Math.abs(O % 60))) },
    P: function () { var P = this.getTimezoneOffset(); return (-P < 0 ? '-' : '+') + (Math.abs(P / 60) < 10 ? '0' : '') + Math.floor(Math.abs(P / 60)) + ':' + (Math.abs(P % 60) === 0 ? '00' : ((Math.abs(P % 60) < 10 ? '0' : '')) + (Math.abs(P % 60))) },
    T: function () { var tz = this.toLocaleTimeString(navigator.language, {timeZoneName: 'short'}).split(' '); return tz[tz.length - 1] },
    Z: function () { return -this.getTimezoneOffset() * 60 },
    // Full Date/Time
    c: function () { return this.format('Y-m-d\\TH:i:sP') },
    r: function () { return this.toString() },
    U: function () { return this.getTime() / 1000 }
  }

  // Simulates PHP's date function
  Date.prototype.format = function (format) {
    var date = this
    return format.replace(/(\\?)(.)/g, function (_, esc, chr) {
      return (esc === '' && replaceChars[chr]) ? replaceChars[chr].call(date) : chr
    })
  }
}).call(this)
<commit_msg>U format should not contain decimals if matching PHP<commit_after>/* eslint no-extend-native: 0 */

(function () {
  // Defining locale
  Date.shortMonths = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
  Date.longMonths = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
  Date.shortDays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
  Date.longDays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
  // Defining patterns
  var replaceChars = {
    // Day
    d: function () { var d = this.getDate(); return (d < 10 ? '0' : '') + d },
    D: function () { return Date.shortDays[this.getDay()] },
    j: function () { return this.getDate() },
    l: function () { return Date.longDays[this.getDay()] },
    N: function () { var N = this.getDay(); return (N === 0 ? 7 : N) },
    S: function () { var S = this.getDate(); return (S % 10 === 1 && S !== 11 ? 'st' : (S % 10 === 2 && S !== 12 ? 'nd' : (S % 10 === 3 && S !== 13 ? 'rd' : 'th'))) },
    w: function () { return this.getDay() },
    z: function () { var d = new Date(this.getFullYear(), 0, 1); return Math.ceil((this - d) / 86400000) },
    // Week
    W: function () {
      var target = new Date(this.valueOf())
      var dayNr = (this.getDay() + 6) % 7
      target.setDate(target.getDate() - dayNr + 3)
      var firstThursday = target.valueOf()
      target.setMonth(0, 1)
      if (target.getDay() !== 4) {
        target.setMonth(0, 1 + ((4 - target.getDay()) + 7) % 7)
      }
      var retVal = 1 + Math.ceil((firstThursday - target) / 604800000)

      return (retVal < 10 ? '0' + retVal : retVal)
    },
    // Month
    F: function () { return Date.longMonths[this.getMonth()] },
    m: function () { var m = this.getMonth(); return (m < 9 ? '0' : '') + (m + 1) },
    M: function () { return Date.shortMonths[this.getMonth()] },
    n: function () { return this.getMonth() + 1 },
    t: function () {
      var year = this.getFullYear()
      var nextMonth = this.getMonth() + 1
      if (nextMonth === 12) {
        year = year++
        nextMonth = 0
      }
      return new Date(year, nextMonth, 0).getDate()
    },
    // Year
    L: function () { var L = this.getFullYear(); return (L % 400 === 0 || (L % 100 !== 0 && L % 4 === 0)) },
    o: function () { var d = new Date(this.valueOf()); d.setDate(d.getDate() - ((this.getDay() + 6) % 7) + 3); return d.getFullYear() },
    Y: function () { return this.getFullYear() },
    y: function () { return ('' + this.getFullYear()).substr(2) },
    // Time
    a: function () { return this.getHours() < 12 ? 'am' : 'pm' },
    A: function () { return this.getHours() < 12 ? 'AM' : 'PM' },
    B: function () { return Math.floor((((this.getUTCHours() + 1) % 24) + this.getUTCMinutes() / 60 + this.getUTCSeconds() / 3600) * 1000 / 24) },
    g: function () { return this.getHours() % 12 || 12 },
    G: function () { return this.getHours() },
    h: function () { var h = this.getHours(); return ((h % 12 || 12) < 10 ? '0' : '') + (h % 12 || 12) },
    H: function () { var H = this.getHours(); return (H < 10 ? '0' : '') + H },
    i: function () { var i = this.getMinutes(); return (i < 10 ? '0' : '') + i },
    s: function () { var s = this.getSeconds(); return (s < 10 ? '0' : '') + s },
    v: function () { var v = this.getMilliseconds(); return (v < 10 ? '00' : (v < 100 ? '0' : '')) + v },
    // Timezone
    e: function () { return Intl.DateTimeFormat().resolvedOptions().timeZone },
    I: function () {
      var DST = null
      for (var i = 0; i < 12; ++i) {
        var d = new Date(this.getFullYear(), i, 1)
        var offset = d.getTimezoneOffset()

        if (DST === null) DST = offset
        else if (offset < DST) { DST = offset; break } else if (offset > DST) break
      }
      return (this.getTimezoneOffset() === DST) | 0
    },
    O: function () { var O = this.getTimezoneOffset(); return (-O < 0 ? '-' : '+') + (Math.abs(O / 60) < 10 ? '0' : '') + Math.floor(Math.abs(O / 60)) + (Math.abs(O % 60) === 0 ? '00' : ((Math.abs(O % 60) < 10 ? '0' : '')) + (Math.abs(O % 60))) },
    P: function () { var P = this.getTimezoneOffset(); return (-P < 0 ? '-' : '+') + (Math.abs(P / 60) < 10 ? '0' : '') + Math.floor(Math.abs(P / 60)) + ':' + (Math.abs(P % 60) === 0 ? '00' : ((Math.abs(P % 60) < 10 ? '0' : '')) + (Math.abs(P % 60))) },
    T: function () { var tz = this.toLocaleTimeString(navigator.language, {timeZoneName: 'short'}).split(' '); return tz[tz.length - 1] },
    Z: function () { return -this.getTimezoneOffset() * 60 },
    // Full Date/Time
    c: function () { return this.format('Y-m-d\\TH:i:sP') },
    r: function () { return this.toString() },
    U: function () { return Math.floor(this.getTime() / 1000) }
  }

  // Simulates PHP's date function
  Date.prototype.format = function (format) {
    var date = this
    return format.replace(/(\\?)(.)/g, function (_, esc, chr) {
      return (esc === '' && replaceChars[chr]) ? replaceChars[chr].call(date) : chr
    })
  }
}).call(this)
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import Link from '../Link';
import s from './LinkList.css';

class LinkList extends React.Component {
  static propTypes = {
    files: PropTypes.arrayOf(PropTypes.object).isRequired,
  };

  genFileList() {
    const { files } = this.props;
    const fileList = [];
    fileList.push((

Back to Home

              ORZ

    ));
    for (let i = 0; i < files.length; i += 1) {
      const { id, name, onCreate, owner } = files[i];
      fileList.push((

          <Link to={`/article/${id}`}>{name}</Link>

            on { new Date(onCreate).toLocaleString()} by {owner}

      ));
    }
    return fileList;
  }

  render() {
    return (

        { this.genFileList() }

    );
  }
}

export default withStyles(s)(LinkList);
<commit_msg>Fix article path<commit_after>import React, { PropTypes } from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import Link from '../Link';
import s from './LinkList.css';

class LinkList extends React.Component {
  static propTypes = {
    files: PropTypes.arrayOf(PropTypes.object).isRequired,
  };

  genFileList() {
    const { files } = this.props;
    const fileList = [];
    fileList.push((

Back to Home

              ORZ

    ));
    for (let i = 0; i < files.length; i += 1) {
      const { id, name, onCreate, owner } = files[i];
      fileList.push((

          <Link to={`/read/${id}`}>{name}</Link>

            on { new Date(onCreate).toLocaleString()} by {owner}

      ));
    }
    return fileList;
  }

  render() {
    return (

        { this.genFileList() }

    );
  }
}

export default withStyles(s)(LinkList);
<|endoftext|>


<commit_before>
/*
 * Wegas
 * http://wegas.albasim.ch
 *
 * Copyright (c) 2013-2018  School of Business and Engineering Vaud, Comem, MEI
 * Licensed under the MIT License
 */
/**
 * @fileoverview
 * @author Maxence Laurent <maxence.laurent> <gmail.com>
 */
/*global YUI*/

YUI.add("wegas-i18n-global-en", function(Y) {
    Y.Wegas.I18n.register("wegas-i18n-global", "en", {
        wegas: {
            player: "player",
            players: "players",
            team: "team",
            teams: "teams"
        },
        global: {
            and: "and",
            description: "description",
            details: "details",
            delete: "delete",
            dunno: "I don't know",
            variableNotFound: "Unable to found \"{{name}}\" variable",
            logout: "logout",
            statistics: "Statistics",
            peerReview: "Peer Review",
            backToMenu: "back to question list"
        },
        i18n:{
            manager: {
                title: "Languages Manager"
            },
            languages: "Languages"
        },
        errors: {
            conflict: "Your request could not be completed due to a conflict. This usually means you tried to update an outdated element.",
            greaterThan: "{{value}} is greater greater than {{max}}",
            lessThan: "{{value}} is less than {{min}}",
            limitReached: "You cannot select more than {{num}} values",
            prohibited: "\"{{value}}\" not allowed. It must be one of these: {{values}}",
            nan: "\"{{value}}\" is not a number",
            notAPositiveInteger: "\"{{value}}\" is not a positive integer",
            outOfBounds: "{{value}} not in [{{min}},{{max}}]"
        },
        inbox: {
            deleteEmailConfirmation: "The e-mail {{subject}} will be permanently deleted. Continue?",
            noMessages: "You have no messages",
            noMessageSelected: "Select an item on the left"
        }
    }, {
        base: {
            prefix: "",
            suffix: "",
            decimalPlaces: "",
            thousandsSeparator: ",",
            decimalSeparator: "."
        },
        extra: {
            chf: {
                prefix: "CHF ",
                decimalPlaces: 2
            },
            euro:{
                prefix: "€",
                decimalPlaces: 2
            },
            pounds: {
                prefix: "£",
                decimalPlaces: 2
            },
            int: {
                decimalPlaces: 0
            },
            fixed2: {
                decimalPlaces: 2
            }
        }
    });
});

<commit_msg>fix ci<commit_after>
/*
 * Wegas
 * http://wegas.albasim.ch
 *
 * Copyright (c) 2013-2018  School of Business and Engineering Vaud, Comem, MEI
 * Licensed under the MIT License
 */
/**
 * @fileoverview
 * @author Maxence Laurent <maxence.laurent> <gmail.com>
 */
/*global YUI*/

YUI.add("wegas-i18n-global-en", function(Y) {
    Y.Wegas.I18n.register("wegas-i18n-global", "en", {
        wegas: {
            player: "player",
            players: "players",
            team: "team",
            teams: "teams"
        },
        global: {
            and: "and",
            description: "description",
            details: "details",
            delete: "delete",
            dunno: "I don't know",
            variableNotFound: "Unable to found \"{{name}}\" variable",
            logout: "logout",
            statistics: "Statistics",
            peerReview: "Peer Review",
            backToMenu: "back to menu",
            mcqBackToMenu: "back to question list"
        },
        i18n:{
            manager: {
                title: "Languages Manager"
            },
            languages: "Languages"
        },
        errors: {
            conflict: "Your request could not be completed due to a conflict. This usually means you tried to update an outdated element.",
            greaterThan: "{{value}} is greater greater than {{max}}",
            lessThan: "{{value}} is less than {{min}}",
            limitReached: "You cannot select more than {{num}} values",
            prohibited: "\"{{value}}\" not allowed. It must be one of these: {{values}}",
            nan: "\"{{value}}\" is not a number",
            notAPositiveInteger: "\"{{value}}\" is not a positive integer",
            outOfBounds: "{{value}} not in [{{min}},{{max}}]"
        },
        inbox: {
            deleteEmailConfirmation: "The e-mail {{subject}} will be permanently deleted. Continue?",
            noMessages: "You have no messages",
            noMessageSelected: "Select an item on the left"
        }
    }, {
        base: {
            prefix: "",
            suffix: "",
            decimalPlaces: "",
            thousandsSeparator: ",",
            decimalSeparator: "."
        },
        extra: {
            chf: {
                prefix: "CHF ",
                decimalPlaces: 2
            },
            euro:{
                prefix: "€",
                decimalPlaces: 2
            },
            pounds: {
                prefix: "£",
                decimalPlaces: 2
            },
            int: {
                decimalPlaces: 0
            },
            fixed2: {
                decimalPlaces: 2
            }
        }
    });
});

<|endoftext|>