<commit_before>/* eslint indent:0 */
import React, {PropTypes} from 'react/addons';
import jss from 'js-stylesheet';
import uuid from '../helpers/uuid';
import childrenPropType from '../helpers/childrenPropType';

// Determine if a node from event.target is a Tab element
function isTabNode(node) {
  return node.nodeName === 'LI' && node.getAttribute('role') === 'tab';
}

// Determine if a tab node is disabled
function isTabDisabled(node) {
  return node.getAttribute('aria-disabled') === 'true';
}

module.exports = React.createClass({
  displayName: 'Tabs',

	propTypes: {
		selectedIndex: PropTypes.number,
		onSelect: PropTypes.func,
		focus: PropTypes.bool,
    children: childrenPropType,
    forceRenderTabPanel: PropTypes.bool
	},

  childContextTypes: {
    forceRenderTabPanel: PropTypes.bool
  },

	getDefaultProps() {
		return {
			selectedIndex: -1,
			focus: false,
      forceRenderTabPanel: false
		};
	},

	getInitialState() {
    return this.copyPropsToState(this.props);
  },

  getChildContext() {
    return {
      forceRenderTabPanel: this.props.forceRenderTabPanel
    };
  },

	componentWillMount() {
    jss(require('../helpers/styles.js'));
	},

  componentWillReceiveProps(newProps) {
    this.setState(this.copyPropsToState(newProps));
  },

	handleClick(e) {
		let node = e.target;
		do {
			if (isTabNode(node)) {
        if (isTabDisabled(node)) {
          return;
        }

        const index = [].slice.call(node.parentNode.children).indexOf(node);
        this.setSelected(index);
				return;
			}
		} while ((node = node.parentNode) !== null);
	},

	handleKeyDown(e) {
		if (isTabNode(e.target)) {
			let index = this.state.selectedIndex;
			let preventDefault = false;

			// Select next tab to the left
			if (e.keyCode === 37 || e.keyCode === 38) {
				index = this.getPrevTab(index);
				preventDefault = true;
			}
			// Select next tab to the right
      /* eslint brace-style:0 */
			else if (e.keyCode === 39 || e.keyCode === 40) {
        index = this.getNextTab(index);
				preventDefault = true;
			}

			// This prevents scrollbars from moving around
			if (preventDefault) {
				e.preventDefault();
			}

			this.setSelected(index, true);
		}
	},

	setSelected(index, focus) {
		// Don't do anything if nothing has changed
    if (index === this.state.selectedIndex) return;
		// Check index boundary
    if (index < 0 || index >= this.getTabsCount()) return;

		// Keep reference to last index for event handler
    const last = this.state.selectedIndex;

		// Update selected index
    this.setState({ selectedIndex: index, focus: focus === true });

		// Call change event handler
    if (typeof this.props.onSelect === 'function') {
      this.props.onSelect(index, last);
    }
	},

  getNextTab(index) {
    const count = this.getTabsCount();

    // Look for non-disabled tab from index to the last tab on the right
    for (let i = index + 1; i < count; i++) {
      const tab = this.getTab(i);
      if (!isTabDisabled(tab.getDOMNode())) {
        return i;
      }
    }

    // If no tab found, continue searching from first on left to index
    for (let i = 0; i < index; i++) {
      const tab = this.getTab(i);
      if (!isTabDisabled(tab.getDOMNode())) {
        return i;
      }
    }

    // No tabs are disabled, return index
    return index;
  },

  getPrevTab(index) {
    let i = index;

    // Look for non-disabled tab from index to first tab on the left
    while (i--) {
      const tab = this.getTab(i);
      if (!isTabDisabled(tab.getDOMNode())) {
        return i;
      }
    }

    // If no tab found, continue searching from last tab on right to index
    i = this.getTabsCount();
    while (i-- > index) {
      const tab = this.getTab(i);
      if (!isTabDisabled(tab.getDOMNode())) {
        return i;
      }
    }

    // No tabs are disabled, return index
    return index;
  },

	getTabsCount() {
    return this.props.children && this.props.children[0] ?
            React.Children.count(this.props.children[0].props.children) :
            0;
	},

	getPanelsCount() {
    return React.Children.count(this.props.children.slice(1));
	},

	getTabList() {
    return this.refs.tablist;
	},

	getTab(index) {
    return this.refs['tabs-' + index];
	},

	getPanel(index) {
    return this.refs['panels-' + index];
	},

  getChildren() {
    let index = 0;
		let count = 0;
		const children = this.props.children;
		const state = this.state;
    const tabIds = this.tabIds = this.tabIds || [];
    const panelIds = this.panelIds = this.panelIds || [];
    let diff = this.tabIds.length - this.getTabsCount();

    // Add ids if new tabs have been added
    // Don't bother removing ids, just keep them in case they are added again
    // This is more efficient, and keeps the uuid counter under control
    while (diff++ < 0) {
      tabIds.push(uuid());
      panelIds.push(uuid());
    }

    // Map children to dynamically setup refs
		return React.Children.map(children, (child) => {
			let result = null;

			// Clone TabList and Tab components to have refs
			if (count++ === 0) {
        // TODO try setting the uuid in the "constructor" for `Tab`/`TabPanel`
				result = React.addons.cloneWithProps(child, {
					ref: 'tablist',
					children: React.Children.map(child.props.children, (tab) => {
						const ref = 'tabs-' + index;
            const id = tabIds[index];
						const panelId = panelIds[index];
						const selected = state.selectedIndex === index;
						const focus = selected && state.focus;

						index++;

						return React.addons.cloneWithProps(tab, {
							ref: ref,
              id: id,
							panelId: panelId,
							selected: selected,
							focus: focus
						});
					})
				});

				// Reset index for panels
				index = 0;
			}
			// Clone TabPanel components to have refs
			else {
				const ref = 'panels-' + index;
        const id = panelIds[index];
				const tabId = tabIds[index];
				const selected = state.selectedIndex === index;

				index++;

				result = React.addons.cloneWithProps(child, {
					ref: ref,
          id: id,
					tabId: tabId,
					selected: selected
				});
			}

			return result;
		});
  },

	render() {
    // This fixes an issue with focus management.
    //
    // Ultimately, when focus is true, and an input has focus,
    // and any change on that input causes a state change/re-render,
    // focus gets sent back to the active tab, and input loses focus.
    //
    // Since the focus state only needs to be remembered
    // for the current render, we can reset it once the
    // render has happened.
    //
    // Don't use setState, because we don't want to re-render.
    //
    // See https://github.com/mzabriskie/react-tabs/pull/7
    if (this.state.focus) {
      setTimeout(() => {
        this.state.focus = false;
      }, 0);
    }

		return (
      <div
        className="react-tabs"
        onClick={this.handleClick}
        onKeyDown={this.handleKeyDown}
      >
        {this.getChildren()}
      </div>
		);
	},

  // This is an anti-pattern, so sue me
  copyPropsToState(props) {
    let selectedIndex = props.selectedIndex;

    // If no selectedIndex prop was supplied, then try
    // preserving the existing selectedIndex from state.
    // If the state has not selectedIndex, default
    // to the first tab in the TabList.
    //
    // TODO: Need automation testing around this
    // Manual testing can be done using examples/focus
    // See 'should preserve selectedIndex when typing' in specs/Tabs.spec.js
    if (selectedIndex === -1) {
      if (this.state && this.state.selectedIndex) {
        selectedIndex = this.state.selectedIndex;
      } else {
        selectedIndex = 0;
      }
    }

    return {
      selectedIndex: selectedIndex,
      focus: props.focus
    };
  }
});
<commit_msg>Add static method Tabs.setUseDefaultStyles(bool) to disable default styling<commit_after>/* eslint indent:0 */
import React, {PropTypes} from 'react/addons';
import jss from 'js-stylesheet';
import uuid from '../helpers/uuid';
import childrenPropType from '../helpers/childrenPropType';

// Determine if a node from event.target is a Tab element
function isTabNode(node) {
  return node.nodeName === 'LI' && node.getAttribute('role') === 'tab';
}

// Determine if a tab node is disabled
function isTabDisabled(node) {
  return node.getAttribute('aria-disabled') === 'true';
}

let useDefaultStyles = true;

