<commit_before>/* eslint-disable no-console */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import ObjectInspector from 'react-object-inspector';
import stringSimilarity from 'string-similarity';
import Command from './args';
import Bar from './Bar';
import Content from './Content';
import './Terminal.css';

// Capture the console.log calls (hijacking)
(function setOldLogger() {
  console['oldLog'] = console['log']; // eslint-disable-line dot-notation
}());

// Handle console logging
function handleLogging(method, addToOutput) {
  // eslint-disable-next-line no-console
  console[method] = (...args) => {
    try {
      console.oldLog(`[${method}]`, ...args);
    } catch (e) {
      throw new Error('Terminal was loaded more than once check script tags');
    }
    const res = [...args].slice(0, 15).map((arg, i) => {
      switch (typeof arg) {
        case 'object':
          return <ObjectInspector data={arg} key={`object-${i}`} />;
        case 'function':
          return `${arg}`;
        default:
          return arg;
      }
    });
    addToOutput(res);
  };
  Object.defineProperty(console[method], 'name', { value: method, writable: false }); // eslint-disable-line no-console
}

const commandsPropType = PropTypes.objectOf(PropTypes.oneOfType([
  PropTypes.func,
  PropTypes.shape({
    options: PropTypes.arrayOf(PropTypes.shape({
      name: PropTypes.string,
      description: PropTypes.string,
      defaultValue: PropTypes.any,
    })),
    method: PropTypes.func,
  }),
]));

const descriptionsPropType = PropTypes.objectOf(PropTypes.oneOfType([
  PropTypes.string,
  PropTypes.bool,
]));

class Terminal extends Component {
  static displayName = 'Terminal';

  static propTypes = {
    msg: PropTypes.string,
    color: PropTypes.string,
    style: PropTypes.object, // eslint-disable-line
    prompt: PropTypes.string,
    barColor: PropTypes.string,
    backgroundColor: PropTypes.string,
    commands: commandsPropType,
    descriptions: descriptionsPropType,
    watchConsoleLogging: PropTypes.bool,
    commandPassThrough: PropTypes.oneOfType([
      PropTypes.func,
      PropTypes.bool,
    ]),
    promptSymbol: PropTypes.string,
    plugins: PropTypes.arrayOf(PropTypes.shape({
      name: PropTypes.string.isRequired,
      load: PropTypes.func,
      commands: commandsPropType,
      descriptions: descriptionsPropType,
    })),
  };

  static defaultProps = {
    msg: '',
    color: 'green',
    style: {},
    prompt: 'green',
    barColor: 'black',
    backgroundColor: 'black',
    commands: {},
    descriptions: {},
    watchConsoleLogging: true,
    commandPassThrough: false,
    promptSymbol: '>',
    plugins: [],
  };

  static childContextTypes = {
    symbol: PropTypes.string,
    show: PropTypes.bool,
    minimise: PropTypes.bool,
    maximise: PropTypes.bool,
    closeWindow: PropTypes.func,
    openWindow: PropTypes.func,
    minimiseWindow: PropTypes.func,
    unminimiseWindow: PropTypes.func,
    maximiseWindow: PropTypes.func,
    unmaximiseWindow: PropTypes.func,
    toggleShow: PropTypes.func,
    toggleMaximise: PropTypes.func,
    toggleMinimize: PropTypes.func,
  };

  state = {
    prompt: '>',
    promptPrefix: '',
    summary: [],
    commands: {},
    descriptions: {},
    history: [],
    historyCounter: 0,
    show: true,
    minimise: false,
    maximise: false,
    input: [],
  };

  getChildContext() {
    return {
      symbol: this.state.promptPrefix + this.state.prompt,
      show: this.state.show,
      minimise: this.state.minimise,
      maximise: this.state.maximise,
      openWindow: this.setTrue('show'),
      closeWindow: this.setFalse('show'),
      minimiseWindow: this.setTrue('minimise'),
      unminimiseWindow: this.setFalse('minimise'),
      maximiseWindow: this.setTrue('maximise'),
      unmaximiseWindow: this.setFalse('maximise'),
      toggleShow: this.toggleState('show'),
      toggleMaximise: this.toggleState('maximise'),
      toggleMinimize: this.toggleState('minimise'),
    };
  }

  // Prepare the symbol
  componentWillMount = () => {
    this.setState({ prompt: this.props.promptSymbol });
  };

  // Load everything!
  componentDidMount = () => {
    this.loadPlugins();
    this.assembleCommands();
    this.setDescriptions();
    this.showMsg();

    if (this.props.watchConsoleLogging) {
      this.watchConsoleLogging();
    }
  };

  // Show the content on toggling
  getAppContent = () => {
    const { show, minimise } = this.state;
    if (!show) {
      return this.getNote();
    }
    if (minimise) {
      return this.getBar();
    }
    return this.getContent();
  };

  // Shows everything (normal window)
  getContent = () => {
    const { backgroundColor, color, style, barColor, prompt } = this.props;

    const inputStyles = { backgroundColor, color };
    const promptStyles = { color: prompt };
    const barColorStyles = { backgroundColor: barColor };
    const backgroundColorStyles = { backgroundColor };

    const output = this.state.summary.map((content, i) => {
      if (typeof content === 'string' && content.length === 0) {
        return

;
      }
      return
{content}
;
    });

    return (

        <Bar style={barColorStyles} />
        <Content
          output={output}
          prompt={promptStyles}
          inputStyles={inputStyles}
          handleChange={this.handleChange}
          backgroundColor={backgroundColorStyles}
          handlerKeyPress={this.handlerKeyPress}
        />

    );
  };

  // Show only bar (minimise)
  getBar = () => {
    const { color, barColor, style } = this.props;
    const barColorStyles = { backgroundColor: barColor };

    return (

        <Bar style={barColorStyles} />

    );
  }

  // Show msg (on window close)
  getNote = () => (

OOPS! You closed the window.

      Click on the icon to reopen.

  );

  // Set descriptions of the commands
  setDescriptions = () => {
    let descriptions = {
      show: 'show the msg',
      clear: 'clear the screen',
      help: 'list all the commands',
      'edit-line': 'edit the contents of an output line',
      ...this.props.descriptions,
    };
    this.props.plugins.forEach((plugin) => {
      if (plugin.descriptions) {
        descriptions = {
          ...descriptions,
          ...plugin.descriptions,
        };
      }
    });
    this.setState({ descriptions });
  };

  setPromptPrefix = (promptPrefix) => {
    this.setState({ promptPrefix });
  };

  // Hide window
  setFalse = name => () => this.setState({ [name]: false });

  // Show window
  setTrue = name => () => this.setState({ [name]: true });

  /**
  * set the input value with the possible history value
  * @param {number} next position on the history
  */
  setValueWithHistory = (position, inputRef) => {
    const { history } = this.state;
    if (history[position]) {
      this.setState({ historyCounter: position });
      inputRef.value = history[position];
    }
  };

  toggleState = name => () => this.setState({ [name]: !this.state[name] });

  // Prepare the built-in commands
  assembleCommands = () => {
    let commands = {
      show: this.showMsg,
      clear: this.clearScreen,
      help: this.showHelp,
      echo: (input) => { console.log(...input.slice(1)); },
      'edit-line': {
        method: this.editLine,
        options: [
          {
            name: 'line',
            description: 'the line you want to edit. -1 is the last line',
            init: value => parseInt(value, 10),
            defaultValue: -1,
          },
        ],
      },
      ...this.props.commands,
    };

    this.props.plugins.forEach((plugin) => {
      if (plugin.commands) {
        commands = {
          ...commands,
          ...plugin.commands,
        };
      }
    });

    Object.keys(commands).forEach((name) => {
      const definition = commands[name];
      let method = definition;
      let parse = i => i;
      if (typeof definition === 'object') {
        const cmd = new Command();
        if (typeof definition.options !== 'undefined') {
          try {
            cmd.options(definition.options);
          } catch (e) {
            throw new Error('options for command wrong format');
          }
        }
        parse = i => cmd.parse(i, {
          name,
          help: true,
          version: false,
        });
        method = definition.method;
      }

      commands[name] = {
        parse,
        method,
      };
    });
    this.setState({ commands });
  };

  /**
   * autocomplete with the command the have the best match
   * @param {object} input reference
   */
  autocompleteValue = (inputRef) => {
    const { descriptions } = this.state;
    const keysToCheck = Object.keys(descriptions).filter(key => descriptions[key] !== false);
    const { bestMatch } = stringSimilarity.findBestMatch(inputRef.value, keysToCheck);

    if (bestMatch.rating >= 0.5) {
      return bestMatch.target;
    }

    return inputRef.value;
  }

  // Refresh or clear the screen
  clearScreen = () => {
    this.setState({ summary: [] });
  };

  // edit-line command
  editLine = (args) => {
    const { summary } = this.state;
    let index = args.line;
    if (index === -1) {
      index = summary.length === 0 ? 0 : summary.length - 1;
    }
    summary[index] = args._.join(' ');
    this.setState({ summary });
  }

  // Listen for user input
  handleChange = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      this.printLine(`${this.state.promptPrefix}${this.state.prompt} ${e.target.value}`);
      const { input } = this.state;

      const res = this.runCommand(
        `${input.join('\n')}${input.length > 0 ? '\n' : ''}${e.target.value}`,
      );

      if (typeof res !== 'undefined') {
        this.printLine(res);
      }

