<commit_before>import React from 'react';
import { shallow, mount } from 'enzyme';
import Decimal from './decimal.component';
import Textbox from '../textbox/textbox.component';

const input = shallow(<Decimal onChange={() => true} />)

describe('Decimal', () => {
  describe('Input validation', () => {
    it('does not allow the user to enter letters or special characters', () => {
      input.setProps({ value: '1hello$1.27' })
      expect(input.find('Textbox').prop('value')).toEqual('11.27');
    });
    it('does not allow the user to enter commas after the decimal point', () => {
      const test = false;
      expect(test).toEqual(true);
    });
    it('formats the commas correctly on blur', () => {
      const test = false;
      expect(test).toEqual(true);
    });
    it('updates the value after increasing the precison', () => {
      const test = false;
      expect(test).toEqual(true);
    });
    it('updates the value after decreasing the precison', () => {
      const test = false;
      expect(test).toEqual(true);
    });
    it('does not allow the precison to be greater than 20', () => {
      const test = false;
      expect(test).toEqual(true);
    });
  });
  // DQ: DO THESE ACTUALLY GO HERE?!?!
  describe('Layout', () => {
    it('allows the input width to be set', () => {
      const test = false;
      expect(test).toEqual(true);
    });
    it('sets the input width correctly if the inlineInput prop is true', () => {
      const test = false;
      expect(test).toEqual(true);
    });
    it('allows the label width to be set if the inlineInput prop is true', () => {
      const test = false;
      expect(test).toEqual(true);
    });
    it('aligns the value within the input based on align prop', () => {
      const test = false;
      expect(test).toEqual(true);
    });
  });
});
<commit_msg>First Spec for Decimal Component<commit_after>import React from 'react';
import { shallow, mount } from 'enzyme';
import Decimal from './decimal.component';
import Textbox from '../textbox/textbox.component';

const input = shallow(<Decimal onChange={() => true} value='12.34' />)

describe('Decimal', () => {
  describe('Input validation', () => {
    it('does not allow the user to enter letters or special characters', () => {
      input.instance().handleChange({ target: {value: '1hello$1.27'} })
      expect(input.find('Textbox').prop('value')).toEqual('12.34');
    });
    it('does not allow the user to enter commas after the decimal point', () => {
      const test = false;
      expect(test).toEqual(true);
    });
    it('formats the commas correctly on blur', () => {
      const test = false;
      expect(test).toEqual(true);
    });
    it('updates the value after increasing the precison', () => {
      const test = false;
      expect(test).toEqual(true);
    });
    it('updates the value after decreasing the precison', () => {
      const test = false;
      expect(test).toEqual(true);
    });
    it('does not allow the precison to be greater than 20', () => {
      const test = false;
      expect(test).toEqual(true);
    });
  });
  // DQ: DO THESE ACTUALLY GO HERE?!?!
  describe('Layout', () => {
    it('allows the input width to be set', () => {
      const test = false;
      expect(test).toEqual(true);
    });
    it('sets the input width correctly if the inlineInput prop is true', () => {
      const test = false;
      expect(test).toEqual(true);
    });
    it('allows the label width to be set if the inlineInput prop is true', () => {
      const test = false;
      expect(test).toEqual(true);
    });
    it('aligns the value within the input based on align prop', () => {
      const test = false;
      expect(test).toEqual(true);
    });
  });
});
<|endoftext|>


<commit_before>const omit = require('omit-deep');
const pick = require('lodash.pick');
const mongoose = require('mongoose');

// try to find an id property, otherwise just use the index in the array
const objectHash = (obj, idx) => obj._id || obj.id || `$$index: ${idx}`;
const diffPatcher = require('jsondiffpatch').create({ objectHash });

const History = require('./diffHistoryModel').model;

const isValidCb = cb => {
    return cb && typeof cb === 'function';
};

const saveDiffObject = (currentObject, original, updated, opts, queryObject) => {
    const { __user: user, __reason: reason } = queryObject && queryObject.options || currentObject;
    const updateObject = (!!updated['toObject'])? updated.toObject({ depopulate: true }) :
    updated;

    let diff = diffPatcher.diff(
        JSON.parse(JSON.stringify(original)),
        JSON.parse(JSON.stringify(updateObject))
    );

    if (opts.omit) {
        omit(diff, opts.omit, {cleanEmpty: true});
    }

    if (opts.pick){
        diff = pick(diff, opts.pick);
    }

    if (!diff || !Object.keys(diff).length) return;

    const collectionId = currentObject._id;
    const collectionName = currentObject.constructor.modelName || queryObject.model.modelName;

    return History.findOne({ collectionId, collectionName })
        .sort('-version')
        .then(lastHistory => {
            const history = new History({
                collectionId,
                collectionName,
                diff,
                user,
                reason,
                version: lastHistory ? lastHistory.version + 1 : 0
            });
            return history.save();
        });
};

const saveDiffHistory = (queryObject, currentObject, opts) => {
    const updateParams = queryObject._update["$set"] || queryObject._update["$push"] || queryObject._update;
    const dbObject = pick(currentObject, Object.keys(updateParams));

    if(queryObject._update["$push"]){
       let originalObj = JSON.parse(JSON.stringify(dbObject));
       Object.keys(updateParams).forEach(updateKey => {
         let existingObjects = originalObj[updateKey];
         existingObjects.push(updateParams[updateKey]);
         updateParams[updateKey] = existingObjects
       });

    }

    return saveDiffObject(currentObject, dbObject, updateParams, opts, queryObject);
};

const saveDiffs = (queryObject, opts) =>
    queryObject
        .find(queryObject._conditions)
        .lean(false)
        .cursor()
        .eachAsync(result => saveDiffHistory(queryObject, result, opts));

const getVersion = (model, id, version, queryOpts, cb) => {
    if (typeof queryOpts === 'function') {
        cb = queryOpts;
        queryOpts = undefined;
    }

    return model
        .findById(id, null, queryOpts)
        .then(latest => {
            latest = latest || {};
            return History.find(
                {
                    collectionName: model.modelName,
                    collectionId: id,
                    version: { $gte: parseInt(version, 10) }
                },
                { diff: 1, version: 1 },
                { sort: '-version' }
            )
                .lean()
                .cursor()
                .eachAsync(history => {
                    diffPatcher.unpatch(latest, history.diff);
                })
                .then(() => {
                    if (isValidCb(cb)) return cb(null, latest);
                    return latest;
                });
        })
        .catch(err => {
            if (isValidCb(cb)) return cb(err, null);
            throw err;
        });
};

const getDiffs = (modelName, id, opts, cb) => {
    opts = opts || {};
    if (typeof opts === 'function') {
        cb = opts;
        opts = {};
    }
    return History.find({ collectionName: modelName, collectionId: id }, null, opts)
        .lean()
        .then(histories => {
            if (isValidCb(cb)) return cb(null, histories);
            return histories;
        })
        .catch(err => {
            if (isValidCb(cb)) return cb(err, null);
            throw err;
        });
};

const getHistories = (modelName, id, expandableFields, cb) => {
    expandableFields = expandableFields || [];
    if (typeof expandableFields === 'function') {
        cb = expandableFields;
        expandableFields = [];
    }

    const histories = [];

    return History.find({ collectionName: modelName, collectionId: id })
        .lean()
        .cursor()
        .eachAsync(history => {
            const changedValues = [];
            const changedFields = [];
            for (const key in history.diff) {
                if (history.diff.hasOwnProperty(key)) {
                    if (expandableFields.indexOf(key) > -1) {
                        const oldValue = history.diff[key][0];
                        const newValue = history.diff[key][1];
                        changedValues.push(key + ' from ' + oldValue + ' to ' + newValue);
                    } else {
                        changedFields.push(key);
                    }
                }
            }
            const comment = 'modified ' + changedFields.concat(changedValues).join(', ');
            histories.push({
                changedBy: history.user,
                changedAt: history.createdAt,
                updatedAt: history.updatedAt,
                reason: history.reason,
                comment: comment
            });
        })
        .then(() => {
            if (isValidCb(cb)) return cb(null, histories);
            return histories;
        })
        .catch(err => {
            if (isValidCb(cb)) return cb(err, null);
            throw err;
        });
};

/**
 * @param {Object} schema - Schema object passed by Mongoose Schema.plugin
 * @param {Object} [opts] - Options passed by Mongoose Schema.plugin
 * @param {string} [opts.uri] - URI for MongoDB (necessary, for instance, when not using mongoose.connect).
 * @param {string|string[]} [opts.omit] - fields to omit from diffs (ex. ['a', 'b.c.d']).
 */
const plugin = function lastModifiedPlugin(schema, opts = {}) {
    if (opts.uri) {
        const mongoVersion = parseInt(mongoose.version);
        if(mongoVersion < 5){
          mongoose.connect(opts.uri, { useMongoClient: true }).catch((e) => {
            console.error('mongoose-diff-history connection error:', e);
          });
        } else {
          mongoose.connect(opts.uri, { useNewUrlParser: true }).catch((e) => {
            console.error('mongoose-diff-history connection error:', e);
          });
        }
    }

    if (opts.omit && !Array.isArray(opts.omit)) {
        if (typeof opts.omit === 'string') {
            opts.omit = [opts.omit];
        } else {
            const errMsg = `opts.omit expects string or array, instead got '${typeof opts.omit}'`;
            throw new TypeError(errMsg);
        }
    }

    schema.pre('save', function (next) {
        if (this.isNew) return next();
        this.constructor
            .findOne({ _id: this._id })
            .then(original => saveDiffObject(this, original, this, opts))
            .then(() => next())
            .catch(next);
    });

    schema.pre('findOneAndUpdate', function (next) {
        saveDiffs(this, opts)
            .then(() => next())
            .catch(next);
    });

    schema.pre('update', function (next) {
        saveDiffs(this, opts)
            .then(() => next())
            .catch(next);
    });

    schema.pre('updateOne', function (next) {
        saveDiffs(this, opts)
            .then(() => next())
            .catch(next);
    });

    schema.pre('remove', function (next) {
        saveDiffObject(this, this, {}, opts)
            .then(() => next())
            .catch(next);
    });
};

module.exports = {
    plugin,
    getVersion,
    getDiffs,
    getHistories
};
<commit_msg>syntax fix<commit_after>const omit = require('omit-deep');
const pick = require('lodash.pick');
const mongoose = require('mongoose');

// try to find an id property, otherwise just use the index in the array
const objectHash = (obj, idx) => obj._id || obj.id || `$$index: ${idx}`;
const diffPatcher = require('jsondiffpatch').create({ objectHash });

const History = require('./diffHistoryModel').model;

const isValidCb = cb => {
    return cb && typeof cb === 'function';
};

const saveDiffObject = (currentObject, original, updated, opts, queryObject) => {
    const { __user: user, __reason: reason } = queryObject && queryObject.options || currentObject;
    const updateObject = (!!updated['toObject'])? updated.toObject({ depopulate: true }) :
    updated;

    let diff = diffPatcher.diff(
        JSON.parse(JSON.stringify(original)),
        JSON.parse(JSON.stringify(updateObject))
    );

    if (opts.omit) {
        omit(diff, opts.omit, {cleanEmpty: true});
    }

    if (opts.pick){
        diff = pick(diff, opts.pick);
    }

    if (!diff || !Object.keys(diff).length) return;

    const collectionId = currentObject._id;
    const collectionName = currentObject.constructor.modelName || queryObject.model.modelName;

    return History.findOne({ collectionId, collectionName })
        .sort('-version')
        .then(lastHistory => {
            const history = new History({
                collectionId,
                collectionName,
                diff,
                user,
                reason,
                version: lastHistory ? lastHistory.version + 1 : 0
            });
            return history.save();
        });
};

const saveDiffHistory = (queryObject, currentObject, opts) => {
    const updateParams = queryObject._update["$set"] || queryObject._update["$push"] || queryObject._update;
    const dbObject = pick(currentObject, Object.keys(updateParams));

    if(queryObject._update["$push"]){
       let originalObj = JSON.parse(JSON.stringify(dbObject));
       Object.keys(updateParams).forEach((updateKey) => {
         let existingObjects = originalObj[updateKey];
         existingObjects.push(updateParams[updateKey]);
         updateParams[updateKey] = existingObjects;
       });

    }

    return saveDiffObject(currentObject, dbObject, updateParams, opts, queryObject);
};

const saveDiffs = (queryObject, opts) =>
    queryObject
        .find(queryObject._conditions)
        .lean(false)
        .cursor()
        .eachAsync(result => saveDiffHistory(queryObject, result, opts));