module.exports = React.createClass({
  displayName: 'Tabs',

	propTypes: {
		selectedIndex: PropTypes.number,
		onSelect: PropTypes.func,
		focus: PropTypes.bool,
    children: childrenPropType,
    forceRenderTabPanel: PropTypes.bool
	},

  childContextTypes: {
    forceRenderTabPanel: PropTypes.bool
  },

  statics: {
    setUseDefaultStyles(use) {
      useDefaultStyles = use;
    }
  },

	getDefaultProps() {
		return {
			selectedIndex: -1,
			focus: false,
      forceRenderTabPanel: false
		};
	},

	getInitialState() {
    return this.copyPropsToState(this.props);
  },

  getChildContext() {
    return {
      forceRenderTabPanel: this.props.forceRenderTabPanel
    };
  },

  componentWillMount() {
    if (useDefaultStyles) {
      jss(require('../helpers/styles.js'));
	}
  },

  componentWillReceiveProps(newProps) {
    this.setState(this.copyPropsToState(newProps));
  },

	handleClick(e) {
		let node = e.target;
		do {
			if (isTabNode(node)) {
        if (isTabDisabled(node)) {
          return;
        }

        const index = [].slice.call(node.parentNode.children).indexOf(node);
        this.setSelected(index);
				return;
			}
		} while ((node = node.parentNode) !== null);
	},

	handleKeyDown(e) {
		if (isTabNode(e.target)) {
			let index = this.state.selectedIndex;
			let preventDefault = false;

			// Select next tab to the left
			if (e.keyCode === 37 || e.keyCode === 38) {
				index = this.getPrevTab(index);
				preventDefault = true;
			}
			// Select next tab to the right
      /* eslint brace-style:0 */
			else if (e.keyCode === 39 || e.keyCode === 40) {
        index = this.getNextTab(index);
				preventDefault = true;
			}

			// This prevents scrollbars from moving around
			if (preventDefault) {
				e.preventDefault();
			}

			this.setSelected(index, true);
		}
	},

	setSelected(index, focus) {
		// Don't do anything if nothing has changed
    if (index === this.state.selectedIndex) return;
		// Check index boundary
    if (index < 0 || index >= this.getTabsCount()) return;

		// Keep reference to last index for event handler
    const last = this.state.selectedIndex;

		// Update selected index
    this.setState({ selectedIndex: index, focus: focus === true });

		// Call change event handler
    if (typeof this.props.onSelect === 'function') {
      this.props.onSelect(index, last);
    }
	},

  getNextTab(index) {
    const count = this.getTabsCount();

    // Look for non-disabled tab from index to the last tab on the right
    for (let i = index + 1; i < count; i++) {
      const tab = this.getTab(i);
      if (!isTabDisabled(tab.getDOMNode())) {
        return i;
      }
    }

    // If no tab found, continue searching from first on left to index
    for (let i = 0; i < index; i++) {
      const tab = this.getTab(i);
      if (!isTabDisabled(tab.getDOMNode())) {
        return i;
      }
    }

    // No tabs are disabled, return index
    return index;
  },

  getPrevTab(index) {
    let i = index;

    // Look for non-disabled tab from index to first tab on the left
    while (i--) {
      const tab = this.getTab(i);
      if (!isTabDisabled(tab.getDOMNode())) {
        return i;
      }
    }

    // If no tab found, continue searching from last tab on right to index
    i = this.getTabsCount();
    while (i-- > index) {
      const tab = this.getTab(i);
      if (!isTabDisabled(tab.getDOMNode())) {
        return i;
      }
    }

    // No tabs are disabled, return index
    return index;
  },

	getTabsCount() {
    return this.props.children && this.props.children[0] ?
            React.Children.count(this.props.children[0].props.children) :
            0;
	},

	getPanelsCount() {
    return React.Children.count(this.props.children.slice(1));
	},

	getTabList() {
    return this.refs.tablist;
	},

	getTab(index) {
    return this.refs['tabs-' + index];
	},

	getPanel(index) {
    return this.refs['panels-' + index];
	},

  getChildren() {
    let index = 0;
		let count = 0;
		const children = this.props.children;
		const state = this.state;
    const tabIds = this.tabIds = this.tabIds || [];
    const panelIds = this.panelIds = this.panelIds || [];
    let diff = this.tabIds.length - this.getTabsCount();

    // Add ids if new tabs have been added
    // Don't bother removing ids, just keep them in case they are added again
    // This is more efficient, and keeps the uuid counter under control
    while (diff++ < 0) {
      tabIds.push(uuid());
      panelIds.push(uuid());
    }

    // Map children to dynamically setup refs
		return React.Children.map(children, (child) => {
			let result = null;

			// Clone TabList and Tab components to have refs
			if (count++ === 0) {
        // TODO try setting the uuid in the "constructor" for `Tab`/`TabPanel`
				result = React.addons.cloneWithProps(child, {
					ref: 'tablist',
					children: React.Children.map(child.props.children, (tab) => {
						const ref = 'tabs-' + index;
            const id = tabIds[index];
						const panelId = panelIds[index];
						const selected = state.selectedIndex === index;
						const focus = selected && state.focus;

						index++;

						return React.addons.cloneWithProps(tab, {
							ref: ref,
              id: id,
							panelId: panelId,
							selected: selected,
							focus: focus
						});
					})
				});

				// Reset index for panels
				index = 0;
			}
			// Clone TabPanel components to have refs
			else {
				const ref = 'panels-' + index;
        const id = panelIds[index];
				const tabId = tabIds[index];
				const selected = state.selectedIndex === index;

				index++;

				result = React.addons.cloneWithProps(child, {
					ref: ref,
          id: id,
					tabId: tabId,
					selected: selected
				});
			}

			return result;
		});
  },

	render() {
    // This fixes an issue with focus management.
    //
    // Ultimately, when focus is true, and an input has focus,
    // and any change on that input causes a state change/re-render,
    // focus gets sent back to the active tab, and input loses focus.
    //
    // Since the focus state only needs to be remembered
    // for the current render, we can reset it once the
    // render has happened.
    //
    // Don't use setState, because we don't want to re-render.
    //
    // See https://github.com/mzabriskie/react-tabs/pull/7
    if (this.state.focus) {
      setTimeout(() => {
        this.state.focus = false;
      }, 0);
    }

		return (
      <div
        className="react-tabs"
        onClick={this.handleClick}
        onKeyDown={this.handleKeyDown}
      >
        {this.getChildren()}
      </div>
		);
	},

  // This is an anti-pattern, so sue me
  copyPropsToState(props) {
    let selectedIndex = props.selectedIndex;

    // If no selectedIndex prop was supplied, then try
    // preserving the existing selectedIndex from state.
    // If the state has not selectedIndex, default
    // to the first tab in the TabList.
    //
    // TODO: Need automation testing around this
    // Manual testing can be done using examples/focus
    // See 'should preserve selectedIndex when typing' in specs/Tabs.spec.js
    if (selectedIndex === -1) {
      if (this.state && this.state.selectedIndex) {
        selectedIndex = this.state.selectedIndex;
      } else {
        selectedIndex = 0;
      }
    }

    return {
      selectedIndex: selectedIndex,
      focus: props.focus
    };
  }
});
<|endoftext|>


<commit_before>var http = require('http');
var url = require("url");
var express = require("express");
var app = express();
var path = require("path");
var appDir = path.dirname(require.main.filename);

var messages = [];
var messageTimes = [];
var amountMessageLimit = 10;

// viewed at http://localhost:8080
app.get('/', function(req, res) {
    res.sendFile(path.join(appDir, 'index.html'));
});

app.get('/jquery', function(req, res) {
    res.sendFile(path.join(appDir, 'node_modules/jquery/dist/jquery.min.js'));
});

app.get('/chat', function(req, res) {
    res.sendFile(path.join(appDir, 'js/chat.js'));
});

app.get('/message/:message', function(req, res) {
    addMessage(req.params.message);
    console.log("Neue Nachricht:",messages);
    console.log("Neue Nachricht:",messageTimes);

    res.end('ok');
});

app.get('/retrieve', function(req, res) {
    var messageData = {messages:messages, messageTime:messageTimes};
    res.end(JSON.stringify(messageData));
});

function addMessage(message) {
  if (message.length > 0) {
    messages.push(message);
    messageTimes.push(new Date().getTime());
  }
  messages = messages.slice(-amountMessageLimit);
  messageTimes = messageTimes.slice(-amountMessageLimit);
}

app.listen(5555);

/*

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  var userIp = req.connection.remoteAddress;

  var message =  getMessage(req);
  if (message.length == 0)  {
    res.end('
blomblers Chat
');
    return;
  }

  if (userIp == "192.168.178.39") {

    addMessage(message);

    res.end(createResponse(messages));
  } else if (userIp == "192.168.178.66" || userIp == "192.168.178.65") {
    // blombler
    var message =  getMessage(req);
    addMessage(message);
    res.end(createResponse(messages));
  } else {
    res.end('Unknown user');
  }

}).listen(5555, '192.168.178.65');*/
console.log('Heute : Rady');
<commit_msg>ohne fehler<commit_after>var http = require('http');
var url = require("url");
var express = require("express");
var app = express();
var path = require("path");
var appDir = path.dirname(require.main.filename);

var messages = [];
var messageTimes = [];
var amountMessageLimit = 10;

// viewed at http://localhost:8080
app.get('/', function(req, res) {
    res.sendFile(path.join(appDir, 'index.html'));
});

app.get('/jquery', function(req, res) {
    res.sendFile(path.join(appDir, 'node_modules/jquery/dist/jquery.min.js'));
});

app.get('/chat', function(req, res) {
    res.sendFile(path.join(appDir, 'js/chat.js'));
});

app.get('/message/:message', function(req, res) {
    addMessage(req.params.message);
    console.log("Neue Nachricht:",messages);
    console.log("Neue Nachricht:",messageTimes);

    res.end('ok');
});

app.get('/retrieve', function(req, res) {
    var messageData = {messages:messages, messageTime:messageTimes};
    res.end(JSON.stringify(messageData));
});

function addMessage(message) {
  if (message.length > 0) {
    messages.push(message);
    messageTimes.push(new Date().getTime());
  }
  messages = messages.slice(-amountMessageLimit);
  messageTimes = messageTimes.slice(-amountMessageLimit);
}

app.listen(5555);

/*

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  var userIp = req.connection.remoteAddress;

  var message =  getMessage(req);
  if (message.length == 0)  {
    res.end('
blomblers Chat
');
    return;
  }

  if (userIp == "192.168.178.39") {

    addMessage(message);

    res.end(createResponse(messages));
  } else if (userIp == "192.168.178.66" || userIp == "192.168.178.65") {
    // blombler
    var message =  getMessage(req);
    addMessage(message);
    res.end(createResponse(messages));
  } else {
    res.end('Unknown user');
  }

}).listen(5555, '192.168.178.65');*/
console.log('Heute : Ready');
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import { Row, Column } from '../row';
import Label from '../../__experimental__/components/label';
import StyledInlineInputs from './inline-inputs.style';

const columnWrapper = (children) => {
  let inputs = children;

  if (!Array.isArray(inputs)) {
    inputs = [children];
  }

  return inputs.map((input, index) => {
    // Input is never going to be re-ordered so we don't require a defined key
    /* eslint-disable react/no-array-index-key */
    return (
      <Column key={ index }>
        { input }
      </Column>
    );
  });
};

const InlineInputs = (props) => {
  const {
    label,
    htmlFor,
    children,
    className
  } = props;

  function renderLabel() {
    if (!label) return null;

    return { label };
  }

  return (

  );
};

// Assign props over for demo site
InlineInputs.propTypes = {
  /** Children elements */
  children: PropTypes.node,
  /** [Legacy prop] A custom class name for the component. */
  className: PropTypes.string,
  /** Defines the label text for the heading. */
  label: PropTypes.string,
  /** The id of the corresponding input control for the label */
  htmlFor: PropTypes.string
};

InlineInputs.defaultProps = {
  children: null,
  className: ''
};

/* eslint-enable react/prop-types */

export default InlineInputs;
<commit_msg>added data-component attribute<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import { Row, Column } from '../row';
import Label from '../../__experimental__/components/label';
import StyledInlineInputs from './inline-inputs.style';

const columnWrapper = (children) => {
  let inputs = children;

  if (!Array.isArray(inputs)) {
    inputs = [children];
  }

  return inputs.map((input, index) => {
    // Input is never going to be re-ordered so we don't require a defined key
    /* eslint-disable react/no-array-index-key */
    return (
      <Column key={ index }>
        { input }
      </Column>
    );
  });
};

const InlineInputs = (props) => {
  const {
    label,
    htmlFor,
    children,
    className
  } = props;

  function renderLabel() {
    if (!label) return null;

    return { label };
  }

  return (

  );
};

// Assign props over for demo site
InlineInputs.propTypes = {
  /** Children elements */
  children: PropTypes.node,
  /** [Legacy prop] A custom class name for the component. */
  className: PropTypes.string,
  /** Defines the label text for the heading. */
  label: PropTypes.string,
  /** The id of the corresponding input control for the label */
  htmlFor: PropTypes.string
};

InlineInputs.defaultProps = {
  children: null,
  className: ''
};

/* eslint-enable react/prop-types */

export default InlineInputs;
<|endoftext|>


<commit_before>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return move||getInput();
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return move||randomPlay();
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
    /* YOUR CODE HERE */
    return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    /* YOUR CODE HERE */
    return [playerWins, computerWins];
}

<commit_msg>Provided code for body of getWinner(playerMove, computerMove) function<commit_after>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return move||getInput();
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return move||randomPlay();
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
    if ((playerMove==='paper' && computerMove==='rock')||
    (playerMove==='rock' && computerMove==='scissors')||
    (playerMove==='scissors' && computerMove==='paper'))
    winner = 'player';

    else if ((playerMove==='scissors' && computerMove==='rock')||
    (playerMove==='rock' && computerMove==='paper')||
    (playerMove==='paper' && computerMove==='scissors'))
    winner = 'computer';

    else
    winner = 'tie';

return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    /* YOUR CODE HERE */
    return [playerWins, computerWins];
}

<|endoftext|>


