<commit_before>/**
 * Copyright (c) 2016-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @flow
 */

var bl = require('bl');
var config = require('./config');
var express = require('express');
var fs = require('fs');
var mentionBot = require('./mention-bot.js');
var messageGenerator = require('./message.js');
var util = require('util');
var schedule = require('./schedule.js');

var GitHubApi = require('github');

var CONFIG_PATH = '.mention-bot';

if (!process.env.GITHUB_TOKEN) {
  console.error('The bot was started without a GitHub account to post with.');
  console.error('To get started:');
  console.error('1) Create a new account for the bot');
  console.error('2) Settings > Personal access tokens > Generate new token');
  console.error('3) Only check `public_repo` and click Generate token');
  console.error('4) Run the following command:');
  console.error('GITHUB_TOKEN=insert_token_here npm start');
  console.error('5) Run the following command in another tab:');
  console.error('curl -X POST -d @__tests__/data/23.webhook http://localhost:5000/');
  console.error('6) Check if it has commented here: https://github.com/fbsamples/bot-testing/pull/23');
  process.exit(1);
}

if (!process.env.GITHUB_USER) {
  console.warn(
    'There was no GitHub user detected.',
    'This is fine, but mention-bot won\'t work with private repos.'
  );
  console.warn(
    'To make mention-bot work with private repos, please expose',
    'GITHUB_USER and GITHUB_PASSWORD as environment variables.',
    'The username and password must have access to the private repo',
    'you want to use.'
  );
}

var github = new GitHubApi({
  version: '3.0.0',
  host: config.github.apiHost,
  pathPrefix: config.github.pathPrefix,
  protocol: config.github.protocol,
  port: config.github.port
});

github.authenticate({
  type: 'oauth',
  token: process.env.GITHUB_TOKEN
});

var app = express();

function buildMentionSentence(reviewers) {
  var atReviewers = reviewers.map(function(owner) { return '@' + owner; });

  if (reviewers.length === 1) {
    return atReviewers[0];
  }

  return (
    atReviewers.slice(0, atReviewers.length - 1).join(', ') +
    ' and ' + atReviewers[atReviewers.length - 1]
  );
}

function defaultMessageGenerator(reviewers, pullRequester) {
  return util.format(
    '%s, thanks for your PR! ' +
    'By analyzing the annotation information on this pull request' +
    ', we identified %s to be%s potential reviewer%s',
    pullRequester,
    buildMentionSentence(reviewers),
    reviewers.length > 1 ? '' : ' a',
    reviewers.length > 1 ? 's' : ''
  );
}

function configMessageGenerator(message, reviewers, pullRequester) {
  var withReviewers = message.replace(/@reviewers/g, buildMentionSentence(reviewers));
  return withReviewers.replace(/@pullRequester/g, pullRequester);
}

function getRepoConfig(request) {
  return new Promise(function(resolve, reject) {
    github.repos.getContent(request, function(err, result) {
      if (err) {
        reject(err);
      }
      resolve(result);
    });
  });
}

async function work(body) {
  var data = {};
  try {
    data = JSON.parse(body.toString());
    console.log(data.pull_request.html_url);
  } catch (e) {
    console.error(e);
  }

  // default config
  var repoConfig = {
    maxReviewers: 3,
    numFilesToCheck: 5,
    userBlacklist: [],
    userBlacklistForPR: [],
    userWhitelist: [],
    fileBlacklist: [],
    requiredOrgs: [],
    findPotentialReviewers: true,
    actions: ['opened'],
    skipAlreadyAssignedPR: false,
    skipAlreadyMentionedPR: false,
    delayed: false,
    delayedUntil: '3d',
    assignToReviewer: false,
    skipTitle: '',
    withLabel: '',
    skipCollaboratorPR: false,
  };

  try {
    // request config from repo
    var configRes = await getRepoConfig({
      user: data.repository.owner.login,
      repo: data.repository.name,
      path: CONFIG_PATH,
      ref: data.pull_request.head.ref,
      headers: {
        Accept: 'application/vnd.github.v3.raw'
      }
    });

    repoConfig = {...repoConfig, ...JSON.parse(configRes)};
  } catch (e) {
    console.error(e);
  }

  function isValid(repoConfig, data) {
    if (repoConfig.actions.indexOf(data.action) === -1) {
      console.log(
        'Skipping because action is ' + data.action + '.',
        'We only care about: "' + repoConfig.actions.join("', '") + '"'
      );
      return false;
    }

    if (repoConfig.withLabel && data.label &&
        data.label.name != repoConfig.withLabel) {
      console.log('Skipping because pull request does not have label: ' + repoConfig.withLabel);
      return false;
    }

    if (repoConfig.skipTitle &&
        data.pull_request.title.indexOf(repoConfig.skipTitle) > -1) {
      console.log('Skipping because pull request title contains: ' + repoConfig.skipTitle);
      return false;
    }

    if (repoConfig.skipCollaboratorPR) {
      github.repos.getCollaborator({
        user: data.repository.owner.login, // 'fbsamples'
        repo: data.repository.name, // 'bot-testing'
        collabuser: data.pull_request.user.login
      }, function(err, res){
        if (res && res.meta.status === '204 No Content') {
          console.log('Skipping because pull request is made by collaborator.');
          return false;
        }
      });
    }

    if (repoConfig.skipAlreadyAssignedPR &&
        data.pull_request.assignee &&
        data.pull_request.assignee.login) {
      console.log('Skipping because pull request is already assigned.');
      return false;
    }

    if (process.env.REQUIRED_ORG) {
      if (repoConfig.requiredOrgs.indexOf(process.env.REQUIRED_ORG) === -1) {
        repoConfig.requiredOrgs.push(process.env.REQUIRED_ORG);
      }
    }

    if (repoConfig.userBlacklistForPR.indexOf(data.pull_request.user.login) >= 0) {
      console.log('Skipping because blacklisted user created Pull Request.');
      return false;
    }

    if (repoConfig.skipTitle &&
        data.pull_request.title.indexOf(repoConfig.skipTitle) > -1) {
      console.log('Skipping because pull request title contains: ' + repoConfig.skipTitle);
      return false;
    }

    return true;
  }

  if (!isValid(repoConfig, data)) {
    return;
  }

  var org = null;

  if (data.organization) {
    org = data.organization.login;
  }

  var reviewers = await mentionBot.guessOwnersForPullRequest(
    data.repository.html_url, // 'https://github.com/fbsamples/bot-testing'
    data.pull_request.number, // 23
    data.pull_request.user.login, // 'mention-bot'
    data.pull_request.base.ref, // 'master'
    data.repository.private, //true or false
    org, //the org name of the repo
    repoConfig,
    github
  );

  console.log('Reviewers:', reviewers);

  if (reviewers.length === 0) {
    console.log('Skipping because there are no reviewers found.');
    return;
  }

  var message = null;
  if (repoConfig.message) {
    message = configMessageGenerator(
      repoConfig.message,
      reviewers,
      '@' + data.pull_request.user.login
    );
  } else {
    message = messageGenerator(
      reviewers,
      '@' + data.pull_request.user.login, // pull-requester
      buildMentionSentence,
      defaultMessageGenerator
    );
  }

  function createComment(data, message, reject) {
    github.issues.createComment({
      user: data.repository.owner.login, // 'fbsamples'
      repo: data.repository.name, // 'bot-testing'
      number: data.pull_request.number, // 23
      body: message
    }, function(err) {
      if (err) {
        if (typeof reject === 'function') {
          return reject(err);
        }
      }
    })
  }

  function assignReviewer(data, reviewers, reject) {
    if (!repoConfig.assignToReviewer) {
      return;
    }

    github.issues.edit({
      user: data.repository.owner.login, // 'fbsamples'
      repo: data.repository.name, // 'bot-testing'
      number: data.pull_request.number, // 23
      assignees: reviewers
    }, function(err) {
      if (err) {
        if (typeof reject === 'function') {
          return reject(err);
        }
      }
    });
  }

  function getComments(data, page) {
    return new Promise(function(resolve, reject) {
      github.issues.getComments({
        user: data.repository.owner.login, // 'fbsamples'
        repo: data.repository.name, // 'bot-testing'
        number: data.pull_request.number, // 23
        page: page, // 1
        per_page: 100 // maximum supported
      }, function(err, result) {
        if (err) {
          reject(err);
        }
        resolve(result);
      });
    });
  }

  if (repoConfig.skipAlreadyMentionedPR) {
    var page;
    var comments = [[]];

    for (page = 1; comments.length != 0; ++page) {
      comments = await getComments(data, page);
      if (comments.find(function(comment) {
        return comment.body == message;
      })) {
        console.log('Skipping because there is already existing an exact mention.');
        return;
      }
    }
  }

  if (repoConfig.delayed) {
    schedule.performAt(schedule.parse(repoConfig.delayedUntil), function(resolve, reject) {
      github.pullRequests.get({
        user: data.repository.owner.login,
        repo: data.repository.name,
        number: data.pull_request.number
      }, function(err, currentData) {
        if (err) {
          reject(err);
          return;
        }

        if (!isValid(repoConfig, currentData)) {
          return;
        }

        createComment(currentData, message, reject);
        assignReviewer(currentData, reviewers, reject);
      });
    });
  } else {
    createComment(data, message);
    assignReviewer(data, reviewers);
  }

  return;
};

app.post('/', function(req, res) {
  req.pipe(bl(function(err, body) {
    work(body).then(function() { res.end(); });
  }));
});

app.get('/', function(req, res) {
  res.send(
    'GitHub Mention Bot Active. ' +
    'Go to https://github.com/facebook/mention-bot for more information.'
  );
});

app.set('port', process.env.PORT || 5000);

app.listen(app.get('port'), function() {
  console.log('Listening on port', app.get('port'));
});
<commit_msg>better error logging for 404<commit_after>/**
 * Copyright (c) 2016-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @flow
 */

var bl = require('bl');
var config = require('./config');
var express = require('express');
var fs = require('fs');
var mentionBot = require('./mention-bot.js');
var messageGenerator = require('./message.js');
var util = require('util');
var schedule = require('./schedule.js');

var GitHubApi = require('github');

var CONFIG_PATH = '.mention-bot';

if (!process.env.GITHUB_TOKEN) {
  console.error('The bot was started without a GitHub account to post with.');
  console.error('To get started:');
  console.error('1) Create a new account for the bot');
  console.error('2) Settings > Personal access tokens > Generate new token');
  console.error('3) Only check `public_repo` and click Generate token');
  console.error('4) Run the following command:');
  console.error('GITHUB_TOKEN=insert_token_here npm start');
  console.error('5) Run the following command in another tab:');
  console.error('curl -X POST -d @__tests__/data/23.webhook http://localhost:5000/');
  console.error('6) Check if it has commented here: https://github.com/fbsamples/bot-testing/pull/23');
  process.exit(1);
}

if (!process.env.GITHUB_USER) {
  console.warn(
    'There was no GitHub user detected.',
    'This is fine, but mention-bot won\'t work with private repos.'
  );
  console.warn(
    'To make mention-bot work with private repos, please expose',
    'GITHUB_USER and GITHUB_PASSWORD as environment variables.',
    'The username and password must have access to the private repo',
    'you want to use.'
  );
}

var github = new GitHubApi({
  version: '3.0.0',
  host: config.github.apiHost,
  pathPrefix: config.github.pathPrefix,
  protocol: config.github.protocol,
  port: config.github.port
});