      const history = [...this.state.history, e.target.value];
      this.setState({
        input: [],
        history,
        historyCounter: history.length,
      });
      e.target.value = ''; // eslint-disable-line no-param-reassign
    } else if (e.key === 'Enter' && e.shiftKey) {
      this.printLine(`${this.state.promptPrefix}${this.state.prompt} ${e.target.value}`);
      const { input } = this.state;
      const history = [...this.state.history, e.target.value];
      this.setState({
        input: [...input, e.target.value],
        history,
        historyCounter: history.length,
      });
      e.target.value = ''; // eslint-disable-line no-param-reassign
    }
  };

  /**
   * Base of key code set the value of the input
   * with the history
   * 38 is key up
   * 40 is key down
   * @param {event} event of input
   */
  handlerKeyPress = (e, inputRef) => {
    const { historyCounter } = this.state;
    switch (e.keyCode) {
      case 38:
        this.setValueWithHistory(historyCounter - 1, inputRef);
        break;
      case 40:
        this.setValueWithHistory(historyCounter + 1, inputRef);
        break;
      case 9:
        inputRef.value = this.autocompleteValue(inputRef);
        e.preventDefault();
        break;
      default:
        break;
    }
  }

  // Plugins
  loadPlugins = () => {
    this.props.plugins.forEach((plugin) => {
      try {
        plugin.load({
          printLine: this.printLine,
          runCommand: this.runCommand,
          setPromptPrefix: this.setPromptPrefix,
        });
      } catch (e) {
        console.error(`Error loading plugin ${plugin.name}`); // eslint-disable-line no-console
        console.dir(e);
      }
    });
  };

  // Print the summary (input -> output)
  printLine = (inp) => {
    const summary = this.state.summary;
    summary.push(inp);
    this.setState({ summary });
  };

  // Execute the commands
  runCommand = (inputText) => {
    const inputArray = inputText.split(' ');
    const input = inputArray[0];
    const args = inputArray; // Undefined for function call
    const command = this.state.commands[input];
    let res;

    if (input === '') {
      // do nothing
    } else if (command === undefined) {
      if (typeof this.props.commandPassThrough === 'function') {
        res = this.props.commandPassThrough(inputArray, this.printLine, this.runCommand);
      } else {
        this.printLine(`-bash:${input}: command not found`);
      }
    } else {
      const parsedArgs = command.parse(args);
      if (typeof parsedArgs !== 'object' || (typeof parsedArgs === 'object' && !parsedArgs.help)) {
        res = command.method(parsedArgs, this.printLine, this.runCommand);
      }
    }
    return res;
  }

  // Listen for console logging and pass the input to handler (handleLogging)
  watchConsoleLogging = () => {
    handleLogging('log', this.printLine);
    handleLogging('info', this.printLine);
    // handleLogging('warn', this.printLine);
    // handleLogging('error', this.printLine);
  };

  // List all the commands (state + user defined)
  showHelp = () => {
    const options = Object.keys(this.state.commands);
    const descriptions = this.state.descriptions;
    for (const option of options) {
      // eslint-disable-line no-restricted-syntax
      if (descriptions[option] !== false) {
        this.printLine(`${option} - ${descriptions[option]}`);
      }
    }
  };

  // Show the msg (prop msg)
  showMsg = () => {
    this.printLine(this.props.msg);
  };

  render() {
    return (

        {this.getAppContent()}

    );
  }
}

export default Terminal;
<commit_msg>fixed lint issues<commit_after>/* eslint-disable no-console */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import ObjectInspector from 'react-object-inspector';
import stringSimilarity from 'string-similarity';
import Command from './args';
import Bar from './Bar';
import Content from './Content';
import './Terminal.css';

// Capture the console.log calls (hijacking)
(function setOldLogger() {
  console['oldLog'] = console['log']; // eslint-disable-line dot-notation
}());

// Handle console logging
function handleLogging(method, addToOutput) {
  // eslint-disable-next-line no-console
  console[method] = (...args) => {
    try {
      console.oldLog(`[${method}]`, ...args);
    } catch (e) {
      throw new Error('Terminal was loaded more than once check script tags');
    }
    const res = [...args].slice(0, 15).map((arg, i) => {
      switch (typeof arg) {
        case 'object':
          return <ObjectInspector data={arg} key={`object-${i}`} />;
        case 'function':
          return `${arg}`;
        default:
          return arg;
      }
    });
    addToOutput(res);
  };
  Object.defineProperty(console[method], 'name', { value: method, writable: false }); // eslint-disable-line no-console
}

const commandsPropType = PropTypes.objectOf(PropTypes.oneOfType([
  PropTypes.func,
  PropTypes.shape({
    options: PropTypes.arrayOf(PropTypes.shape({
      name: PropTypes.string,
      description: PropTypes.string,
      defaultValue: PropTypes.any,
    })),
    method: PropTypes.func,
  }),
]));

const descriptionsPropType = PropTypes.objectOf(PropTypes.oneOfType([
  PropTypes.string,
  PropTypes.bool,
]));

class Terminal extends Component {
  static displayName = 'Terminal';

  static propTypes = {
    msg: PropTypes.string,
    color: PropTypes.string,
    style: PropTypes.object, // eslint-disable-line
    prompt: PropTypes.string,
    barColor: PropTypes.string,
    backgroundColor: PropTypes.string,
    commands: commandsPropType,
    descriptions: descriptionsPropType,
    watchConsoleLogging: PropTypes.bool,
    commandPassThrough: PropTypes.oneOfType([
      PropTypes.func,
      PropTypes.bool,
    ]),
    promptSymbol: PropTypes.string,
    plugins: PropTypes.arrayOf(PropTypes.shape({
      name: PropTypes.string.isRequired,
      load: PropTypes.func,
      commands: commandsPropType,
      descriptions: descriptionsPropType,
    })),
  };

  static defaultProps = {
    msg: '',
    color: 'green',
    style: {},
    prompt: 'green',
    barColor: 'black',
    backgroundColor: 'black',
    commands: {},
    descriptions: {},
    watchConsoleLogging: true,
    commandPassThrough: false,
    promptSymbol: '>',
    plugins: [],
  };

  static childContextTypes = {
    symbol: PropTypes.string,
    show: PropTypes.bool,
    minimise: PropTypes.bool,
    maximise: PropTypes.bool,
    closeWindow: PropTypes.func,
    openWindow: PropTypes.func,
    minimiseWindow: PropTypes.func,
    unminimiseWindow: PropTypes.func,
    maximiseWindow: PropTypes.func,
    unmaximiseWindow: PropTypes.func,
    toggleShow: PropTypes.func,
    toggleMaximise: PropTypes.func,
    toggleMinimize: PropTypes.func,
  };

  state = {
    prompt: '>',
    promptPrefix: '',
    summary: [],
    commands: {},
    descriptions: {},
    history: [],
    historyCounter: 0,
    show: true,
    minimise: false,
    maximise: false,
    input: [],
  };

  getChildContext() {
    return {
      symbol: this.state.promptPrefix + this.state.prompt,
      show: this.state.show,
      minimise: this.state.minimise,
      maximise: this.state.maximise,
      openWindow: this.setTrue('show'),
      closeWindow: this.setFalse('show'),
      minimiseWindow: this.setTrue('minimise'),
      unminimiseWindow: this.setFalse('minimise'),
      maximiseWindow: this.setTrue('maximise'),
      unmaximiseWindow: this.setFalse('maximise'),
      toggleShow: this.toggleState('show'),
      toggleMaximise: this.toggleState('maximise'),
      toggleMinimize: this.toggleState('minimise'),
    };
  }

  // Prepare the symbol
  componentWillMount = () => {
    this.setState({ prompt: this.props.promptSymbol });
  };

  // Load everything!
  componentDidMount = () => {
    this.loadPlugins();
    this.assembleCommands();
    this.setDescriptions();
    this.showMsg();

    if (this.props.watchConsoleLogging) {
      this.watchConsoleLogging();
    }
  };

  // Show the content on toggling
  getAppContent = () => {
    const { show, minimise } = this.state;
    if (!show) {
      return this.getNote();
    }
    if (minimise) {
      return this.getBar();
    }
    return this.getContent();
  };

  // Shows everything (normal window)
  getContent = () => {
    const { backgroundColor, color, style, barColor, prompt } = this.props;

    const inputStyles = { backgroundColor, color };
    const promptStyles = { color: prompt };
    const barColorStyles = { backgroundColor: barColor };
    const backgroundColorStyles = { backgroundColor };

    const output = this.state.summary.map((content, i) => {
      if (typeof content === 'string' && content.length === 0) {
        return

;
      }
      return
{content}
;
    });

    return (

        <Bar style={barColorStyles} />
        <Content
          output={output}
          prompt={promptStyles}
          inputStyles={inputStyles}
          handleChange={this.handleChange}
          backgroundColor={backgroundColorStyles}
          handlerKeyPress={this.handlerKeyPress}
        />

    );
  };

  // Show only bar (minimise)
  getBar = () => {
    const { color, barColor, style } = this.props;
    const barColorStyles = { backgroundColor: barColor };

    return (

        <Bar style={barColorStyles} />

    );
  }

  // Show msg (on window close)
  getNote = () => (

OOPS! You closed the window.

      Click on the icon to reopen.

  );

  // Set descriptions of the commands
  setDescriptions = () => {
    let descriptions = {
      show: 'show the msg',
      clear: 'clear the screen',
      help: 'list all the commands',
      'edit-line': 'edit the contents of an output line',
      ...this.props.descriptions,
    };
    this.props.plugins.forEach((plugin) => {
      if (plugin.descriptions) {
        descriptions = {
          ...descriptions,
          ...plugin.descriptions,
        };
      }
    });
    this.setState({ descriptions });
  };