<commit_before>// Generated by CoffeeScript 2.0.0-beta7
void function () {
  var config;
  module.exports = config = {};
  config.env = process.env.NODE_ENV || 'development';
  config.defaultSitemapConfig = {
    targetDirectory: '' + process.cwd() + '/tmp/sitemaps/' + config.env,
    sitemapIndex: 'sitemap.xml',
    sitemapRootUrl: 'http://www.mysite.com',
    sitemapFileDirectory: '/sitemaps',
    maxUrlsPerFile: 5e4,
    urlBase: 'http://www.mysite.com'
  };
  config.sitemapIndexHeader = '<?xml version="1.0" encoding="UTF-8"?><sitemapindex xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/siteindex.xsd" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
  config.sitemapHeader = '<?xml version="1.0" encoding="UTF-8"?><urlset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:video="http://www.google.com/schemas/sitemap-video/1.1" xmlns:geo="http://www.google.com/geo/schemas/sitemap/1.0" xmlns:news="http://www.google.com/schemas/sitemap-news/0.9/">';
  config.defaultUrlFormatter = function (options) {
    return function (href) {
      if ('/' === href) {
        return options.urlBase;
      } else if (href && href.length && href[0] === '/') {
        return '' + options.urlBase + href;
      } else if (href && href.length && href.match(/^https?:\/\//)) {
        return href;
      } else if (href.length) {
        return '' + options.urlBase + '/' + href;
      } else {
        return options.urlBase;
      }
    };
  };
}.call(this);
<commit_msg>default config js<commit_after>// Generated by CoffeeScript 2.0.0-beta7
void function () {
  var config;
  module.exports = config = {};
  config.env = process.env.NODE_ENV || 'development';
  config.defaultSitemapConfig = {
    targetDirectory: '' + process.cwd() + '/tmp/sitemaps/' + config.env,
    sitemapIndex: 'sitemap.xml',
    sitemapRootUrl: 'http://www.mysite.com',
    sitemapFileDirectory: '/sitemaps',
    maxUrlsPerFile: 5e4,
    urlBase: 'http://www.mysite.com'
  };
  config.sitemapIndexHeader = '<?xml version="1.0" encoding="UTF-8"?><sitemapindex xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/siteindex.xsd" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
  config.sitemapHeader = '<?xml version="1.0" encoding="UTF-8"?><urlset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:image="http://www.google.com/schemas/sitemap-image/1.1" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd" xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:video="http://www.google.com/schemas/sitemap-video/1.1" xmlns:geo="http://www.google.com/geo/schemas/sitemap/1.0" xmlns:news="http://www.google.com/schemas/sitemap-news/0.9/" xmlns:xhtml="http://www.w3.org/1999/xhtml">';
  config.defaultUrlFormatter = function (options) {
    return function (href) {
      if ('/' === href) {
        return options.urlBase;
      } else if (href && href.length && href[0] === '/') {
        return '' + options.urlBase + href;
      } else if (href && href.length && href.match(/^https?:\/\//)) {
        return href;
      } else if (href.length) {
        return '' + options.urlBase + '/' + href;
      } else {
        return options.urlBase;
      }
    };
  };
}.call(this);
<|endoftext|>


<commit_before>describe('packs/global.js', function() {
  context("jquery modules", function() {
    it('loads bootstrap', function() {
      expect($.fn.modal).toBeDefined();
    });

    it('loads bootstrap-datepicker', function() {
      expect($.fn.datepicker).toBeDefined();
    });

    it('loads bootstrap-select', function() {
      expect($.fn.selectpicker).toBeDefined();
    });

    it('loads bootstrap-switch', function() {
      expect($.fn.bootstrapSwitch).toBeDefined();
    });

    it('loads bootstrap-touchspin', function() {
      expect($.fn.TouchSpin).toBeDefined();
    });

    it('loads c3', function() {
      expect(window.c3).toBeDefined();
    });

    it('loads d3', function() {
      expect(window.d3).toBeDefined();
    });

    it('loads eonasdan-bootstrap-datetimepicker', function() {
      expect($.fn.datetimepicker).toBeDefined();
    });
  });

  context('angular modules', function() {
    it('loads angular-bootstrap-switch', function() {
      expect(angular.module('frapontillo.bootstrap-switch')).toBeDefined();
    });

    it('loads angular-patternfly', function() {
      expect(angular.module('patternfly')).toBeDefined();
    });

    it('loads angular-ui-bootstrap', function() {
      expect(angular.module('ui.bootstrap')).toBeDefined();
    });
  });

  context('d3 plugins', function() {
    it('loads patternfly-timeline', function() {
      expect(d3.chart.timeline).toBeDefined();
      expect(d3.chart.timeline().start).toBeDefined();
      expect(d3.chart.timeline().end).toBeDefined();
    });
  });
});
<commit_msg>Add test that kubernetes-topology-graph is loaded<commit_after>describe('packs/global.js', function() {
  context("jquery modules", function() {
    it('loads bootstrap', function() {
      expect($.fn.modal).toBeDefined();
    });

    it('loads bootstrap-datepicker', function() {
      expect($.fn.datepicker).toBeDefined();
    });

    it('loads bootstrap-select', function() {
      expect($.fn.selectpicker).toBeDefined();
    });

    it('loads bootstrap-switch', function() {
      expect($.fn.bootstrapSwitch).toBeDefined();
    });

    it('loads bootstrap-touchspin', function() {
      expect($.fn.TouchSpin).toBeDefined();
    });

    it('loads c3', function() {
      expect(window.c3).toBeDefined();
    });

    it('loads d3', function() {
      expect(window.d3).toBeDefined();
    });

    it('loads eonasdan-bootstrap-datetimepicker', function() {
      expect($.fn.datetimepicker).toBeDefined();
    });
  });

  context('angular modules', function() {
    it('loads angular-bootstrap-switch', function() {
      expect(angular.module('frapontillo.bootstrap-switch')).toBeDefined();
    });

    it('loads angular-patternfly', function() {
      expect(angular.module('patternfly')).toBeDefined();
    });

    it('loads angular-ui-bootstrap', function() {
      expect(angular.module('ui.bootstrap')).toBeDefined();
    });

    it('loads kubernetes-topology-graph', function() {
      expect(angular.module('kubernetesUI')).toBeDefined();
    });
  });

  context('d3 plugins', function() {
    it('loads patternfly-timeline', function() {
      expect(d3.chart.timeline).toBeDefined();
      expect(d3.chart.timeline().start).toBeDefined();
      expect(d3.chart.timeline().end).toBeDefined();
    });
  });
});
<|endoftext|>


<commit_before>import path from 'path';

export default {
  base: '.',
  dist: path.resolve(__dirname, 'dist/'),
  copyAssets: [
    'src/index.html',
    {
      asset: 'src/img/**',
      dist: 'dist/img/'
    }
  ],
  scssAssets: ['src/scss/**/*.scss'],
  jsAssets: ['src/js/**/*.js'],
  mainJs: 'src/js/index.js',
  mainScss: 'src/scss/index.scss',
  sync: {
    hostname: 'grommet.us.rdlabs.hpecorp.net',
    username: 'ligo',
    remoteDestination: '/var/www/html/examples/ferret/dist'
  },
  webpack: {
    resolve: {
      root: [
        path.resolve(__dirname, 'src/js'),
        path.resolve(__dirname, 'src/scss'),
        path.resolve(__dirname, 'node_modules')
      ]
    }
  },
  devServerPort: 8001,
  // The 8010 port number needs to align with hostName in index.js
  devServerProxy: {
    "/rest/*": 'http://localhost:8010'
  },
  websocketHost: 'localhost:8010',
  alias: {
    'grommet-index/scss': path.resolve(__dirname, '../grommet-index/src/scss'),
    'grommet-index': path.resolve(__dirname, '../grommet-index/src/js'),
    'grommet/scss': path.resolve(__dirname, '../grommet/src/scss'),
    'grommet': path.resolve(__dirname, '../grommet/src/js')
  },
  devPreprocess: ['set-webpack-alias']
};
<commit_msg>Set up specific loader for react-gravatar<commit_after>import path from 'path';

export default {
  base: '.',
  dist: path.resolve(__dirname, 'dist/'),
  copyAssets: [
    'src/index.html',
    {
      asset: 'src/img/**',
      dist: 'dist/img/'
    }
  ],
  scssAssets: ['src/scss/**/*.scss'],
  jsAssets: ['src/js/**/*.js'],
  mainJs: 'src/js/index.js',
  mainScss: 'src/scss/index.scss',
  sync: {
    hostname: 'grommet.us.rdlabs.hpecorp.net',
    username: 'ligo',
    remoteDestination: '/var/www/html/examples/ferret/dist'
  },
  webpack: {
    resolve: {
      root: [
        path.resolve(__dirname, 'src/js'),
        path.resolve(__dirname, 'src/scss'),
        path.resolve(__dirname, 'node_modules')
      ]
    },
    module: {
      loaders: [
        {
          test: /\.jsx?$/,
          loader: 'babel-loader',
          include: /node_modules\/react-gravatar/
        }
      ]
    }
  },
  devServerPort: 8001,
  // The 8010 port number needs to align with hostName in index.js
  devServerProxy: {
    "/rest/*": 'http://localhost:8010'
  },
  websocketHost: 'localhost:8010',
  alias: {
    'grommet-index/scss': path.resolve(__dirname, '../grommet-index/src/scss'),
    'grommet-index': path.resolve(__dirname, '../grommet-index/src/js'),
    'grommet/scss': path.resolve(__dirname, '../grommet/src/scss'),
    'grommet': path.resolve(__dirname, '../grommet/src/js')
  },
  devPreprocess: ['set-webpack-alias']
};
<|endoftext|>


<commit_before>import {h} from 'preact/preact';

import Util from './Util';

import BlockSpoiler from 'com/block-spoiler/spoiler';
import MailLink from 'com/content-maillink/maillink';

//COMPONENT IMPORTS
import NavLink from 'com/nav-link/link';
import AutoEmbed from 'com/autoembed/autoembed';

export default class Renderer {
  constructor(options) {
    this.options = options || {};
  }

  code(code, lang, escaped) {
    if (this.options.highlight) {
      var out = this.options.highlight(code, lang);
      if (out != null && out !== code) {
        escaped = true;
        code = out;

        return (

);
      }
    }

    if (!lang) {
      return (

{(escaped
        ? code
        : Util.escape(code, true))}

      );
    }

    return (

        {(escaped ? code : Util.escape(code, true))}

    );
  };
  spoiler(secret) {
    return (
      <BlockSpoiler>{secret}</BlockSpoiler>
    );
  };
  blockquote(quote) {
    return (

{quote}

    );
  };

  html(html) {
    return {html};
  };

  heading(text, level, raw) {
    const HeaderTag = `h${level}`;
    return (
      <HeaderTag id={this.options.headerPrefix + raw.toLowerCase().replace(/[^\w]+/g, '-').replace(/-$/, "")}>{text}</HeaderTag>
    );
  };

  hr() {
    return (
);
  };

  list(body, ordered) {
    var Type = ordered
      ? 'ol'
      : 'ul';
    return (
      <Type>{'\n'}{body}</Type>
    );
  };

  listitem(text) {
    return (

{text}

    );
  };

  paragraph(text) {
    return (

{text}

    );
  };

  table(header, body) {
    return (

{header}

{body}

    );
  };

  tablerow(content) {
    return (

{content}

    );
  };

  tablecell(content, flags) {
    var Type = flags.header
      ? 'th'
      : 'td';
    return (
      <Type style={"text-align:" + flags.align
        ? flags.align
        : ''}>{content}</Type>
    );
  };

  // span level renderer
  strong(text) {
    return (
      {text}
    );
  };

  em(text) {
    return (
      {text}
    );
  };

  emoji(text) {
    return ();
  };

  //email(text) {
  //  return 'VEOO'+text+'OOEV';
  //};

  atname(text) {
    return (
      <NavLink href={"/users/" + text}>@{text}</NavLink>
    );
  };

  codespan(text) {
    return (
      {text}
    );
    // text.replace('\n','') // ??
  };

  br() {
    //    if(this.options.xhtml) {
    return (
);
    // } else {
    //   return (
);
    // }

  };

  del(text) {
    return (
      {text}
    );
  };

  link(href, title, text) {
    if (this.options.sanitize) {
      try {
        var prot = decodeURIComponent(unescape(href)).replace(/[^\w:]/g, '').toLowerCase();
      } catch (e) {
        return '';
      }
      if (prot.indexOf('javascript:') === 0 || prot.indexOf('vbscript:') === 0 || prot.indexOf('data:') === 0) {
        return '';
      }
    }

    href = extractFromURL(href).href;

    var isExternal = href.indexOf('//') != -1;
    var isInternal = href.indexOf('///') === 0;
    if ( isInternal ) {
      isExternal = false;
      href = href.substr(2);
    }

    if ( isExternal ) {
		var target = "_blank";
	}

    // If text is blank, use the URL itself
    if ( !text || text.length < 1 ) {
      text = href;
    }

    if(AutoEmbed.hasEmbed(href) || AutoEmbed.hasSmartLink(href)) {
      return (<AutoEmbed href={href} title={title} text={text} />);
    }

    var out = (
      <NavLink href={href} title={title} target={target}>{text}</NavLink>
    );
    return out;

  };

  mail(leftSide, rightSide, text) {
	href = '{0}@{1}'.replace('{1}', rightSide, 1).replace('{0}', leftSide, 1);
    if (this.options.sanitize) {
      try {
        var prot = decodeURIComponent(unescape(href)).replace(/[^\w:]/g, '').toLowerCase();
      } catch (e) {
        return '';
      }
      if (prot.indexOf('javascript:') === 0 || prot.indexOf('vbscript:') === 0 || prot.indexOf('data:') === 0) {
        return '';
      }
    }

	//text = leftSide + '[at]' + rightSide;

    var out = (
      <MailLink href={href} title={text}>{text}</MailLink>
    );

    return out;

  };

  image(href, title, text) {
    // Customized. Disable image rendering if URLs are used to files not on our safe list.
    // Also, rewrite URLs to our static domain if the short form is used.

    if ( href.indexOf("///") === 0 ) {
    	// Rewrite URL to replace the first two slashes with the endpoint
      href = STATIC_ENDPOINT + href.substr(2);
    }
    // Disabled this. Only Triple slash URLs should be allow.
  //  else if ( href.indexOf(STATIC_ENDPOINT) >= 0 && href.indexOf(STATIC_ENDPOINT) <= 5 ) {
  //  	// Everything is okay. Use this URL as-is
  //  }
    else {
      //return '
' + text + '
';
      href = STATIC_ENDPOINT + '/content/internal/pleaseupload.png';
    }
    var out = ();
    /*if (title) {
      out += ' title="' + title + '"';
    }
    out += this.options.xhtml
      ? '/>'
      : '>';*/
    return out;
  };

  text(text) {
    return (Util.htmldecode(text));
  };
}
<commit_msg>fixed the name<commit_after>import {h} 					from 'preact/preact';

import Util 				from './Util';

//COMPONENT IMPORTS
import NavLink 				from 'com/nav-link/link';
import LinkMail				from 'com/link-mail/mail';		// TODO: Obsolete me
import AutoEmbed 			from 'com/autoembed/autoembed';
import BlockSpoiler 		from 'com/block-spoiler/spoiler';

export default class Renderer {
  constructor(options) {
    this.options = options || {};
  }

  code(code, lang, escaped) {
    if (this.options.highlight) {
      var out = this.options.highlight(code, lang);
      if (out != null && out !== code) {
        escaped = true;
        code = out;

        return (

);
      }
    }

    if (!lang) {
      return (

{(escaped
        ? code
        : Util.escape(code, true))}

      );
    }

    return (

        {(escaped ? code : Util.escape(code, true))}

    );
  };
  spoiler(secret) {
    return (
      <BlockSpoiler>{secret}</BlockSpoiler>
    );
  };
  blockquote(quote) {
    return (

{quote}

    );
  };

  html(html) {
    return {html};
  };

  heading(text, level, raw) {
    const HeaderTag = `h${level}`;
    return (
      <HeaderTag id={this.options.headerPrefix + raw.toLowerCase().replace(/[^\w]+/g, '-').replace(/-$/, "")}>{text}</HeaderTag>
    );
  };

  hr() {
    return (
);
  };

  list(body, ordered) {
    var Type = ordered
      ? 'ol'
      : 'ul';
    return (
      <Type>{'\n'}{body}</Type>
    );
  };

  listitem(text) {
    return (

{text}

    );
  };

  paragraph(text) {
    return (

{text}

    );
  };

  table(header, body) {
    return (

{header}

{body}

    );
  };

  tablerow(content) {
    return (

{content}

    );
  };

  tablecell(content, flags) {
    var Type = flags.header
      ? 'th'
      : 'td';
    return (
      <Type style={"text-align:" + flags.align
        ? flags.align
        : ''}>{content}</Type>
    );
  };

  // span level renderer
  strong(text) {
    return (
      {text}
    );
  };

  em(text) {
    return (
      {text}
    );
  };

  emoji(text) {
    return ();
  };

  //email(text) {
  //  return 'VEOO'+text+'OOEV';
  //};

  atname(text) {
    return (
      <NavLink href={"/users/" + text}>@{text}</NavLink>
    );
  };

  codespan(text) {
    return (
      {text}
    );
    // text.replace('\n','') // ??
  };

  br() {
    //    if(this.options.xhtml) {
    return (
);
    // } else {
    //   return (
);
    // }

  };

  del(text) {
    return (
      {text}
    );
  };

  link(href, title, text) {
    if (this.options.sanitize) {
      try {
        var prot = decodeURIComponent(unescape(href)).replace(/[^\w:]/g, '').toLowerCase();
      } catch (e) {
        return '';
      }
      if (prot.indexOf('javascript:') === 0 || prot.indexOf('vbscript:') === 0 || prot.indexOf('data:') === 0) {
        return '';
      }
    }

    href = extractFromURL(href).href;

    var isExternal = href.indexOf('//') != -1;
    var isInternal = href.indexOf('///') === 0;
    if ( isInternal ) {
      isExternal = false;
      href = href.substr(2);
    }

    if ( isExternal ) {
		var target = "_blank";
	}

    // If text is blank, use the URL itself
    if ( !text || text.length < 1 ) {
      text = href;
    }

    if(AutoEmbed.hasEmbed(href) || AutoEmbed.hasSmartLink(href)) {
      return (<AutoEmbed href={href} title={title} text={text} />);
    }

    var out = (
      <NavLink href={href} title={title} target={target}>{text}</NavLink>
    );
    return out;

  };

  mail(leftSide, rightSide, text) {
	href = '{0}@{1}'.replace('{1}', rightSide, 1).replace('{0}', leftSide, 1);
    if (this.options.sanitize) {
      try {
        var prot = decodeURIComponent(unescape(href)).replace(/[^\w:]/g, '').toLowerCase();
      } catch (e) {
        return '';
      }
      if (prot.indexOf('javascript:') === 0 || prot.indexOf('vbscript:') === 0 || prot.indexOf('data:') === 0) {
        return '';
      }
    }

	//text = leftSide + '[at]' + rightSide;

    var out = (
      <LinkMail href={href} title={text}>{text}</LinkMail>
    );

    return out;

  };

  image(href, title, text) {
    // Customized. Disable image rendering if URLs are used to files not on our safe list.
    // Also, rewrite URLs to our static domain if the short form is used.

    if ( href.indexOf("///") === 0 ) {
    	// Rewrite URL to replace the first two slashes with the endpoint
      href = STATIC_ENDPOINT + href.substr(2);
    }
    // Disabled this. Only Triple slash URLs should be allow.
  //  else if ( href.indexOf(STATIC_ENDPOINT) >= 0 && href.indexOf(STATIC_ENDPOINT) <= 5 ) {
  //  	// Everything is okay. Use this URL as-is
  //  }
    else {
      //return '
' + text + '
';
      href = STATIC_ENDPOINT + '/content/internal/pleaseupload.png';
    }
    var out = ();
    /*if (title) {
      out += ' title="' + title + '"';
    }
    out += this.options.xhtml
      ? '/>'
      : '>';*/
    return out;
  };

  text(text) {
    return (Util.htmldecode(text));
  };
}
<|endoftext|>