github.authenticate({
  type: 'oauth',
  token: process.env.GITHUB_TOKEN
});

var app = express();

function buildMentionSentence(reviewers) {
  var atReviewers = reviewers.map(function(owner) { return '@' + owner; });

  if (reviewers.length === 1) {
    return atReviewers[0];
  }

  return (
    atReviewers.slice(0, atReviewers.length - 1).join(', ') +
    ' and ' + atReviewers[atReviewers.length - 1]
  );
}

function defaultMessageGenerator(reviewers, pullRequester) {
  return util.format(
    '%s, thanks for your PR! ' +
    'By analyzing the annotation information on this pull request' +
    ', we identified %s to be%s potential reviewer%s',
    pullRequester,
    buildMentionSentence(reviewers),
    reviewers.length > 1 ? '' : ' a',
    reviewers.length > 1 ? 's' : ''
  );
}

function configMessageGenerator(message, reviewers, pullRequester) {
  var withReviewers = message.replace(/@reviewers/g, buildMentionSentence(reviewers));
  return withReviewers.replace(/@pullRequester/g, pullRequester);
}

function getRepoConfig(request) {
  return new Promise(function(resolve, reject) {
    github.repos.getContent(request, function(err, result) {
      if (err) {
        reject(err);
      }
      resolve(result);
    });
  });
}

async function work(body) {
  var data = {};
  try {
    data = JSON.parse(body.toString());
    console.log(data.pull_request.html_url);
  } catch (e) {
    console.error(e);
  }

  // default config
  var repoConfig = {
    maxReviewers: 3,
    numFilesToCheck: 5,
    userBlacklist: [],
    userBlacklistForPR: [],
    userWhitelist: [],
    fileBlacklist: [],
    requiredOrgs: [],
    findPotentialReviewers: true,
    actions: ['opened'],
    skipAlreadyAssignedPR: false,
    skipAlreadyMentionedPR: false,
    delayed: false,
    delayedUntil: '3d',
    assignToReviewer: false,
    skipTitle: '',
    withLabel: '',
    skipCollaboratorPR: false,
  };

  try {
    // request config from repo
    var configRes = await getRepoConfig({
      user: data.repository.owner.login,
      repo: data.repository.name,
      path: CONFIG_PATH,
      ref: data.pull_request.head.ref,
      headers: {
        Accept: 'application/vnd.github.v3.raw'
      }
    });

    repoConfig = {...repoConfig, ...JSON.parse(configRes)};
  } catch (e) {
    if (error.code === 404) {
      console.log('Skipping because the repo is not visible from mention-bot.');
      return;
    }
    console.error(e);
  }

  function isValid(repoConfig, data) {
    if (repoConfig.actions.indexOf(data.action) === -1) {
      console.log(
        'Skipping because action is ' + data.action + '.',
        'We only care about: "' + repoConfig.actions.join("', '") + '"'
      );
      return false;
    }

    if (repoConfig.withLabel && data.label &&
        data.label.name != repoConfig.withLabel) {
      console.log('Skipping because pull request does not have label: ' + repoConfig.withLabel);
      return false;
    }

    if (repoConfig.skipTitle &&
        data.pull_request.title.indexOf(repoConfig.skipTitle) > -1) {
      console.log('Skipping because pull request title contains: ' + repoConfig.skipTitle);
      return false;
    }

    if (repoConfig.skipCollaboratorPR) {
      github.repos.getCollaborator({
        user: data.repository.owner.login, // 'fbsamples'
        repo: data.repository.name, // 'bot-testing'
        collabuser: data.pull_request.user.login
      }, function(err, res){
        if (res && res.meta.status === '204 No Content') {
          console.log('Skipping because pull request is made by collaborator.');
          return false;
        }
      });
    }

    if (repoConfig.skipAlreadyAssignedPR &&
        data.pull_request.assignee &&
        data.pull_request.assignee.login) {
      console.log('Skipping because pull request is already assigned.');
      return false;
    }

    if (process.env.REQUIRED_ORG) {
      if (repoConfig.requiredOrgs.indexOf(process.env.REQUIRED_ORG) === -1) {
        repoConfig.requiredOrgs.push(process.env.REQUIRED_ORG);
      }
    }

    if (repoConfig.userBlacklistForPR.indexOf(data.pull_request.user.login) >= 0) {
      console.log('Skipping because blacklisted user created Pull Request.');
      return false;
    }

    if (repoConfig.skipTitle &&
        data.pull_request.title.indexOf(repoConfig.skipTitle) > -1) {
      console.log('Skipping because pull request title contains: ' + repoConfig.skipTitle);
      return false;
    }

    return true;
  }

  if (!isValid(repoConfig, data)) {
    return;
  }

  var org = null;

  if (data.organization) {
    org = data.organization.login;
  }

  var reviewers = await mentionBot.guessOwnersForPullRequest(
    data.repository.html_url, // 'https://github.com/fbsamples/bot-testing'
    data.pull_request.number, // 23
    data.pull_request.user.login, // 'mention-bot'
    data.pull_request.base.ref, // 'master'
    data.repository.private, //true or false
    org, //the org name of the repo
    repoConfig,
    github
  );

  console.log('Reviewers:', reviewers);

  if (reviewers.length === 0) {
    console.log('Skipping because there are no reviewers found.');
    return;
  }

  var message = null;
  if (repoConfig.message) {
    message = configMessageGenerator(
      repoConfig.message,
      reviewers,
      '@' + data.pull_request.user.login
    );
  } else {
    message = messageGenerator(
      reviewers,
      '@' + data.pull_request.user.login, // pull-requester
      buildMentionSentence,
      defaultMessageGenerator
    );
  }

  function createComment(data, message, reject) {
    github.issues.createComment({
      user: data.repository.owner.login, // 'fbsamples'
      repo: data.repository.name, // 'bot-testing'
      number: data.pull_request.number, // 23
      body: message
    }, function(err) {
      if (err) {
        if (typeof reject === 'function') {
          return reject(err);
        }
      }
    })
  }

  function assignReviewer(data, reviewers, reject) {
    if (!repoConfig.assignToReviewer) {
      return;
    }

    github.issues.edit({
      user: data.repository.owner.login, // 'fbsamples'
      repo: data.repository.name, // 'bot-testing'
      number: data.pull_request.number, // 23
      assignees: reviewers
    }, function(err) {
      if (err) {
        if (typeof reject === 'function') {
          return reject(err);
        }
      }
    });
  }

  function getComments(data, page) {
    return new Promise(function(resolve, reject) {
      github.issues.getComments({
        user: data.repository.owner.login, // 'fbsamples'
        repo: data.repository.name, // 'bot-testing'
        number: data.pull_request.number, // 23
        page: page, // 1
        per_page: 100 // maximum supported
      }, function(err, result) {
        if (err) {
          reject(err);
        }
        resolve(result);
      });
    });
  }

  if (repoConfig.skipAlreadyMentionedPR) {
    var page;
    var comments = [[]];

    for (page = 1; comments.length != 0; ++page) {
      comments = await getComments(data, page);
      if (comments.find(function(comment) {
        return comment.body == message;
      })) {
        console.log('Skipping because there is already existing an exact mention.');
        return;
      }
    }
  }

  if (repoConfig.delayed) {
    schedule.performAt(schedule.parse(repoConfig.delayedUntil), function(resolve, reject) {
      github.pullRequests.get({
        user: data.repository.owner.login,
        repo: data.repository.name,
        number: data.pull_request.number
      }, function(err, currentData) {
        if (err) {
          reject(err);
          return;
        }

        if (!isValid(repoConfig, currentData)) {
          return;
        }

        createComment(currentData, message, reject);
        assignReviewer(currentData, reviewers, reject);
      });
    });
  } else {
    createComment(data, message);
    assignReviewer(data, reviewers);
  }

  return;
};

app.post('/', function(req, res) {
  req.pipe(bl(function(err, body) {
    work(body).then(function() { res.end(); });
  }));
});

app.get('/', function(req, res) {
  res.send(
    'GitHub Mention Bot Active. ' +
    'Go to https://github.com/facebook/mention-bot for more information.'
  );
});

app.set('port', process.env.PORT || 5000);

app.listen(app.get('port'), function() {
  console.log('Listening on port', app.get('port'));
});
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { List, ListItem } from 'material-ui/List';
import Divider from 'material-ui/Divider';
import { Accordion, AccordionItem } from 'react-sanfona';
import './accordian.css';
import Moment from 'moment';
import { Link } from 'react-router-dom';
import CircularProgress from 'material-ui/CircularProgress';
import ProgressLabel from './progressLabelWidget';
import { GridList, GridTile } from 'material-ui/GridList';
import ReactTooltip from 'react-tooltip';
import Slider from 'react-slick';
import _ from 'lodash';
import { StatefulToolTip } from "react-portal-tooltip"