  setPromptPrefix = (promptPrefix) => {
    this.setState({ promptPrefix });
  };

  // Hide window
  setFalse = name => () => this.setState({ [name]: false });

  // Show window
  setTrue = name => () => this.setState({ [name]: true });

  /**
  * set the input value with the possible history value
  * @param {number} next position on the history
  */
  setValueWithHistory = (position, inputRef) => {
    const { history } = this.state;
    if (history[position]) {
      this.setState({ historyCounter: position });
      inputRef.value = history[position];
    }
  };

  toggleState = name => () => this.setState({ [name]: !this.state[name] });

  // Prepare the built-in commands
  assembleCommands = () => {
    let commands = {
      show: this.showMsg,
      clear: this.clearScreen,
      help: this.showHelp,
      echo: (input) => { console.log(...input.slice(1)); },
      'edit-line': {
        method: this.editLine,
        options: [
          {
            name: 'line',
            description: 'the line you want to edit. -1 is the last line',
            init: value => parseInt(value, 10),
            defaultValue: -1,
          },
        ],
      },
      ...this.props.commands,
    };

    this.props.plugins.forEach((plugin) => {
      if (plugin.commands) {
        commands = {
          ...commands,
          ...plugin.commands,
        };
      }
    });

    Object.keys(commands).forEach((name) => {
      const definition = commands[name];
      let method = definition;
      let parse = i => i;
      if (typeof definition === 'object') {
        const cmd = new Command();
        if (typeof definition.options !== 'undefined') {
          try {
            cmd.options(definition.options);
          } catch (e) {
            throw new Error('options for command wrong format');
          }
        }
        parse = i => cmd.parse(i, {
          name,
          help: true,
          version: false,
        });
        method = definition.method;
      }

      commands[name] = {
        parse,
        method,
      };
    });
    this.setState({ commands });
  };

  /**
   * autocomplete with the command the have the best match
   * @param {object} input reference
   */
  autocompleteValue = (inputRef) => {
    const { descriptions } = this.state;
    const keysToCheck = Object.keys(descriptions).filter(key => descriptions[key] !== false);
    const { bestMatch } = stringSimilarity.findBestMatch(inputRef.value, keysToCheck);

    if (bestMatch.rating >= 0.5) {
      return bestMatch.target;
    }

    return inputRef.value;
  }

  // Refresh or clear the screen
  clearScreen = () => {
    this.setState({ summary: [] });
  };

  // edit-line command
  editLine = (args) => {
    const { summary } = this.state;
    let index = args.line;
    if (index === -1) {
      index = summary.length === 0 ? 0 : summary.length - 1;
    }
    summary[index] = args._.join(' ');
    this.setState({ summary });
  }

  // Listen for user input
  handleChange = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      this.printLine(`${this.state.promptPrefix}${this.state.prompt} ${e.target.value}`);
      const { input } = this.state;

      const res = this.runCommand(
        `${input.join('\n')}${input.length > 0 ? '\n' : ''}${e.target.value}`,
      );

      if (typeof res !== 'undefined') {
        this.printLine(res);
      }

      const history = [...this.state.history, e.target.value];
      this.setState({
        input: [],
        history,
        historyCounter: history.length,
      });
      e.target.value = ''; // eslint-disable-line no-param-reassign
    } else if (e.key === 'Enter' && e.shiftKey) {
      this.printLine(`${this.state.promptPrefix}${this.state.prompt} ${e.target.value}`);
      const { input } = this.state;
      const history = [...this.state.history, e.target.value];
      this.setState({
        input: [...input, e.target.value],
        history,
        historyCounter: history.length,
      });
      e.target.value = ''; // eslint-disable-line no-param-reassign
    }
  };

  /**
   * Base of key code set the value of the input
   * with the history
   * 38 is key up
   * 40 is key down
   * @param {event} event of input
   */
  handlerKeyPress = (e, inputRef) => {
    const { historyCounter } = this.state;
    switch (e.keyCode) {
      case 38:
        this.setValueWithHistory(historyCounter - 1, inputRef);
        break;
      case 40:
        this.setValueWithHistory(historyCounter + 1, inputRef);
        break;
      case 9:
        inputRef.value = this.autocompleteValue(inputRef);
        e.preventDefault();
        break;
      default:
        break;
    }
  }

  // Plugins
  loadPlugins = () => {
    this.props.plugins.forEach((plugin) => {
      try {
        plugin.load({
          printLine: this.printLine,
          runCommand: this.runCommand,
          setPromptPrefix: this.setPromptPrefix,
        });
      } catch (e) {
        console.error(`Error loading plugin ${plugin.name}`); // eslint-disable-line no-console
        console.dir(e);
      }
    });
  };

  // Print the summary (input -> output)
  printLine = (inp) => {
    const summary = this.state.summary;
    summary.push(inp);
    this.setState({ summary });
  };

  // Execute the commands
  runCommand = (inputText) => {
    const inputArray = inputText.split(' ');
    const input = inputArray[0];
    const args = inputArray; // Undefined for function call
    const command = this.state.commands[input];
    let res;

    if (input === '') {
      // do nothing
    } else if (command === undefined) {
      if (typeof this.props.commandPassThrough === 'function') {
        res = this.props.commandPassThrough(inputArray, this.printLine, this.runCommand);
      } else {
        this.printLine(`-bash:${input}: command not found`);
      }
    } else {
      const parsedArgs = command.parse(args);
      if (typeof parsedArgs !== 'object' || (typeof parsedArgs === 'object' && !parsedArgs.help)) {
        res = command.method(parsedArgs, this.printLine, this.runCommand);
      }
    }
    return res;
  }

  // Listen for console logging and pass the input to handler (handleLogging)
  watchConsoleLogging = () => {
    handleLogging('log', this.printLine);
    handleLogging('info', this.printLine);
    // handleLogging('warn', this.printLine);
    // handleLogging('error', this.printLine);
  };

  // List all the commands (state + user defined)
  showHelp = () => {
    const options = Object.keys(this.state.commands);
    const descriptions = this.state.descriptions;
    for (const option of options) {
      // eslint-disable-line no-restricted-syntax
      if (descriptions[option] !== false) {
        this.printLine(`${option} - ${descriptions[option]}`);
      }
    }
  };

  // Show the msg (prop msg)
  showMsg = () => {
    this.printLine(this.props.msg);
  };

  render() {
    return (

        {this.getAppContent()}

    );
  }
}

export default Terminal;
<|endoftext|>


<commit_before>import React, {
  View,
  Text,
  StyleSheet,
  Component,
  ListView
} from 'react-native';

import baseStyles from '../baseStyles';

export default class UserList extends Component {
  constructor() {
    super();
    var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.state = {
      dataSource: ds.cloneWithRows(['leo', 'careca', 'gordo'])
    }
  }

  render() {
    return(
      <View style={[baseStyles.container, styles.container]}>
        <Text style={[baseStyles.title, styles.title]}>Marrecos</Text>
        <ListView
          dataSource={this.state.dataSource}
          renderRow={(rowData) => <Text style={[baseStyles.title, styles.title, baseStyles.subtitle]}>{rowData}</Text>}/>
      </View>
    );
  }
}

var styles = StyleSheet.create({
  container: {
    padding: 10
  },
  title: {
    fontSize: 30,
    margin: 10
  },
});
<commit_msg>Style UserList<commit_after>import React, {
  View,
  Text,
  StyleSheet,
  Component,
  ListView,
  TouchableHighlight
} from 'react-native';

import baseStyles from '../baseStyles';

export default class UserList extends Component {
  constructor() {
    super();
    var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.state = {
      dataSource: ds.cloneWithRows(['leo', 'careca', 'gordo'])
    }
  }

  render() {
    return(
      <View style={[baseStyles.container, styles.container]}>
        <Text style={[baseStyles.title, styles.title]}>Marrecos</Text>
        <ListView
          dataSource={this.state.dataSource}
          renderRow={this._renderRow.bind(this)}/>
      </View>
    );
  }

  _onClick() {
  }

  _renderRow(rowData, sectionID, rowID) {
    return(
      <View style={styles.row}>
        <Text style={[baseStyles.title, styles.title, baseStyles.subtitle]}>{rowData}</Text>
        <TouchableHighlight style={[baseStyles.button, styles.button]} onPress={this._onClick.bind(this)}  underlayColor='#FFE082'>
          <Text style={baseStyles.buttonText}>Truco nele!</Text>
        </TouchableHighlight>
      </View>
    );
  }
}

var styles = StyleSheet.create({
  container: {
    padding: 10
  },
  row: {
    flexDirection: 'row',
    justifyContent: 'space-between'
  },
  title: {
    fontSize: 30,
    margin: 10
  },
  button: {
    height: 30
  }
});
<|endoftext|>


<commit_before>import React, {Component} from 'react'
import Loader from './Loader'
import Card from './Card'
import {Section, Header, Title, RightContent, DraggableList} from '../styles/Base'

export default class Lane extends Component {

  state = {cards: this.props.cards, loading: false, currentPage: 1}

  handleScroll = (evt) => {
    const node = evt.target
    const elemScrolPosition = node.scrollHeight - node.scrollTop - node.clientHeight
    const {onScroll} = this.props
    if (elemScrolPosition <= 0 && onScroll && !this.state.loading) {
      const {currentPage, cards} = this.state
      this.setState({loading: true})
      const nextPage = currentPage + 1;
      onScroll(nextPage, this.props.id)
        .then((moreCards) => {
          this.setState({cards: [...cards, ...moreCards], loading: false, currentPage: nextPage})
        })
    }
  }