<commit_before>'use strict';

const fs = require('fs');

function readJson(path) {
	return JSON.parse(fs.readFileSync(path, 'utf8'));
}

function writeJson(path, obj) {
	fs.writeFileSync(path, JSON.stringify(obj), {
		mode: 0o600
	});
}

module.exports = {
	readJson: readJson,
	writeJson: writeJson
};
<commit_msg>Add newline at the end of JSON files<commit_after>'use strict';

const fs = require('fs');

function readJson(path) {
	return JSON.parse(fs.readFileSync(path, 'utf8'));
}

function writeJson(path, obj) {
	fs.writeFileSync(path, JSON.stringify(obj) + '\n', {
		mode: 0o600
	});
}

module.exports = {
	readJson: readJson,
	writeJson: writeJson
};
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import Dialog from 'material-ui/Dialog';
import PropTypes from 'prop-types';

import QuetionsList from './QuetionsList';
import QuestionForm from './QuestionForm';
import AddQuestionBtn from './AddQuestionBtn';

/**
 * @description propTypes for QuestionsDialogBox
 * @type {Object}
 */
const propTypes = {
  handleCloseDialog: PropTypes.func.isRequired,
  submitQuestionForm: PropTypes.func.isRequired,
  onDeleteQuestion: PropTypes.func.isRequired,
  openDialog: PropTypes.bool.isRequired,
  questions: PropTypes.arrayOf(PropTypes.shape({
    id: PropTypes.string.isRequired,
    question: PropTypes.string.isRequired,
  })).isRequired,
};

/**
 * @class QuestionsDialogBox
 * @extends React.Component
 * @description Render component
 */
class QuestionsDialogBox extends Component {
  state = {
    showForm: false,
    clickedQuestion: null,
  };

  /**
   * @description Handle click on Add Question btn
   */
  handleAddQuestion = () => {
    this.setState({ showForm: true });
  };

  /**
   * @description handle on close dialog box
   */
  handleClose = () => {
    this.hideForm();
    this.props.handleCloseDialog();
  };

  /**
   * @description set state on close form
   */
  hideForm = () => {
    this.setState({ showForm: false, clickedQuestion: null });
  };

  /**
   * @description handle on submit question form
   * @param data
   */
  handleFormSubmit = (data) => {
    this.props.submitQuestionForm(data);
    this.hideForm();
  };

  /**
   * @description handle form cancel
   */
  handleFormCancel = () => {
    this.hideForm();
  };

  /**
   * @description handle Question Item on click
   * @param {Object} data question data
   */
  handleClickOnItem = (data) => {
    this.setState({
      showForm: true,
      clickedQuestion: data,
    });
  };