/**
*
* This class the component for rendering the events in the approval page.
*
*/
const pw = 6;
const cw = pw / 2;
const tw = pw;
const styles = {
    root: {
        display: 'flex',
        flexWrap: 'wrap',
        justifyContent: 'space-around',
    },
    gridList: {
        display: 'flex',
        overflowX: 'visible',
        margintop: '0px',
        marginleft: '0px',
    },
    titleStyle: {
        color: 'rgb(0, 188, 212)',
        height: 30
    },
};
class ProgressWidget extends Component {
    constructor(props) {
        super(props);
        this.state = {
            categoryMap: {}
        };
    }
    /**
    * This method gets the list of categories and their progress when the component is mounted.
    */
    componentDidMount = () => {
        this.props.getCategories(this.props.userInfo).then((response, error) => {
            this.props.updateCategoriesList(JSON.parse(response.data));
            let catMap = {};
            this.props.categories.map((event, index) => {
                let key = event.type;
                if (key != '') {
                    if (catMap[key] === undefined) {
                        let catArr = [];
                        catArr.push(this.props.categories[index]);
                        catMap[key] = catArr;
                    } else {
                        let catArr = catMap[key];
                        delete catMap[key];
                        catArr.push(this.props.categories[index]);
                        catMap[key] = catArr;
                    }
                }
            });
            console.log(catMap);
            this.setState({
                categoryMap: catMap
            });
            this.props.getProgressCategoriesList(this.props.userInfo.id).then((response, error) => {
                this.props.updateProgressCategoriesInfo(JSON.parse(response.data));
                console.log(this.props.progressCategories);
            }, (error) => {
                console.log(error);
            });
        });
    }
    /**
    * This method renders the progress bar.
    */
    renderProgressBar = (categoryName, points, allLevels) => {
        if (points > 0) {
            let totalLevels = allLevels.length;
            let maxLevel = allLevels[totalLevels - 1];
            let maxPointsForCategory = maxLevel.pointsEndRange;
            let progress = (points / maxPointsForCategory) * 100;
            let pointProgress = 0;
            let levelProgress = 0;
            let currentLevel = "0";
            let pointsNeededForNextLevel = 0;
            let totalPointsForCurrentLevel = 0;
            let startLevelPoints = 0;
            let endLevelPoints = 0;
            allLevels.map((event, index) => {
                endLevelPoints = event.pointsEndRange;
                if (event.sequence === "1") {
                    startLevelPoints = event.pointsEndRange;
                }
                if (parseInt(points) > parseInt(event.pointsStartRange) && parseInt(points) <= parseInt(event.pointsEndRange)) {
                    currentLevel = event.sequence;
                    pointsNeededForNextLevel = parseInt(event.pointsEndRange) - parseInt(points);
                    totalPointsForCurrentLevel = parseInt(event.pointsEndRange);
                }
                if (parseInt(points) + 1 === parseInt(event.pointsStartRange)) {
                    pointsNeededForNextLevel = parseInt(event.pointsEndRange) - parseInt(points);
                    totalPointsForCurrentLevel = parseInt(event.pointsEndRange);
                }
            });
            if (currentLevel !== "0") {
                pointProgress = 100 - ((pointsNeededForNextLevel / totalPointsForCurrentLevel) * 100);
                if (points >= endLevelPoints) {
                    levelProgress = ((currentLevel) / totalLevels) * 100;
                } else {
                    levelProgress = ((currentLevel - 1) / totalLevels) * 100;
                }
            } else {
                pointProgress = "1";
                levelProgress = "1";
            }
            if (levelProgress === 0) {
                levelProgress = "1";
            }
            let msg = "";
            if (currentLevel === "0") {
                pointsNeededForNextLevel = startLevelPoints;
                msg = "You need " + pointsNeededForNextLevel + " points to reach level " + (parseInt(currentLevel) + 1)
            } else if (pointsNeededForNextLevel <= 0) {
                msg = "You have completed " + "Level " + (parseInt(currentLevel))
            } else {
                msg = "You need " + pointsNeededForNextLevel + " more points to complete level " + (parseInt(currentLevel));
            }
        }
        return (

                {categoryName}

                {console.log({ points })}

        );
    }
    renderProgressCategories = () => {
        let catArr = Object.keys(this.state.categoryMap);
        let progressCat = {};
        let allCat = [];
        let foundProgress1;

        var settings = {
            arrows: true,
            infinite: false,
            speed: 500,
            slidesToShow: 1,
            slidesToScroll: 1,
            centerPadding: '50px'
          };

        return catArr.map((event, index) => {
            let rows = _.chunk(this.state.categoryMap[event], 3);
            console.log("Category Name = " + event);
            console.log(JSON.stringify(this.state.categoryMap[event]));
            return

{event}

                        {
                        this.state.categoryMap[event].map((event1, index) => {
                            let foundProgress = false;

                           /* this.props.progressCategories.map((event2, index) => {
                                if (event1.id === event2.category.id) {
                                    foundProgress = true;
                                    progressCat = event2;
                                }
                            });*/
                            if (foundProgress) {
                                console.log("Sub category progress = " + event1.name);
                                // return this.renderProgressBar(event1.name, progressCat.points, progressCat.levels);
                            } else {
                                console.log("Sub category no progress = " + event1.name);
                                // return this.renderProgressBar(event1.name, 0, null);
                            }
                        })
                    }

                       <Slider {...settings}>
                       {
                        rows.map((row) => (

                             {
                            row.map((event1,index) => (
                                foundProgress1 = false,
                                this.props.progressCategories.map((event2, index) => {
                                    if (event1.id === event2.category.id) {
                                        foundProgress1 = true;
                                        progressCat = event2;
                                    }

                                }),

                                    {event1.name}

                            ))

                            }

                        ))
                    }
                    </Slider>

        });
    }
    /**
    * This method renders the categories and their progress.
    */
    render = () => {
        let progress = 50;
        return (
            this.props.progressCategories && this.props.progressCategories.length > 0 ? this.renderProgressCategories() :

        )
    }
}
export default ProgressWidget;
<commit_msg>slider in progress widget<commit_after>import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { List, ListItem } from 'material-ui/List';
import Divider from 'material-ui/Divider';
import { Accordion, AccordionItem } from 'react-sanfona';
import './accordian.css';
import Moment from 'moment';
import { Link } from 'react-router-dom';
import CircularProgress from 'material-ui/CircularProgress';
import ProgressLabel from './progressLabelWidget';
import { GridList, GridTile } from 'material-ui/GridList';
import ReactTooltip from 'react-tooltip';
import Slider from 'react-slick';
import _ from 'lodash';
import { StatefulToolTip } from "react-portal-tooltip"

/**
*
* This class the component for rendering the events in the approval page.
*
*/
const pw = 6;
const cw = pw / 2;
const tw = pw;
const styles = {
    root: {
        display: 'flex',
        flexWrap: 'wrap',
        justifyContent: 'space-around',
    },
    gridList: {
        display: 'flex',
        overflowX: 'visible',
        margintop: '0px',
        marginleft: '0px',
    },
    titleStyle: {
        color: 'rgb(0, 188, 212)',
        height: 30
    },
};
class ProgressWidget extends Component {
    constructor(props) {
        super(props);
        this.state = {
            categoryMap: {}
        };
    }
    /**
    * This method gets the list of categories and their progress when the component is mounted.
    */
    componentDidMount = () => {
        this.props.getCategories(this.props.userInfo).then((response, error) => {
            this.props.updateCategoriesList(JSON.parse(response.data));
            let catMap = {};
            this.props.categories.map((event, index) => {
                let key = event.type;
                if (key != '') {
                    if (catMap[key] === undefined) {
                        let catArr = [];
                        catArr.push(this.props.categories[index]);
                        catMap[key] = catArr;
                    } else {
                        let catArr = catMap[key];
                        delete catMap[key];
                        catArr.push(this.props.categories[index]);
                        catMap[key] = catArr;
                    }
                }
            });
            console.log(catMap);
            this.setState({
                categoryMap: catMap
            });
            this.props.getProgressCategoriesList(this.props.userInfo.id).then((response, error) => {
                this.props.updateProgressCategoriesInfo(JSON.parse(response.data));
                console.log(this.props.progressCategories);
            }, (error) => {
                console.log(error);
            });
        });
    }
    /**
    * This method renders the progress bar.
    */
    renderProgressBar = (categoryName, points, allLevels) => {
        if (points > 0) {
            let totalLevels = allLevels.length;
            let maxLevel = allLevels[totalLevels - 1];
            let maxPointsForCategory = maxLevel.pointsEndRange;
            let progress = (points / maxPointsForCategory) * 100;
            let pointProgress = 0;
            let levelProgress = 0;
            let currentLevel = "0";
            let pointsNeededForNextLevel = 0;
            let totalPointsForCurrentLevel = 0;
            let startLevelPoints = 0;
            let endLevelPoints = 0;
            allLevels.map((event, index) => {
                endLevelPoints = event.pointsEndRange;
                if (event.sequence === "1") {
                    startLevelPoints = event.pointsEndRange;
                }
                if (parseInt(points) > parseInt(event.pointsStartRange) && parseInt(points) <= parseInt(event.pointsEndRange)) {
                    currentLevel = event.sequence;
                    pointsNeededForNextLevel = parseInt(event.pointsEndRange) - parseInt(points);
                    totalPointsForCurrentLevel = parseInt(event.pointsEndRange);
                }
                if (parseInt(points) + 1 === parseInt(event.pointsStartRange)) {
                    pointsNeededForNextLevel = parseInt(event.pointsEndRange) - parseInt(points);
                    totalPointsForCurrentLevel = parseInt(event.pointsEndRange);
                }
            });
            if (currentLevel !== "0") {
                pointProgress = 100 - ((pointsNeededForNextLevel / totalPointsForCurrentLevel) * 100);
                if (points >= endLevelPoints) {
                    levelProgress = ((currentLevel) / totalLevels) * 100;
                } else {
                    levelProgress = ((currentLevel - 1) / totalLevels) * 100;
                }
            } else {
                pointProgress = "1";
                levelProgress = "1";
            }
            if (levelProgress === 0) {
                levelProgress = "1";
            }
            let msg = "";
            if (currentLevel === "0") {
                pointsNeededForNextLevel = startLevelPoints;
                msg = pointsNeededForNextLevel + "more points for next level" + (parseInt(currentLevel) + 1)
            } else if (pointsNeededForNextLevel <= 0) {
                msg = "You have completed " + "Level " + (parseInt(currentLevel))
            } else {
                msg = pointsNeededForNextLevel + "more points for next level" + (parseInt(currentLevel));
            }
            return (

                   Points {points}
                   {msg}

           );
        }

    }
    renderProgressCategories = () => {
        let catArr = Object.keys(this.state.categoryMap);
        let progressCat = {};
        let allCat = [];
        let foundProgress1;

        var settings = {
            arrows: true,
            infinite: false,
            speed: 500,
            slidesToShow: 1,
            slidesToScroll: 1,
            centerPadding: '50px'
          };

        return catArr.map((event, index) => {
            let rows = _.chunk(this.state.categoryMap[event], 3);

            return

{event}

                       <Slider {...settings}>
                       {
                        rows.map((row) => (

                             {
                            row.map((event1,index) => (
                                foundProgress1 = false,
                                this.props.progressCategories.map((event2, index) => {
                                    if (event1.id === event2.category.id) {
                                        foundProgress1 = true;
                                        progressCat = event2;
                                    }

                                }),

                                    {event1.name}

                            ))

                            }

                        ))
                    }
                    </Slider>
                    {
                        this.state.categoryMap[event].map((event1, index) => {
                            let foundProgress = false;

                            this.props.progressCategories.map((event2, index) => {
                                if (event1.id === event2.category.id) {
                                    foundProgress = true;
                                    progressCat = event2;
                                }
                            });
                            if (foundProgress) {
                                console.log("Sub category progress = " + event1.name);
                                return this.renderProgressBar(event1.name, progressCat.points, progressCat.levels);
                            }
                        })
                    }

        });
    }
    /**
    * This method renders the categories and their progress.
    */
    render = () => {
        let progress = 50;
        return (
            this.props.progressCategories && this.props.progressCategories.length > 0 ? this.renderProgressCategories() :

        )
    }
}
export default ProgressWidget;
<|endoftext|>


<commit_before>// Copyright (c) 2011, Chris Umbel, James Coglan
// This file is required in order for any other classes to work. Some Vector methods work with the
// other Sylvester classes and are useless unless they are included. Other classes such as Line and
// Plane will not function at all without Vector being loaded first.

var Sylvester = {
  precision: 1e-6
};