  componentWillReceiveProps(nextProps) {
    this.setState({cards: nextProps.cards})
  }

  laneDidMount = (node) => {
    if (node) {
      node.addEventListener('scroll', this.handleScroll);
    }
  };

  render() {
    const {loading} = this.state
    const {title, rightHeader, cards, onScroll, ...otherProps} = this.props
    return <Section {...otherProps} innerRef={this.laneDidMount}>
      <Header>
        <Title>{title}</Title>
        <RightContent>{rightHeader}</RightContent>
      </Header>
      <DraggableList>
        {this.state.cards && this.state.cards.map((card) => (
          <Card key={card.key}
                title={card.title}
                description={card.description}/>
        ))
        }
        {this.props.children}
      </DraggableList>
      {loading && <Loader/>}
    </Section>
  }
}

Lane.propTypes = {
  title: React.PropTypes.string.isRequired,
  cards: React.PropTypes.array,
  rightHeader: React.PropTypes.string,
  onScroll: React.PropTypes.func
}
<commit_msg>passing right header to card when cards is passed as json data<commit_after>import React, {Component} from 'react'
import Loader from './Loader'
import Card from './Card'
import {Section, Header, Title, RightContent, DraggableList} from '../styles/Base'

export default class Lane extends Component {

  state = {cards: this.props.cards, loading: false, currentPage: 1}

  handleScroll = (evt) => {
    const node = evt.target
    const elemScrolPosition = node.scrollHeight - node.scrollTop - node.clientHeight
    const {onScroll} = this.props
    if (elemScrolPosition <= 0 && onScroll && !this.state.loading) {
      const {currentPage, cards} = this.state
      this.setState({loading: true})
      const nextPage = currentPage + 1;
      onScroll(nextPage, this.props.id)
        .then((moreCards) => {
          this.setState({cards: [...cards, ...moreCards], loading: false, currentPage: nextPage})
        })
    }
  }

  componentWillReceiveProps(nextProps) {
    this.setState({cards: nextProps.cards})
  }

  laneDidMount = (node) => {
    if (node) {
      node.addEventListener('scroll', this.handleScroll);
    }
  };

  render() {
    const {loading} = this.state
    const {title, rightHeader, cards, onScroll, ...otherProps} = this.props
    return <Section {...otherProps} innerRef={this.laneDidMount}>
      <Header>
        <Title>{title}</Title>
        <RightContent>{rightHeader}</RightContent>
      </Header>
      <DraggableList>
        {this.state.cards && this.state.cards.map((card) => (
          <Card key={card.key}
                title={card.title}
                rightHeader={card.rightHeader}
                description={card.description}/>
        ))
        }
        {this.props.children}
      </DraggableList>
      {loading && <Loader/>}
    </Section>
  }
}

Lane.propTypes = {
  title: React.PropTypes.string.isRequired,
  cards: React.PropTypes.array,
  rightHeader: React.PropTypes.string,
  onScroll: React.PropTypes.func
}
<|endoftext|>