  /**
   * @description handle click on delete icon
   * @param {String} id
   */
  handleOnDeleteItem = (id) => {
    if (window.confirm('Delete Question?')) {
      this.props.onDeleteQuestion(id);
    }
  };

  setDialogPropsForQestionList = () => ({
    title: 'Suggested Questions',
    actions: <AddQuestionBtn handleAddQuestion={this.handleAddQuestion} />,
    actionsContainerStyle: { padding: 20, textAlign: 'center' },
  });

  setDialogPropsForQuestionForm = () => ({
    title: `${this.state.clickedQuestion ? 'Update' : 'Add'} Questions`,
    actions: null,
    actionsContainerStyle: {},
  });

  renderQuestionList = () => {
    const { questions } = this.props;
    return (
      <QuetionsList
        clickOnItem={this.handleClickOnItem}
        onDelete={this.handleOnDeleteItem}
        questions={questions}
      />
    );
  };

  renderQuestionForm = () => {
    const { clickedQuestion } = this.state;
    return (
      <QuestionForm
        handleFormSubmit={this.handleFormSubmit}
        handleFormCancel={this.handleFormCancel}
        initialValues={clickedQuestion}
      />
    );
  };

  /**
   * @description render
   * @return {Object} JSX HTML Content
   */
  render() {
    const { showForm } = this.state;
    const { openDialog } = this.props;

    let content = this.renderQuestionList();
    let dialogProps = this.setDialogPropsForQestionList();

    if (showForm) {
      content = this.renderQuestionForm();
      dialogProps = this.setDialogPropsForQuestionForm();
    }

    return (
      <Dialog
        modal={false}
        open={openDialog}
        onRequestClose={this.handleClose}
        autoScrollBodyContent={true}
        {...dialogProps}
      >
        {content}
      </Dialog>
    );
  }
}

QuestionsDialogBox.propTypes = propTypes;

export default QuestionsDialogBox;
<commit_msg>refactoring questions dialog box<commit_after>import React, { Component } from 'react';
import Dialog from 'material-ui/Dialog';
import PropTypes from 'prop-types';

import QuetionsList from './QuetionsList';
import QuestionForm from './QuestionForm';
import AddQuestionBtn from './AddQuestionBtn';

/**
 * @description propTypes for QuestionsDialogBox
 * @type {Object}
 */
const propTypes = {
  handleCloseDialog: PropTypes.func.isRequired,
  submitQuestionForm: PropTypes.func.isRequired,
  onDeleteQuestion: PropTypes.func.isRequired,
  openDialog: PropTypes.bool.isRequired,
  questions: PropTypes.arrayOf(PropTypes.shape({
    id: PropTypes.string.isRequired,
    question: PropTypes.string.isRequired,
  })).isRequired,
};

/**
 * @class QuestionsDialogBox
 * @extends React.Component
 * @description Render component
 */
class QuestionsDialogBox extends Component {
  state = {
    showForm: false,
    clickedQuestion: null,
  };

  setDialogPropsForQestionList = () => ({
    title: 'Suggested Questions',
    actions: <AddQuestionBtn handleAddQuestion={this.handleAddQuestion} />,
    actionsContainerStyle: { padding: 20, textAlign: 'center' },
  });

  setDialogPropsForQuestionForm = () => ({
    title: `${this.state.clickedQuestion ? 'Update' : 'Add'} Questions`,
    actions: null,
    actionsContainerStyle: {},
  });

  /**
   * @description Handle click on Add Question btn
   */
  handleAddQuestion = () => {
    this.setState({ showForm: true });
  };

  /**
   * @description handle on close dialog box
   */
  handleClose = () => {
    this.hideForm();
    this.props.handleCloseDialog();
  };

  /**
   * @description set state on close form
   */
  hideForm = () => {
    this.setState({ showForm: false, clickedQuestion: null });
  };

  /**
   * @description handle on submit question form
   * @param data
   */
  handleFormSubmit = (data) => {
    this.props.submitQuestionForm(data);
    this.hideForm();
  };

  /**
   * @description handle form cancel
   */
  handleFormCancel = () => {
    this.hideForm();
  };

  /**
   * @description handle Question Item on click
   * @param {Object} data question data
   */
  handleClickOnItem = (data) => {
    this.setState({
      showForm: true,
      clickedQuestion: data,
    });
  };

  /**
   * @description handle click on delete icon
   * @param {String} id
   */
  handleOnDeleteItem = (id) => {
    if (window.confirm('Delete Question?')) {
      this.props.onDeleteQuestion(id);
    }
  };

  renderQuestionList = () => {
    const { questions } = this.props;
    return (
      <QuetionsList
        clickOnItem={this.handleClickOnItem}
        onDelete={this.handleOnDeleteItem}
        questions={questions}
      />
    );
  };

  renderQuestionForm = () => {
    const { clickedQuestion } = this.state;
    return (
      <QuestionForm
        handleFormSubmit={this.handleFormSubmit}
        handleFormCancel={this.handleFormCancel}
        initialValues={clickedQuestion}
      />
    );
  };

  /**
   * @description render
   * @return {Object} JSX HTML Content
   */
  render() {
    const { showForm } = this.state;
    const { openDialog } = this.props;

    let content = this.renderQuestionList();
    let dialogProps = this.setDialogPropsForQestionList();

    if (showForm) {
      content = this.renderQuestionForm();
      dialogProps = this.setDialogPropsForQuestionForm();
    }

    return (
      <Dialog
        modal={false}
        open={openDialog}
        onRequestClose={this.handleClose}
        autoScrollBodyContent={true}
        {...dialogProps}
      >
        {content}
      </Dialog>
    );
  }
}

QuestionsDialogBox.propTypes = propTypes;

export default QuestionsDialogBox;
<|endoftext|>


<commit_before>/** @babel */
/** @jsx etch.dom */
/* eslint react/no-unknown-property: "off" */

import etch from 'etch';
import {Disposable, CompositeDisposable} from 'atom';

import FilePatchListItemView from './file-patch-list-item-view';
import MergeConflictListItemView from './merge-conflict-list-item-view';
import CompositeListSelection from './composite-list-selection';
import {shortenSha} from '../helpers';

const debounce = (fn, wait) => {
  let timeout;
  return (...args) => {
    return new Promise(resolve => {
      clearTimeout(timeout);
      timeout = setTimeout(() => {
        resolve(fn(...args));
      }, wait);
    });
  };
};

export default class StagingView {
  constructor(props) {
    this.props = props;
    atom.config.observe('github.keyboardNavigationDelay', value => {
      if (value === 0) {
        this.debouncedDidChangeSelectedItem = this.didChangeSelectedItem.bind(this);
      } else {
        this.debouncedDidChangeSelectedItem = debounce(this.didChangeSelectedItem.bind(this), value);
      }
    });
    this.mouseSelectionInProgress = false;
    this.listElementsByItem = new WeakMap();
    this.registerItemElement = this.registerItemElement.bind(this);
    this.mousedownOnItem = this.mousedownOnItem.bind(this);
    this.mousemoveOnItem = this.mousemoveOnItem.bind(this);
    this.mouseup = this.mouseup.bind(this);
    this.selection = new CompositeListSelection({
      listsByKey: {
        unstaged: this.props.unstagedChanges,
        conflicts: this.props.mergeConflicts || [],
        staged: this.props.stagedChanges,
      },
      idForItem: item => item.filePath,
    });
    etch.initialize(this);

    this.subscriptions = new CompositeDisposable();
    this.subscriptions.add(atom.commands.add(this.element, {
      'core:move-up': () => this.selectPrevious(),
      'core:move-down': () => this.selectNext(),
      'core:select-up': () => this.selectPrevious(true),
      'core:select-down': () => this.selectNext(true),
      'core:select-all': () => this.selectAll(),
      'core:move-to-top': () => this.selectFirst(),
      'core:move-to-bottom': () => this.selectLast(),
      'core:select-to-top': () => this.selectFirst(true),
      'core:select-to-bottom': () => this.selectLast(true),
      'core:confirm': () => this.confirmSelectedItems(),
      'git:activate-next-list': () => this.activateNextList(),
      'git:activate-previous-list': () => this.activatePreviousList(),
      'git:focus-diff-view': () => this.props.focusFilePatchView(),
    }));
    window.addEventListener('mouseup', this.mouseup);
    this.subscriptions.add(new Disposable(() => window.removeEventListener('mouseup', this.mouseup)));
  }

  update(props) {
    this.props = props;
    this.selection.updateLists({
      unstaged: this.props.unstagedChanges,
      conflicts: this.props.mergeConflicts || [],
      staged: this.props.stagedChanges,
    });
    return etch.update(this);
  }

  activateNextList() {
    this.selection.activateNextSelection();
    return etch.update(this);
  }

  activatePreviousList() {
    this.selection.activatePreviousSelection();
    return etch.update(this);
  }

  confirmSelectedItems() {
    const itemPaths = Array.from(this.selection.getSelectedItems()).map(item => item.filePath);
    if (this.selection.getActiveListKey() === 'staged') {
      return this.props.unstageFiles(itemPaths);
    } else {
      return this.props.stageFiles(itemPaths);
    }
  }

  selectPrevious(preserveTail = false) {
    this.selection.selectPreviousItem(preserveTail);
    this.selection.coalesce();
    if (!preserveTail) { this.debouncedDidChangeSelectedItem(); }
    return etch.update(this);
  }

  selectNext(preserveTail = false) {
    this.selection.selectNextItem(preserveTail);
    this.selection.coalesce();
    if (!preserveTail) { this.debouncedDidChangeSelectedItem(); }
    return etch.update(this);
  }

  selectAll() {
    this.selection.selectAllItems();
    this.selection.coalesce();
    return etch.update(this);
  }

  selectFirst(preserveTail = false) {
    this.selection.selectFirstItem(preserveTail);
    this.selection.coalesce();
    if (!preserveTail) { this.debouncedDidChangeSelectedItem(); }
    return etch.update(this);
  }

  selectLast(preserveTail = false) {
    this.selection.selectLastItem(preserveTail);
    this.selection.coalesce();
    if (!preserveTail) { this.debouncedDidChangeSelectedItem(); }
    return etch.update(this);
  }

  writeAfterUpdate() {
    const headItem = this.selection.getHeadItem();
    if (headItem) { this.listElementsByItem.get(headItem).scrollIntoViewIfNeeded(); }
  }

  didChangeSelectedItem() {
    const selectedItem = this.selection.getHeadItem();
    if (!this.isFocused() || !selectedItem) { return; }

    if (this.selection.getActiveListKey() === 'conflicts') {
      if (this.props.didSelectMergeConflictFile) {
        this.props.didSelectMergeConflictFile(selectedItem.filePath);
      }
    } else {
      if (this.props.didSelectFilePath) {
        const amending = this.props.isAmending && this.selection.getActiveListKey() === 'staged';
        this.props.didSelectFilePath(
          selectedItem.filePath,
          this.selection.getActiveListKey(),
          {amending, activate: true},
        );
      }
    }
  }

  async mousedownOnItem(event, item) {
    if (event.detail >= 2) {
      if (this.selection.listKeyForItem(item) === 'staged') {
        await this.props.unstageFiles([item.filePath]);
      } else {
        await this.props.stageFiles([item.filePath]);
      }
    } else {
      if (event.ctrlKey || event.metaKey) {
        this.selection.addOrSubtractSelection(item);
      } else {
        this.selection.selectItem(item, event.shiftKey);
      }
      await etch.update(this);
      this.mouseSelectionInProgress = true;
    }
  }