function Vector() {}
Vector.prototype = {

  // Returns element i of the vector
  e: function(i) {
    return (i < 1 || i > this.elements.length) ? null : this.elements[i-1];
  },

  // Returns the number of elements the vector has
  dimensions: function() {
    return this.elements.length;
  },

  // Returns the modulus ('length') of the vector
  modulus: function() {
    return Math.sqrt(this.dot(this));
  },

  // Returns true iff the vector is equal to the argument
  eql: function(vector) {
    var n = this.elements.length;
    var V = vector.elements || vector;
    if (n != V.length) { return false; }
    while (n--) {
      if (Math.abs(this.elements[n] - V[n]) > Sylvester.precision) { return false; }
    }
    return true;
  },

  // Returns a copy of the vector
  dup: function() {
    return Vector.create(this.elements);
  },

  // Maps the vector to another vector according to the given function
  map: function(fn) {
    var elements = [];
    this.each(function(x, i) {
      elements.push(fn(x, i));
    });
    return Vector.create(elements);
  },

  // Calls the iterator for each element of the vector in turn
  each: function(fn) {
    var n = this.elements.length;
    for (var i = 0; i < n; i++) {
      fn(this.elements[i], i+1);
    }
  },

  // Returns a new vector created by normalizing the receiver
  toUnitVector: function() {
    var r = this.modulus();
    if (r === 0) { return this.dup(); }
    return this.map(function(x) { return x/r; });
  },

  // Returns the angle between the vector and the argument (also a vector)
  angleFrom: function(vector) {
    var V = vector.elements || vector;
    var n = this.elements.length, k = n, i;
    if (n != V.length) { return null; }
    var dot = 0, mod1 = 0, mod2 = 0;
    // Work things out in parallel to save time
    this.each(function(x, i) {
      dot += x * V[i-1];
      mod1 += x * x;
      mod2 += V[i-1] * V[i-1];
    });
    mod1 = Math.sqrt(mod1); mod2 = Math.sqrt(mod2);
    if (mod1*mod2 === 0) { return null; }
    var theta = dot / (mod1*mod2);
    if (theta < -1) { theta = -1; }
    if (theta > 1) { theta = 1; }
    return Math.acos(theta);
  },

  // Returns true iff the vector is parallel to the argument
  isParallelTo: function(vector) {
    var angle = this.angleFrom(vector);
    return (angle === null) ? null : (angle <= Sylvester.precision);
  },

  // Returns true iff the vector is antiparallel to the argument
  isAntiparallelTo: function(vector) {
    var angle = this.angleFrom(vector);
    return (angle === null) ? null : (Math.abs(angle - Math.PI) <= Sylvester.precision);
  },

  // Returns true iff the vector is perpendicular to the argument
  isPerpendicularTo: function(vector) {
    var dot = this.dot(vector);
    return (dot === null) ? null : (Math.abs(dot) <= Sylvester.precision);
  },

  // Returns the result of adding the argument to the vector
  add: function(vector) {
    var V = vector.elements || vector;
    if (this.elements.length != V.length) { return null; }
    return this.map(function(x, i) { return x + V[i-1]; });
  },

  // Returns the result of subtracting the argument from the vector
  subtract: function(v) {
      if(typeof(v) == 'number')
	  return this.map(function(k){ return k - v; });

      var V = v.elements || v;
      if (this.elements.length != V.length) { return null; }
      return this.map(function(x, i) { return x - V[i-1]; });
  },

  // Returns the result of multiplying the elements of the vector by the argument
  multiply: function(k) {
    return this.map(function(x) { return x*k; });
  },

    elementMultiply: function(v) {
	return this.map(function(k, i) {
	    return v.e(i) * k;
	});
    },

    sum: function() {
	var sum = 0;

	this.map(function(x) { sum += x;});

	return sum;
    },

  x: function(k) { return this.multiply(k); },

  log: function() {
      return Vector.log(this);
  },

  // Returns the scalar product of the vector with the argument
  // Both vectors must have equal dimensionality
  dot: function(vector) {
    var V = vector.elements || vector;
    var i, product = 0, n = this.elements.length;
    if (n != V.length) { return null; }
    while (n--) { product += this.elements[n] * V[n]; }
    return product;
  },

  // Returns the vector product of the vector with the argument
  // Both vectors must have dimensionality 3
  cross: function(vector) {
    var B = vector.elements || vector;
    if (this.elements.length != 3 || B.length != 3) { return null; }
    var A = this.elements;
    return Vector.create([
      (A[1] * B[2]) - (A[2] * B[1]),
      (A[2] * B[0]) - (A[0] * B[2]),
      (A[0] * B[1]) - (A[1] * B[0])
    ]);
  },

  // Returns the (absolute) largest element of the vector
  max: function() {
    var m = 0, i = this.elements.length;
    while (i--) {
      if (Math.abs(this.elements[i]) > Math.abs(m)) { m = this.elements[i]; }
    }
    return m;
  },

  // Returns the index of the first match found
  indexOf: function(x) {
    var index = null, n = this.elements.length;
    for (var i = 0; i < n; i++) {
      if (index === null && this.elements[i] == x) {
        index = i + 1;
      }
    }
    return index;
  },

  // Returns a diagonal matrix with the vector's elements as its diagonal elements
  toDiagonalMatrix: function() {
    return Matrix.Diagonal(this.elements);
  },

  // Returns the result of rounding the elements of the vector
  round: function() {
    return this.map(function(x) { return Math.round(x); });
  },

  // Transpose a Vector, return a 1xn Matrix
  transpose: function() {
    Matrix = require('./matrix');
    var rows = this.elements.length;
    var elements = [];

    for(var i = 0; i < rows; i++) {
      elements.push([this.elements[i]])
    }
    return Matrix.create(elements);
  },

  // Returns a copy of the vector with elements set to the given value if they
  // differ from it by less than Sylvester.precision
  snapTo: function(x) {
    return this.map(function(y) {
      return (Math.abs(y - x) <= Sylvester.precision) ? x : y;
    });
  },

  // Returns the vector's distance from the argument, when considered as a point in space
  distanceFrom: function(obj) {
    if (obj.anchor || (obj.start && obj.end)) { return obj.distanceFrom(this); }
    var V = obj.elements || obj;
    if (V.length != this.elements.length) { return null; }
    var sum = 0, part;
    this.each(function(x, i) {
      part = x - V[i-1];
      sum += part * part;
    });
    return Math.sqrt(sum);
  },

  // Returns true if the vector is point on the given line
  liesOn: function(line) {
    return line.contains(this);
  },

  // Return true iff the vector is a point in the given plane
  liesIn: function(plane) {
    return plane.contains(this);
  },

  // Rotates the vector about the given object. The object should be a
  // point if the vector is 2D, and a line if it is 3D. Be careful with line directions!
  rotate: function(t, obj) {
    var V, R = null, x, y, z;
    if (t.determinant) { R = t.elements; }
    switch (this.elements.length) {
      case 2:
        V = obj.elements || obj;
        if (V.length != 2) { return null; }
        if (!R) { R = Matrix.Rotation(t).elements; }
        x = this.elements[0] - V[0];
        y = this.elements[1] - V[1];
        return Vector.create([
          V[0] + R[0][0] * x + R[0][1] * y,
          V[1] + R[1][0] * x + R[1][1] * y
        ]);
        break;
      case 3:
        if (!obj.direction) { return null; }
        var C = obj.pointClosestTo(this).elements;
        if (!R) { R = Matrix.Rotation(t, obj.direction).elements; }
        x = this.elements[0] - C[0];
        y = this.elements[1] - C[1];
        z = this.elements[2] - C[2];
        return Vector.create([
          C[0] + R[0][0] * x + R[0][1] * y + R[0][2] * z,
          C[1] + R[1][0] * x + R[1][1] * y + R[1][2] * z,
          C[2] + R[2][0] * x + R[2][1] * y + R[2][2] * z
        ]);
        break;
      default:
        return null;
    }
  },

  // Returns the result of reflecting the point in the given point, line or plane
  reflectionIn: function(obj) {
    if (obj.anchor) {
      // obj is a plane or line
      var P = this.elements.slice();
      var C = obj.pointClosestTo(P).elements;
      return Vector.create([C[0] + (C[0] - P[0]), C[1] + (C[1] - P[1]), C[2] + (C[2] - (P[2] || 0))]);
    } else {
      // obj is a point
      var Q = obj.elements || obj;
      if (this.elements.length != Q.length) { return null; }
      return this.map(function(x, i) { return Q[i-1] + (Q[i-1] - x); });
    }
  },

  // Utility to make sure vectors are 3D. If they are 2D, a zero z-component is added
  to3D: function() {
    var V = this.dup();
    switch (V.elements.length) {
      case 3: break;
      case 2: V.elements.push(0); break;
      default: return null;
    }
    return V;
  },

  // Returns a string representation of the vector
  inspect: function() {
    return '[' + this.elements.join(', ') + ']';
  },

  // Set vector's elements from an array
  setElements: function(els) {
    this.elements = (els.elements || els).slice();
    return this;
  }
};

// Constructor function
Vector.create = function(elements) {
  var V = new Vector();
  return V.setElements(elements);
};

// i, j, k unit vectors
Vector.i = Vector.create([1,0,0]);
Vector.j = Vector.create([0,1,0]);
Vector.k = Vector.create([0,0,1]);

// Random vector of size n
Vector.Random = function(n) {
  var elements = [];
  while (n--) { elements.push(Math.random()); }
  return Vector.create(elements);
};

Vector.Fill = function(n, v) {
  var elements = [];
  while (n--) { elements.push(v); }
  return Vector.create(elements);
};

// Vector filled with zeros
Vector.Zero = function(n) {
    return Vector.Fill(n, 0);
};

Vector.One = function(n) {
    return Vector.Fill(n, 1);
};

Vector.log = function(v) {
  return v.map(function(x) {
      return Math.log(x);
  });
};

module.exports = Vector;
<commit_msg>added chomp() and top() to vector<commit_after>// Copyright (c) 2011, Chris Umbel, James Coglan
// This file is required in order for any other classes to work. Some Vector methods work with the
// other Sylvester classes and are useless unless they are included. Other classes such as Line and
// Plane will not function at all without Vector being loaded first.

var Sylvester = {
  precision: 1e-6
};