const getVersion = (model, id, version, queryOpts, cb) => {
    if (typeof queryOpts === 'function') {
        cb = queryOpts;
        queryOpts = undefined;
    }

    return model
        .findById(id, null, queryOpts)
        .then(latest => {
            latest = latest || {};
            return History.find(
                {
                    collectionName: model.modelName,
                    collectionId: id,
                    version: { $gte: parseInt(version, 10) }
                },
                { diff: 1, version: 1 },
                { sort: '-version' }
            )
                .lean()
                .cursor()
                .eachAsync(history => {
                    diffPatcher.unpatch(latest, history.diff);
                })
                .then(() => {
                    if (isValidCb(cb)) return cb(null, latest);
                    return latest;
                });
        })
        .catch(err => {
            if (isValidCb(cb)) return cb(err, null);
            throw err;
        });
};

const getDiffs = (modelName, id, opts, cb) => {
    opts = opts || {};
    if (typeof opts === 'function') {
        cb = opts;
        opts = {};
    }
    return History.find({ collectionName: modelName, collectionId: id }, null, opts)
        .lean()
        .then(histories => {
            if (isValidCb(cb)) return cb(null, histories);
            return histories;
        })
        .catch(err => {
            if (isValidCb(cb)) return cb(err, null);
            throw err;
        });
};

const getHistories = (modelName, id, expandableFields, cb) => {
    expandableFields = expandableFields || [];
    if (typeof expandableFields === 'function') {
        cb = expandableFields;
        expandableFields = [];
    }

    const histories = [];

    return History.find({ collectionName: modelName, collectionId: id })
        .lean()
        .cursor()
        .eachAsync(history => {
            const changedValues = [];
            const changedFields = [];
            for (const key in history.diff) {
                if (history.diff.hasOwnProperty(key)) {
                    if (expandableFields.indexOf(key) > -1) {
                        const oldValue = history.diff[key][0];
                        const newValue = history.diff[key][1];
                        changedValues.push(key + ' from ' + oldValue + ' to ' + newValue);
                    } else {
                        changedFields.push(key);
                    }
                }
            }
            const comment = 'modified ' + changedFields.concat(changedValues).join(', ');
            histories.push({
                changedBy: history.user,
                changedAt: history.createdAt,
                updatedAt: history.updatedAt,
                reason: history.reason,
                comment: comment
            });
        })
        .then(() => {
            if (isValidCb(cb)) return cb(null, histories);
            return histories;
        })
        .catch(err => {
            if (isValidCb(cb)) return cb(err, null);
            throw err;
        });
};

/**
 * @param {Object} schema - Schema object passed by Mongoose Schema.plugin
 * @param {Object} [opts] - Options passed by Mongoose Schema.plugin
 * @param {string} [opts.uri] - URI for MongoDB (necessary, for instance, when not using mongoose.connect).
 * @param {string|string[]} [opts.omit] - fields to omit from diffs (ex. ['a', 'b.c.d']).
 */
const plugin = function lastModifiedPlugin(schema, opts = {}) {
    if (opts.uri) {
        const mongoVersion = parseInt(mongoose.version);
        if(mongoVersion < 5){
          mongoose.connect(opts.uri, { useMongoClient: true }).catch((e) => {
            console.error('mongoose-diff-history connection error:', e);
          });
        } else {
          mongoose.connect(opts.uri, { useNewUrlParser: true }).catch((e) => {
            console.error('mongoose-diff-history connection error:', e);
          });
        }
    }

    if (opts.omit && !Array.isArray(opts.omit)) {
        if (typeof opts.omit === 'string') {
            opts.omit = [opts.omit];
        } else {
            const errMsg = `opts.omit expects string or array, instead got '${typeof opts.omit}'`;
            throw new TypeError(errMsg);
        }
    }

    schema.pre('save', function (next) {
        if (this.isNew) return next();
        this.constructor
            .findOne({ _id: this._id })
            .then(original => saveDiffObject(this, original, this, opts))
            .then(() => next())
            .catch(next);
    });

    schema.pre('findOneAndUpdate', function (next) {
        saveDiffs(this, opts)
            .then(() => next())
            .catch(next);
    });

    schema.pre('update', function (next) {
        saveDiffs(this, opts)
            .then(() => next())
            .catch(next);
    });

    schema.pre('updateOne', function (next) {
        saveDiffs(this, opts)
            .then(() => next())
            .catch(next);
    });

    schema.pre('remove', function (next) {
        saveDiffObject(this, this, {}, opts)
            .then(() => next())
            .catch(next);
    });
};

module.exports = {
    plugin,
    getVersion,
    getDiffs,
    getHistories
};
<|endoftext|>


<commit_before>var semver = require('semver');
var _ = require('lodash');
var agent = require('superagent');

var SEMVER = /[0-9]+\.[0-9]+\.[0-9]+(-rc[0-9]+)?/g;
var TIMEOUT = 20000;
var NOOP = function() {};

function MongoDBSource(options) {
  _.extend(this, {
    name: 'mongodb',
    url: 'https://www.mongodb.org/dl/osx',
    all: [],
    stable: [],
    updated: undefined
  }, options);
}

MongoDBSource.prototype.update = function(done) {
  done = done || NOOP;

  return agent.get(this.url)
    .timeout(TIMEOUT)
    .end(parseResponse.bind(this));

  function parseResponse(err, res) {
    if (err) {
      return done(err, false);
    }
    if (!res.text) {
      return done(new Error('No response'), false);
    }
    if (res.status !== 200) {
      return done(new Error('Bad response'), false);
    }

    this._parse(res.text);

    return done(undefined, true);
  }
};

MongoDBSource.prototype._parse = function(body) {
  var matches = body.match(SEMVER);
  var versions = _.unique(matches);

  this.all = versions.sort(semver.compare);
  this.stable = versions.filter(function(version) {
    return semver(version).prerelease.length === 0;
  });
  this.updated = new Date();
};

module.exports = MongoDBSource;
<commit_msg>MongoDBSource now uses linux url<commit_after>var semver = require('semver');
var _ = require('lodash');
var agent = require('superagent');

var SEMVER = /[0-9]+\.[0-9]+\.[0-9]+(-rc[0-9]+)?/g;
var TIMEOUT = 20000;
var NOOP = function() {};

function MongoDBSource(options) {
  _.extend(this, {
    name: 'mongodb',
    url: 'https://www.mongodb.org/dl/linux',
    all: [],
    stable: [],
    updated: undefined
  }, options);
}

MongoDBSource.prototype.update = function(done) {
  done = done || NOOP;

  return agent.get(this.url)
    .timeout(TIMEOUT)
    .end(parseResponse.bind(this));

  function parseResponse(err, res) {
    if (err) {
      return done(err, false);
    }
    if (!res.text) {
      return done(new Error('No response'), false);
    }
    if (res.status !== 200) {
      return done(new Error('Bad response'), false);
    }

    this._parse(res.text);

    return done(undefined, true);
  }
};

MongoDBSource.prototype._parse = function(body) {
  var matches = body.match(SEMVER);
  var versions = _.unique(matches);

  this.all = versions.sort(semver.compare);
  this.stable = versions.filter(function(version) {
    return semver(version).prerelease.length === 0;
  });
  this.updated = new Date();
};

module.exports = MongoDBSource;
<|endoftext|>


<commit_before>const express = require('express');
const Router = express.Router;
const userRouter = Router();
const mongoose = require('mongoose');
const User = require('../models/user.model.js');
const Asset = require('../models/asset.model.js');
const Job = require('../models/job.model');
const token = require('../auth/token.js');
const bodyParser = require('body-parser').json();
const ensureAuth = require('../auth/ensure-auth')();

function hasUserNameAndPassword(req, res, next) {
    const user = req.body;
    if(!user.username || !user.password) {
        return next({
            code: 400,
            error: 'username and password must be provided'
        });
    }
    next();
}

function getRandomJob() {
    let entryJob = {};
    return Job.find( { jobLevel: 'Entry' } )
        .then(jobs => {
            //TODO: investigate using aggregate $sample
            if(!jobs.length) return;
            let maxJobs = jobs.length + 1;
            let randomNum = Math.floor(Math.random() * maxJobs);
            entryJob.start_date = new Date();
            entryJob.job_name = jobs[randomNum]._id;
            console.log('entry', entryJob);
            return entryJob;
        })
}

userRouter
    .get('/verify', ensureAuth, (req, res) => {
        res.send({ valid: true });
    })

    .post('/signup', bodyParser, hasUserNameAndPassword, (req, res, next) => {
        let data = req.body;
        User.find({ username: data.username }).count()
            .then(count => {
                if(count > 0) throw {
                    code: 400,
                    error: `username ${data.username} already exists`
                };
                else {
                    data.retired = false;
                    data.age = 18;
                    data.bank_account = Math.floor(Math.random()*200000) + 1;
                    data.networth = data.bank_account;
                    data.assets = [];
                    data.original_signup = new Date();
                    data.last_sign_in = data.original_signup;
                    return getRandomJob();
                }
            })
            .then(job => {
                data.job = job;
                return new User(data).save();
            })
            .then(user => token.sign(user))
            .then(token => res.send({ token }))
            .catch(next);
    })

    .post('/signin', bodyParser, hasUserNameAndPassword, ensureAuth, (req, res, next) => {
        const data = req.body;

        User.findOne({ username: data.username })
            .then(user => {
                if(!user || !user.comparePassword(data.password)) {
                    throw {
                        code: 400,
                        error: 'invalid username or password'
                    };
                }
                user.last_sign_in = new Date();
                user.save();
                return user;
            })
            .then(user => token.sign(user))
            .then(token => res.send({token}))
            .catch(next);
    })

    .post('/:username/assets', bodyParser, ensureAuth, (req, res, next) => {
        let data = req.body;
        let desiredAsset = {};
        let savedAsset = {};
        const username = req.params.username;
        Asset.findById(data._id)
            .then(asset => {
                desiredAsset = asset;
            });
        return User.findOne({username: username})
            .then(user => {
                const cash = user.bank_account;
                if(desiredAsset.purchase_price > cash) {
                    res.status(400).send({error: 'You do have funds for this purchase'});
                } else {

                    user.bank_account = user.bank_account - desiredAsset.purchase_price;
                    savedAsset.purchase_date = new Date();
                    savedAsset.asset_name = desiredAsset._id;
                    user.assets.push(savedAsset);
                }
                return user.save();
            })
            .then(user => res.send(user))
            .catch(next);
    })

    .get('/:username', ensureAuth, (req, res, next) => {
        const username = req.params.username;
        User.findOne({ username: username })
            .populate('job.job_name')
            .populate('assets.asset_name')
            .then(user => {
                console.log('user',user)
                if(!user){
                    res.status(404).send({error: 'Cannot Find User'});
                } else {
                    res.send(user);
                }
            });
    });

module.exports = userRouter;<commit_msg>added semicolons<commit_after>const express = require('express');
const Router = express.Router;
const userRouter = Router();
const mongoose = require('mongoose');
const User = require('../models/user.model.js');
const Asset = require('../models/asset.model.js');
const Job = require('../models/job.model');
const token = require('../auth/token.js');
const bodyParser = require('body-parser').json();
const ensureAuth = require('../auth/ensure-auth')();

function hasUserNameAndPassword(req, res, next) {
    const user = req.body;
    if(!user.username || !user.password) {
        return next({
            code: 400,
            error: 'username and password must be provided'
        });
    }
    next();
}

function getRandomJob() {
    let entryJob = {};
    return Job.find( { jobLevel: 'Entry' } )
        .then(jobs => {
            //TODO: investigate using aggregate $sample
            if(!jobs.length) return;
            let maxJobs = jobs.length + 1;
            let randomNum = Math.floor(Math.random() * maxJobs);
            entryJob.start_date = new Date();
            entryJob.job_name = jobs[randomNum]._id;
            return entryJob;
        });
}