  mousemoveOnItem(event, item) {
    if (this.mouseSelectionInProgress) {
      this.selection.selectItem(item, true);
      return etch.update(this);
    } else {
      return Promise.resolve();
    }
  }

  mouseup() {
    if (this.mouseSelectionInProgress) {
      this.mouseSelectionInProgress = false;
      this.selection.coalesce();
      this.didChangeSelectedItem();
    }
  }

  render() {
    const selectedItems = this.selection.getSelectedItems();

    return (
      <div
        className={`git-StagingView ${this.selection.getActiveListKey()}-changes-focused`}
        style={{width: 200}}
        tabIndex="-1">
        <div className={`git-StagingView-group git-UnstagedChanges ${this.getFocusClass('unstaged')}`}>

            Unstaged Changes

            {
              this.props.unstagedChanges.map(filePatch => (
                <FilePatchListItemView
                  key={filePatch.filePath}
                  registerItemElement={this.registerItemElement}
                  filePatch={filePatch}
                  onmousedown={event => this.mousedownOnItem(event, filePatch)}
                  onmousemove={event => this.mousemoveOnItem(event, filePatch)}
                  selected={selectedItems.has(filePatch)}
                />
              ))
            }

        { this.renderMergeConflicts() }
        <div className={`git-StagingView-group git-StagedChanges ${this.getFocusClass('staged')}`} >

              Staged Changes
              {
                this.props.isAmending
                  ? ` (amending ${shortenSha(this.props.lastCommit.sha)})`
                  : ''
              }

            {
              this.props.stagedChanges.map(filePatch => (
                <FilePatchListItemView
                  key={filePatch.filePath}
                  filePatch={filePatch}
                  registerItemElement={this.registerItemElement}
                  onmousedown={event => this.mousedownOnItem(event, filePatch)}
                  onmousemove={event => this.mousemoveOnItem(event, filePatch)}
                  selected={selectedItems.has(filePatch)}
                />
              ))
            }

    );
  }

  renderMergeConflicts() {
    const mergeConflicts = this.props.mergeConflicts;

    if (mergeConflicts && mergeConflicts.length > 0) {
      const selectedItems = this.selection.getSelectedItems();
      return (
        <div className={`git-StagingView-group git-MergeConflictPaths ${this.getFocusClass('conflicts')}`}>

            Merge Conflicts

            {
              mergeConflicts.map(mergeConflict => (
                <MergeConflictListItemView
                  key={mergeConflict.filePath}
                  mergeConflict={mergeConflict}
                  registerItemElement={this.registerItemElement}
                  onmousedown={event => this.mousedownOnItem(event, mergeConflict)}
                  onmousemove={event => this.mousemoveOnItem(event, mergeConflict)}
                  selected={selectedItems.has(mergeConflict)}
                />
              ))
            }

      );
    } else {
      return ;
    }
  }

  getFocusClass(listKey) {
    return this.selection.getActiveListKey() === listKey ? 'is-focused' : '';
  }

  registerItemElement(item, element) {
    this.listElementsByItem.set(item, element);
  }

  destroy() {
    this.subscriptions.dispose();
    etch.destroy(this);
  }

  focus() {
    this.element.focus();
  }

  isFocused() {
    return document.activeElement === this.element;
  }
}
<commit_msg>Fix logic for selecting single/multiple items in StagingView<commit_after>/** @babel */
/** @jsx etch.dom */
/* eslint react/no-unknown-property: "off" */

import etch from 'etch';
import {Disposable, CompositeDisposable} from 'atom';

import FilePatchListItemView from './file-patch-list-item-view';
import MergeConflictListItemView from './merge-conflict-list-item-view';
import CompositeListSelection from './composite-list-selection';
import {shortenSha} from '../helpers';

const debounce = (fn, wait) => {
  let timeout;
  return (...args) => {
    return new Promise(resolve => {
      clearTimeout(timeout);
      timeout = setTimeout(() => {
        resolve(fn(...args));
      }, wait);
    });
  };
};

export default class StagingView {
  constructor(props) {
    this.props = props;
    atom.config.observe('github.keyboardNavigationDelay', value => {
      if (value === 0) {
        this.debouncedDidChangeSelectedItem = this.didChangeSelectedItems.bind(this);
      } else {
        this.debouncedDidChangeSelectedItem = debounce(this.didChangeSelectedItems.bind(this), value);
      }
    });
    this.mouseSelectionInProgress = false;
    this.listElementsByItem = new WeakMap();
    this.registerItemElement = this.registerItemElement.bind(this);
    this.mousedownOnItem = this.mousedownOnItem.bind(this);
    this.mousemoveOnItem = this.mousemoveOnItem.bind(this);
    this.mouseup = this.mouseup.bind(this);
    this.selection = new CompositeListSelection({
      listsByKey: {
        unstaged: this.props.unstagedChanges,
        conflicts: this.props.mergeConflicts || [],
        staged: this.props.stagedChanges,
      },
      idForItem: item => item.filePath,
    });
    etch.initialize(this);

    this.subscriptions = new CompositeDisposable();
    this.subscriptions.add(atom.commands.add(this.element, {
      'core:move-up': () => this.selectPrevious(),
      'core:move-down': () => this.selectNext(),
      'core:select-up': () => this.selectPrevious(true),
      'core:select-down': () => this.selectNext(true),
      'core:select-all': () => this.selectAll(),
      'core:move-to-top': () => this.selectFirst(),
      'core:move-to-bottom': () => this.selectLast(),
      'core:select-to-top': () => this.selectFirst(true),
      'core:select-to-bottom': () => this.selectLast(true),
      'core:confirm': () => this.confirmSelectedItems(),
      'git:activate-next-list': () => this.activateNextList(),
      'git:activate-previous-list': () => this.activatePreviousList(),
      'git:focus-diff-view': () => this.props.focusFilePatchView(),
    }));
    window.addEventListener('mouseup', this.mouseup);
    this.subscriptions.add(new Disposable(() => window.removeEventListener('mouseup', this.mouseup)));
  }

  update(props) {
    this.props = props;
    this.selection.updateLists({
      unstaged: this.props.unstagedChanges,
      conflicts: this.props.mergeConflicts || [],
      staged: this.props.stagedChanges,
    });
    return etch.update(this);
  }

  activateNextList() {
    this.selection.activateNextSelection();
    return etch.update(this);
  }

  activatePreviousList() {
    this.selection.activatePreviousSelection();
    return etch.update(this);
  }

  confirmSelectedItems() {
    const itemPaths = Array.from(this.selection.getSelectedItems()).map(item => item.filePath);
    if (this.selection.getActiveListKey() === 'staged') {
      return this.props.unstageFiles(itemPaths);
    } else {
      return this.props.stageFiles(itemPaths);
    }
  }

  selectPrevious(preserveTail = false) {
    this.selection.selectPreviousItem(preserveTail);
    this.selection.coalesce();
    if (!preserveTail) { this.debouncedDidChangeSelectedItem(); }
    return etch.update(this);
  }

  selectNext(preserveTail = false) {
    this.selection.selectNextItem(preserveTail);
    this.selection.coalesce();
    if (!preserveTail) { this.debouncedDidChangeSelectedItem(); }
    return etch.update(this);
  }

  selectAll() {
    this.selection.selectAllItems();
    this.selection.coalesce();
    return etch.update(this);
  }

  selectFirst(preserveTail = false) {
    this.selection.selectFirstItem(preserveTail);
    this.selection.coalesce();
    if (!preserveTail) { this.debouncedDidChangeSelectedItem(); }
    return etch.update(this);
  }

  selectLast(preserveTail = false) {
    this.selection.selectLastItem(preserveTail);
    this.selection.coalesce();
    if (!preserveTail) { this.debouncedDidChangeSelectedItem(); }
    return etch.update(this);
  }

  writeAfterUpdate() {
    const headItem = this.selection.getHeadItem();
    if (headItem) { this.listElementsByItem.get(headItem).scrollIntoViewIfNeeded(); }
  }

  didChangeSelectedItems() {
    const selectedItems = Array.from(this.selection.getSelectedItems());
    if (!this.isFocused() || !selectedItems.length) { return; }

    if (selectedItems.length === 1) {
      this.didSelectSingleItem(selectedItems[0]);
    }
  }

  didSelectSingleItem(selectedItem) {
    if (this.selection.getActiveListKey() === 'conflicts') {
      if (this.props.didSelectMergeConflictFile) {
        this.props.didSelectMergeConflictFile(selectedItem.filePath);
      }
    } else {
      if (this.props.didSelectFilePath) {
        const amending = this.props.isAmending && this.selection.getActiveListKey() === 'staged';
        this.props.didSelectFilePath(
          selectedItem.filePath,
          this.selection.getActiveListKey(),
          {amending, activate: true},
        );
      }
    }
  }

  async mousedownOnItem(event, item) {
    if (event.detail >= 2) {
      if (this.selection.listKeyForItem(item) === 'staged') {
        await this.props.unstageFiles([item.filePath]);
      } else {
        await this.props.stageFiles([item.filePath]);
      }
    } else {
      if (event.ctrlKey || event.metaKey) {
        this.selection.addOrSubtractSelection(item);
      } else {
        this.selection.selectItem(item, event.shiftKey);
      }
      await etch.update(this);
      this.mouseSelectionInProgress = true;
    }
  }

  mousemoveOnItem(event, item) {
    if (this.mouseSelectionInProgress) {
      this.selection.selectItem(item, true);
      return etch.update(this);
    } else {
      return Promise.resolve();
    }
  }

  mouseup() {
    if (this.mouseSelectionInProgress) {
      this.mouseSelectionInProgress = false;
      this.selection.coalesce();
      this.didChangeSelectedItems();
    }
  }

  render() {
    const selectedItems = this.selection.getSelectedItems();

    return (
      <div
        className={`git-StagingView ${this.selection.getActiveListKey()}-changes-focused`}
        style={{width: 200}}
        tabIndex="-1">
        <div className={`git-StagingView-group git-UnstagedChanges ${this.getFocusClass('unstaged')}`}>

            Unstaged Changes

            {
              this.props.unstagedChanges.map(filePatch => (
                <FilePatchListItemView
                  key={filePatch.filePath}
                  registerItemElement={this.registerItemElement}
                  filePatch={filePatch}
                  onmousedown={event => this.mousedownOnItem(event, filePatch)}
                  onmousemove={event => this.mousemoveOnItem(event, filePatch)}
                  selected={selectedItems.has(filePatch)}
                />
              ))
            }

        { this.renderMergeConflicts() }
        <div className={`git-StagingView-group git-StagedChanges ${this.getFocusClass('staged')}`} >

              Staged Changes
              {
                this.props.isAmending
                  ? ` (amending ${shortenSha(this.props.lastCommit.sha)})`
                  : ''
              }

            {
              this.props.stagedChanges.map(filePatch => (
                <FilePatchListItemView
                  key={filePatch.filePath}
                  filePatch={filePatch}
                  registerItemElement={this.registerItemElement}
                  onmousedown={event => this.mousedownOnItem(event, filePatch)}
                  onmousemove={event => this.mousemoveOnItem(event, filePatch)}
                  selected={selectedItems.has(filePatch)}
                />
              ))
            }

    );
  }