function Vector() {}
Vector.prototype = {

  // Returns element i of the vector
  e: function(i) {
    return (i < 1 || i > this.elements.length) ? null : this.elements[i-1];
  },

  // Returns the number of elements the vector has
  dimensions: function() {
    return this.elements.length;
  },

  // Returns the modulus ('length') of the vector
  modulus: function() {
    return Math.sqrt(this.dot(this));
  },

  // Returns true iff the vector is equal to the argument
  eql: function(vector) {
    var n = this.elements.length;
    var V = vector.elements || vector;
    if (n != V.length) { return false; }
    while (n--) {
      if (Math.abs(this.elements[n] - V[n]) > Sylvester.precision) { return false; }
    }
    return true;
  },

  // Returns a copy of the vector
  dup: function() {
    return Vector.create(this.elements);
  },

  // Maps the vector to another vector according to the given function
  map: function(fn) {
    var elements = [];
    this.each(function(x, i) {
      elements.push(fn(x, i));
    });
    return Vector.create(elements);
  },

  // Calls the iterator for each element of the vector in turn
  each: function(fn) {
    var n = this.elements.length;
    for (var i = 0; i < n; i++) {
      fn(this.elements[i], i+1);
    }
  },

  // Returns a new vector created by normalizing the receiver
  toUnitVector: function() {
    var r = this.modulus();
    if (r === 0) { return this.dup(); }
    return this.map(function(x) { return x/r; });
  },

  // Returns the angle between the vector and the argument (also a vector)
  angleFrom: function(vector) {
    var V = vector.elements || vector;
    var n = this.elements.length, k = n, i;
    if (n != V.length) { return null; }
    var dot = 0, mod1 = 0, mod2 = 0;
    // Work things out in parallel to save time
    this.each(function(x, i) {
      dot += x * V[i-1];
      mod1 += x * x;
      mod2 += V[i-1] * V[i-1];
    });
    mod1 = Math.sqrt(mod1); mod2 = Math.sqrt(mod2);
    if (mod1*mod2 === 0) { return null; }
    var theta = dot / (mod1*mod2);
    if (theta < -1) { theta = -1; }
    if (theta > 1) { theta = 1; }
    return Math.acos(theta);
  },

  // Returns true iff the vector is parallel to the argument
  isParallelTo: function(vector) {
    var angle = this.angleFrom(vector);
    return (angle === null) ? null : (angle <= Sylvester.precision);
  },

  // Returns true iff the vector is antiparallel to the argument
  isAntiparallelTo: function(vector) {
    var angle = this.angleFrom(vector);
    return (angle === null) ? null : (Math.abs(angle - Math.PI) <= Sylvester.precision);
  },

  // Returns true iff the vector is perpendicular to the argument
  isPerpendicularTo: function(vector) {
    var dot = this.dot(vector);
    return (dot === null) ? null : (Math.abs(dot) <= Sylvester.precision);
  },

  // Returns the result of adding the argument to the vector
  add: function(vector) {
    var V = vector.elements || vector;
    if (this.elements.length != V.length) { return null; }
    return this.map(function(x, i) { return x + V[i-1]; });
  },

  // Returns the result of subtracting the argument from the vector
  subtract: function(v) {
      if(typeof(v) == 'number')
	  return this.map(function(k){ return k - v; });

      var V = v.elements || v;
      if (this.elements.length != V.length) { return null; }
      return this.map(function(x, i) { return x - V[i-1]; });
  },

  // Returns the result of multiplying the elements of the vector by the argument
  multiply: function(k) {
    return this.map(function(x) { return x*k; });
  },

    elementMultiply: function(v) {
	return this.map(function(k, i) {
	    return v.e(i) * k;
	});
    },

    sum: function() {
	var sum = 0;

	this.map(function(x) { sum += x;});

	return sum;
    },

    chomp: function(n) {
	var elements = [];

	for(var i = n; i < this.elements.length; i++) {
	    elements.push(this.elements[i]);
	}

	return Vector.create(elements);
    },

    top: function(n) {
	var elements = [];

	for(var i = 0; i < n; i++) {
	    elements.push(this.elements[i]);
	}

	return Vector.create(elements);
    },

    augment: function(elements) {
	var newElements = this.elements;

	for(var i = 0; i < elements.length; i++) {
	    newElements.push(elements[i])
	}

	return Vector.create(newElements);
    },

  x: function(k) { return this.multiply(k); },

  log: function() {
      return Vector.log(this);
  },

  // Returns the scalar product of the vector with the argument
  // Both vectors must have equal dimensionality
  dot: function(vector) {
    var V = vector.elements || vector;
    var i, product = 0, n = this.elements.length;
    if (n != V.length) { return null; }
    while (n--) { product += this.elements[n] * V[n]; }
    return product;
  },

  // Returns the vector product of the vector with the argument
  // Both vectors must have dimensionality 3
  cross: function(vector) {
    var B = vector.elements || vector;
    if (this.elements.length != 3 || B.length != 3) { return null; }
    var A = this.elements;
    return Vector.create([
      (A[1] * B[2]) - (A[2] * B[1]),
      (A[2] * B[0]) - (A[0] * B[2]),
      (A[0] * B[1]) - (A[1] * B[0])
    ]);
  },

  // Returns the (absolute) largest element of the vector
  max: function() {
    var m = 0, i = this.elements.length;
    while (i--) {
      if (Math.abs(this.elements[i]) > Math.abs(m)) { m = this.elements[i]; }
    }
    return m;
  },

  // Returns the index of the first match found
  indexOf: function(x) {
    var index = null, n = this.elements.length;
    for (var i = 0; i < n; i++) {
      if (index === null && this.elements[i] == x) {
        index = i + 1;
      }
    }
    return index;
  },

  // Returns a diagonal matrix with the vector's elements as its diagonal elements
  toDiagonalMatrix: function() {
    return Matrix.Diagonal(this.elements);
  },

  // Returns the result of rounding the elements of the vector
  round: function() {
    return this.map(function(x) { return Math.round(x); });
  },

  // Transpose a Vector, return a 1xn Matrix
  transpose: function() {
    Matrix = require('./matrix');
    var rows = this.elements.length;
    var elements = [];

    for(var i = 0; i < rows; i++) {
      elements.push([this.elements[i]])
    }
    return Matrix.create(elements);
  },

  // Returns a copy of the vector with elements set to the given value if they
  // differ from it by less than Sylvester.precision
  snapTo: function(x) {
    return this.map(function(y) {
      return (Math.abs(y - x) <= Sylvester.precision) ? x : y;
    });
  },

  // Returns the vector's distance from the argument, when considered as a point in space
  distanceFrom: function(obj) {
    if (obj.anchor || (obj.start && obj.end)) { return obj.distanceFrom(this); }
    var V = obj.elements || obj;
    if (V.length != this.elements.length) { return null; }
    var sum = 0, part;
    this.each(function(x, i) {
      part = x - V[i-1];
      sum += part * part;
    });
    return Math.sqrt(sum);
  },

  // Returns true if the vector is point on the given line
  liesOn: function(line) {
    return line.contains(this);
  },

  // Return true iff the vector is a point in the given plane
  liesIn: function(plane) {
    return plane.contains(this);
  },

  // Rotates the vector about the given object. The object should be a
  // point if the vector is 2D, and a line if it is 3D. Be careful with line directions!
  rotate: function(t, obj) {
    var V, R = null, x, y, z;
    if (t.determinant) { R = t.elements; }
    switch (this.elements.length) {
      case 2:
        V = obj.elements || obj;
        if (V.length != 2) { return null; }
        if (!R) { R = Matrix.Rotation(t).elements; }
        x = this.elements[0] - V[0];
        y = this.elements[1] - V[1];
        return Vector.create([
          V[0] + R[0][0] * x + R[0][1] * y,
          V[1] + R[1][0] * x + R[1][1] * y
        ]);
        break;
      case 3:
        if (!obj.direction) { return null; }
        var C = obj.pointClosestTo(this).elements;
        if (!R) { R = Matrix.Rotation(t, obj.direction).elements; }
        x = this.elements[0] - C[0];
        y = this.elements[1] - C[1];
        z = this.elements[2] - C[2];
        return Vector.create([
          C[0] + R[0][0] * x + R[0][1] * y + R[0][2] * z,
          C[1] + R[1][0] * x + R[1][1] * y + R[1][2] * z,
          C[2] + R[2][0] * x + R[2][1] * y + R[2][2] * z
        ]);
        break;
      default:
        return null;
    }
  },

  // Returns the result of reflecting the point in the given point, line or plane
  reflectionIn: function(obj) {
    if (obj.anchor) {
      // obj is a plane or line
      var P = this.elements.slice();
      var C = obj.pointClosestTo(P).elements;
      return Vector.create([C[0] + (C[0] - P[0]), C[1] + (C[1] - P[1]), C[2] + (C[2] - (P[2] || 0))]);
    } else {
      // obj is a point
      var Q = obj.elements || obj;
      if (this.elements.length != Q.length) { return null; }
      return this.map(function(x, i) { return Q[i-1] + (Q[i-1] - x); });
    }
  },

  // Utility to make sure vectors are 3D. If they are 2D, a zero z-component is added
  to3D: function() {
    var V = this.dup();
    switch (V.elements.length) {
      case 3: break;
      case 2: V.elements.push(0); break;
      default: return null;
    }
    return V;
  },

  // Returns a string representation of the vector
  inspect: function() {
    return '[' + this.elements.join(', ') + ']';
  },

  // Set vector's elements from an array
  setElements: function(els) {
    this.elements = (els.elements || els).slice();
    return this;
  }
};

// Constructor function
Vector.create = function(elements) {
  var V = new Vector();
  return V.setElements(elements);
};

// i, j, k unit vectors
Vector.i = Vector.create([1,0,0]);
Vector.j = Vector.create([0,1,0]);
Vector.k = Vector.create([0,0,1]);

// Random vector of size n
Vector.Random = function(n) {
  var elements = [];
  while (n--) { elements.push(Math.random()); }
  return Vector.create(elements);
};

Vector.Fill = function(n, v) {
  var elements = [];
  while (n--) { elements.push(v); }
  return Vector.create(elements);
};

// Vector filled with zeros
Vector.Zero = function(n) {
    return Vector.Fill(n, 0);
};

Vector.One = function(n) {
    return Vector.Fill(n, 1);
};

Vector.log = function(v) {
  return v.map(function(x) {
      return Math.log(x);
  });
};

module.exports = Vector;
<|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