userRouter
    .get('/verify', ensureAuth, (req, res) => {
        res.send({ valid: true });
    })

    .post('/signup', bodyParser, hasUserNameAndPassword, (req, res, next) => {
        let data = req.body;
        User.find({ username: data.username }).count()
            .then(count => {
                if(count > 0) throw {
                    code: 400,
                    error: `username ${data.username} already exists`
                };
                else {
                    data.retired = false;
                    data.age = 18;
                    data.bank_account = Math.floor(Math.random()*200000) + 1;
                    data.networth = data.bank_account;
                    data.assets = [];
                    data.original_signup = new Date();
                    data.last_sign_in = data.original_signup;
                    return getRandomJob();
                }
            })
            .then(job => {
                data.job = job;
                return new User(data).save();
            })
            .then(user => token.sign(user))
            .then(token => res.send({ token }))
            .catch(next);
    })

    .post('/signin', bodyParser, hasUserNameAndPassword, ensureAuth, (req, res, next) => {
        const data = req.body;

        User.findOne({ username: data.username })
            .then(user => {
                if(!user || !user.comparePassword(data.password)) {
                    throw {
                        code: 400,
                        error: 'invalid username or password'
                    };
                }
                user.last_sign_in = new Date();
                user.save();
                return user;
            })
            .then(user => token.sign(user))
            .then(token => res.send({token}))
            .catch(next);
    })

    .post('/:username/assets', bodyParser, ensureAuth, (req, res, next) => {
        let data = req.body;
        let desiredAsset = {};
        let savedAsset = {};
        const username = req.params.username;
        Asset.findById(data._id)
            .then(asset => {
                desiredAsset = asset;
            });
        return User.findOne({username: username})
            .then(user => {
                const cash = user.bank_account;
                if(desiredAsset.purchase_price > cash) {
                    res.status(400).send({error: 'You do have funds for this purchase'});
                } else {

                    user.bank_account = user.bank_account - desiredAsset.purchase_price;
                    savedAsset.purchase_date = new Date();
                    savedAsset.asset_name = desiredAsset._id;
                    user.assets.push(savedAsset);
                }
                return user.save();
            })
            .then(user => res.send(user))
            .catch(next);
    })

    .get('/:username', ensureAuth, (req, res, next) => {
        const username = req.params.username;
        User.findOne({ username: username })
            .populate('job.job_name')
            .populate('assets.asset_name')
            .then(user => {
                console.log('user',user);
                if(!user){
                    res.status(404).send({error: 'Cannot Find User'});
                } else {
                    res.send(user);
                }
            });
    });

module.exports = userRouter;<|endoftext|>


<commit_before>/**
 * @file:   Implementation of Myers longest common subsequence algorithm using
 *          an edit graph.
 * @see:
 * * http://dx.doi.org/10.1007/BF01840446
 * * http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927
 */

(function(exports){
    function Editgraph(a, b, x, y, N, M, dmax) {
        this.a = a;
        this.b = b;

        this.x = (typeof x === 'undefined') ? 0 : x;
        this.y = (typeof y === 'undefined') ? 0 : y;
        this.N = (typeof N === 'undefined') ? a.length : N;
        this.M = (typeof M === 'undefined') ? b.length : M;
        this.dmax = (typeof dmax === 'undefined') ? this.N + this.M : dmax;
    }

    Editgraph.prototype.equals = function(a, b) {
        return (a === b);
    };

    /**
     * Call a function for each D-Path identified using myers basic greedy lcs
     * algorithm.
     *
     * Returns the length of the shortest edit script, i.e. the minimal number
     * of insert and delete operations required to turn a into b.
     *
     * @param onsnake function(snake, k0)
     */
    Editgraph.prototype.forEachSnakeHead = function (onsnake, T) {
        var d, k, snake, k0, end;
        var V = {};

        V[1] = 0;
        snake = new SnakeHead();
        for (d = 0; d <= this.dmax; d++) {
            for (k = -d; k <= d; k+=2) {
                k0 = this.nextSnakeHeadForward(snake, k, -d, d, V);
                if (onsnake) {
                    onsnake.call(T, snake, k0, d);
                }

                // check if we are done
                end = snake.toPoint();
                if (end.x >= this.N && end.y >= this.M) {
                    return d;
                }
            }
        }
    };

    /**
     * Call a function for each reverse D-Path identified using myers basic
     * greedy lcs algorithm.
     *
     * Returns the length of the shortest edit script, i.e. the minimal number
     * of insert and delete operations required to turn a into b.
     *
     * @param onsnake function(dsnake, precedessor)
     */
    Editgraph.prototype.forEachReverseSnakeHead = function (onsnake, T) {
        var delta = this.N - this.M;
        var d, k, snake, k0, end;
        var V = {};

        V[delta-1] = this.N;
        snake = new SnakeHead();
        for (d = 0; d <= this.dmax; d++) {
            for (k = -d+delta; k <= d+delta; k+=2) {
                snake.k = k;
                k0 = this.nextSnakeHeadBackward(snake, k, -d+delta, d+delta, V);
                if (onsnake) {
                    onsnake.call(T, snake, k0, d);
                }

                // check if we are done
                end = snake.toPoint();
                if (end.x <= 0 && end.y <= 0) {
                    return d;
                }
            }
        }
    };

    Editgraph.prototype.nextSnakeHeadForward = function(snake, k, kmin, kmax, V) {
        var k0, x;

        // Store current k-value in the snake.
        snake.k = k;

        // Determine the preceeding snake. Pick the one whose furthest reaching
        // x value is greatest.
        if (k === kmin || (k !== kmax && V[k-1] < V[k+1])) {
            // Furthest reaching snake is above (k+1), move down.
            k0 = k+1;
            x = V[k0];
        }
        else {
            // Furthest reaching snake is left (k-1), move right.
            k0 = k-1;
            x = V[k0] + 1;
        }

        // Compute the snake: Move along the diagonal as long as there are
        // common values in a and b.
        while (x < this.N && x - k < this.M && this.equals(
                    this.a[this.x + x], this.b[this.y + x - k])) {
            x++;
        }

        // Store x value of snake after traversing the diagonal in forward
        // direction.
        snake.x = x;

        // Memozie furthest reaching x for k
        V[k] = x;

        // Return k-value of preceeding snake
        return k0;
    };

    Editgraph.prototype.nextSnakeHeadBackward = function(snake, k, kmin, kmax, V) {
        var k0, x, k = snake.k;

        // Store current k-value in the snake.
        snake.k = k;

        // Determine the preceeding snake. Pick the one whose furthest reaching
        // x value is greatest.
        if (k === kmax || (k !== kmin && V[k-1] < V[k+1])) {
            // Furthest reaching snake is underneath (k-1), move up.
            k0 = k-1;
            x = V[k-1];
        }
        else {
            // Furthest reaching snake is left (k-1), move right.
            k0 = k+1;
            x = V[k0]-1;
        }

        // Store x value of snake before traversing the diagonal in reverse
        // direction.
        snake.x = x;

        // Compute the snake: Move along the diagonal as long as there are
        // common values in a and b.
        while (x > 0 && x - k > 0 && this.equals(
                    this.a[this.x + x - 1], this.b[this.y + x - k - 1])) {
            x--;
        }

        // Memozie furthest reaching x for k
        V[k] = x;

        // Return k-value of preceeding snake
        return k0;
    };

    /**
     * Middle snake
     */
    Editgraph.prototype.middleSnakeHead = function (onpath) {
        var delta = this.N - this.M;
        var d, k;
        var Vf = {'1': 0};
        var Vb = {'1': 0};
        var result;

        for (d = 0; d <= this.dmax/2; d++) {
            for (k = -d; k <= d; k+=2) {
                result = this.nextSnakeHeadForward(k, -d, d, Vf, function(x, x0, k0) {
                    var y = x-k;
                    var y0 = x0-k;

                    if (onpath) onpath(d, x, k, x0, k0);

                    // check for overlap
                    if (delta % 2 === 1 && (k === delta - (d-1) || k === delta + (d+1))) {
                        if (Vf[k] >= Vb[k]) {
                            // return last forward snake
                            return [this.x + x, this.y + y, this.x + x0, this.y + y0]
                        }
                    }
                });
                if (result) {
                    return result;
                }
            }

            for (k = -d; k <= d; k+=2) {
                result = this.nextSnakeHeadBackward(k+delta, -d+delta, d+delta, Vb, function(d, x, k, x0, k0) {
                    var y = x-k;
                    var y0 = x0-k;

                    if (onpath) onpath(d, x, k, x0, k0);

                    // check for overlap
                    if (delta % 2 === 0 && (k + delta === -d || k + delta === d)) {
                        if (Vf[k+delta] >= Vb[k+delta]) {
                            // return last forward snake
                            return [this.x + x, this.y + y, this.x + x0, this.y + y0]
                        }
                    }
                });
                if (result) {
                    return result;
                }
            }
        }
    }

    /**
     * Returns the edit position for the operation between the two snakes left
     * and right.
     */
    Editgraph.prototype.editPosition = function(left, right) {
        return left.toPoint();
    }

    /**
     * Returns true if the edit operation between the two snakes left and right
     * is an insert operation. Returns false for a delete operation.
     */
    Editgraph.prototype.editIsInsert = function(left, right) {
        return left.k > right.k;
    }

    /**
     * Calculates the longest common subsequence of a and b.
     */
    Editgraph.prototype.lcs_simple = function () {
        var snake_heads = [];
        var last_snake;
        var snake;
        var result;

        this.forEachSnakeHead(function(snake, k0) {
            var prev = snake_heads[k0];
            snake = snake.copy();

            if (prev) {
                snake.previous = prev;
            }

            snake_heads[snake.k] = snake;
            last_snake = snake;
        });

        if (last_snake.x !== this.a.length) {
            throw new Error('Programming error: end-point of last snake must match the length of the input array.\n');
        }

        result = [];
        for (snake = last_snake; snake.previous; snake = snake.previous) {
            SnakeHead.forEachCommonSymbolBackward(snake.previous, snake, function(x,y) {
                result.unshift(this.a[x]);
            }, this);
        }

        return result;
    };

    /**
     * Create the shortest edit script turning a into b. Editor should be an
     * object with the following two methods:
     *
     * * insert(idx, symbol)
     * * remove(idx)
     */
    Editgraph.prototype.ses_simple = function (editor) {
        var snake_heads = [];
        var last_snake;
        var snake;
        var pos;

        this.forEachSnakeHead(function(snake, k0) {
            var prev = snake_heads[k0];
            snake = snake.copy();

            if (prev) {
                snake.previous = prev;
            }

            snake_heads[snake.k] = snake;
            last_snake = snake;
        });

        result = [];
        for (snake = last_snake; snake.previous; snake = snake.previous) {
            pos = this.editPosition(snake.previous, snake);
            if (this.editIsInsert(snake.previous, snake)) {
                editor.insert(pos.x, this.b[pos.y]);
            }
            else {
                editor.remove(pos.x);
            }
        }
    };

    /**
     * SnakeHead
     */
    function SnakeHead(k, x) {
        /**
         * The k-line on which the snake-part is located at.
         */
        this.k = k;

        /**
         * The end of the snake nearest to (N,M)
         */
        this.x = x;
    }

    /**
     * Return a new copy of this snake head.
     */
    SnakeHead.prototype.copy = function() {
        return new SnakeHead(this.k, this.x);
    }

    /**
     * Return the snake head in x-y coordinates.
     */
    SnakeHead.prototype.toPoint = function() {
        return {
            'x': this.x,
            'y': this.x-this.k
        };
    };

    /**
     * Calls callback for each common symbol encountered when traversing the
     * right snake bound by the left one from left to right.
     *
     * @param left Left snake head
     * @param right Right snake head
     */
    SnakeHead.forEachCommonSymbolForward = function(left, right, callback, T) {
        var k = right.k;
        var x = k > left.k ? left.x + 1 : left.x;
        var xmax = right.x;

        while (x < xmax) {
            callback.call(T, x, x-k);
            x++;
        }
    }

    /**
     * Calls callback for each common symbol encountered when traversing the
     * right snake bound by the left one from right to left.
     *
     * @param left Left snake head
     * @param right Right snake head
     */
    SnakeHead.forEachCommonSymbolBackward = function(left, right, callback, T) {
        var k = right.k;
        var xmin = k > left.k ? left.x + 1 : left.x;
        var x = right.x;

        while (x > xmin) {
            x--;
            callback.call(T, x, x-k);
        }
    }

    /**
     * Return an array of edges representing the operation as well as the snake
     * between the given origin and destination snake-heads.
     *
     * This function returns at least one orthogonal edge representing the
     * operation between the given snake-heads. If the destination is further
     * away than only one unit, an additional diagonal edge gets appended to
     * the operation edge. Each edge is represented by an array of the form
     * [x-start, y-start, x-end, y-end].
     *
     * Thus, you can expect a result like this, where the middle-point marks
     * the point between the orthogonal operation-edge and the diagonal
     * skip-edge.
     * <pre>
     * [[x-origin, y-origin, x-middle, y-middle],
     *  [x-middle, y-middle, x-destination, y-destination]]
     * </pre>
     *
     * @param ox X-coordinate of the origin snake-head.
     * @param ok k-line the origin snake-head is located at.
     * @param dx X-coordinate of the destination snake-head.
     * @param dk k-line the destination snake-head is located at.
     */
    SnakeHead.edges = function(ox, ok, dx, dk) {
        // Initialy set x-coordinate of mid-point M to origins x.
        var mx = ox;
        var result = [];

        // M is right of O if destinations k is greater than origins k and
        // destinations x is greater than origins x.
        if (dk > ok && dx > ox) {
            mx++;
        }
        // M is left of O if destinations k is smaller than origins k and
        // destinations x is smaller than origins x.
        else if(dk < ok && dx < ox) {
            mx--;
        }
        // In all other cases M is above or below O. The exact position is
        // determined by destinations k.

        result.push([ox, ox-ok, mx, mx-dk]);
        if (mx !== dx) {
            result.push([mx, mx-dk, dx, dx-dk]);
        }
        return result;
    };

    // CommonJS exports
    exports.Editgraph = Editgraph;
    exports.SnakeHead = SnakeHead;

}(typeof exports === 'undefined' ? (this.editgraph={}) : exports));
<commit_msg>Clear up some identifier names and comments<commit_after>/**
 * @file:   Implementation of Myers longest common subsequence algorithm using
 *          an edit graph.
 * @see:
 * * http://dx.doi.org/10.1007/BF01840446
 * * http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927
 */