  renderMergeConflicts() {
    const mergeConflicts = this.props.mergeConflicts;

    if (mergeConflicts && mergeConflicts.length > 0) {
      const selectedItems = this.selection.getSelectedItems();
      return (
        <div className={`git-StagingView-group git-MergeConflictPaths ${this.getFocusClass('conflicts')}`}>

            Merge Conflicts

            {
              mergeConflicts.map(mergeConflict => (
                <MergeConflictListItemView
                  key={mergeConflict.filePath}
                  mergeConflict={mergeConflict}
                  registerItemElement={this.registerItemElement}
                  onmousedown={event => this.mousedownOnItem(event, mergeConflict)}
                  onmousemove={event => this.mousemoveOnItem(event, mergeConflict)}
                  selected={selectedItems.has(mergeConflict)}
                />
              ))
            }

      );
    } else {
      return ;
    }
  }

  getFocusClass(listKey) {
    return this.selection.getActiveListKey() === listKey ? 'is-focused' : '';
  }

  registerItemElement(item, element) {
    this.listElementsByItem.set(item, element);
  }

  destroy() {
    this.subscriptions.dispose();
    etch.destroy(this);
  }

  focus() {
    this.element.focus();
  }

  isFocused() {
    return document.activeElement === this.element;
  }
}
<|endoftext|>


<commit_before>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return var move; move || 'getInput()';
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return var move; move || 'randomPlay()';
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
    /* YOUR CODE HERE */
    return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    /* YOUR CODE HERE */
    return [playerWins, computerWins];
}

<commit_msg>Made chapter 4 changes to app/js/rockpaperscissors.js file<commit_after>////////////////////////////////////////////////
/*   Provided Code - Please Don't Edit   */
////////////////////////////////////////////////
'use strict';

function getInput() {
    console.log("Please choose either 'rock', 'paper', or 'scissors'.")
    return prompt();
}
function randomPlay() {
    var randomNumber = Math.random();
    if (randomNumber < 0.33) {
        return "rock";
    } else if (randomNumber < 0.66) {
        return "paper";
    } else {
        return "scissors";
    }
}
////////////////////////////////////////////////
/*           Write Your Code Below            */
////////////////////////////////////////////////

function getPlayerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `getInput()`.
    return var move; move || 'getInput()';
}

function getComputerMove(move) {
    // Write an expression that operates on a variable called `move`
    // If a `move` has a value, your expression should evaluate to that value.
    // However, if `move` is not specified / is null, your expression should equal `randomPlay()`.
    return var move; move || 'randomPlay()';
}

function getWinner(playerMove,computerMove) {
    var winner;
    // Write code that will set winner to either 'player', 'computer', or 'tie' based on the values of playerMove and computerMove.
    // Assume that the only values playerMove and computerMove can have are 'rock', 'paper', and 'scissors'.
    // The rules of the game are that 'rock' beats 'scissors', 'scissors' beats 'paper', and 'paper' beats 'rock'.
  if (computerMove === 'rock' && playerMove === 'scissors') {
    winner = 'computer';
} else if (computerMove === 'scissors' && playerMove === 'paper') {
    winner = 'computer';
} else if (computerMove === 'paper' && playerMove === 'rock') {
    winner = 'computer';
} else if (computerMove === 'scissors' && playerMove === ' rock') {
    winner = 'player';
} else if (computerMove === 'paper' && playerMove === 'scissors') {
    winner = 'player';
} else if (computerMove === 'rock' && playerMove === 'paper') {
    winner = 'player';
}  else if (computerMove === playerMove) {
        winner = 'tie';
    }    return winner;
}

function playToFive() {
    console.log("Let's play Rock, Paper, Scissors");
    var playerWins = 0;
    var computerWins = 0;
    // Write code that plays 'Rock, Paper, Scissors' until either the player or the computer has won five times.
    /* YOUR CODE HERE */
    return [playerWins, computerWins];
}

<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash'),
    async = require('async'),
    cloneDeep = require('clone'),
    config = require('./config'),
    ConfigVersion = require('./models/config_version'),
    DnsResolver = require('./config_reloader/dns_resolver').DnsResolver,
    events = require('events'),
    exec = require('child_process').exec,
    fs = require('fs'),
    handlebars = require('handlebars'),
    logger = require('./logger'),
    mongoConnect = require('./mongo_connect'),
    path = require('path'),
    traverse = require('traverse'),
    util = require('util');

process.on('uncaughtException', function(err) {
  console.log(err.stack);
  throw err;
});

var ConfigReloader = function() {
  this.initialize.apply(this, arguments);
};

util.inherits(ConfigReloader, events.EventEmitter);
_.extend(ConfigReloader.prototype, {
  initialize: function(readyCallback) {
    var templatePath = path.resolve(__dirname, '../templates/nginx.hbs');
    var templateContent = fs.readFileSync(templatePath);
    this.nginxTemplate = handlebars.compile(templateContent.toString());

    if(readyCallback) {
      this.once('reloaded', readyCallback);
    }

    async.parallel([
      this.connectMongo.bind(this),
      this.setupDnsResolver.bind(this),
    ], this.handleStartup.bind(this));
  },

  connectMongo: function(asyncReadyCallback) {
    mongoConnect(asyncReadyCallback);
  },

  setupDnsResolver: function(asyncReadyCallback) {
    this.resolver = new DnsResolver(this, asyncReadyCallback);
  },

  handleStartup: function(error) {
    if(error) {
      logger.error('Config reloader startup error: ', error);
      process.exit(1);
      return false;
    }

    // Force a reload on initial boot (in case internal changes have been made
    // that would affect the output even if the configuration values haven't
    // changed).
    this.reload({ force: true });
  },

  reload: function(options) {
    ConfigVersion
      .find()
      .sort({ version: -1 })
      .limit(1)
      .exec(this.handleFetchConfigVersion.bind(this, options));
  },

  handleFetchConfigVersion: function(options, error, configVersions) {
    if(configVersions) {
      this.lastConfig = configVersions[0];
    }

    this.apis = [];
    if(config.getOriginal('apis')) {
      this.apis = this.apis.concat(config.getOriginal('apis'));
    }

    if(this.lastConfig && this.lastConfig.config.apis) {
      this.apis = this.apis.concat(this.lastConfig.config.apis);
    }

    var lastId = null;
    if(this.lastConfig && this.lastConfig._id) {
      lastId = this.lastConfig._id.toHexString();
    }

    var activeId = config.get('version_id');

    if((options && options.force) || (this.lastConfig && lastId !== activeId)) {
      logger.info('Writing new config...');
      this.writeConfigs();
    } else {
      this.poll();
    }
  },

  writeConfigs: function() {
    // Write nginx config's first.
    async.series([
      this.resolveHosts.bind(this),
      this.writeNginxConfig.bind(this),
      this.writeGatekeeperConfig.bind(this),
    ], this.handleWriteConfigs.bind(this));
  },

  resolveHosts: function(writeConfigsCallback) {
    logger.info('Resolving all hosts..');
    this.resolver.resolveAllHosts(this.handleResolveHosts.bind(this, writeConfigsCallback));
  },

  handleResolveHosts: function(writeConfigsCallback, error) {
    logger.info('Handle resolving all hosts..');
    writeConfigsCallback(error);

    // After resolving all the hosts, listen for one-off DNS changes for hosts
    // and re-write the nginx config file as needed.
    this.resolver.on('hostChanged', function() {
      if(this.hostChangedRestart) {
        logger.info('IP changes - restart already scheduled');
      } else {
        var restartIn = 0;

        // Prevent a problematic host from constantly restarting the server in
        // quick succession.
        if(this.restartedRecently) {
          restartIn = 15 * 60 * 1000; // 15 minutes
        }

        logger.info('IP changes - scheduling restart in ' + restartIn + 'ms');
        this.hostChangedRestart = setTimeout(function() {
          logger.info('IP changes - restarting now');
          this.writeNginxConfig.bind(this);
          this.hostChangedRestart = null;

          this.restartedRecently = true
          setTimeout(function() {
            this.restartedRecently = false
          }.bind(this), 15 * 60 * 1000);
        }.bind(this), restartIn);
      }
    }.bind(this));
  },

  writeNginxConfig: function(writeConfigsCallback) {
    logger.info('Writing nginx config...');

    var apis = _.reject(cloneDeep(this.apis), function(api) {
      return (!api.servers || api.servers.length === 0);
    });

    var frontendHosts = _.reject(_.uniq(_.pluck(apis, 'frontend_host')), function(host) {
      return !host;
    });

    apis.forEach(function(api) {
      if(api.balance_algorithm === 'least_conn' || api.balance_algorithm === 'ip_hash') {
        api.defaultBalance = false;
      } else {
        api.defaultBalance = true;
      }

      api.servers.forEach(function(server) {
        server.ip = this.resolver.getIp(server.host);
      }.bind(this));
    }.bind(this));

    var newContent = this.nginxTemplate({
      logDir: config.logDir,
      hosts: frontendHosts,
      apis: apis,
    });

    var nginxPath = path.join(config.configDir, 'nginx.conf');

    var write = function() {
      fs.writeFile(nginxPath, newContent, function(error) {
        if(error) {
          logger.error('Error writing nginx config: ', error);
          if(writeConfigsCallback) {
            writeConfigsCallback(error);
          }

          return false;
        }

        logger.info('Nginx config written...');

        this.emit('nginx');

        this.reloadNginx(writeConfigsCallback);
      }.bind(this));
    }.bind(this);

    fs.exists(nginxPath, function(exists) {
      if(exists) {
        fs.readFile(nginxPath, function(error, data) {
          var oldContent = data.toString();
          if(oldContent === newContent) {
            logger.info('Nginx config already up-to-date - skipping...');

            if(writeConfigsCallback) {
              writeConfigsCallback(null);
            }
          } else {
            write();
          }
        });
      } else {
        write();
      }
    });
  },

  reloadNginx: function(writeConfigsCallback) {
    logger.info('Reloading nginx...');
    exec('sudo /etc/init.d/nginx configtest && sudo /etc/init.d/nginx reload', function(error, stdout, stderr) {
      if(error) {
        logger.error('Error reloading nginx: ', error, stderr, stdout);
      }

      logger.info('Nginx reloaded... ', stdout + ' ' + stderr);

      if(writeConfigsCallback) {
        writeConfigsCallback(null);
      }
    });
  },

  writeGatekeeperConfig: function(writeConfigsCallback) {
    logger.info('Writing gatekeeper config...');

    config.reset({ quiet: true });

    if(this.lastConfig) {
      var values = cloneDeep(this.lastConfig.config);
      traverse(values).forEach(function(value) {
        if(value && value._bsontype && value._bsontype === 'ObjectID') {
          this.update(value.toHexString());
        }
      });

      _.extend(values, {
        version_id: this.lastConfig._id.toHexString(),
        version: this.lastConfig.version,
      });

      config.updateRuntime({ apiUmbrella: values }, { quiet: true });
    } else {
      logger.info('No gatekeeper config changes found - reseting...');
    }

    config.saveRuntime(function(error) {
      if(error) {
        logger.error('Error writing gatekeeper config: ', error);
        writeConfigsCallback(error);
        return false;
      }

      logger.info('Gatekeeper config written...');
      writeConfigsCallback(null);
    });
  },

  handleWriteConfigs: function(error) {
    if(error) {
      logger.error('Error writing configs: ', error);
    } else {
      logger.info('Config files written...');
      this.emit('reloaded');
    }

    this.poll();
  },

  // FIXME: We're polling for configuration changes from mongoid right now. Not
  // polling would obviously be better. Using something like Zookeeper might be
  // appropriate to better ensure all nodes are running the same config
  // versions at the same time. We could also use Zookeeper to store the active
  // config version on each node so the web admin could more easily keep track
  // of when publishing is complete to all the active nodes.
  poll: function() {
    this.pollTimeout = setTimeout(this.reload.bind(this), 500);
  },

  close: function(callback) {
    if(this.pollTimeout) {
      clearTimeout(this.pollTimeout);
    }

    if(mongoose.connection) {
      mongoose.connection.close();
    }

    if(this.resolver) {
      this.resolver.close();
    }

    if(callback) {
      callback(null);
    }
  },
});