<commit_before>(function (webgl) {

    var CHANGE_STATE = {
        NOTHING_CHANGED : 0,
        TYPE_STRUCTURE_CHANGED : 1,
        TYPE_DATA_CHANGED : 2,
        TYPE_CHANGED: 3,
        ATTRIBUTE_STRUCTURE_CHANGED : 8,
        ATTRIBUTE_DATA_CHANGED : 16,
        ATTRIBUTE_CHANGED: 24
    };

    var READY_STATE = webgl.DrawableClosure.READY_STATE;

    var MESH_PARAMETERS = {};
    MESH_PARAMETERS[WebGLRenderingContext.TRIANGLES] = { position: { required: true }, index: true };
    MESH_PARAMETERS[WebGLRenderingContext.LINE_STRIP] = { position: { required: true }, index: true };
    MESH_PARAMETERS[WebGLRenderingContext.LINES] = { position: { required: true }, index: true };
    MESH_PARAMETERS[WebGLRenderingContext.POINTS] = { position: { required: true }, index: true };

    var TYPE_FILTER = {};
    for (var param in MESH_PARAMETERS) {
        TYPE_FILTER[param] = Object.keys(MESH_PARAMETERS[param]);
    }

    var getGLTypeFromArray = function(array) {
        var GL = window.WebGLRenderingContext;
        if (array instanceof Int8Array)
            return GL.BYTE;
        if (array instanceof Uint8Array)
            return GL.UNSIGNED_BYTE;
        if (array instanceof Int16Array)
            return GL.SHORT;
        if (array instanceof Uint16Array)
            return GL.UNSIGNED_SHORT;
        if (array instanceof Int32Array)
            return GL.INT;
        if (array instanceof Uint32Array)
            return GL.UNSIGNED_INT;
        if (array instanceof Float32Array)
            return GL.FLOAT;
        return GL.FLOAT;
    };
    /**
     * @param {WebGLRenderingContext} gl
     * @param {number} type
     * @param {Object} data
     */
    var createBuffer = function(gl, type, data) {
        var buffer = gl.createBuffer();
        gl.bindBuffer(type, buffer);
        gl.bufferData(type, data, gl.STATIC_DRAW);
        buffer.length = data.length;
        buffer.glType = getGLTypeFromArray(data);
        return buffer;
    };

    /**
     *
     * @param {webgl.GLContext} context
     * @param {string} type
     * @param {Xflow.DataNode} data
     * @extends {DrawableClosure}
     * @constructor
     */
    var MeshClosure = function (context, type, data, opt) {
        webgl.DrawableClosure.call(this, context, webgl.DrawableClosure.TYPES.MESH);
        opt = opt || {};
        this.mesh = new webgl.GLMesh(context, type);
        this.data = data;

        /**
         * Attributes required to create the GLMesh
         * @type {Xflow.ComputeRequest}
         */
        this.typeRequest = null;

        /**
         * Are all attributes required by drawable available?
         * @type {boolean}
         */
        this.typeDataValid = false;

        /**
         * Attributes required for the attached shader
         * @type {Xflow.ComputeRequest}
         */
        this.attributeRequest = null;

        /**
         * Are all attributes required by shader available?
         * @type {boolean}
         */
        this.attributeDataValid = true;

        /**
         * Bitfield that records the changes reported by Xflow
         * @private
         * @type {number}
         */
        this.changeState = CHANGE_STATE.TYPE_STRUCTURE_CHANGED;

        /**
         * Do we have to calculate the bounding box of this mesh?
         * @type {boolean}
         */
        this.boundingBoxRequired = true;

        /**
         * Callback if bounding box has changed. Gets only called if
         * this.boundingBoxRequired is true.
         * @type {*|function(Float32Array)}
         */
        this.boundingBoxChanged = opt.boundingBoxChanged || function() {};

        this.initialize();
    };

    XML3D.createClass(MeshClosure, webgl.DrawableClosure, {
        initialize: function () {
            var typeFilter = TYPE_FILTER[this.getMeshType()];
            if (!typeFilter) {
                XML3D.debug.logError("Unsupported Mesh request: ", this.mesh);
                this.typeDataValid = false;
                return;
            }
            this.typeRequest = new Xflow.ComputeRequest(this.data, typeFilter, this.typeDataChanged.bind(this));
            this.typeDataChanged(this.typeRequest, Xflow.RESULT_STATE.CHANGED_STRUCTURE);
        },
        setBoundingBoxRequired: function(required) {
            this.boundingBoxRequired = required;
            this.calculateBoundingBox();
        },
        calculateBoundingBox: (function() {
            var c_empty = XML3D.math.bbox.create();

            return function() {
                if(!this.boundingBoxRequired)
                    return;

                // compute bounding box from positions and indices, if present
                var dataResult = this.typeRequest.getResult();
                var positionEntry = dataResult.getOutputData("position");
                if(!positionEntry)   {
                    this.boundingBoxChanged(c_empty);
                    return;
                }
                var indexEntry = dataResult.getOutputData("index");
                this.boundingBoxChanged(XML3D.webgl.calculateBoundingBox(positionEntry.getValue(), indexEntry ? indexEntry.getValue() : null));
            }
        }()),
        /**
         *
         * @param {Xflow.ComputeRequest} request
         * @param {Xflow.RESULT_STATE} state
         */
        typeDataChanged: function (request, state) {
            this.changeState |= state == Xflow.RESULT_STATE.CHANGED_STRUCTURE ? CHANGE_STATE.TYPE_STRUCTURE_CHANGED : CHANGE_STATE.TYPE_DATA_CHANGED;
            this.context.requestRedraw("Mesh Type Data Change");
            XML3D.debug.logInfo("MeshClosure: Type data changed", request, state, this.changeState);
        },
        getMesh: function () {
            return this.mesh;
        },
        getMeshType: function () {
            return this.mesh.glType;
        },
        update: function () {

            if(this.changeState === CHANGE_STATE.NOTHING_CHANGED) {
                return;
            }
            XML3D.debug.logDebug("Update mesh closure", this.changeState);

            var oldValid = this.attributeDataValid && this.typeDataValid;

            if (this.changeState & CHANGE_STATE.TYPE_CHANGED) {
                this.updateTypeData();
            }
            if (this.changeState & CHANGE_STATE.ATTRIBUTE_CHANGED) {
                this.updateAttributeData();
            }

            var newValid = this.attributeDataValid && this.typeDataValid;

            if(oldValid != newValid) {
                this.dispatchEvent({
                    type: webgl.Scene.EVENT_TYPE.DRAWABLE_STATE_CHANGED,
                    newState: newValid ? READY_STATE.COMPLETE : READY_STATE.INCOMPLETE,
                    oldState: oldValid ? READY_STATE.COMPLETE : READY_STATE.INCOMPLETE
                });
            }

            this.changeState = CHANGE_STATE.NOTHING_CHANGED;
        },
        /**
         * @param {Object<string,*>} attributes
         * @param {Xflow.ComputeResult} dataResult
         * @param {function(string)} missingCB
         * @returns boolean true, if all required attributes were set
         */
        updateMeshFromResult: function (attributes, dataResult, missingCB) {
            var complete = true;
            for (var name in attributes) {
                var param = attributes[name] || {};
                var entry = dataResult.getOutputData(name);
                if (!entry || !entry.getValue()) {
                    if (param.required) {
                        // If required and loading has finished, give a call
                        dataResult.loading || missingCB(name);
                        complete = false;
                    }
                    continue;
                }
                if (name == "vertexCount") {
                    continue;
                }
                switch (entry.type) {
                    case Xflow.DATA_TYPE.TEXTURE:
                        XML3D.debug.logError("Texture as mesh parameter is not yet supported");
                        break;
                    default:
                        this.handleBuffer(name, param, entry, this.mesh);
                }
            }
            return complete;
        },
        updateAttributeData: function() {
            if (!this.attributeDataValid && !(this.changeState & CHANGE_STATE.ATTRIBUTE_STRUCTURE_CHANGED)) {
                return; // if only the data has changed, it can't get valid after update
            }
            var dataResult = this.attributeRequest.getResult();
            var attributes = this.attributes;
            var complete = this.updateMeshFromResult(attributes, dataResult, function(name) {
                XML3D.debug.logError("Required shader attribute", name, "is missing for mesh");
            });

            this.attributeDataValid = complete;
        },

        updateTypeData: function () {
            if (!this.typeDataValid && !(this.changeState & CHANGE_STATE.TYPE_STRUCTURE_CHANGED)) {
                return; // only if structure has changed, it can't get valid after update
            }
            var dataResult = this.typeRequest.getResult();
            var meshParams = MESH_PARAMETERS[this.getMeshType()];
            XML3D.debug.assert(meshParams, "At this point, we need parameters for the type");

            var vertexCount = 0;
            var complete = this.updateMeshFromResult(meshParams, dataResult, function(name) {
                XML3D.debug.logError("Required mesh attribute ", name, "is missing for mesh");
            });

            this.calculateBoundingBox();
            var entry = dataResult.getOutputData("vertexCount");
            this.mesh.setVertexCount(entry && entry.getValue() ? entry.getValue()[0] : null);
            this.typeDataValid = complete;
        },
        /**
         * @param {string} name
         * @param {Object} attr
         * @param {Xflow.BufferEntry} entry
         * @param {GLMesh} mesh
         */
        handleBuffer: function (name, attr, entry, mesh) {
            var webglData = XML3D.webgl.getXflowEntryWebGlData(entry, this.context.id);
            var buffer = webglData.buffer;
            var gl = this.context.gl;

            switch (webglData.changed) {
                case Xflow.DATA_ENTRY_STATE.CHANGED_VALUE:
                    var bufferType = name == "index" ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER;

                    gl.bindBuffer(bufferType, buffer);
                    gl.bufferSubData(bufferType, 0, entry.getValue());
                    break;
                case Xflow.DATA_ENTRY_STATE.CHANGED_NEW:
                case Xflow.DATA_ENTRY_STATE.CHANGED_SIZE:
                    if (name == "index") {
                        buffer = createBuffer(gl, gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(entry.getValue()));
                    } else {
                        buffer = createBuffer(gl, gl.ARRAY_BUFFER, entry.getValue());
                    }
                    buffer.tupleSize = entry.getTupleSize();
                    webglData.buffer = buffer;
                    break;
            }
            // In every case, set the buffer, because other meshes might have already
            // performed one or more of the tasks above
            mesh.setBuffer(name, buffer);

            webglData.changed = 0;
        },
        /**
         *
         * @param {Object.<string, *>} attributes
         */
        setAttributeRequest: function(attributes) {
            this.attributes = attributes;
            this.attributeRequest = new Xflow.ComputeRequest(this.data, Object.keys(attributes), this.attributeDataChanged.bind(this));
            this.attributeDataChanged(this.attributeRequest, Xflow.RESULT_STATE.CHANGED_STRUCTURE);
        },
        /**
         * @param {Xflow.ComputeRequest} request
         * @param {Xflow.RESULT_STATE} state
         */
        attributeDataChanged: function (request, state) {
            this.changeState |= state == Xflow.RESULT_STATE.CHANGED_STRUCTURE ? CHANGE_STATE.ATTRIBUTE_STRUCTURE_CHANGED : CHANGE_STATE.ATTRIBUTE_DATA_CHANGED;
            this.context.requestRedraw("Mesh Attribute Data Changed");
            XML3D.debug.logInfo("MeshClosure: Attribute data changed", request, state, this.changeState);
        },

        /**
         * Returns a compute request for custom mesh parameters
         * @param {Array.<string>} filter
         * @param {function(Xflow.ComputeRequest, Xflow.RESULT_STATE)} callback
         */
        getRequest: function(filter, callback) {
            return new Xflow.ComputeRequest(this.data, filter, callback);
        }
    });

    webgl.MeshClosure = MeshClosure;

}(XML3D.webgl));
<commit_msg>Can set mesh attributes from outside now<commit_after>(function (webgl) {

    var CHANGE_STATE = {
        NOTHING_CHANGED : 0,
        TYPE_STRUCTURE_CHANGED : 1,
        TYPE_DATA_CHANGED : 2,
        TYPE_CHANGED: 3,
        ATTRIBUTE_STRUCTURE_CHANGED : 8,
        ATTRIBUTE_DATA_CHANGED : 16,
        ATTRIBUTE_CHANGED: 24
    };

    var READY_STATE = webgl.DrawableClosure.READY_STATE;

    var MESH_PARAMETERS = {};
    MESH_PARAMETERS[WebGLRenderingContext.TRIANGLES] = { position: { required: true }, index: true };
    MESH_PARAMETERS[WebGLRenderingContext.LINE_STRIP] = { position: { required: true }, index: true };
    MESH_PARAMETERS[WebGLRenderingContext.LINES] = { position: { required: true }, index: true };
    MESH_PARAMETERS[WebGLRenderingContext.POINTS] = { position: { required: true }, index: true };

    var getGLTypeFromArray = function(array) {
        var GL = window.WebGLRenderingContext;
        if (array instanceof Int8Array)
            return GL.BYTE;
        if (array instanceof Uint8Array)
            return GL.UNSIGNED_BYTE;
        if (array instanceof Int16Array)
            return GL.SHORT;
        if (array instanceof Uint16Array)
            return GL.UNSIGNED_SHORT;
        if (array instanceof Int32Array)
            return GL.INT;
        if (array instanceof Uint32Array)
            return GL.UNSIGNED_INT;
        if (array instanceof Float32Array)
            return GL.FLOAT;
        return GL.FLOAT;
    };
    /**
     * @param {WebGLRenderingContext} gl
     * @param {number} type
     * @param {Object} data
     */
    var createBuffer = function(gl, type, data) {
        var buffer = gl.createBuffer();
        gl.bindBuffer(type, buffer);
        gl.bufferData(type, data, gl.STATIC_DRAW);
        buffer.length = data.length;
        buffer.glType = getGLTypeFromArray(data);
        return buffer;
    };

    /**
     *
     * @param {webgl.GLContext} context
     * @param {string} type
     * @param {Xflow.DataNode} data
     * @extends {DrawableClosure}
     * @constructor
     */
    var MeshClosure = function (context, type, data, opt) {
        webgl.DrawableClosure.call(this, context, webgl.DrawableClosure.TYPES.MESH);
        opt = opt || {};
        this.mesh = new webgl.GLMesh(context, type);
        this.data = data;

        /**
         * Attributes required to create the GLMesh
         * @type {Xflow.ComputeRequest}
         */
        this.typeRequest = null;

        /**
         * Are all attributes required by drawable available?
         * @type {boolean}
         */
        this.typeDataValid = false;

        /**
         * Attributes required for the attached shader
         * @type {Xflow.ComputeRequest}
         */
        this.attributeRequest = null;

        /**
         * Are all attributes required by shader available?
         * @type {boolean}
         */
        this.attributeDataValid = true;

        /**
         * Bitfield that records the changes reported by Xflow
         * @private
         * @type {number}
         */
        this.changeState = CHANGE_STATE.TYPE_STRUCTURE_CHANGED;

        /**
         * Do we have to calculate the bounding box of this mesh?
         * @type {boolean}
         */
        this.boundingBoxRequired = true;

        /**
         * Callback if bounding box has changed. Gets only called if
         * this.boundingBoxRequired is true.
         * @type {*|function(Float32Array)}
         */
        this.boundingBoxChanged = opt.boundingBoxChanged || function() {};

        this.initialize();
    };

    XML3D.createClass(MeshClosure, webgl.DrawableClosure, {
        initialize: function () {
            var meshConfig = MESH_PARAMETERS[this.getMeshType()];
            if (!meshConfig) {
                XML3D.debug.logError("Unsupported Mesh request: ", this.mesh, this.getMeshType());
                this.typeDataValid = false;
                return;
            }
            this.setTypeRequest(meshConfig);
        },
        setBoundingBoxRequired: function(required) {
            this.boundingBoxRequired = required;
            this.calculateBoundingBox();
        },
        calculateBoundingBox: (function() {
            var c_empty = XML3D.math.bbox.create();

            return function() {
                if(!this.boundingBoxRequired)
                    return;

                // compute bounding box from positions and indices, if present
                var dataResult = this.typeRequest.getResult();
                var positionEntry = dataResult.getOutputData("position");
                if(!positionEntry)   {
                    this.boundingBoxChanged(c_empty);
                    return;
                }
                var indexEntry = dataResult.getOutputData("index");
                this.boundingBoxChanged(XML3D.webgl.calculateBoundingBox(positionEntry.getValue(), indexEntry ? indexEntry.getValue() : null));
            }
        }()),
        /**
         *
         * @param {Xflow.ComputeRequest} request
         * @param {Xflow.RESULT_STATE} state
         */
        typeDataChanged: function (request, state) {
            this.changeState |= state == Xflow.RESULT_STATE.CHANGED_STRUCTURE ? CHANGE_STATE.TYPE_STRUCTURE_CHANGED : CHANGE_STATE.TYPE_DATA_CHANGED;
            this.context.requestRedraw("Mesh Type Data Change");
            XML3D.debug.logInfo("MeshClosure: Type data changed", request, state, this.changeState);
        },
        getMesh: function () {
            return this.mesh;
        },
        getMeshType: function () {
            return this.mesh.glType;
        },
        update: function () {

            if(this.changeState === CHANGE_STATE.NOTHING_CHANGED) {
                return;
            }
            XML3D.debug.logDebug("Update mesh closure", this.changeState);

            var oldValid = this.attributeDataValid && this.typeDataValid;

            if (this.changeState & CHANGE_STATE.TYPE_CHANGED) {
                this.updateTypeData();
            }
            if (this.changeState & CHANGE_STATE.ATTRIBUTE_CHANGED) {
                this.updateAttributeData();
            }

            var newValid = this.attributeDataValid && this.typeDataValid;

            if(oldValid != newValid) {
                this.dispatchEvent({
                    type: webgl.Scene.EVENT_TYPE.DRAWABLE_STATE_CHANGED,
                    newState: newValid ? READY_STATE.COMPLETE : READY_STATE.INCOMPLETE,
                    oldState: oldValid ? READY_STATE.COMPLETE : READY_STATE.INCOMPLETE
                });
            }

            this.changeState = CHANGE_STATE.NOTHING_CHANGED;
        },
        /**
         * @param {Object<string,*>} attributes
         * @param {Xflow.ComputeResult} dataResult
         * @param {function(string)} missingCB
         * @returns boolean true, if all required attributes were set
         */
        updateMeshFromResult: function (attributes, dataResult, missingCB) {
            var complete = true;
            for (var name in attributes) {
                var param = attributes[name] || {};
                var entry = dataResult.getOutputData(name);
                if (!entry || !entry.getValue()) {
                    if (param.required) {
                        // If required and loading has finished, give a call
                        dataResult.loading || missingCB(name);
                        complete = false;
                    }
                    continue;
                }
                if (name == "vertexCount") {
                    continue;
                }
                switch (entry.type) {
                    case Xflow.DATA_TYPE.TEXTURE:
                        XML3D.debug.logError("Texture as mesh parameter is not yet supported");
                        break;
                    default:
                        this.handleBuffer(name, param, entry, this.mesh);
                }
            }
            return complete;
        },
        updateAttributeData: function() {
            if (!this.attributeDataValid && !(this.changeState & CHANGE_STATE.ATTRIBUTE_STRUCTURE_CHANGED)) {
                return; // if only the data has changed, it can't get valid after update
            }
            var dataResult = this.attributeRequest.getResult();
            var attributes = this.attributes;
            var complete = this.updateMeshFromResult(attributes, dataResult, function(name) {
                XML3D.debug.logError("Required shader attribute", name, "is missing for mesh");
            });

            this.attributeDataValid = complete;
        },

        updateTypeData: function () {
            if (!this.typeDataValid && !(this.changeState & CHANGE_STATE.TYPE_STRUCTURE_CHANGED)) {
                return; // only if structure has changed, it can't get valid after update
            }
            var dataResult = this.typeRequest.getResult();
            var meshAttributes = this.meshAttributes;

            var vertexCount = 0;
            var complete = this.updateMeshFromResult(meshAttributes, dataResult, function(name) {
                XML3D.debug.logError("Required mesh attribute ", name, "is missing for mesh");
            });

            this.calculateBoundingBox();
            var entry = dataResult.getOutputData("vertexCount");
            this.mesh.setVertexCount(entry && entry.getValue() ? entry.getValue()[0] : null);
            this.typeDataValid = complete;
        },
        /**
         * @param {string} name
         * @param {Object} attr
         * @param {Xflow.BufferEntry} entry
         * @param {GLMesh} mesh
         */
        handleBuffer: function (name, attr, entry, mesh) {
            var webglData = XML3D.webgl.getXflowEntryWebGlData(entry, this.context.id);
            var buffer = webglData.buffer;
            var gl = this.context.gl;

            switch (webglData.changed) {
                case Xflow.DATA_ENTRY_STATE.CHANGED_VALUE:
                    var bufferType = name == "index" ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER;

                    gl.bindBuffer(bufferType, buffer);
                    gl.bufferSubData(bufferType, 0, entry.getValue());
                    break;
                case Xflow.DATA_ENTRY_STATE.CHANGED_NEW:
                case Xflow.DATA_ENTRY_STATE.CHANGED_SIZE:
                    if (name == "index") {
                        buffer = createBuffer(gl, gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(entry.getValue()));
                    } else {
                        buffer = createBuffer(gl, gl.ARRAY_BUFFER, entry.getValue());
                    }
                    buffer.tupleSize = entry.getTupleSize();
                    webglData.buffer = buffer;
                    break;
            }
            // In every case, set the buffer, because other meshes might have already
            // performed one or more of the tasks above
            mesh.setBuffer(name, buffer);

            webglData.changed = 0;
        },
        /**
         *
         * @param {Object.<string, *>} attributes
         */
        setAttributeRequest: function(attributes) {
            this.attributes = attributes;
            this.attributeRequest = new Xflow.ComputeRequest(this.data, Object.keys(attributes), this.attributeDataChanged.bind(this));
            this.attributeDataChanged(this.attributeRequest, Xflow.RESULT_STATE.CHANGED_STRUCTURE);
        },

        /**
         *
         * @param {Object.<string, *>} attributes
         */
        setTypeRequest: function(attributes) {
            this.meshAttributes = attributes;
            this.typeRequest = new Xflow.ComputeRequest(this.data, Object.keys(attributes), this.typeDataChanged.bind(this));
            this.typeDataChanged(this.typeRequest, Xflow.RESULT_STATE.CHANGED_STRUCTURE);
        },

        /**
         * @param {Xflow.ComputeRequest} request
         * @param {Xflow.RESULT_STATE} state
         */
        attributeDataChanged: function (request, state) {
            this.changeState |= state == Xflow.RESULT_STATE.CHANGED_STRUCTURE ? CHANGE_STATE.ATTRIBUTE_STRUCTURE_CHANGED : CHANGE_STATE.ATTRIBUTE_DATA_CHANGED;
            this.context.requestRedraw("Mesh Attribute Data Changed");
            XML3D.debug.logInfo("MeshClosure: Attribute data changed", request, state, this.changeState);
        },

        /**
         * Returns a compute request for custom mesh parameters
         * @param {Array.<string>} filter
         * @param {function(Xflow.ComputeRequest, Xflow.RESULT_STATE)} callback
         */
        getRequest: function(filter, callback) {
            return new Xflow.ComputeRequest(this.data, filter, callback);
        }
    });

    webgl.MeshClosure = MeshClosure;

}(XML3D.webgl));
<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_s<commit_msg>Should work now<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sl<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-upda<commit_msg>Well that seemed pretty easy<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updat<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",<commit_msg>Re-commiting last<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the read<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, functio<commit_msg>Sprint complete<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",<commit_msg>Sprint complete<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding <|endoftext|>