cr.define('cr.ui', function() {
  /**
   * Creates a selection controller that is to be used with lists. This is
   * implemented for vertical lists but changing the behavior for horizontal
   * lists or icon views is a matter of overriding {@code getIndexBefore},
   * {@code getIndexAfter}, {@code getIndexAbove} as well as
   * {@code getIndexBelow}.
   *
   * @param {cr.ui.ListSelectionModel} selectionModel The selection model to
   *     interact with.
   *
   * @constructor
   * @extends {!cr.EventTarget}
   */
  function ListSelectionController(selectionModel) {
    this.selectionModel_ = selectionModel;
  }

  ListSelectionController.prototype = {

    /**
     * The selection model we are interacting with.
     * @type {cr.ui.ListSelectionModel}
     */
    get selectionModel() {
      return this.selectionModel_;
    },

    /**
     * Returns the index below (y axis) the given element.
     * @param {number} index The index to get the index below.
     * @return {number} The index below or -1 if not found.
     */
    getIndexBelow: function(index) {
      if (index == this.getLastIndex())
        return -1;
      return index + 1;
    },

    /**
     * Returns the index above (y axis) the given element.
     * @param {number} index The index to get the index above.
     * @return {number} The index below or -1 if not found.
     */
    getIndexAbove: function(index) {
      return index - 1;
    },

    /**
     * Returns the index before (x axis) the given element. This returns -1
     * by default but override this for icon view and horizontal selection
     * models.
     *
     * @param {number} index The index to get the index before.
     * @return {number} The index before or -1 if not found.
     */
    getIndexBefore: function(index) {
      return -1;
    },

    /**
     * Returns the index after (x axis) the given element. This returns -1
     * by default but override this for icon view and horizontal selection
     * models.
     *
     * @param {number} index The index to get the index after.
     * @return {number} The index after or -1 if not found.
     */
    getIndexAfter: function(index) {
      return -1;
    },

    /**
     * Returns the next list index. This is the next logical and should not
     * depend on any kind of layout of the list.
     * @param {number} index The index to get the next index for.
     * @return {number} The next index or -1 if not found.
     */
    getNextIndex: function(index) {
      if (index == this.getLastIndex())
        return -1;
      return index + 1;
    },

    /**
     * Returns the prevous list index. This is the previous logical and should
     * not depend on any kind of layout of the list.
     * @param {number} index The index to get the previous index for.
     * @return {number} The previous index or -1 if not found.
     */
    getPreviousIndex: function(index) {
      return index - 1;
    },

    /**
     * @return {number} The first index.
     */
    getFirstIndex: function() {
      return 0;
    },

    /**
     * @return {number} The last index.
     */
    getLastIndex: function() {
      return this.selectionModel.length - 1;
    },

    /**
     * Called by the view when the user does a mousedown or mouseup on the list.
     * @param {!Event} e The browser mousedown event.
     * @param {number} index The index that was under the mouse pointer, -1 if
     *     none.
     */
    handleMouseDownUp: function(e, index) {
      var sm = this.selectionModel;
      var anchorIndex = sm.anchorIndex;
      var isDown = e.type == 'mousedown';

      sm.beginChange();

      if (index == -1) {
        // On Mac we always clear the selection if the user clicks a blank area.
        // On Windows, we only clear the selection if neither Shift nor Ctrl are
        // pressed.
        if (cr.isMac) {
          sm.leadIndex = sm.anchorIndex = -1;
          if (sm.multiple)
            sm.unselectAll();
        } else if (!isDown && !e.shiftKey && !e.ctrlKey)
          // Keep anchor and lead indexes. Note that this is intentionally
          // different than on the Mac.
          if (sm.multiple)
            sm.unselectAll();
      } else {
        if (sm.multiple && (cr.isMac ? e.metaKey : e.ctrlKey)) {
          // Selection is handled at mouseUp on windows/linux, mouseDown on mac.
          if (cr.isMac? isDown : !isDown) {
            // toggle the current one and make it anchor index
            sm.setIndexSelected(index, !sm.getIndexSelected(index));
            sm.leadIndex = index;
            sm.anchorIndex = index;
          }
        } else if (e.shiftKey && anchorIndex != -1 && anchorIndex != index) {
          // Shift is done in mousedown
          if (isDown) {
            sm.unselectAll();
            sm.leadIndex = index;
            if (sm.multiple)
              sm.selectRange(anchorIndex, index);
            else
              sm.setIndexSelected(index, true);
          }
        } else {
          // Right click for a context menu need to not clear the selection.
          var isRightClick = e.button == 2;

          // If the index is selected this is handled in mouseup.
          var indexSelected = sm.getIndexSelected(index);
          if ((indexSelected && !isDown || !indexSelected && isDown) &&
              !(indexSelected && isRightClick)) {
            sm.unselectAll();
            sm.setIndexSelected(index, true);
            sm.leadIndex = index;
            sm.anchorIndex = index;
          }
        }
      }

      sm.endChange();
    },

    /**
     * Called by the view when it recieves a keydown event.
     * @param {Event} e The keydown event.
     */
    handleKeyDown: function(e) {
      var sm = this.selectionModel;
      var newIndex = -1;
      var leadIndex = sm.leadIndex;
      var prevent = true;

      // Ctrl/Meta+A
      if (sm.multiple && e.keyCode == 65 &&
          (cr.isMac && e.metaKey || !cr.isMac && e.ctrlKey)) {
        sm.selectAll();
        e.preventDefault();
        return;
      }

      // Space
      if (e.keyCode == 32) {
        if (leadIndex != -1) {
          var selected = sm.getIndexSelected(leadIndex);
          if (e.ctrlKey || !selected) {
            sm.setIndexSelected(leadIndex, !selected || !sm.multiple);
            return;
          }
        }
      }

      switch (e.keyIdentifier) {
        case 'Home':
          newIndex = this.getFirstIndex();
          break;
        case 'End':
          newIndex = this.getLastIndex();
          break;
        case 'Up':
          newIndex = leadIndex == -1 ?
              this.getLastIndex() : this.getIndexAbove(leadIndex);
          break;
        case 'Down':
          newIndex = leadIndex == -1 ?
              this.getFirstIndex() : this.getIndexBelow(leadIndex);
          break;
        case 'Left':
          newIndex = leadIndex == -1 ?
              this.getLastIndex() : this.getIndexBefore(leadIndex);
          break;
        case 'Right':
          newIndex = leadIndex == -1 ?
              this.getFirstIndex() : this.getIndexAfter(leadIndex);
          break;
        default:
          prevent = false;
      }

      if (newIndex != -1) {
        sm.beginChange();

        sm.leadIndex = newIndex;
        if (e.shiftKey) {
          var anchorIndex = sm.anchorIndex;
          if (sm.multiple)
            sm.unselectAll();
          if (anchorIndex == -1) {
            sm.setIndexSelected(newIndex, true);
            sm.anchorIndex = newIndex;
          } else {
            sm.selectRange(anchorIndex, newIndex);
          }
        } else if (e.ctrlKey && !cr.isMac) {
          // Setting the lead index is done above
          // Mac does not allow you to change the lead.
        } else {
          if (sm.multiple)
            sm.unselectAll();
          sm.setIndexSelected(newIndex, true);
          sm.anchorIndex = newIndex;
        }

        sm.endChange();

        if (prevent)
          e.preventDefault();
      }
    }
  };

  return {
    ListSelectionController: ListSelectionController
  };
});
<commit_msg>DOMUI: Fix Shift+Ctrl selection of the list for Windows.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

cr.define('cr.ui', function() {
  /**
   * Creates a selection controller that is to be used with lists. This is
   * implemented for vertical lists but changing the behavior for horizontal
   * lists or icon views is a matter of overriding {@code getIndexBefore},
   * {@code getIndexAfter}, {@code getIndexAbove} as well as
   * {@code getIndexBelow}.
   *
   * @param {cr.ui.ListSelectionModel} selectionModel The selection model to
   *     interact with.
   *
   * @constructor
   * @extends {!cr.EventTarget}
   */
  function ListSelectionController(selectionModel) {
    this.selectionModel_ = selectionModel;
  }

  ListSelectionController.prototype = {

    /**
     * The selection model we are interacting with.
     * @type {cr.ui.ListSelectionModel}
     */
    get selectionModel() {
      return this.selectionModel_;
    },

    /**
     * Returns the index below (y axis) the given element.
     * @param {number} index The index to get the index below.
     * @return {number} The index below or -1 if not found.
     */
    getIndexBelow: function(index) {
      if (index == this.getLastIndex())
        return -1;
      return index + 1;
    },

    /**
     * Returns the index above (y axis) the given element.
     * @param {number} index The index to get the index above.
     * @return {number} The index below or -1 if not found.
     */
    getIndexAbove: function(index) {
      return index - 1;
    },

    /**
     * Returns the index before (x axis) the given element. This returns -1
     * by default but override this for icon view and horizontal selection
     * models.
     *
     * @param {number} index The index to get the index before.
     * @return {number} The index before or -1 if not found.
     */
    getIndexBefore: function(index) {
      return -1;
    },

    /**
     * Returns the index after (x axis) the given element. This returns -1
     * by default but override this for icon view and horizontal selection
     * models.
     *
     * @param {number} index The index to get the index after.
     * @return {number} The index after or -1 if not found.
     */
    getIndexAfter: function(index) {
      return -1;
    },

    /**
     * Returns the next list index. This is the next logical and should not
     * depend on any kind of layout of the list.
     * @param {number} index The index to get the next index for.
     * @return {number} The next index or -1 if not found.
     */
    getNextIndex: function(index) {
      if (index == this.getLastIndex())
        return -1;
      return index + 1;
    },

    /**
     * Returns the prevous list index. This is the previous logical and should
     * not depend on any kind of layout of the list.
     * @param {number} index The index to get the previous index for.
     * @return {number} The previous index or -1 if not found.
     */
    getPreviousIndex: function(index) {
      return index - 1;
    },

    /**
     * @return {number} The first index.
     */
    getFirstIndex: function() {
      return 0;
    },

    /**
     * @return {number} The last index.
     */
    getLastIndex: function() {
      return this.selectionModel.length - 1;
    },

    /**
     * Called by the view when the user does a mousedown or mouseup on the list.
     * @param {!Event} e The browser mousedown event.
     * @param {number} index The index that was under the mouse pointer, -1 if
     *     none.
     */
    handleMouseDownUp: function(e, index) {
      var sm = this.selectionModel;
      var anchorIndex = sm.anchorIndex;
      var isDown = e.type == 'mousedown';

      sm.beginChange();

      if (index == -1) {
        // On Mac we always clear the selection if the user clicks a blank area.
        // On Windows, we only clear the selection if neither Shift nor Ctrl are
        // pressed.
        if (cr.isMac) {
          sm.leadIndex = sm.anchorIndex = -1;
          if (sm.multiple)
            sm.unselectAll();
        } else if (!isDown && !e.shiftKey && !e.ctrlKey)
          // Keep anchor and lead indexes. Note that this is intentionally
          // different than on the Mac.
          if (sm.multiple)
            sm.unselectAll();
      } else {
        if (sm.multiple && (cr.isMac ? e.metaKey :
                                       (e.ctrlKey && !e.shiftKey))) {
          // Selection is handled at mouseUp on windows/linux, mouseDown on mac.
          if (cr.isMac? isDown : !isDown) {
            // toggle the current one and make it anchor index
            sm.setIndexSelected(index, !sm.getIndexSelected(index));
            sm.leadIndex = index;
            sm.anchorIndex = index;
          }
        } else if (e.shiftKey && anchorIndex != -1 && anchorIndex != index) {
          // Shift is done in mousedown
          if (isDown) {
            sm.unselectAll();
            sm.leadIndex = index;
            if (sm.multiple)
              sm.selectRange(anchorIndex, index);
            else
              sm.setIndexSelected(index, true);
          }
        } else {
          // Right click for a context menu need to not clear the selection.
          var isRightClick = e.button == 2;

          // If the index is selected this is handled in mouseup.
          var indexSelected = sm.getIndexSelected(index);
          if ((indexSelected && !isDown || !indexSelected && isDown) &&
              !(indexSelected && isRightClick)) {
            sm.unselectAll();
            sm.setIndexSelected(index, true);
            sm.leadIndex = index;
            sm.anchorIndex = index;
          }
        }
      }

      sm.endChange();
    },

    /**
     * Called by the view when it recieves a keydown event.
     * @param {Event} e The keydown event.
     */
    handleKeyDown: function(e) {
      var sm = this.selectionModel;
      var newIndex = -1;
      var leadIndex = sm.leadIndex;
      var prevent = true;

      // Ctrl/Meta+A
      if (sm.multiple && e.keyCode == 65 &&
          (cr.isMac && e.metaKey || !cr.isMac && e.ctrlKey)) {
        sm.selectAll();
        e.preventDefault();
        return;
      }

      // Space
      if (e.keyCode == 32) {
        if (leadIndex != -1) {
          var selected = sm.getIndexSelected(leadIndex);
          if (e.ctrlKey || !selected) {
            sm.setIndexSelected(leadIndex, !selected || !sm.multiple);
            return;
          }
        }
      }

      switch (e.keyIdentifier) {
        case 'Home':
          newIndex = this.getFirstIndex();
          break;
        case 'End':
          newIndex = this.getLastIndex();
          break;
        case 'Up':
          newIndex = leadIndex == -1 ?
              this.getLastIndex() : this.getIndexAbove(leadIndex);
          break;
        case 'Down':
          newIndex = leadIndex == -1 ?
              this.getFirstIndex() : this.getIndexBelow(leadIndex);
          break;
        case 'Left':
          newIndex = leadIndex == -1 ?
              this.getLastIndex() : this.getIndexBefore(leadIndex);
          break;
        case 'Right':
          newIndex = leadIndex == -1 ?
              this.getFirstIndex() : this.getIndexAfter(leadIndex);
          break;
        default:
          prevent = false;
      }

      if (newIndex != -1) {
        sm.beginChange();

        sm.leadIndex = newIndex;
        if (e.shiftKey) {
          var anchorIndex = sm.anchorIndex;
          if (sm.multiple)
            sm.unselectAll();
          if (anchorIndex == -1) {
            sm.setIndexSelected(newIndex, true);
            sm.anchorIndex = newIndex;
          } else {
            sm.selectRange(anchorIndex, newIndex);
          }
        } else if (e.ctrlKey && !cr.isMac) {
          // Setting the lead index is done above
          // Mac does not allow you to change the lead.
        } else {
          if (sm.multiple)
            sm.unselectAll();
          sm.setIndexSelected(newIndex, true);
          sm.anchorIndex = newIndex;
        }

        sm.endChange();

        if (prevent)
          e.preventDefault();
      }
    }
  };

  return {
    ListSelectionController: ListSelectionController
  };
});
<|endoftext|>