module.exports.ConfigReloader = ConfigReloader;
<commit_msg>Fix missing semi-colons.<commit_after>'use strict';

var _ = require('lodash'),
    async = require('async'),
    cloneDeep = require('clone'),
    config = require('./config'),
    ConfigVersion = require('./models/config_version'),
    DnsResolver = require('./config_reloader/dns_resolver').DnsResolver,
    events = require('events'),
    exec = require('child_process').exec,
    fs = require('fs'),
    handlebars = require('handlebars'),
    logger = require('./logger'),
    mongoConnect = require('./mongo_connect'),
    path = require('path'),
    traverse = require('traverse'),
    util = require('util');

process.on('uncaughtException', function(err) {
  console.log(err.stack);
  throw err;
});

var ConfigReloader = function() {
  this.initialize.apply(this, arguments);
};

util.inherits(ConfigReloader, events.EventEmitter);
_.extend(ConfigReloader.prototype, {
  initialize: function(readyCallback) {
    var templatePath = path.resolve(__dirname, '../templates/nginx.hbs');
    var templateContent = fs.readFileSync(templatePath);
    this.nginxTemplate = handlebars.compile(templateContent.toString());

    if(readyCallback) {
      this.once('reloaded', readyCallback);
    }

    async.parallel([
      this.connectMongo.bind(this),
      this.setupDnsResolver.bind(this),
    ], this.handleStartup.bind(this));
  },

  connectMongo: function(asyncReadyCallback) {
    mongoConnect(asyncReadyCallback);
  },

  setupDnsResolver: function(asyncReadyCallback) {
    this.resolver = new DnsResolver(this, asyncReadyCallback);
  },

  handleStartup: function(error) {
    if(error) {
      logger.error('Config reloader startup error: ', error);
      process.exit(1);
      return false;
    }

    // Force a reload on initial boot (in case internal changes have been made
    // that would affect the output even if the configuration values haven't
    // changed).
    this.reload({ force: true });
  },

  reload: function(options) {
    ConfigVersion
      .find()
      .sort({ version: -1 })
      .limit(1)
      .exec(this.handleFetchConfigVersion.bind(this, options));
  },

  handleFetchConfigVersion: function(options, error, configVersions) {
    if(configVersions) {
      this.lastConfig = configVersions[0];
    }

    this.apis = [];
    if(config.getOriginal('apis')) {
      this.apis = this.apis.concat(config.getOriginal('apis'));
    }

    if(this.lastConfig && this.lastConfig.config.apis) {
      this.apis = this.apis.concat(this.lastConfig.config.apis);
    }

    var lastId = null;
    if(this.lastConfig && this.lastConfig._id) {
      lastId = this.lastConfig._id.toHexString();
    }

    var activeId = config.get('version_id');

    if((options && options.force) || (this.lastConfig && lastId !== activeId)) {
      logger.info('Writing new config...');
      this.writeConfigs();
    } else {
      this.poll();
    }
  },

  writeConfigs: function() {
    // Write nginx config's first.
    async.series([
      this.resolveHosts.bind(this),
      this.writeNginxConfig.bind(this),
      this.writeGatekeeperConfig.bind(this),
    ], this.handleWriteConfigs.bind(this));
  },

  resolveHosts: function(writeConfigsCallback) {
    logger.info('Resolving all hosts..');
    this.resolver.resolveAllHosts(this.handleResolveHosts.bind(this, writeConfigsCallback));
  },

  handleResolveHosts: function(writeConfigsCallback, error) {
    logger.info('Handle resolving all hosts..');
    writeConfigsCallback(error);

    // After resolving all the hosts, listen for one-off DNS changes for hosts
    // and re-write the nginx config file as needed.
    this.resolver.on('hostChanged', function() {
      if(this.hostChangedRestart) {
        logger.info('IP changes - restart already scheduled');
      } else {
        var restartIn = 0;

        // Prevent a problematic host from constantly restarting the server in
        // quick succession.
        if(this.restartedRecently) {
          restartIn = 15 * 60 * 1000; // 15 minutes
        }

        logger.info('IP changes - scheduling restart in ' + restartIn + 'ms');
        this.hostChangedRestart = setTimeout(function() {
          logger.info('IP changes - restarting now');
          this.writeNginxConfig.bind(this);
          this.hostChangedRestart = null;

          this.restartedRecently = true;
          setTimeout(function() {
            this.restartedRecently = false;
          }.bind(this), 15 * 60 * 1000);
        }.bind(this), restartIn);
      }
    }.bind(this));
  },

  writeNginxConfig: function(writeConfigsCallback) {
    logger.info('Writing nginx config...');

    var apis = _.reject(cloneDeep(this.apis), function(api) {
      return (!api.servers || api.servers.length === 0);
    });

    var frontendHosts = _.reject(_.uniq(_.pluck(apis, 'frontend_host')), function(host) {
      return !host;
    });

    apis.forEach(function(api) {
      if(api.balance_algorithm === 'least_conn' || api.balance_algorithm === 'ip_hash') {
        api.defaultBalance = false;
      } else {
        api.defaultBalance = true;
      }

      api.servers.forEach(function(server) {
        server.ip = this.resolver.getIp(server.host);
      }.bind(this));
    }.bind(this));

    var newContent = this.nginxTemplate({
      logDir: config.logDir,
      hosts: frontendHosts,
      apis: apis,
    });

    var nginxPath = path.join(config.configDir, 'nginx.conf');

    var write = function() {
      fs.writeFile(nginxPath, newContent, function(error) {
        if(error) {
          logger.error('Error writing nginx config: ', error);
          if(writeConfigsCallback) {
            writeConfigsCallback(error);
          }

          return false;
        }

        logger.info('Nginx config written...');

        this.emit('nginx');

        this.reloadNginx(writeConfigsCallback);
      }.bind(this));
    }.bind(this);

    fs.exists(nginxPath, function(exists) {
      if(exists) {
        fs.readFile(nginxPath, function(error, data) {
          var oldContent = data.toString();
          if(oldContent === newContent) {
            logger.info('Nginx config already up-to-date - skipping...');

            if(writeConfigsCallback) {
              writeConfigsCallback(null);
            }
          } else {
            write();
          }
        });
      } else {
        write();
      }
    });
  },

  reloadNginx: function(writeConfigsCallback) {
    logger.info('Reloading nginx...');
    exec('sudo /etc/init.d/nginx configtest && sudo /etc/init.d/nginx reload', function(error, stdout, stderr) {
      if(error) {
        logger.error('Error reloading nginx: ', error, stderr, stdout);
      }

      logger.info('Nginx reloaded... ', stdout + ' ' + stderr);

      if(writeConfigsCallback) {
        writeConfigsCallback(null);
      }
    });
  },

  writeGatekeeperConfig: function(writeConfigsCallback) {
    logger.info('Writing gatekeeper config...');

    config.reset({ quiet: true });

    if(this.lastConfig) {
      var values = cloneDeep(this.lastConfig.config);
      traverse(values).forEach(function(value) {
        if(value && value._bsontype && value._bsontype === 'ObjectID') {
          this.update(value.toHexString());
        }
      });

      _.extend(values, {
        version_id: this.lastConfig._id.toHexString(),
        version: this.lastConfig.version,
      });

      config.updateRuntime({ apiUmbrella: values }, { quiet: true });
    } else {
      logger.info('No gatekeeper config changes found - reseting...');
    }

    config.saveRuntime(function(error) {
      if(error) {
        logger.error('Error writing gatekeeper config: ', error);
        writeConfigsCallback(error);
        return false;
      }

      logger.info('Gatekeeper config written...');
      writeConfigsCallback(null);
    });
  },

  handleWriteConfigs: function(error) {
    if(error) {
      logger.error('Error writing configs: ', error);
    } else {
      logger.info('Config files written...');
      this.emit('reloaded');
    }

    this.poll();
  },

  // FIXME: We're polling for configuration changes from mongoid right now. Not
  // polling would obviously be better. Using something like Zookeeper might be
  // appropriate to better ensure all nodes are running the same config
  // versions at the same time. We could also use Zookeeper to store the active
  // config version on each node so the web admin could more easily keep track
  // of when publishing is complete to all the active nodes.
  poll: function() {
    this.pollTimeout = setTimeout(this.reload.bind(this), 500);
  },

  close: function(callback) {
    if(this.pollTimeout) {
      clearTimeout(this.pollTimeout);
    }

    if(mongoose.connection) {
      mongoose.connection.close();
    }

    if(this.resolver) {
      this.resolver.close();
    }

    if(callback) {
      callback(null);
    }
  },
});

module.exports.ConfigReloader = ConfigReloader;
<|endoftext|>


<commit_before>define(["helper/util", "handlebars", "jquery", "can"], function (util, Handlebars, $, can) {
    "use strict";

    var log = util.log.bind(util);

    var App = {

        init() {
            log("spacedRep initializing...");

            // Observable object
            var person = new can.List(["Icíar", "González"]);

            var info = can.compute(function () {
                return person.join(" ") + " rules!";
            });

            log(info());

            info.bind("change", function (ev, newVal) {
                log("Cabió!: " + newVal);
            });

            person.pop();

            this.domCache();
            this.render();
        },

        domCache() {
            this.loginArea = $(".login-tag");
        },

        render() {
            this.loginArea.html(Handlebars.compile($("#login-template").html()));
        }
    };

    // Se exporta la funcionalidad que se desea exponer
    return App;

}); // Fin requirejs define
<commit_msg>Just play with canjs (I need share changes with my work place)<commit_after>define(["helper/util", "handlebars", "jquery", "can"], function (util, Handlebars, $, can) {
    "use strict";

    var log = util.log.bind(util);

    var App = {

        init() {
            log("spacedRep initializing...");

            // -------

            var Person = can.Map.extend({
                define: {
                    fullName: {
                        get() {
                            return this.attr("first") + " " + this.attr("last");
                        }
                    }
                }
            });

            var person = new Person({
                first: "Icíar",
                last: "González Izquierdo"
            });

            log(person.attr("fullName"));

            person.bind("fullName", function (ev, newVal) {
                log("Cambio: " + newVal);
            });

            person.attr("first", "Ramiya");

            // -------

            this.domCache();
            this.render();
        },

        domCache() {
            this.loginArea = $(".login-tag");
        },

        render() {
            this.loginArea.html(Handlebars.compile($("#login-template").html()));
        }
    };

    // Se exporta la funcionalidad que se desea exponer
    return App;

}); // Fin requirejs define
<|endoftext|>


<commit_before><commit_msg>adds d3-array and d3-collection to available CMS libs<commit_after><|endoftext|>