(function(exports){
    function Editgraph(a, b, x, y, N, M, dmax) {
        this.a = a;
        this.b = b;

        this.x = (typeof x === 'undefined') ? 0 : x;
        this.y = (typeof y === 'undefined') ? 0 : y;
        this.N = (typeof N === 'undefined') ? a.length : N;
        this.M = (typeof M === 'undefined') ? b.length : M;
        this.dmax = (typeof dmax === 'undefined') ? this.N + this.M : dmax;
    }

    Editgraph.prototype.equals = function(a, b) {
        return (a === b);
    };

    /**
     * Call a function for each D-Path identified using myers basic greedy lcs
     * algorithm.
     *
     * Returns the length of the shortest edit script, i.e. the minimal number
     * of insert and delete operations required to turn a into b.
     *
     * @param onhead function(head, k0)
     */
    Editgraph.prototype.forEachSnakeHead = function (onhead, T) {
        var d, k, head, k0, end;
        var V = {};

        V[1] = 0;
        head = new SnakeHead();
        for (d = 0; d <= this.dmax; d++) {
            for (k = -d; k <= d; k+=2) {
                k0 = this.nextSnakeHeadForward(head, k, -d, d, V);
                if (onhead) {
                    onhead.call(T, head, k0, d);
                }

                // check if we are done
                end = head.toPoint();
                if (end.x >= this.N && end.y >= this.M) {
                    return d;
                }
            }
        }
    };

    /**
     * Call a function for each reverse D-Path identified using myers basic
     * greedy lcs algorithm.
     *
     * Returns the length of the shortest edit script, i.e. the minimal number
     * of insert and delete operations required to turn a into b.
     *
     * @param onhead function(dhead, precedessor)
     */
    Editgraph.prototype.forEachReverseSnakeHead = function (onhead, T) {
        var delta = this.N - this.M;
        var d, k, head, k0, end;
        var V = {};

        V[delta-1] = this.N;
        head = new SnakeHead();
        for (d = 0; d <= this.dmax; d++) {
            for (k = -d+delta; k <= d+delta; k+=2) {
                head.k = k;
                k0 = this.nextSnakeHeadBackward(head, k, -d+delta, d+delta, V);
                if (onhead) {
                    onhead.call(T, head, k0, d);
                }

                // check if we are done
                end = head.toPoint();
                if (end.x <= 0 && end.y <= 0) {
                    return d;
                }
            }
        }
    };

    Editgraph.prototype.nextSnakeHeadForward = function(head, k, kmin, kmax, V) {
        var k0, x;

        // Store current k-value in the snake head.
        head.k = k;

        // Determine the preceeding snake head. Pick the one whose furthest
        // reaching x value is greatest.
        if (k === kmin || (k !== kmax && V[k-1] < V[k+1])) {
            // Furthest reaching snake is above (k+1), move down.
            k0 = k+1;
            x = V[k0];
        }
        else {
            // Furthest reaching snake is left (k-1), move right.
            k0 = k-1;
            x = V[k0] + 1;
        }

        // Follow the diagonal as long as there are common values in a and b.
        while (x < this.N && x - k < this.M && this.equals(
                    this.a[this.x + x], this.b[this.y + x - k])) {
            x++;
        }

        // Store x value of snake head after traversing the diagonal in forward
        // direction.
        head.x = x;

        // Memozie furthest reaching x for k
        V[k] = x;

        // Return k-value of preceeding snake head
        return k0;
    };

    Editgraph.prototype.nextSnakeHeadBackward = function(head, k, kmin, kmax, V) {
        var k0, x, k = head.k;

        // Store current k-value in the snake head.
        head.k = k;

        // Determine the preceeding snake head. Pick the one whose furthest
        // reaching x value is greatest.
        if (k === kmax || (k !== kmin && V[k-1] < V[k+1])) {
            // Furthest reaching snake is underneath (k-1), move up.
            k0 = k-1;
            x = V[k-1];
        }
        else {
            // Furthest reaching snake is left (k-1), move right.
            k0 = k+1;
            x = V[k0]-1;
        }

        // Store x value of snake head before traversing the diagonal in
        // reverse direction.
        head.x = x;

        // Follow the diagonal as long as there are common values in a and b.
        while (x > 0 && x - k > 0 && this.equals(
                    this.a[this.x + x - 1], this.b[this.y + x - k - 1])) {
            x--;
        }

        // Memozie furthest reaching x for k
        V[k] = x;

        // Return k-value of preceeding snake head
        return k0;
    };

    /**
     * Middle snake
     */
    Editgraph.prototype.middleSnakeHead = function (onpath) {
        var delta = this.N - this.M;
        var d, k;
        var Vf = {'1': 0};
        var Vb = {'1': 0};
        var result;

        for (d = 0; d <= this.dmax/2; d++) {
            for (k = -d; k <= d; k+=2) {
                result = this.nextSnakeHeadForward(k, -d, d, Vf, function(x, x0, k0) {
                    var y = x-k;
                    var y0 = x0-k;

                    if (onpath) onpath(d, x, k, x0, k0);

                    // check for overlap
                    if (delta % 2 === 1 && (k === delta - (d-1) || k === delta + (d+1))) {
                        if (Vf[k] >= Vb[k]) {
                            // return last forward snake
                            return [this.x + x, this.y + y, this.x + x0, this.y + y0]
                        }
                    }
                });
                if (result) {
                    return result;
                }
            }

            for (k = -d; k <= d; k+=2) {
                result = this.nextSnakeHeadBackward(k+delta, -d+delta, d+delta, Vb, function(d, x, k, x0, k0) {
                    var y = x-k;
                    var y0 = x0-k;

                    if (onpath) onpath(d, x, k, x0, k0);

                    // check for overlap
                    if (delta % 2 === 0 && (k + delta === -d || k + delta === d)) {
                        if (Vf[k+delta] >= Vb[k+delta]) {
                            // return last forward snake
                            return [this.x + x, this.y + y, this.x + x0, this.y + y0]
                        }
                    }
                });
                if (result) {
                    return result;
                }
            }
        }
    }

    /**
     * Returns the edit position for the operation between the two snake heads
     * left and right.
     */
    Editgraph.prototype.editPosition = function(left, right) {
        return left.toPoint();
    }

    /**
     * Returns true if the edit operation between the two snake heads left and
     * right is an insert operation. Returns false for a delete operation.
     */
    Editgraph.prototype.editIsInsert = function(left, right) {
        return left.k > right.k;
    }

    /**
     * Calculates the longest common subsequence of a and b.
     */
    Editgraph.prototype.lcs_simple = function () {
        var snake_heads = [];
        var last_head;
        var head;
        var result;

        this.forEachSnakeHead(function(head, k0) {
            var prev = snake_heads[k0];
            head = head.copy();

            if (prev) {
                head.previous = prev;
            }

            snake_heads[head.k] = head;
            last_head = head;
        });

        if (last_head.x !== this.a.length) {
            throw new Error('Programming error: end-point of last head must match the length of the input array.\n');
        }

        result = [];
        for (head = last_head; head.previous; head = head.previous) {
            SnakeHead.forEachCommonSymbolBackward(head.previous, head, function(x,y) {
                result.unshift(this.a[x]);
            }, this);
        }

        return result;
    };

    /**
     * Create the shortest edit script turning a into b. Editor should be an
     * object with the following two methods:
     *
     * * insert(idx, symbol)
     * * remove(idx)
     */
    Editgraph.prototype.ses_simple = function (editor) {
        var snake_heads = [];
        var last_head;
        var head;
        var pos;

        this.forEachSnakeHead(function(head, k0) {
            var prev = snake_heads[k0];
            head = head.copy();

            if (prev) {
                head.previous = prev;
            }

            snake_heads[head.k] = head;
            last_head = head;
        });

        result = [];
        for (head = last_head; head.previous; head = head.previous) {
            pos = this.editPosition(head.previous, head);
            if (this.editIsInsert(head.previous, head)) {
                editor.insert(pos.x, this.b[pos.y]);
            }
            else {
                editor.remove(pos.x);
            }
        }
    };

    /**
     * SnakeHead
     */
    function SnakeHead(k, x) {
        /**
         * The k-line on which the snake head is located at.
         */
        this.k = k;

        /**
         * The x-coordinate of the snake head.
         */
        this.x = x;
    }

    /**
     * Return a new copy of this snake head.
     */
    SnakeHead.prototype.copy = function() {
        return new SnakeHead(this.k, this.x);
    }

    /**
     * Return the snake head in x-y coordinates.
     */
    SnakeHead.prototype.toPoint = function() {
        return {
            'x': this.x,
            'y': this.x-this.k
        };
    };

    /**
     * Calls callback for each common symbol encountered when traversing the
     * right snake bound by the left one from left to right.
     *
     * @param left Left snake head
     * @param right Right snake head
     */
    SnakeHead.forEachCommonSymbolForward = function(left, right, callback, T) {
        var k = right.k;
        var x = k > left.k ? left.x + 1 : left.x;
        var xmax = right.x;

        while (x < xmax) {
            callback.call(T, x, x-k);
            x++;
        }
    }

    /**
     * Calls callback for each common symbol encountered when traversing the
     * right snake bound by the left one from right to left.
     *
     * @param left Left snake head
     * @param right Right snake head
     */
    SnakeHead.forEachCommonSymbolBackward = function(left, right, callback, T) {
        var k = right.k;
        var xmin = k > left.k ? left.x + 1 : left.x;
        var x = right.x;

        while (x > xmin) {
            x--;
            callback.call(T, x, x-k);
        }
    }

    /**
     * Return an array of edges representing the operation as well as the snake
     * between the given origin and destination snake-heads.
     *
     * This function returns at least one orthogonal edge representing the
     * operation between the given snake-heads. If the destination is further
     * away than only one unit, an additional diagonal edge gets appended to
     * the operation edge. Each edge is represented by an array of the form
     * [x-start, y-start, x-end, y-end].
     *
     * Thus, you can expect a result like this, where the middle-point marks
     * the point between the orthogonal operation-edge and the diagonal
     * skip-edge.
     * <pre>
     * [[x-origin, y-origin, x-middle, y-middle],
     *  [x-middle, y-middle, x-destination, y-destination]]
     * </pre>
     *
     * @param ox X-coordinate of the origin snake-head.
     * @param ok k-line the origin snake-head is located at.
     * @param dx X-coordinate of the destination snake-head.
     * @param dk k-line the destination snake-head is located at.
     */
    SnakeHead.edges = function(ox, ok, dx, dk) {
        // Initialy set x-coordinate of mid-point M to origins x.
        var mx = ox;
        var result = [];

        // M is right of O if destinations k is greater than origins k and
        // destinations x is greater than origins x.
        if (dk > ok && dx > ox) {
            mx++;
        }
        // M is left of O if destinations k is smaller than origins k and
        // destinations x is smaller than origins x.
        else if(dk < ok && dx < ox) {
            mx--;
        }
        // In all other cases M is above or below O. The exact position is
        // determined by destinations k.

        result.push([ox, ox-ok, mx, mx-dk]);
        if (mx !== dx) {
            result.push([mx, mx-dk, dx, dx-dk]);
        }
        return result;
    };

    // CommonJS exports
    exports.Editgraph = Editgraph;
    exports.SnakeHead = SnakeHead;

}(typeof exports === 'undefined' ? (this.editgraph={}) : exports));
<|endoftext|>