<commit_before>import userController from '../../controllers/userController';
import * as config from './config';

export default [
  {
    method: 'POST',
    path: '/user',
    handler: userController.createUser,
    config: config.user,
  },
  {
    method: 'PUT',
    path: '/user',
    handler: userController.updateUser,
    // config: config.updatedUser,
  },
  {
    method: 'GET',
    path: '/users',
    handler: userController.getUsers,
  },
  {
    method: 'GET',
    path: '/user/{userID}',
    handler: userController.getUser,
    // config: config.id,
  },
];
<commit_msg>remove validation (for now)<commit_after>import userController from '../../controllers/userController';
import * as config from './config';

export default [
  {
    method: 'POST',
    path: '/user',
    handler: userController.createUser,
    // config: config.user,
  },
  {
    method: 'PUT',
    path: '/user',
    handler: userController.updateUser,
    // config: config.updatedUser,
  },
  {
    method: 'GET',
    path: '/users',
    handler: userController.getUsers,
  },
  {
    method: 'GET',
    path: '/user/{userID}',
    handler: userController.getUser,
    // config: config.id,
  },
];
<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",<commit_msg>Someone poisoned the waterhole!<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
<|endoftext|>


<commit_before>/**
 * Game Controller
 */
function GameController()
{
    var controller = this;

    this.games = new Collection([], 'name');

    this.onDie         = this.onDie.bind(this);
    this.onAngle       = this.onAngle.bind(this);
    this.onPosition    = this.onPosition.bind(this);
    this.onBonusPop    = this.onBonusPop.bind(this);
    this.onBonusClear  = this.onBonusClear.bind(this);
    this.onPrinting    = this.onPrinting.bind(this);
    this.onPoint       = this.onPoint.bind(this);
    this.onScore       = this.onScore.bind(this);
    this.onTrailClear  = this.onTrailClear.bind(this);
    this.onRoundNew    = this.onRoundNew.bind(this);
    this.onRoundEnd    = this.onRoundEnd.bind(this);
    this.onRoundWinner = this.onRoundWinner.bind(this);
    this.onEnd         = this.onEnd.bind(this);

    this.callbacks = {
        onGameLoaded: function () { controller.onGameLoaded(this); },
        onMove: function (data) { controller.onMove(this, data); },
    };
}