<commit_before>'use babel';
'use strict';

import DiceExpression from 'dice-expression-evaluator';
import nbsp from '../../util/nbsp';
import logger from '../../util/logger';

const pattern = /^(.+?)(?:(>|<)\s*([0-9]+?))?\s*$/;

export default {
	name: 'roll',
	aliases: ['dice', 'rolldice', 'diceroll', '(roll: xxxx)'],
	group: 'dice',
	groupName: 'roll',
	description: 'Rolls specified dice.',
	usage: 'roll <dice expression>',
	details: 'Dice expressions can contain the standard representations of dice in text form (e.g. 2d20 is two 20-sided dice), with addition and subtraction allowed. You may also use a single greater-than (>) or less-than (<) symbol at the end of the expression to add a target - if that target is met, a success message is displayed. Otherwise, a failure message is shown.',
	examples: ['!roll 2d20', '!roll 3d20 - d10 + 6', '!roll d20 > 10', 'Billy McBillface attempts to slay the dragon. (Roll: d20 > 10)'],
	singleArgument: true,
	patterns: [
		/\(\s*(?:roll|dice|rolldice|diceroll):\s*(.+?)(?:(>|<)\s*([0-9]+?))?\s*\)/i
	],

	isRunnable() {
		return true;
	},

	run(message, args, fromPattern) {
		if(!args[0]) return false;
		try {
			const matches = fromPattern ? args : pattern.exec(args[0]);
			const dice = new DiceExpression(matches[1]);

			// Restrict the maximum dice count
			const totalDice = dice.dice.reduce((prev, d) => prev + d.diceCount, 0);
			if(totalDice > 200) {
				message.client.sendMessage(message, `${message.author} might hurt themselves by rolling that many dice at once!`);
				return;
			}

			// Roll the dice
			const rollResult = dice.roll();
			logger.debug(rollResult);

			// Build the list of dice
			let diceList = '';
			if(totalDice <= 100 && (rollResult.diceRaw.length > 1 || (rollResult.diceRaw.length > 0 && rollResult.diceRaw[0].length > 1))) {
				diceList = rollResult.diceRaw.map((r, i) => nbsp(r.length > 1 ? r.join(' + ') + ' = ' + rollResult.diceSums[i] : r[0])).join(',   ');
			}

			if(matches[2]) {
				// Determine whether or not the target is met
				const target = parseInt(matches[3]);
				let success = false;
				let targetMessage;
				if(matches[2] === '>') {
					success = rollResult.roll > target;
					targetMessage = `${!success ? 'not' : ''} greater than ${target}`;
				} else {
					success = rollResult.roll < target;
					targetMessage = `${!success ? 'not' : ''} less than ${target}`;
				}

				const diceInfo = diceList ? `;   ${diceList}` : '';
				message.client.sendMessage(message, `${message.author} has **${success ? 'succeeded' : 'failed'}**. (Rolled ${rollResult.roll}, ${targetMessage}${diceInfo})`);
			} else {
				const diceInfo = diceList ? ` (${diceList})` : '';
				message.client.sendMessage(message, `${message.author} rolled **${rollResult.roll}**.${diceInfo}`);
			}
		} catch(e) {
			logger.error(e);
			message.client.sendMessage(message, `${message.author} specified an invalid dice expression.`);
			return;
		}
	}
};
<commit_msg>Drastically increased max dice for roll<commit_after>'use babel';
'use strict';

import DiceExpression from 'dice-expression-evaluator';
import nbsp from '../../util/nbsp';
import logger from '../../util/logger';

const pattern = /^(.+?)(?:(>|<)\s*([0-9]+?))?\s*$/;

export default {
	name: 'roll',
	aliases: ['dice', 'rolldice', 'diceroll', '(roll: xxxx)'],
	group: 'dice',
	groupName: 'roll',
	description: 'Rolls specified dice.',
	usage: 'roll <dice expression>',
	details: 'Dice expressions can contain the standard representations of dice in text form (e.g. 2d20 is two 20-sided dice), with addition and subtraction allowed. You may also use a single greater-than (>) or less-than (<) symbol at the end of the expression to add a target - if that target is met, a success message is displayed. Otherwise, a failure message is shown.',
	examples: ['!roll 2d20', '!roll 3d20 - d10 + 6', '!roll d20 > 10', 'Billy McBillface attempts to slay the dragon. (Roll: d20 > 10)'],
	singleArgument: true,
	patterns: [
		/\(\s*(?:roll|dice|rolldice|diceroll):\s*(.+?)(?:(>|<)\s*([0-9]+?))?\s*\)/i
	],

	isRunnable() {
		return true;
	},

	run(message, args, fromPattern) {
		if(!args[0]) return false;
		try {
			const matches = fromPattern ? args : pattern.exec(args[0]);
			const dice = new DiceExpression(matches[1]);

			// Restrict the maximum dice count
			const totalDice = dice.dice.reduce((prev, d) => prev + d.diceCount, 0);
			if(totalDice > 1000) {
				message.client.sendMessage(message, `${message.author} might hurt themselves by rolling that many dice at once!`);
				return;
			}

			// Roll the dice
			const rollResult = dice.roll();
			logger.debug(rollResult);

			// Build the list of dice
			let diceList = '';
			if(totalDice <= 100 && (rollResult.diceRaw.length > 1 || (rollResult.diceRaw.length > 0 && rollResult.diceRaw[0].length > 1))) {
				diceList = rollResult.diceRaw.map((r, i) => nbsp(r.length > 1 ? r.join(' + ') + ' = ' + rollResult.diceSums[i] : r[0])).join(',   ');
			}

			if(matches[2]) {
				// Determine whether or not the target is met
				const target = parseInt(matches[3]);
				let success = false;
				let targetMessage;
				if(matches[2] === '>') {
					success = rollResult.roll > target;
					targetMessage = `${!success ? 'not' : ''} greater than ${target}`;
				} else {
					success = rollResult.roll < target;
					targetMessage = `${!success ? 'not' : ''} less than ${target}`;
				}

				const diceInfo = diceList ? `;   ${diceList}` : '';
				message.client.sendMessage(message, `${message.author} has **${success ? 'succeeded' : 'failed'}**. (Rolled ${rollResult.roll}, ${targetMessage}${diceInfo})`);
			} else {
				const diceInfo = diceList ? ` (${diceList})` : '';
				message.client.sendMessage(message, `${message.author} rolled **${rollResult.roll}**.${diceInfo}`);
			}
		} catch(e) {
			logger.error(e);
			message.client.sendMessage(message, `${message.author} specified an invalid dice expression.`);
			return;
		}
	}
};
<|endoftext|>


<commit_before>let gridSize = 32
let grid

function setup() {
  grid = makeGrid(32, 32)
  createCanvas(512, 512)
  drawGrid(grid)
}

function makeGrid(x, y) {
  let g = new Array(x)
  for (var i = 0; i < g.length; i++) {
    g[i] = new Array(y)
  }

  return g
}

function drawGrid(grid, xoff = 0, yoff = 0) {
  if (xoff >= 32) {
    xoff = 32
  } else if (yoff >= 32) {
    yoff = 32
  }

  tileSize = floor(width / gridSize)

  for (var i = 0; i < grid.length; i++) {
    for (var j = 0; j < grid[i].length; j++) {
      if (grid[i][j] === undefined) {
        fill(51)
        stroke(0)
      } else {
        noStroke()
        fill(grid[i][j])
      }
      x = map(i + xoff, 0, 32, 0, 512)
      y = map(j + yoff, 0, 32, 0, 512)
      rect(x, y, tileSize, tileSize)
    }
  }
}

class Cat {
  constructor() {
    console.log("Everything is under control")
  }

  makePaw() {
    // generate variables that describe the paw
    let length = parseInt(random(5, 14))
    let thickness = parseInt(random(1, 3))
    let pawHeight = parseInt(random(1, 2))

    // make grid that will contain paw infos
    let paw = makeGrid(thickness + 1, length)

    // fill the grid with paw
    for (var x = 0; x < paw.length; x++) {
      for (var y = 0; y < paw[x].length; y++) {
        if (x === 0 && y < paw[x].length - pawHeight) {
          continue
        }
        paw[x][y] = color(255)
      }
    }

    return paw
  }
}
<commit_msg>replaced 'magic numbers' with variable references<commit_after>let gridSize = 32
let grid

function setup() {
  grid = makeGrid(gridSize, gridSize)
  createCanvas(512, 512)
  drawGrid(grid)
}

function makeGrid(x, y) {
  let g = new Array(x)
  for (var i = 0; i < g.length; i++) {
    g[i] = new Array(y)
  }

  return g
}

function drawGrid(grid, xoff = 0, yoff = 0) {
  if (xoff >= gridSize) {
    xoff = gridSize
  } else if (yoff >= gridSize) {
    yoff = gridSize
  }

  tileSize = floor(width / gridSize)

  for (var i = 0; i < grid.length; i++) {
    for (var j = 0; j < grid[i].length; j++) {
      if (grid[i][j] === undefined) {
        fill(51)
        stroke(0)
      } else {
        noStroke()
        fill(grid[i][j])
      }
      x = map(i + xoff, 0, gridSize, 0, width)
      y = map(j + yoff, 0, gridSize, 0, height)
      rect(x, y, tileSize, tileSize)
    }
  }
}

class Cat {
  constructor() {
    console.log("Everything is under control")
  }

  makePaw() {
    // generate variables that describe the paw
    let length = parseInt(random(5, 14))
    let thickness = parseInt(random(1, 3))
    let pawHeight = parseInt(random(1, 2))

    // make grid that will contain paw infos
    let paw = makeGrid(thickness + 1, length)

    // fill the grid with paw
    for (var x = 0; x < paw.length; x++) {
      for (var y = 0; y < paw[x].length; y++) {
        if (x === 0 && y < paw[x].length - pawHeight) {
          continue
        }
        paw[x][y] = color(255)
      }
    }

    return paw
  }
}
<|endoftext|>


<commit_before>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
var path = require("path");
var ModuleAliasPlugin = require("enhanced-resolve/lib/ModuleAliasPlugin");
var ModuleParserHelpers = require("./ModuleParserHelpers");