<commit_before><commit_msg>fix delete draft issue<commit_after><|endoftext|>


<commit_before>window.addEventListener("load", function () {
    var a = document.querySelector("a.PostLogoutRedirectUri");
    if (a) {
        window.location = a.href;
    }
});
<commit_msg>one more UI update for 2.5.0<commit_after>$(function () {
    var a = document.querySelector("a.PostLogoutRedirectUri");
    if (a) {
        window.location = a.href;
    }
});
<|endoftext|>


<commit_before>var user;
var scope = 'publish_actions read_stream user_photos user_friends friends_photos';
$('document').ready(function() {
	queueAdd(start)
});

function start() {
	console.log('start was called in loginPage.js...');
	FB.getLoginStatus(function(response) {
		if(response.status === 'connected') {
			console.log('Logged in, redirecting to index...');
			console.log('////////////////////////////////\n');
			redirect('index');
		} else {
			console.log('User not logged in. Waiting for authorization.');
		}
	});
}

function loginToFacebook() {
	FB.login(function(response) {
		if (response.authResponse) {
			user = response;
			console.log('Welcome, ' + user.name);
			redirect('index');
		} else {
			// The person cancelled the login dialog
			console.log('User cancelled connection.');
		}
	}, {scope: scope});
}<commit_msg>Changed login button function call<commit_after>var user;
var scope = 'publish_actions read_stream user_photos user_friends friends_photos';
$('document').ready(function() {
	queueAdd(start)
});

function start() {
	console.log('start was called in loginPage.js...');
	FB.getLoginStatus(function(response) {
		if(response.status === 'connected') {
			console.log('Logged in, redirecting to index...');
			console.log('////////////////////////////////\n');
			redirect('index');
		} else {
			console.log('User not logged in. Waiting for authorization.');
		}
	});
}

$('#loginButton').click(function() {
	FB.login(function(response) {
		if (response.authResponse) {
			user = response;
			console.log('Welcome, ' + user.name);
			redirect('index');
		} else {
			// The person cancelled the login dialog
			console.log('User cancelled connection.');
		}
	}, {scope: scope});
});<|endoftext|>


<commit_before>function placeBsBtn(){
	var importBtn = "<button class='bs-btn bs-btn-default'>Import</button>";
    $("#import-1_wrapper").append(importBtn);
    $(".bs-btn").click(function() {
		var pokes = document.getElementsByClassName("import-team-text")[0].value;
		addSets(pokes);
    });

}
function getAbility(row){
	ability = row[1].trim();
	if (ABILITIES_XY.indexOf(ability) != -1){
		return(ability);

	}else{
		return;

	}

}

function statConverter(stat){
	switch(stat){
		case 'hp':
			return "hp";
		case 'atk':
			return "at";
		case 'def':
			return "df";
		case 'spa':
			return "sa";
		case 'spd':
			return "sd";
		case 'spe':
			return "sp";

	}

}

function getStats(currentPoke,rows,i){
	currentPoke.nature = "Serious";
	var currentEV;
	var currentIV;
	var currentNature;
	currentPoke.level = 100;
	for(x = i;x<i+6;x++){
		var currentRow = rows[x].split(/[/:]/);
		var evs = new Object();
		var ivs = new Object();
		var ev

		switch(currentRow[0]){
			case 'Level':
				currentPoke.level = parseInt(currentRow[1].trim());
				break;
			case 'EVs':

				for(j = 1;j<currentRow.length;j++){
					currentEV = currentRow[j].trim().split(" ");
					currentEV[1] = statConverter(currentEV[1].toLowerCase());
					evs[currentEV[1]] = parseInt(currentEV[0]);

				}
				currentPoke.evs = evs;
				break;
			case 'IVs':
				for(j = 1;j<currentRow.length;j++){
					currentIV = currentRow[j].trim().split(" ");
					currentIV[1] = statConverter(currentIV[1].toLowerCase());
					ivs[currentIV[1]] = parseInt(currentIV[0]);
				}
				currentPoke.ivs = ivs;
				break;

		}
		currentNature = rows[x].trim().split(" ");
		if ( currentNature[1] == "Nature"){
			currentPoke.nature = currentNature[0];

		}
	}
	return currentPoke;

}

function getItem(currentRow,j){
	for(;j<currentRow.length;j++){
		var item = currentRow[j].trim();
		if(ITEMS_XY.indexOf(item) != -1){
			return item;

		}
	}
	return;

}

function getMoves(currentPoke,rows,i){
	var movesFound = false;
	var moves = new Array();
	for(x = i;x<i+10;x++){

		if(rows[x]){
			if(rows[x][0] == "-"){
				movesFound = true;

				var move = rows[x].substr(2,rows[x].length-2).replace("[","").replace("]","").replace("  ","");
				moves.push(move);

			}else {
				if (movesFound == true){
					break;

				}

			}
		}
	}
	currentPoke.moves = moves;
	return currentPoke;

}

function addToDex(poke){
	var dexObject = new Object();
	if(SETDEX_XY[poke.name] == undefined){
		SETDEX_XY[poke.name] = new Object();
	}
	if (poke.ability !== undefined){
		dexObject.ability = poke.ability;

	}
	dexObject.level = poke.level;
	dexObject.evs = poke.evs;
	dexObject.ivs = poke.ivs;
	dexObject.moves = poke.moves;
	dexObject.nature = poke.nature;
	dexObject.item = poke.item;
	if(localStorage.customsets){
		customsets = JSON.parse(localStorage.customsets);
	}
	else{
		customsets = {};
	}
	if(!customsets[poke.name]){
		customsets[poke.name] = {};
	}
	customsets[poke.name][poke.nameProp] = dexObject;
	if(poke.name == "Aegislash-Blade"){
		if(!customsets["Aegislash-Shield"]){
			customsets["Aegislash-Shield"] = {};
		}
		customsets["Aegislash-Shield"][poke.nameProp] = 	dexObject;
	}
	updateDex(customsets);
}

function updateDex(customsets){
	for(pokemon in customsets){
		for(moveset in customsets[pokemon]){
			if(!SETDEX_XY[pokemon]){
				SETDEX_XY[pokemon] = {};
			}
			SETDEX_XY[pokemon][moveset] = customsets[pokemon][moveset];
		}
	}
	localStorage.customsets = JSON.stringify(customsets);
}

function addSets(pokes){
	var rows = pokes.split("\n");
	var currentRow;
	var currentPoke;
	var addedpokes = 0;
	for (i = 0; i < rows.length; i++) {
		currentRow = rows[i].split(/[\(\)@]/);
		for (j = 0; j<currentRow.length;j++){
			currentRow[j] = checkExeptions(currentRow[j].trim());
			if(POKEDEX_XY[currentRow[j].trim()] !== undefined){
				currentPoke = POKEDEX_XY[currentRow[j].trim()];
				currentPoke.name = currentRow[j].trim();
				currentPoke.item = getItem(currentRow,j+1);
				if(j===1){
					currentPoke.nameProp = currentRow[j-1].trim();

				}else{
					currentPoke.nameProp = "Custom Set";

				}
				currentPoke.ability = getAbility(rows[i+1].split(":"));
				currentPoke = getStats(currentPoke,rows,i+2);
				currentPoke = getMoves(currentPoke,rows,i+2);
				addToDex(currentPoke);
				addedpokes++;

			}
		}
	}
	alert("Successfully imported "+addedpokes+" sets");
}

function checkExeptions(poke){
	switch(poke){
		case 'Houndoom-Mega':
			poke = "Mega Houndoom";
			break;
		case 'Venusaur-Mega':
			poke = "Mega Venusaur";
			break;
		case 'Blastoise-Mega':
			poke = "Mega Blastoise";
			break;
		case 'Alakazam-Mega':
			poke = "Mega Alakazam";
			break;
		case 'Gengar-Mega':
			poke = "Mega Gengar";
			break;
		case 'Kangaskhan-Mega':
			poke = "Mega Kangaskhan";
			break;
		case 'Pinsir-Mega':
			poke = "Mega Pinsir";
			break;
		case 'Gyarados-Mega':
			poke = "Mega Gyarados";
			break;
		case 'Aerodactyl-Mega':
			poke = "Mega Aerodactyl";
			break;
		case 'Ampharos-Mega':
			poke = "Mega Ampharos";
			break;
		case 'Scizor-Mega':
			poke = "Mega Scizor";
			break;
		case 'Heracross-Mega':
			poke = "Mega Heracross";
			break;
		case 'Tyranitar-Mega':
			poke = "Mega Tyranitar";
			break;
		case 'Blaziken-Mega':
			poke = "Mega Blaziken";
			break;
		case 'Gardevoir-Mega':
			poke = "Mega Gardevoir";
			break;
		case 'Mawile-Mega':
			poke = "Mega Mawile";
			break;
		case 'Aggron-Mega':
			poke = "Mega Aggron";
			break;
		case 'Medicham-Mega':
			poke = "Mega Medicham";
			break;
		case 'Manectric-Mega':
			poke = "Mega Manectric";
			break;
		case 'Banette-Mega':
			poke = "Mega Banette";
			break;
		case 'Absol-Mega':
			poke = "Mega Absol";
			break;
		case 'Garchomp-Mega':
			poke = "Mega Garchomp";
			break;
		case 'Lucario-Mega':
			poke = "Mega Lucario";
			break;
		case 'Beedrill-Mega':
			poke = "Mega Beedrill";
			break;
		case 'Pidgeot-Mega':
			poke = "Mega Pidgeot";
			break;
		case 'Slowbro-Mega':
			poke = "Mega Slowbro";
			break;
		case 'Steelix-Mega':
			poke = "Mega Steelix";
			break;
		case 'Sceptile-Mega':
			poke = "Mega Sceptile";
			break;
		case 'Swampert-Mega':
			poke = "Mega Swampert";
			break;
		case 'Sableye-Mega':
			poke = "Mega Sableye";
			break;
		case 'Sharpedo-Mega':
			poke = "Mega Sharpedo";
			break;
		case 'Camerupt-Mega':
			poke = "Mega Camerupt";
			break;
		case 'Altaria-Mega':
			poke = "Mega Altaria";
			break;
		case 'Salamence-Mega':
			poke = "Mega Salamence";
			break;
		case 'Metagross-Mega':
			poke = "Mega Metagross";
			break;
		case 'Latias-Mega':
			poke = "Mega Latias";
			break;
		case 'Latios-Mega':
			poke = "Mega Latios";
			break;
		case 'Rayquaza-Mega':
			poke = "Mega Rayquaza";
			break;
		case 'Lopunny-Mega':
			poke = "Mega Lopunny";
			break;
		case 'Gallade-Mega':
			poke = "Mega Gallade";
			break;
		case 'Audino-Mega':
			poke = "Mega Audino";
			break;
		case 'Diancie-Mega':
			poke = "Mega Diancie";
			break;
		case 'Charizard-Mega-X':
			poke = "Mega Charizard X";
			break;
		case 'Charizard-Mega-Y':
			poke = "Mega Charizard Y";
			break;
		case 'Mewtwo-Mega-X':
			poke = "Mega Mewtwo X";
			break;
		case 'Mewtwo-Mega-Y':
			poke = "Mega Mewtwo Y";
			break;
		case 'Groudon-Primal':
			poke = "Primal Groudon";
			break;
		case 'Kyogre-Primal':
			poke = "Primal Kyogre";
			break;
		case 'Rotom-Fan':
			poke = "Rotom-S";
			break;
		case 'Rotom-Mow':
			poke = "Rotom-C";
			break;
		case 'Rotom-Frost':
			poke = "Rotom-F";
			break;
		case 'Rotom-Wash':
			poke = "Rotom-W";
			break;
		case 'Rotom-Heat':
			poke = "Rotom-H";
			break;
		case 'Meowstic-F':
			poke = "Meowstic";
			break;
		case 'Kyurem-Black':
			poke = "Kyurem-B";
			break;
		case 'Kyurem-White':
			poke = "Kyurem-W";
			break;
		case 'Landorus-Therian':
			poke = "Landorus-T";
			break;
		case 'Tornadus-Therian':
			poke = "Tornadus-T";
			break;
		case 'Thundurus-Therian':
			poke = "Thundurus-T";
			break;
		case 'Giratina-Origin':
			poke = "Giratina-O";
			break;
		case 'Hoopa-Unbound':
			poke = "Hoopa Unbound";
			break;
		case 'Gourgeist':
			poke = "Gourgeist-Average";
			break;
		case 'Shaymin-Sky':
			poke = "Shaymin-S";
			break;
		case 'Wormadam-Sandy':
			poke = "Wormadam-G";
			break;
		case 'Wormadam-Trash':
			poke = "Wormadam-S";
			break;
		case 'Deoxys-Attack':
			poke = "Deoxys-A";
			break;
		case 'Deoxys-Defense':
			poke = "Deoxys-D";
			break;
		case 'Deoxys-Speed':
			poke = "Deoxys-S";
			break;
		case 'Aegislash':
			poke = "Aegislash-Blade";
			break;
		case 'Pikachu-Belle':
		case 'Pikachu-Cosplay':
		case 'Pikachu-Libre':
		case 'Pikachu-PhD':
		case 'Pikachu-Pop-Star':
		case 'Pikachu-Rock-Star':
			poke = "Pikachu";
			break;
	}
	return poke;

}