/**
 * Add game
 *
 * @param {Game} game
 */
GameController.prototype.addGame = function(game)
{
    if (this.games.add(game)) {
        game.on('end', this.onEnd);
        game.on('round:new', this.onRoundNew);
        game.on('round:end', this.onRoundEnd);
        game.on('round:winner', this.onRoundWinner);

        game.on('bonus:pop', this.onBonusPop);
        game.on('bonus:clear', this.onBonusClear);

        for (var i = game.clients.items.length - 1; i >= 0; i--) {
            this.attach(game.clients.items[i], game);
        }
    }
};

/**
 * Remove game
 *
 * @param {Game} game
 */
GameController.prototype.removeGame = function(game)
{
    if (this.games.remove(game)) {
        game.removeListener('end', this.onEnd);
        game.removeListener('round:new', this.onRoundNew);
        game.removeListener('round:end', this.onRoundEnd);
        game.removeListener('round:winner', this.onRoundWinner);
        game.removeListener('bonus:pop', this.onBonusPop);
        game.removeListener('bonus:clear', this.onBonusClear);

        for (var i = game.clients.items.length - 1; i >= 0; i--) {
            this.detach(game.clients.items[i], game);
        }
    }
};

/**
 * Attach events
 *
 * @param {SocketClient} client
 */
GameController.prototype.attach = function(client, game)
{
    this.attachEvents(client);
};

/**
 * Attach events
 *
 * @param {SocketClient} client
 */
GameController.prototype.detach = function(client)
{
    this.detachEvents(client);

    var avatar;

    if (client.room.game) {
        for (var i = client.players.items.length - 1; i >= 0; i--) {
            avatar = client.players.items[i].avatar;
            client.room.game.client.addEvent('game:leave', {avatar: avatar.name});
            client.room.game.removeAvatar(avatar);
        }
    }
};

/**
 * Detach events
 *
 * @param {SocketClient} client
 */
GameController.prototype.attachEvents = function(client)
{
    var controller = this,
        avatar;

    client.on('loaded', this.callbacks.onGameLoaded);
    client.on('player:move', this.callbacks.onMove);

    for (var i = client.players.items.length - 1; i >= 0; i--) {
        avatar = client.players.items[i].avatar;

        avatar.on('die', this.onDie);
        avatar.on('angle', this.onAngle);
        avatar.on('position', this.onPosition);
        avatar.on('printing', this.onPrinting);
        avatar.on('point', this.onPoint);
        avatar.on('score', this.onScore);
        avatar.trail.on('clear', this.onTrailClear);
    }
};

/**
 * Detach events
 *
 * @param {SocketClient} client
 */
GameController.prototype.detachEvents = function(client)
{
    var avatar;

    client.removeListener('loaded', this.callbacks.onGameLoaded);
    client.removeListener('player:move', this.callbacks.onMove);

    for (var i = client.players.items.length - 1; i >= 0; i--) {
        avatar = client.players.items[i].avatar;

        avatar.removeListener('die', this.onDie);
        avatar.removeListener('angle', this.onAngle);
        avatar.removeListener('position', this.onPosition);
        avatar.removeListener('printing', this.onPrinting);
        avatar.removeListener('point', this.onPoint);
        avatar.removeListener('score', this.onScore);
        avatar.trail.removeListener('clear', this.onTrailClear);
    }
};

/**
 * On game loaded
 *
 * @param {SocketClient} client
 */
GameController.prototype.onGameLoaded = function(client)
{
    var game = client.room.game,
        avatar;

    for (var i = client.players.items.length - 1; i >= 0; i--) {
        avatar = client.players.items[i].avatar;
        avatar.ready = true;
    }

    if (game.isReady()) {
        game.newRound();
    }
};

/**
 * On move
 *
 * @param {SocketClient} client
 * @param {Number} move
 */
GameController.prototype.onMove = function(client, data)
{
    var player = client.players.getById(data.avatar);

    if (player && player.avatar) {
        player.avatar.setAngularVelocity(data.move);
    }
};

/**
 * On position
 *
 * @param {Object} data
 */
GameController.prototype.onPosition = function(data)
{
    var avatar = data.avatar,
        game = avatar.player.client.room.game,
        point = data.point;

    game.client.addEvent('position', {avatar: avatar.name, point: point});
};

/**
 * On printing
 *
 * @param {Object} data
 */
GameController.prototype.onPrinting = function(data)
{
    var avatar = data.avatar,
        game = avatar.player.client.room.game,
        printing = data.printing;

    game.client.addEvent('printing', {avatar: avatar.name, printing: printing});
};

/**
 * On angle
 *
 * @param {Object} data
 */
GameController.prototype.onAngle = function(data)
{
    var avatar = data.avatar,
        game = avatar.player.client.room.game,
        angle = data.angle;

    if(!avatar.player.client.room.game.isPlaying()) {
        game.client.addEvent('angle', {avatar: avatar.name, angle: angle});
    }
};

/**
 * On point
 *
 * @param {Object} data
 */
GameController.prototype.onPoint = function(data)
{
    var avatar = data.avatar,
        game = avatar.player.client.room.game,
        point = data.point;

    if (data.important) {
        game.client.addEvent('point', {avatar: avatar.name, point: point});
    }
};

/**
 * On die
 *
 * @param {Object} data
 */
GameController.prototype.onDie = function(data)
{
    var avatar = data.avatar,
        game = avatar.player.client.room.game;

    game.client.addEvent('die', {avatar: avatar.name});
};

/**
 * On bonus pop
 *
 * @param {SocketClient} game
 */
GameController.prototype.onBonusPop = function(data)
{
    var game = data.game,
        channel = data.game.channel;

    this.io.sockets.in(channel).emit('bonus:pop', data.bonus);
};

/**
 * On bonus clear
 *
 * @param {SocketClient}client
 * @param data
 */
GameController.prototype.onBonusClear = function(data)
{
    var game = data.game,
        channel = data.game.channel;

    this.io.sockets.in(channel).emit('bonus:clear', data.bonus);
};

/**
 * On score
 *
 * @param {Object} data
 */
GameController.prototype.onScore = function(data)
{
    var avatar = data.avatar,
        game = avatar.player.client.room.game,
        score = data.score;

    game.client.addEvent('score', {avatar: avatar.name, score: score});
};

/**
 * On point
 *
 * @param {Object} data
 */
GameController.prototype.onTrailClear = function(data)
{
    var avatar = data.avatar,
        game = avatar.player.client.room.game;

    game.client.addEvent('trail:clear', {avatar: avatar.name});
};

// Game events:

/**
 * On round new
 *
 * @param {Object} data
 */
GameController.prototype.onRoundNew = function(data)
{
    data.game.client.addEvent('round:new');
};

/**
 * On round new
 *
 * @param {Object} data
 */
GameController.prototype.onRoundEnd = function(data)
{
    data.game.client.addEvent('round:end');
};

/**
 * On round winner
 *
 * @param {Object} data
 */
GameController.prototype.onRoundWinner = function(data)
{
    data.game.client.addEvent('round:winner', {winner: data.winner.name});
};

/**
 * On end
 *
 * @param {Object} data
 */
GameController.prototype.onEnd = function(data)
{
    data.game.client.addEvent('end');
};
<commit_msg>remove bubbling of velocity events<commit_after>/**
 * Game Controller
 */
function GameController()
{
    var controller = this;

    this.games = new Collection([], 'name');

    this.onDie         = this.onDie.bind(this);
    this.onAngle       = this.onAngle.bind(this);
    this.onPosition    = this.onPosition.bind(this);
    this.onBonusPop    = this.onBonusPop.bind(this);
    this.onBonusClear  = this.onBonusClear.bind(this);
    this.onPrinting    = this.onPrinting.bind(this);
    this.onPoint       = this.onPoint.bind(this);
    this.onScore       = this.onScore.bind(this);
    this.onTrailClear  = this.onTrailClear.bind(this);
    this.onRoundNew    = this.onRoundNew.bind(this);
    this.onRoundEnd    = this.onRoundEnd.bind(this);
    this.onRoundWinner = this.onRoundWinner.bind(this);
    this.onEnd         = this.onEnd.bind(this);

    this.callbacks = {
        onGameLoaded: function () { controller.onGameLoaded(this); },
        onMove: function (data) { controller.onMove(this, data); },
    };
}

/**
 * Add game
 *
 * @param {Game} game
 */
GameController.prototype.addGame = function(game)
{
    if (this.games.add(game)) {
        game.on('end', this.onEnd);
        game.on('round:new', this.onRoundNew);
        game.on('round:end', this.onRoundEnd);
        game.on('round:winner', this.onRoundWinner);

        game.on('bonus:pop', this.onBonusPop);
        game.on('bonus:clear', this.onBonusClear);

        for (var i = game.clients.items.length - 1; i >= 0; i--) {
            this.attach(game.clients.items[i], game);
        }
    }
};