function NodeSourcePlugin() {
}
module.exports = NodeSourcePlugin;
NodeSourcePlugin.prototype.apply = function(compiler) {
	function ignore() { return true; }
	compiler.parser.plugin("expression process", function(expr) {
		return ModuleParserHelpers.addParsedVariable(this, "process", "require(" + JSON.stringify(path.join(__dirname, "..", "..", "buildin", "process.js")) + ")");
	});
	compiler.parser.plugin("expression global", function(expr) {
		this.state.current.addVariable("global", "this");
		return true;
	});
	compiler.parser.plugin("expression __filename", function(expr) {
		this.state.current.addVariable("__filename", JSON.stringify("/index.js"));
		return true;
	});
	compiler.parser.plugin("expression __dirname", function(expr) {
		this.state.current.addVariable("__dirname", JSON.stringify("/"));
		return true;
	});
	compiler.parser.plugin("expression module.exports", ignore);
	compiler.parser.plugin("expression module.loaded", ignore);
	compiler.parser.plugin("expression module.id", ignore);
	compiler.parser.plugin("expression module", function(expr) {
		return ModuleParserHelpers.addParsedVariable(this, "module", "require(" + JSON.stringify(path.join(__dirname, "..", "..", "buildin", "module.js")) + ")(module)");
	});
	compiler.resolvers.normal.apply(
		new ModuleAliasPlugin((function() {
			return [
				"assert",
				"buffer",
				"child_process",
				"events",
				"path",
				"punycode",
				"querystring",
				"url",
				"util"
			].reduce(function(o, v) {
				o[v] = path.join(__dirname, "..", "..", "buildin", "web_modules", v + ".js")
				return o;
			}, {});
		}()))
	);
};<commit_msg>path fix<commit_after>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
var path = require("path");
var ModuleAliasPlugin = require("enhanced-resolve/lib/ModuleAliasPlugin");
var ModuleParserHelpers = require("../ModuleParserHelpers");

function NodeSourcePlugin() {
}
module.exports = NodeSourcePlugin;
NodeSourcePlugin.prototype.apply = function(compiler) {
	function ignore() { return true; }
	compiler.parser.plugin("expression process", function(expr) {
		return ModuleParserHelpers.addParsedVariable(this, "process", "require(" + JSON.stringify(path.join(__dirname, "..", "..", "buildin", "process.js")) + ")");
	});
	compiler.parser.plugin("expression global", function(expr) {
		this.state.current.addVariable("global", "this");
		return true;
	});
	compiler.parser.plugin("expression __filename", function(expr) {
		this.state.current.addVariable("__filename", JSON.stringify("/index.js"));
		return true;
	});
	compiler.parser.plugin("expression __dirname", function(expr) {
		this.state.current.addVariable("__dirname", JSON.stringify("/"));
		return true;
	});
	compiler.parser.plugin("expression module.exports", ignore);
	compiler.parser.plugin("expression module.loaded", ignore);
	compiler.parser.plugin("expression module.id", ignore);
	compiler.parser.plugin("expression module", function(expr) {
		return ModuleParserHelpers.addParsedVariable(this, "module", "require(" + JSON.stringify(path.join(__dirname, "..", "..", "buildin", "module.js")) + ")(module)");
	});
	compiler.resolvers.normal.apply(
		new ModuleAliasPlugin((function() {
			return [
				"assert",
				"buffer",
				"child_process",
				"events",
				"path",
				"punycode",
				"querystring",
				"url",
				"util"
			].reduce(function(o, v) {
				o[v] = path.join(__dirname, "..", "..", "buildin", "web_modules", v + ".js")
				return o;
			}, {});
		}()))
	);
};<|endoftext|>


<commit_before>/*
This file is part of the Juju GUI, which lets users view and manage Juju
environments within a graphical interface (https://launchpad.net/juju-gui).
Copyright (C) 2012-2013 Canonical Ltd.

This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3, as published by
the Free Software Foundation.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranties of MERCHANTABILITY,
SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero
General Public License for more details.

You should have received a copy of the GNU Affero General Public License along
with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

'use strict';

/**
   Provides the sharing overlay widget.

   @namespace juju
   @module widgets
   @submodule browser
 */
YUI.add('browser-sharing-overlay', function(Y) {
  var ns = Y.namespace('juju.widgets.browser');
  ns.SharingOverlay= Y.Base.create('SharingOverlay', Y.Widget, [], {
    TEMPLATE: Y.namespace('juju.views').Templates['sharing-overlay'],

    _handleClick: function(e) {
      if (this.get('visible')) {
        this.hide();
      } else {
        this.show();
      }
    },

    /**
       Binds the button events to the UI

       @method bindUI
     */
    bindUI: function() {
      var button = this.get('button');
      button.on('click', this._handleClick, this);
    },

    /**
       Renders the overlay.

       @method renderUI
     */
    renderUI: function() {
      var content = this.TEMPLATE();
      var container = this.get('contentBox');
      container.setHTML(content);
      this.hide();
    }
  }, {
    ATTRS: {
      button: {}
    }
  });

}, '0.1.0', {
  requires: [
    'base',
    'handlebars',
    'juju-templates',
    'widget'
  ]
});
<commit_msg>Better name<commit_after>/*
This file is part of the Juju GUI, which lets users view and manage Juju
environments within a graphical interface (https://launchpad.net/juju-gui).
Copyright (C) 2012-2013 Canonical Ltd.

This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3, as published by
the Free Software Foundation.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranties of MERCHANTABILITY,
SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero
General Public License for more details.

You should have received a copy of the GNU Affero General Public License along
with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

'use strict';

/**
   Provides the sharing overlay widget.

   @namespace juju
   @module widgets
   @submodule browser
 */
YUI.add('browser-sharing-overlay', function(Y) {
  var ns = Y.namespace('juju.widgets.browser');
  ns.SharingOverlay= Y.Base.create('SharingOverlay', Y.Widget, [], {
    TEMPLATE: Y.namespace('juju.views').Templates['sharing-overlay'],

    /**
       Toggles the sharing overlay's visibility.

       @method _toggleVisible
       @param {Y.EventFacade} e The click event.
     */
    _toggleVisible: function(e) {
      if (this.get('visible')) {
        this.hide();
      } else {
        this.show();
      }
    },

    /**
       Binds the button events to the UI

       @method bindUI
     */
    bindUI: function() {
      this.get('button').on('click', this._toggleVisible, this);
    },

    /**
       Renders the overlay.

       @method renderUI
     */
    renderUI: function() {
      var content = this.TEMPLATE();
      var container = this.get('contentBox');
      container.setHTML(content);
      this.hide();
    }
  }, {
    ATTRS: {
      button: {}
    }
  });

}, '0.1.0', {
  requires: [
    'base',
    'handlebars',
    'juju-templates',
    'widget'
  ]
});
<|endoftext|>


<commit_before>/**
 * @file Various information of the bot.
 * @author Ovyerus
 */

/* eslint-env node */

const prettyBytes = require('pretty-bytes');
const fs = require('fs');
const path = require('path');
var version;

try {
    version = JSON.parse(fs.readFile(path.normalize(`${__baseDir}/../package.json`))).version;
} catch(_) {
    version = JSON.parse(fs.readFile(`${__baseDir}/package.json`)).version;
}

exports.commands = [
    'info'
];

exports.info = {
    desc: 'Information about the bot.',
    main(bot, ctx) {
        return new Promise((resolve, reject) => {
            let date = new Date();
            let sysTime = `${date.getFullYear()}-${('0' + (date.getMonth() + 1)).slice(-2)}-${date.getDate()}\n${('0' + (date.getHours() + 1)).slice(-2)}:${('0' + (date.getMinutes() + 1)).slice(-2)}:${('0' + (date.getSeconds() + 1)).slice(-2)}`;
            let roleColour = ctx.guildBot.roles.sort((a, b) => ctx.guild.roles.get(b).position - ctx.guild.roles.get(a).position)[0];
            roleColour = roleColour ? ctx.guild.roles.get(roleColour).color : 0;

            ctx.createMessage({embed: {
                title: `${bot.user.username}'s Info`,
                description: `[${localeManager.t('info-source')}](https://github.com/ClaraIO/Clara) | [${localeManager.t('info-supportServer')}](https://discord.gg/rmMTZue)`,
                thumbnail: {url: bot.user.avatarURL},
                color: roleColour,
                fields: [
                    {name: 'info-guilds', value: bot.guilds.size, inline: true},
                    {name: 'info-users', value: bot.users.size, inline: true},
                    {name: 'info-uptime', value: utils.msToTime(bot.uptime), inline: true},
                    {name: 'info-sysTime', value: sysTime, inline: true},
                    {name: 'info-shards', value: bot.shards.size, inline: true},
                    {name: 'info-mem', value: prettyBytes(process.memoryUsage().rss), inline: true},
                    {name: 'info-NodeVersion', value: process.version, inline: true},
                    {name: 'info-version', value: version, inline: true}
                ],
                footer: {text: 'info-footer'}
            }}, null, 'channel', {name: bot.user.username}).then(resolve).catch(reject);
        });
    }
};<commit_msg>Revert "use asynchronus readFile for FS"<commit_after>/**
 * @file Various information of the bot.
 * @author Ovyerus
 */

/* eslint-env node */

const prettyBytes = require('pretty-bytes');
const fs = require('fs');
const path = require('path');
var version;

try {
    version = JSON.parse(fs.readFileSync(path.normalize(`${__baseDir}/../package.json`))).version;
} catch(_) {
    version = JSON.parse(fs.readFileSync(`${__baseDir}/package.json`)).version;
}

exports.commands = [
    'info'
];

exports.info = {
    desc: 'Information about the bot.',
    main(bot, ctx) {
        return new Promise((resolve, reject) => {
            let date = new Date();
            let sysTime = `${date.getFullYear()}-${('0' + (date.getMonth() + 1)).slice(-2)}-${date.getDate()}\n${('0' + (date.getHours() + 1)).slice(-2)}:${('0' + (date.getMinutes() + 1)).slice(-2)}:${('0' + (date.getSeconds() + 1)).slice(-2)}`;
            let roleColour = ctx.guildBot.roles.sort((a, b) => ctx.guild.roles.get(b).position - ctx.guild.roles.get(a).position)[0];
            roleColour = roleColour ? ctx.guild.roles.get(roleColour).color : 0;

            ctx.createMessage({embed: {
                title: `${bot.user.username}'s Info`,
                description: `[${localeManager.t('info-source')}](https://github.com/ClaraIO/Clara) | [${localeManager.t('info-supportServer')}](https://discord.gg/rmMTZue)`,
                thumbnail: {url: bot.user.avatarURL},
                color: roleColour,
                fields: [
                    {name: 'info-guilds', value: bot.guilds.size, inline: true},
                    {name: 'info-users', value: bot.users.size, inline: true},
                    {name: 'info-uptime', value: utils.msToTime(bot.uptime), inline: true},
                    {name: 'info-sysTime', value: sysTime, inline: true},
                    {name: 'info-shards', value: bot.shards.size, inline: true},
                    {name: 'info-mem', value: prettyBytes(process.memoryUsage().rss), inline: true},
                    {name: 'info-NodeVersion', value: process.version, inline: true},
                    {name: 'info-version', value: version, inline: true}
                ],
                footer: {text: 'info-footer'}
            }}, null, 'channel', {name: bot.user.username}).then(resolve).catch(reject);
        });
    }
};<|endoftext|>


<commit_before>var express = require('express');
var compress = require('compression');

var app = express();

app.use(compress());

app.all(/.*/, function(req, res, next) {
	var host = req.header("host");
	if (host.match(/^www\..*/)) {
		res.redirect(301, req.protocol + '://alreadycoding.com');
		res.end();
	} else {
		next();
	}
});

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

var port = process.env.PORT || 1337;
app.listen(port);<commit_msg>updated redirect logic<commit_after>var express = require('express');
var compress = require('compression');

var app = express();

app.use(compress());

app.all(/.*/, function(req, res, next) {
	if (req.headers.host.match(/^www\./) !== null) {
		res.redirect(301, req.protocol + '://' + req.headers.host.replace(/^www\./, '') + req.url);
	} else {
		next();
	}
});

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

var port = process.env.PORT || 1337;
app.listen(port);<|endoftext|>