$(document).ready(function() {
    placeBsBtn();
	if(localStorage.customsets){
		updateDex(JSON.parse(localStorage.customsets));
	}
});
<commit_msg>Support importing sets for all gens<commit_after>function placeBsBtn(){
	var importBtn = "<button class='bs-btn bs-btn-default'>Import</button>";
    $("#import-1_wrapper").append(importBtn);
    $(".bs-btn").click(function() {
		var pokes = document.getElementsByClassName("import-team-text")[0].value;
		addSets(pokes);
    });

}
function getAbility(row){
	ability = row[1] ? row[1].trim() : '';
	if (ABILITIES_XY.indexOf(ability) != -1){
		return(ability);

	}else{
		return;

	}

}

function statConverter(stat){
	switch(stat){
		case 'hp':
			return "hp";
		case 'atk':
			return "at";
		case 'def':
			return "df";
		case 'spa':
			return "sa";
		case 'spd':
			return "sd";
		case 'spe':
			return "sp";

	}

}

function getStats(currentPoke,rows,i){
	currentPoke.nature = "Serious";
	var currentEV;
	var currentIV;
	var currentNature;
	currentPoke.level = 100;
	for(x = i;x<i+7;x++){
		var currentRow = rows[x] ? rows[x].split(/[/:]/) : '';
		var evs = new Object();
		var ivs = new Object();
		var ev

		switch(currentRow[0]){
			case 'Level':
				currentPoke.level = parseInt(currentRow[1].trim());
				break;
			case 'EVs':

				for(j = 1;j<currentRow.length;j++){
					currentEV = currentRow[j].trim().split(" ");
					currentEV[1] = statConverter(currentEV[1].toLowerCase());
					evs[currentEV[1]] = parseInt(currentEV[0]);

				}
				currentPoke.evs = evs;
				break;
			case 'IVs':
				for(j = 1;j<currentRow.length;j++){
					currentIV = currentRow[j].trim().split(" ");
					currentIV[1] = statConverter(currentIV[1].toLowerCase());
					ivs[currentIV[1]] = parseInt(currentIV[0]);
				}
				currentPoke.ivs = ivs;
				break;

		}
		currentNature = rows[x] ? rows[x].trim().split(" ") : '';
		if ( currentNature[1] == "Nature"){
			currentPoke.nature = currentNature[0];

		}
	}
	return currentPoke;

}

function getItem(currentRow,j){
	for(;j<currentRow.length;j++){
		var item = currentRow[j].trim();
		if(ITEMS_XY.indexOf(item) != -1){
			return item;

		}
	}
	return;

}

function getMoves(currentPoke,rows,i){
	var movesFound = false;
	var moves = new Array();
	for(x = i;x<i+12;x++){

		if(rows[x]){
			if(rows[x][0] == "-"){
				movesFound = true;

				var move = rows[x].substr(2,rows[x].length-2).replace("[","").replace("]","").replace("  ","");
				moves.push(move);

			}else {
				if (movesFound == true){
					break;

				}

			}
		}
	}
	currentPoke.moves = moves;
	return currentPoke;

}

function addToDex(poke){
	var dexObject = new Object();
	if(SETDEX_XY[poke.name] == undefined) SETDEX_XY[poke.name] = new Object();
	if(SETDEX_BW[poke.name] == undefined) SETDEX_BW[poke.name] = new Object();
	if(SETDEX_DPP[poke.name] == undefined) SETDEX_DPP[poke.name] = new Object();
	if(SETDEX_ADV[poke.name] == undefined) SETDEX_ADV[poke.name] = new Object();
	if(SETDEX_GSC[poke.name] == undefined) SETDEX_GSC[poke.name] = new Object();
	if(SETDEX_RBY[poke.name] == undefined) SETDEX_RBY[poke.name] = new Object();

	if (poke.ability !== undefined){
		dexObject.ability = poke.ability;

	}
	dexObject.level = poke.level;
	dexObject.evs = poke.evs;
	dexObject.ivs = poke.ivs;
	dexObject.moves = poke.moves;
	dexObject.nature = poke.nature;
	dexObject.item = poke.item;
	if(localStorage.customsets){
		customsets = JSON.parse(localStorage.customsets);
	}
	else{
		customsets = {};
	}
	if(!customsets[poke.name]){
		customsets[poke.name] = {};
	}
	customsets[poke.name][poke.nameProp] = dexObject;
	if(poke.name == "Aegislash-Blade"){
		if(!customsets["Aegislash-Shield"]){
			customsets["Aegislash-Shield"] = {};
		}
		customsets["Aegislash-Shield"][poke.nameProp] = 	dexObject;
	}
	updateDex(customsets);
}

function updateDex(customsets){
	for(pokemon in customsets){
		for(moveset in customsets[pokemon]){
			if(!SETDEX_XY[pokemon]) SETDEX_XY[pokemon] = {};
			SETDEX_XY[pokemon][moveset] = customsets[pokemon][moveset];
			if(!SETDEX_BW[pokemon]) SETDEX_BW[pokemon] = {};
			SETDEX_BW[pokemon][moveset] = customsets[pokemon][moveset];
			if(!SETDEX_DPP[pokemon]) SETDEX_DPP[pokemon] = {};
			SETDEX_DPP[pokemon][moveset] = customsets[pokemon][moveset];
			if(!SETDEX_ADV[pokemon]) SETDEX_ADV[pokemon] = {};
			SETDEX_ADV[pokemon][moveset] = customsets[pokemon][moveset];
			if(!SETDEX_GSC[pokemon]) SETDEX_GSC[pokemon] = {};
			SETDEX_GSC[pokemon][moveset] = customsets[pokemon][moveset];
			if(!SETDEX_RBY[pokemon]) SETDEX_RBY[pokemon] = {};
			SETDEX_RBY[pokemon][moveset] = customsets[pokemon][moveset];
		}
	}
	localStorage.customsets = JSON.stringify(customsets);
}

function addSets(pokes){
	var rows = pokes.split("\n");
	var currentRow;
	var currentPoke;
	var addedpokes = 0;
	for (i = 0; i < rows.length; i++) {
		currentRow = rows[i].split(/[\(\)@]/);
		for (j = 0; j<currentRow.length;j++){
			currentRow[j] = checkExeptions(currentRow[j].trim());
			if(POKEDEX_XY[currentRow[j].trim()] !== undefined){
				currentPoke = POKEDEX_XY[currentRow[j].trim()];
				currentPoke.name = currentRow[j].trim();
				currentPoke.item = getItem(currentRow,j+1);
				if(j===1){
					currentPoke.nameProp = currentRow[j-1].trim();

				}else{
					currentPoke.nameProp = "Custom Set";

				}
				currentPoke.ability = getAbility(rows[i+1].split(":"));
				currentPoke = getStats(currentPoke,rows,i+1);
				currentPoke = getMoves(currentPoke,rows,i);
				addToDex(currentPoke);
				addedpokes++;

			}
		}
	}
	alert("Successfully imported "+addedpokes+" sets");
}

function checkExeptions(poke){
	switch(poke){
		case 'Houndoom-Mega':
			poke = "Mega Houndoom";
			break;
		case 'Venusaur-Mega':
			poke = "Mega Venusaur";
			break;
		case 'Blastoise-Mega':
			poke = "Mega Blastoise";
			break;
		case 'Alakazam-Mega':
			poke = "Mega Alakazam";
			break;
		case 'Gengar-Mega':
			poke = "Mega Gengar";
			break;
		case 'Kangaskhan-Mega':
			poke = "Mega Kangaskhan";
			break;
		case 'Pinsir-Mega':
			poke = "Mega Pinsir";
			break;
		case 'Gyarados-Mega':
			poke = "Mega Gyarados";
			break;
		case 'Aerodactyl-Mega':
			poke = "Mega Aerodactyl";
			break;
		case 'Ampharos-Mega':
			poke = "Mega Ampharos";
			break;
		case 'Scizor-Mega':
			poke = "Mega Scizor";
			break;
		case 'Heracross-Mega':
			poke = "Mega Heracross";
			break;
		case 'Tyranitar-Mega':
			poke = "Mega Tyranitar";
			break;
		case 'Blaziken-Mega':
			poke = "Mega Blaziken";
			break;
		case 'Gardevoir-Mega':
			poke = "Mega Gardevoir";
			break;
		case 'Mawile-Mega':
			poke = "Mega Mawile";
			break;
		case 'Aggron-Mega':
			poke = "Mega Aggron";
			break;
		case 'Medicham-Mega':
			poke = "Mega Medicham";
			break;
		case 'Manectric-Mega':
			poke = "Mega Manectric";
			break;
		case 'Banette-Mega':
			poke = "Mega Banette";
			break;
		case 'Absol-Mega':
			poke = "Mega Absol";
			break;
		case 'Garchomp-Mega':
			poke = "Mega Garchomp";
			break;
		case 'Lucario-Mega':
			poke = "Mega Lucario";
			break;
		case 'Beedrill-Mega':
			poke = "Mega Beedrill";
			break;
		case 'Pidgeot-Mega':
			poke = "Mega Pidgeot";
			break;
		case 'Slowbro-Mega':
			poke = "Mega Slowbro";
			break;
		case 'Steelix-Mega':
			poke = "Mega Steelix";
			break;
		case 'Sceptile-Mega':
			poke = "Mega Sceptile";
			break;
		case 'Swampert-Mega':
			poke = "Mega Swampert";
			break;
		case 'Sableye-Mega':
			poke = "Mega Sableye";
			break;
		case 'Sharpedo-Mega':
			poke = "Mega Sharpedo";
			break;
		case 'Camerupt-Mega':
			poke = "Mega Camerupt";
			break;
		case 'Altaria-Mega':
			poke = "Mega Altaria";
			break;
		case 'Salamence-Mega':
			poke = "Mega Salamence";
			break;
		case 'Metagross-Mega':
			poke = "Mega Metagross";
			break;
		case 'Latias-Mega':
			poke = "Mega Latias";
			break;
		case 'Latios-Mega':
			poke = "Mega Latios";
			break;
		case 'Rayquaza-Mega':
			poke = "Mega Rayquaza";
			break;
		case 'Lopunny-Mega':
			poke = "Mega Lopunny";
			break;
		case 'Gallade-Mega':
			poke = "Mega Gallade";
			break;
		case 'Audino-Mega':
			poke = "Mega Audino";
			break;
		case 'Diancie-Mega':
			poke = "Mega Diancie";
			break;
		case 'Charizard-Mega-X':
			poke = "Mega Charizard X";
			break;
		case 'Charizard-Mega-Y':
			poke = "Mega Charizard Y";
			break;
		case 'Mewtwo-Mega-X':
			poke = "Mega Mewtwo X";
			break;
		case 'Mewtwo-Mega-Y':
			poke = "Mega Mewtwo Y";
			break;
		case 'Groudon-Primal':
			poke = "Primal Groudon";
			break;
		case 'Kyogre-Primal':
			poke = "Primal Kyogre";
			break;
		case 'Rotom-Fan':
			poke = "Rotom-S";
			break;
		case 'Rotom-Mow':
			poke = "Rotom-C";
			break;
		case 'Rotom-Frost':
			poke = "Rotom-F";
			break;
		case 'Rotom-Wash':
			poke = "Rotom-W";
			break;
		case 'Rotom-Heat':
			poke = "Rotom-H";
			break;
		case 'Meowstic-F':
			poke = "Meowstic";
			break;
		case 'Kyurem-Black':
			poke = "Kyurem-B";
			break;
		case 'Kyurem-White':
			poke = "Kyurem-W";
			break;
		case 'Landorus-Therian':
			poke = "Landorus-T";
			break;
		case 'Tornadus-Therian':
			poke = "Tornadus-T";
			break;
		case 'Thundurus-Therian':
			poke = "Thundurus-T";
			break;
		case 'Giratina-Origin':
			poke = "Giratina-O";
			break;
		case 'Hoopa-Unbound':
			poke = "Hoopa Unbound";
			break;
		case 'Gourgeist':
			poke = "Gourgeist-Average";
			break;
		case 'Shaymin-Sky':
			poke = "Shaymin-S";
			break;
		case 'Wormadam-Sandy':
			poke = "Wormadam-G";
			break;
		case 'Wormadam-Trash':
			poke = "Wormadam-S";
			break;
		case 'Deoxys-Attack':
			poke = "Deoxys-A";
			break;
		case 'Deoxys-Defense':
			poke = "Deoxys-D";
			break;
		case 'Deoxys-Speed':
			poke = "Deoxys-S";
			break;
		case 'Aegislash':
			poke = "Aegislash-Blade";
			break;
		case 'Pikachu-Belle':
		case 'Pikachu-Cosplay':
		case 'Pikachu-Libre':
		case 'Pikachu-PhD':
		case 'Pikachu-Pop-Star':
		case 'Pikachu-Rock-Star':
			poke = "Pikachu";
			break;
	}
	return poke;

}