/**
 * Remove game
 *
 * @param {Game} game
 */
GameController.prototype.removeGame = function(game)
{
    if (this.games.remove(game)) {
        game.removeListener('end', this.onEnd);
        game.removeListener('round:new', this.onRoundNew);
        game.removeListener('round:end', this.onRoundEnd);
        game.removeListener('round:winner', this.onRoundWinner);
        game.removeListener('bonus:pop', this.onBonusPop);
        game.removeListener('bonus:clear', this.onBonusClear);

        for (var i = game.clients.items.length - 1; i >= 0; i--) {
            this.detach(game.clients.items[i], game);
        }
    }
};

/**
 * Attach events
 *
 * @param {SocketClient} client
 */
GameController.prototype.attach = function(client, game)
{
    this.attachEvents(client);
};

/**
 * Attach events
 *
 * @param {SocketClient} client
 */
GameController.prototype.detach = function(client)
{
    this.detachEvents(client);

    var avatar;

    if (client.room.game) {
        for (var i = client.players.items.length - 1; i >= 0; i--) {
            avatar = client.players.items[i].avatar;
            client.room.game.client.addEvent('game:leave', {avatar: avatar.name});
            client.room.game.removeAvatar(avatar);
        }
    }
};

/**
 * Detach events
 *
 * @param {SocketClient} client
 */
GameController.prototype.attachEvents = function(client)
{
    var controller = this,
        avatar;

    client.on('loaded', this.callbacks.onGameLoaded);
    client.on('player:move', this.callbacks.onMove);

    for (var i = client.players.items.length - 1; i >= 0; i--) {
        avatar = client.players.items[i].avatar;

        avatar.on('die', this.onDie);
        avatar.on('angle', this.onAngle);
        avatar.on('position', this.onPosition);
        avatar.on('printing', this.onPrinting);
        avatar.on('point', this.onPoint);
        avatar.on('score', this.onScore);
        avatar.trail.on('clear', this.onTrailClear);
    }
};

/**
 * Detach events
 *
 * @param {SocketClient} client
 */
GameController.prototype.detachEvents = function(client)
{
    var avatar;

    client.removeListener('loaded', this.callbacks.onGameLoaded);
    client.removeListener('player:move', this.callbacks.onMove);

    for (var i = client.players.items.length - 1; i >= 0; i--) {
        avatar = client.players.items[i].avatar;

        avatar.removeListener('die', this.onDie);
        avatar.removeListener('angle', this.onAngle);
        avatar.removeListener('position', this.onPosition);
        avatar.removeListener('printing', this.onPrinting);
        avatar.removeListener('point', this.onPoint);
        avatar.removeListener('score', this.onScore);
        avatar.trail.removeListener('clear', this.onTrailClear);
    }
};

/**
 * On game loaded
 *
 * @param {SocketClient} client
 */
GameController.prototype.onGameLoaded = function(client)
{
    var game = client.room.game,
        avatar;

    for (var i = client.players.items.length - 1; i >= 0; i--) {
        avatar = client.players.items[i].avatar;
        avatar.ready = true;
    }

    if (game.isReady()) {
        game.newRound();
    }
};

/**
 * On move
 *
 * @param {SocketClient} client
 * @param {Number} move
 */
GameController.prototype.onMove = function(client, data)
{
    var player = client.players.getById(data.avatar);

    if (player && player.avatar) {
        player.avatar.setAngularVelocity(data.move);
    }
};

/**
 * On position
 *
 * @param {Object} data
 */
GameController.prototype.onPosition = function(data)
{
    var avatar = data.avatar,
        game = avatar.player.client.room.game,
        point = data.point;

    game.client.addEvent('position', {avatar: avatar.name, point: point});
};

/**
 * On printing
 *
 * @param {Object} data
 */
GameController.prototype.onPrinting = function(data)
{
    var avatar = data.avatar,
        game = avatar.player.client.room.game,
        printing = data.printing;

    game.client.addEvent('printing', {avatar: avatar.name, printing: printing});
};

/**
 * On angle
 *
 * @param {Object} data
 */
GameController.prototype.onAngle = function(data)
{
    var avatar = data.avatar,
        game = avatar.player.client.room.game,
        angle = data.angle;

    if(!avatar.player.client.room.game.isPlaying()) {
        game.client.addEvent('angle', {avatar: avatar.name, angle: angle});
    }
};

/**
 * On point
 *
 * @param {Object} data
 */
GameController.prototype.onPoint = function(data)
{
    var avatar = data.avatar,
        game = avatar.player.client.room.game,
        point = data.point;

    if (data.important) {
        game.client.addEvent('point', {avatar: avatar.name, point: point});
    }
};

/**
 * On die
 *
 * @param {Object} data
 */
GameController.prototype.onDie = function(data)
{
    var avatar = data.avatar,
        game = avatar.player.client.room.game;

    game.client.addEvent('die', {avatar: avatar.name});
};

/**
};

/**
 * On bonus pop
 *
 * @param {SocketClient} game
 */
GameController.prototype.onBonusPop = function(data)
{
    var game = data.game,
        channel = data.game.channel;

    this.io.sockets.in(channel).emit('bonus:pop', data.bonus.serialize());
};

/**
 * On bonus clear
 *
 * @param {SocketClient}client
 * @param data
 */
GameController.prototype.onBonusClear = function(data)
{
    var game = data.game,
        channel = data.game.channel;

    this.io.sockets.in(channel).emit('bonus:clear', data.bonus.serialize());
};

/**
 * On score
 *
 * @param {Object} data
 */
GameController.prototype.onScore = function(data)
{
    var avatar = data.avatar,
        game = avatar.player.client.room.game,
        score = data.score;

    game.client.addEvent('score', {avatar: avatar.name, score: score});
};

/**
 * On point
 *
 * @param {Object} data
 */
GameController.prototype.onTrailClear = function(data)
{
    var avatar = data.avatar,
        game = avatar.player.client.room.game;

    game.client.addEvent('trail:clear', {avatar: avatar.name});
};

// Game events:

/**
 * On round new
 *
 * @param {Object} data
 */
GameController.prototype.onRoundNew = function(data)
{
    data.game.client.addEvent('round:new');
};

/**
 * On round new
 *
 * @param {Object} data
 */
GameController.prototype.onRoundEnd = function(data)
{
    data.game.client.addEvent('round:end');
};

/**
 * On round winner
 *
 * @param {Object} data
 */
GameController.prototype.onRoundWinner = function(data)
{
    data.game.client.addEvent('round:winner', {winner: data.winner.name});
};

/**
 * On end
 *
 * @param {Object} data
 */
GameController.prototype.onEnd = function(data)
{
    data.game.client.addEvent('end');
};
<|endoftext|>


<commit_before>
var sqs = require('./lib/sqs'),
    assert = require('assert');

function queue(options) {
  'use strict';

  assert(options, 'missing options');
  assert(options.queueUrl, 'missing queueUrl');

  var seneca = this;  // jshint ignore:line
  var queueUrl = options.queueUrl;

  options = seneca.util.deepextend({
    role: 'queue',
    queueUrl: queueUrl,
    sendParams: {
      QueueUrl: queueUrl
    },
    recvParams: {
      QueueUrl: queueUrl
    }
  }, options);

  // You can change the _role_ value for the plugin patterns.
  // Use this when you want to load multiple versions of the plugin
  // and expose them via different patterns.
  var role = options.role;

  sqs(role, seneca, options);

  seneca.add({init:role},function(args,done){
    done();
  });

  return {
    name: role
  };
}

module.exports = queue;
<commit_msg>Do not pass queueUrl to deepextend.<commit_after>
var sqs = require('./lib/sqs'),
    assert = require('assert');

function queue(options) {
  'use strict';

  assert(options, 'missing options');
  assert(options.queueUrl, 'missing queueUrl');

  var seneca = this;  // jshint ignore:line
  var queueUrl = options.queueUrl;

  options = seneca.util.deepextend({
    role: 'queue',
    sendParams: {
      QueueUrl: queueUrl
    },
    recvParams: {
      QueueUrl: queueUrl
    }
  }, options);

  // You can change the _role_ value for the plugin patterns.
  // Use this when you want to load multiple versions of the plugin
  // and expose them via different patterns.
  var role = options.role;

  sqs(role, seneca, options);

  seneca.add({init:role},function(args,done){
    done();
  });

  return {
    name: role
  };
}

module.exports = queue;
<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    for (var counter = 0; counter < length; counter++)
    {
      var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
      var args = ['commit', outFile, '-m', message]
      fs.writeSync(outFD, data.slice(counter, counter+1), 0, 1)
      sleep(Math.random() * max_sleep)
      child_process.execFileSync('/usr/bin/git', args)
    }
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [time in seconds]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

process.on('exit', function () {
  var args = ['push']
  child_process.execFileSync('/usr/bin/git', args)
})

function randomIntFromI<commit_msg>You feeling lucky punk?<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    for (var counter = 0; counter < length; counter++)
    {
      var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
      var args = ['commit', outFile, '-m', message]
      fs.writeSync(outFD, data.slice(counter, counter+1), 0, 1)
      sleep(Math.random() * max_sleep)
      child_process.execFileSync('/usr/bin/git', args)
    }
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [time in seconds]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (seconds * 1000);
  while (new Date().getTime() <= endTime) {;}
}

process.on('exit', function () {
  var args = ['push']
  child_process.execFileSync('/usr/bin/git', args)
})

function randomIntFromIn<|endoftext|>