$(document).ready(function() {
    placeBsBtn();
	if(localStorage.customsets){
		updateDex(JSON.parse(localStorage.customsets));
	}
});
<|endoftext|>


<commit_before>// @flow
import clientConfig from "utils/clientConfig"

// helper function to set redirect URL with basename if included
const redirectUrlGenerator = provider => {
  let url
  if (
    process.env.REACT_APP_BASENAME === "" ||
    process.env.REACT_APP_BASENAME === "/"
  ) {
    url = `${window.location.origin}/${provider}/callback`
  } else {
    url = `${window.location.origin}/${
      process.env.REACT_APP_BASENAME
    }/${provider}/callback`
  }
  return url
}

const oauthConfig = {
  google: {
    name: "Google",
    url: "/auth/google",
    authorizationEndpoint: "https://accounts.google.com/o/oauth2/v2/auth",
    clientId: clientConfig.google.clientId,
    redirectUrl: redirectUrlGenerator("google"),
    requiredUrlParams: [["response_type", "code"]],
    scopes: ["email"],
    scopeDelimiter: " ",
    optionalUrlParams: [["state", "google"]],
    popupOptions: { width: 1020, height: 633 },
  },
  linkedin: {
    name: "LinkedIn",
    url: "/auth/linkedin",
    authorizationEndpoint: "https://www.linkedin.com/uas/oauth2/authorization",
    clientId: clientConfig.linkedin.clientId,
    redirectUrl: redirectUrlGenerator("linkedin"),
    scopes: ["r_emailaddress"],
    scopeDelimiter: " ",
    requiredUrlParams: [["state", "linkedin"], ["response_type", "code"]],
    popupOptions: { width: 1028, height: 640 },
  },
  orcid: {
    name: "ORCID",
    url: "/auth/orcid",
    authorizationEndpoint: "https://orcid.org/oauth/authorize",
    clientId: clientConfig.orcid.clientId,
    redirectUrl: redirectUrlGenerator("orcid"),
    scopes: ["/authenticate"],
    scopeDelimiter: " ",
    requiredUrlParams: [["response_type", "code"]],
    popupOptions: { width: 1028, height: 640 },
  },
}

export default oauthConfig
<commit_msg>update linkedin auth url<commit_after>// @flow
import clientConfig from "utils/clientConfig"

// helper function to set redirect URL with basename if included
const redirectUrlGenerator = provider => {
  let url
  if (
    process.env.REACT_APP_BASENAME === "" ||
    process.env.REACT_APP_BASENAME === "/"
  ) {
    url = `${window.location.origin}/${provider}/callback`
  } else {
    url = `${window.location.origin}/${
      process.env.REACT_APP_BASENAME
    }/${provider}/callback`
  }
  return url
}

const oauthConfig = {
  google: {
    name: "Google",
    url: "/auth/google",
    authorizationEndpoint: "https://accounts.google.com/o/oauth2/v2/auth",
    clientId: clientConfig.google.clientId,
    redirectUrl: redirectUrlGenerator("google"),
    requiredUrlParams: [["response_type", "code"]],
    scopes: ["email"],
    scopeDelimiter: " ",
    optionalUrlParams: [["state", "google"]],
    popupOptions: { width: 1020, height: 633 },
  },
  linkedin: {
    name: "LinkedIn",
    url: "/auth/linkedin",
    authorizationEndpoint: "https://www.linkedin.com/oauth/v2/authorization",
    clientId: clientConfig.linkedin.clientId,
    redirectUrl: redirectUrlGenerator("linkedin"),
    scopes: ["r_emailaddress"],
    scopeDelimiter: " ",
    requiredUrlParams: [["state", "linkedin"], ["response_type", "code"]],
    popupOptions: { width: 1028, height: 640 },
  },
  orcid: {
    name: "ORCID",
    url: "/auth/orcid",
    authorizationEndpoint: "https://orcid.org/oauth/authorize",
    clientId: clientConfig.orcid.clientId,
    redirectUrl: redirectUrlGenerator("orcid"),
    scopes: ["/authenticate"],
    scopeDelimiter: " ",
    requiredUrlParams: [["response_type", "code"]],
    popupOptions: { width: 1028, height: 640 },
  },
}

export default oauthConfig
<|endoftext|>


<commit_before>/**
 * Created by nuintun on 2015/4/27.
 */

'use strict';

var is = require('is');
var css = require('css');
var path = require('path');
var join = path.join;
var extname = path.extname;
var rename = require('./rename');
var udeps = require('umd-deps');
var cdeps = require('./css-deps');
var util = require('./util');
var debug = util.debug;
var colors = util.colors;
var inlinePlugins = require('./plugins/');

/**
 * Resolve id leading
 * @param idleading
 * @param path
 * @param pkg
 * @returns {*}
 */

function resolveIdleading(idleading, path, pkg){
  return is.fn(idleading) ? idleading(path, pkg) : idleading;
}

/**
 * Transport vinyl id
 * - vinyl: vinyl object
 * - required options: idleading, rename
 */

function transportId(vinyl, options){
  var id;
  var pkg = util.parsePackage(vinyl, options.wwwroot);
  var idleading = resolveIdleading(options.idleading, vinyl.path, pkg);

  // get id
  id = util.template(idleading, pkg);
  // rename id
  id = util.addExt(id);
  id = rename(id, options.rename);
  id = util.hideExt(id);

  // seajs has hacked css before 3.0.0
  // https://github.com/seajs/seajs/blob/2.2.1/src/util-path.js#L49
  // demo https://github.com/popomore/seajs-test/tree/master/css-deps
  if (extname(id) === '.css') {
    id += '.js';
  }

  // normalize id
  id = util.normalize(id);

  // debug
  debug('transport id: %s', colors.magenta(id));

  // rewrite vinyl path
  if (path.isAbsolute(id)) {
    vinyl.path = join(options.wwwroot, util.addExt(id));
  } else {
    vinyl.path = join(vinyl.cwd, vinyl.base, util.addExt(id));
  }

  // set vinyl package info
  vinyl.package = util.extend(pkg, { id: id });

  return id;
}

/**
 * Transport cmd dependencies.
 * - vinyl: vinyl object
 * - required options: idleading
 */

function transportDeps(vinyl, options){
  var deps = [];
  var include = [];
  var vars = options.vars;
  var alias = options.alias;
  var paths = options.paths;
  var pkg = vinyl.package || {};

  // replace require and collect dependencies
  vinyl.contents = new Buffer(udeps(vinyl.contents.toString(), function (id, flag){
    // parse id form alias, paths, vars
    id = util.parseAlias(id, alias);
    id = util.parsePaths(id, paths);
    id = util.parseAlias(id, alias);
    id = util.parseVars(id, vars);
    id = util.parseAlias(id, alias);

    // id is not a local file
    if (!util.isLocal(id)) {
      // cache dependencie id
      deps.push(id);

      return id;
    }

    var path;

    // normalize id
    id = util.normalize(id);

    // if end with /, find index file
    if (id.substring(id.length - 1) === '/') {
      id += 'index';
    }

    // debug
    debug('transport%s deps: %s', flag ? ' ' + flag : '', colors.magenta(id));

    // add extname
    path = util.addExt(id);
    // rename id
    id = rename(path, options.rename);
    // hide extname
    id = util.hideExt(id);

    // seajs has hacked css before 3.0.0
    // https://github.com/seajs/seajs/blob/2.2.1/src/util-path.js#L49
    // demo https://github.com/popomore/seajs-test/tree/master/css-deps
    if (extname(id) === '.css') {
      id += '.js';
    }

    // normalize id
    id = util.normalize(id);

    // cache dependencie id and path
    if (flag === null) {
      // cache dependencie id
      deps.push(id);

      // get absolute path
      path = util.resolve(path, vinyl, options.wwwroot);

      // cache dependencie absolute path
      include.push({
        id: id,
        path: path
      });
    }

    return id;
  }, true));

  // Cache file dependencies
  vinyl.package = util.extend(pkg, {
    include: include,
    dependencies: deps
  });

  return deps;
}

/**
 * Transport css dependencies.
 * - vinyl: vinyl object
 */

function transportCssDeps(vinyl, options){
  var deps = [];
  var include = [];
  var pkg = vinyl.package || {};
  var onpath = options.css.onpath;
  var prefix = options.css.prefix;

  // init css settings
  onpath = is.fn(onpath) ? function (path, property){
    return options.css.onpath(path, property, pkg.id || null, vinyl.path);
  } : null;
  prefix = is.fn(prefix) ? prefix(pkg.id || null, vinyl.path) : prefix;

  // replace imports and collect dependencies
  vinyl.contents = new Buffer(cdeps(vinyl.contents, function (id){
    var path;

    // id is not a local file
    if (!util.isLocal(id)) {
      // cache dependencie id
      deps.push(id);

      // keep import
      return id;
    }

    // normalize id
    id = util.normalize(id);

    var isRelative = util.isRelative(id);
    var isAbsolute = util.isAbsolute(id);

    // css import parsing rules using html
    if (!isAbsolute && !isRelative) {
      id = './' + id;
    }

    // if end with /, find index file
    if (id.substring(id.length - 1) === '/') {
      id += 'index.css';
    }

    // add extname
    path = util.addExt(id);
    // rename id
    id = rename(path, options.rename);
    // hide extname
    id = util.hideExt(id);

    // seajs has hacked css before 3.0.0
    // https://github.com/seajs/seajs/blob/2.2.1/src/util-path.js#L49
    // demo https://github.com/popomore/seajs-test/tree/master/css-deps
    if (extname(id) === '.css') {
      id += '.js';
    }

    // normalize id
    id = util.normalize(id);

    // debug
    debug('transport deps: %s', colors.magenta(id));

    // get absolute path
    path = util.resolve(path, vinyl, options.wwwroot);

    // cache dependencie id
    deps.push(id);
    // cache dependencie absolute path
    include.push({
      id: id,
      path: path
    });

    // delete all import
    return false;
  }, onpath, prefix));

  // Cache file dependencies
  vinyl.package = util.extend(pkg, {
    include: include,
    dependencies: deps
  });

  return deps;
}

/**
 * Init plugins
 * @param plugins
 * @returns {{defined: {}, other: *}}
 */

function initPlugins(plugins){
  var name;
  var plugin;
  plugins = plugins || {};

  for (name in plugins) {
    if (plugins.hasOwnProperty(name)) {
      plugin = plugins[name];

      if (is.fn(plugin)) {
        plugin = util.plugin(name, plugin);
      } else {
        util.throwError('options.plugins.' + name + ' should be function.');
      }

      plugins[name] = plugin;
    }
  }

  for (name in inlinePlugins) {
    if (inlinePlugins.hasOwnProperty(name)) {
      plugins[name] = plugins[name] || inlinePlugins[name];
    }
  }

  return plugins;
}

/**
 * Get rename options
 * @param transform
 * @returns {*}
 */

function initRenameOptions(transform){
  if (is.fn(transform)) {
    return transform;
  }

  transform = transform || {};

  if (transform.min) {
    transform.suffix = '-min';
  }

  if (transform.debug) {
    transform.suffix = '-debug';
  }

  return transform;
}

/**
 * Init options
 * @param options
 * @returns {object}
 */

function initOptions(options){
  var defaults = {
    css: {}, // { prefix: null, onpath: null }
    vars: {}, // the vars
    paths: {}, // the paths
    alias: {}, // the alias
    cache: true, // use memory file cahe
    ignore: [], // omit the given dependencies when include
    wwwroot: '', // web root
    rename: null, // { debug: boolean, min: boolean }
    include: 'relative', // include model: self, relative, all

    idleading: '{{name}}/{{version}}/{{file}}' // the id prefix template
  };

  // mix
  util.extend(true, defaults, options);

  if (defaults.wwwroot && !is.string(defaults.wwwroot)) {
    throwError('options.wwwroot\'s value should be string.');
  }

  // init css settings
  defaults.css = defaults.css || {};
  // init wwwroot
  defaults.wwwroot = join(util.cwd, defaults.wwwroot);
  // init plugins
  defaults.plugins = initPlugins(defaults.plugins);
  // init rename
  defaults.rename = initRenameOptions(defaults.rename);
  // init ignore
  defaults.ignore = Array.isArray(defaults.ignore) ? defaults.ignore : [];

  return defaults;
}

/**
 * Exports module.
 */

exports.initOptions = initOptions;
exports.transportId = transportId;
exports.transportDeps = transportDeps;
exports.transportCssDeps = transportCssDeps;
<commit_msg>bug fixed<commit_after>/**
 * Created by nuintun on 2015/4/27.
 */

'use strict';

var is = require('is');
var css = require('css');
var path = require('path');
var join = path.join;
var extname = path.extname;
var rename = require('./rename');
var udeps = require('umd-deps');
var cdeps = require('./css-deps');
var util = require('./util');
var debug = util.debug;
var colors = util.colors;
var inlinePlugins = require('./plugins/');

/**
 * Resolve id leading
 * @param idleading
 * @param path
 * @param pkg
 * @returns {*}
 */

function resolveIdleading(idleading, path, pkg){
  return is.fn(idleading) ? idleading(path, pkg) : idleading;
}

/**
 * Transport vinyl id
 * - vinyl: vinyl object
 * - required options: idleading, rename
 */

function transportId(vinyl, options){
  var id;
  var pkg = util.parsePackage(vinyl, options.wwwroot);
  var idleading = resolveIdleading(options.idleading, vinyl.path, pkg);

  // get id
  id = util.template(idleading, pkg);
  // rename id
  id = util.addExt(id);
  id = rename(id, options.rename);
  id = util.hideExt(id);

  // seajs has hacked css before 3.0.0
  // https://github.com/seajs/seajs/blob/2.2.1/src/util-path.js#L49
  // demo https://github.com/popomore/seajs-test/tree/master/css-deps
  if (extname(id) === '.css') {
    id += '.js';
  }

  // normalize id
  id = util.normalize(id);

  // debug
  debug('transport id: %s', colors.magenta(id));

  // rewrite vinyl path
  if (path.isAbsolute(id)) {
    vinyl.path = join(options.wwwroot, util.addExt(id));
  } else {
    vinyl.path = join(vinyl.cwd, vinyl.base, util.addExt(id));
  }

  // set vinyl package info
  vinyl.package = util.extend(pkg, { id: id });

  return id;
}

/**
 * Transport cmd dependencies.
 * - vinyl: vinyl object
 * - required options: idleading
 */

function transportDeps(vinyl, options){
  var deps = [];
  var include = [];
  var vars = options.vars;
  var alias = options.alias;
  var paths = options.paths;
  var pkg = vinyl.package || {};

  // replace require and collect dependencies
  vinyl.contents = new Buffer(udeps(vinyl.contents.toString(), function (id, flag){
    // parse id form alias, paths, vars
    id = util.parseAlias(id, alias);
    id = util.parsePaths(id, paths);
    id = util.parseAlias(id, alias);
    id = util.parseVars(id, vars);
    id = util.parseAlias(id, alias);

    // id is not a local file
    if (!util.isLocal(id)) {
      // cache dependencie id
      deps.push(id);

      return id;
    }

    var path;

    // normalize id
    id = util.normalize(id);

    // if end with /, find index file
    if (id.substring(id.length - 1) === '/') {
      id += 'index';
    }

    // debug
    debug('transport%s deps: %s', flag ? ' ' + flag : '', colors.magenta(id));

    // add extname
    path = util.addExt(id);
    // rename id
    id = rename(path, options.rename);
    // hide extname
    id = util.hideExt(id);

    // seajs has hacked css before 3.0.0
    // https://github.com/seajs/seajs/blob/2.2.1/src/util-path.js#L49
    // demo https://github.com/popomore/seajs-test/tree/master/css-deps
    if (extname(id) === '.css') {
      id += '.js';
    }

    // normalize id
    id = util.normalize(id);

    // cache dependencie id and path
    if (flag === null) {
      // cache dependencie id
      deps.push(id);

      // get absolute path
      path = util.resolve(path, vinyl, options.wwwroot);

      // cache dependencie absolute path
      include.push({
        id: id,
        path: path
      });
    }

    return id;
  }, true));

  // Cache file dependencies
  vinyl.package = util.extend(pkg, {
    include: include,
    dependencies: deps
  });

  return deps;
}

/**
 * Transport css dependencies.
 * - vinyl: vinyl object
 */

function transportCssDeps(vinyl, options){
  var deps = [];
  var include = [];
  var pkg = vinyl.package || {};
  var onpath = options.css.onpath;
  var prefix = options.css.prefix;

  // init css settings
  onpath = is.fn(onpath) ? function (path, property){
    return options.css.onpath(path, property, pkg.id || null, vinyl.path);
  } : null;
  prefix = is.fn(prefix) ? prefix(pkg.id || null, vinyl.path) : prefix;

  // replace imports and collect dependencies
  vinyl.contents = new Buffer(cdeps(vinyl.contents, function (id){
    var path;

    // id is not a local file
    if (!util.isLocal(id)) {
      // cache dependencie id
      deps.push(id);

      // keep import
      return id;
    }

    // normalize id
    id = util.normalize(id);

    var isRelative = util.isRelative(id);
    var isAbsolute = util.isAbsolute(id);

    // css import parsing rules using html
    if (!isAbsolute && !isRelative) {
      id = './' + id;
    }

    // if end with /, find index file
    if (id.substring(id.length - 1) === '/') {
      id += 'index.css';
    }

    // add extname
    path = util.addExt(id);
    // rename id
    id = rename(path, options.rename);
    // hide extname
    id = util.hideExt(id);

    // seajs has hacked css before 3.0.0
    // https://github.com/seajs/seajs/blob/2.2.1/src/util-path.js#L49
    // demo https://github.com/popomore/seajs-test/tree/master/css-deps
    if (extname(id) === '.css') {
      id += '.js';
    }

    // normalize id
    id = util.normalize(id);

    // debug
    debug('transport deps: %s', colors.magenta(id));

    // get absolute path
    path = util.resolve(path, vinyl, options.wwwroot);

    // cache dependencie id
    deps.push(id);
    // cache dependencie absolute path
    include.push({
      id: id,
      path: path
    });

    // delete all import
    return false;
  }, onpath, prefix));

  // Cache file dependencies
  vinyl.package = util.extend(pkg, {
    include: include,
    dependencies: deps
  });

  return deps;
}

/**
 * Init plugins
 * @param plugins
 * @returns {{defined: {}, other: *}}
 */

function initPlugins(plugins){
  var name;
  var plugin;
  plugins = plugins || {};

  for (name in plugins) {
    if (plugins.hasOwnProperty(name)) {
      plugin = plugins[name];

      if (is.fn(plugin)) {
        plugin = util.plugin(name, plugin);
      } else {
        util.throwError('options.plugins.' + name + ' should be function.');
      }

      plugins[name] = plugin;
    }
  }

  for (name in inlinePlugins) {
    if (inlinePlugins.hasOwnProperty(name)) {
      plugins[name] = plugins[name] || inlinePlugins[name];
    }
  }

  return plugins;
}

/**
 * Get rename options
 * @param transform
 * @returns {*}
 */

function initRenameOptions(transform){
  if (is.fn(transform)) {
    return transform;
  }

  transform = transform || {};

  if (transform.min) {
    transform.suffix = '-min';
  }

  if (transform.debug) {
    transform.suffix = '-debug';
  }

  return transform;
}

/**
 * Init options
 * @param options
 * @returns {object}
 */

function initOptions(options){
  var defaults = {
    css: {}, // { prefix: null, onpath: null }
    vars: {}, // the vars
    paths: {}, // the paths
    alias: {}, // the alias
    cache: true, // use memory file cahe
    ignore: [], // omit the given dependencies when include
    wwwroot: '', // web root
    rename: null, // { debug: boolean, min: boolean }
    include: 'relative', // include model: self, relative, all

    idleading: '{{name}}/{{version}}/{{file}}' // the id prefix template
  };

  // mix
  util.extend(true, defaults, options);

  if (defaults.wwwroot && !is.string(defaults.wwwroot)) {
    util.throwError('options.wwwroot\'s value should be string.');
  }

  // init css settings
  defaults.css = defaults.css || {};
  // init wwwroot
  defaults.wwwroot = join(util.cwd, defaults.wwwroot);
  // init plugins
  defaults.plugins = initPlugins(defaults.plugins);
  // init rename
  defaults.rename = initRenameOptions(defaults.rename);
  // init ignore
  defaults.ignore = Array.isArray(defaults.ignore) ? defaults.ignore : [];

  return defaults;
}

/**
 * Exports module.
 */

exports.initOptions = initOptions;
exports.transportId = transportId;
exports.transportDeps = transportDeps;
exports.transportCssDeps = transportCssDeps;
<|endoftext|>


<commit_before>var _ = require('underscore');

module.exports = function(name) {

  var nameConversions = [
    firstInitialAndLastName = /^(\w).*\s(\w+)$/,
    firstAndLastName = /^(\w+)\s(\w+)$/,
    firstNameAndLastInitial = /^(\w+)\s(\w).+$/
  ];

  var emailDelimiters = [
    contiguous = "$1$2",
    dot = "$1.$2",
    dash = "$1-$2",
    underscore = "$1_$2",
    reversed = "$2$1",
    reversedDot = "$2.$1",
    reversedDash = "$2-$1",
    reversedUnderscore = "$2_$1",
    justLastName = "$2",
    justFirstName = "$1",
  ];

  return name.toLowerCase().replace(
    _.shuffle(nameConversions)[0],
    _.shuffle(emailDelimiters)[0]
  ) + randomSuffix();

};

// Generate the random chance that a random number will be affixed to the end

function randomSuffix() {

  var randomChance = Math.round(Math.random());

  if ( randomChance ) {
    return Math.floor(Math.random()*1001);
  } else {
    return "";
  }

}<commit_msg>Add initials and lower random number<commit_after>var _ = require('underscore');

module.exports = function(name) {

  var nameConversions = [
    initials = /^(\w).*\s(\w).*$/
    firstInitialAndLastName = /^(\w).*\s(\w+)$/,
    firstAndLastName = /^(\w+)\s(\w+)$/,
    firstNameAndLastInitial = /^(\w+)\s(\w).+$/
  ];

  var emailDelimiters = [
    contiguous = "$1$2",
    dot = "$1.$2",
    dash = "$1-$2",
    underscore = "$1_$2",
    reversed = "$2$1",
    reversedDot = "$2.$1",
    reversedDash = "$2-$1",
    reversedUnderscore = "$2_$1",
    justLastName = "$2",
    justFirstName = "$1",
  ];

  return name.toLowerCase().replace(
    _.shuffle(nameConversions)[0],
    _.shuffle(emailDelimiters)[0]
  ) + randomSuffix();

};

// Generate the random chance that a random number will be affixed to the end

function randomSuffix() {

  var randomChance = Math.round(Math.random());

  if ( randomChance ) {
    return Math.floor(Math.random()*101);
  } else {
    return "";
  }

}<|endoftext|>