<commit_before>// @flow

import {
  getSource,
  hasSymbols,
  getSelectedLocation,
  getSelectedSource,
  getSelectedFrame,
  getPreview
} from "../selectors";

import { PROMISE } from "../utils/redux/middleware/promise";
import * as parser from "../utils/parser";

import type { SourceId } from "debugger-html";
import type { ThunkArgs } from "./types";
import type { AstLocation } from "../utils/parser";

export function setSymbols(sourceId: SourceId) {
  return async ({ dispatch, getState }: ThunkArgs) => {
    const sourceRecord = getSource(getState(), sourceId);
    if (!sourceRecord) {
      return;
    }

    const source = sourceRecord.toJS();
    if (!source.text || hasSymbols(getState(), source)) {
      return;
    }

    const symbols = await parser.getSymbols(source);

    dispatch({
      type: "SET_SYMBOLS",
      source,
      symbols
    });
  };
}

export function setEmptyLines(sourceId: SourceId) {
  return async ({ dispatch, getState }: ThunkArgs) => {
    const sourceRecord = getSource(getState(), sourceId);
    if (!sourceRecord) {
      return;
    }

    const source = sourceRecord.toJS();
    if (!source.text) {
      return;
    }

    const emptyLines = await parser.getEmptyLines(source);

    dispatch({
      type: "SET_EMPTY_LINES",
      source,
      emptyLines
    });
  };
}

export function setOutOfScopeLocations() {
  return async ({ dispatch, getState }: ThunkArgs) => {
    const location = getSelectedLocation(getState());
    if (!location) {
      return;
    }

    const source = getSource(getState(), location.sourceId);

    if (!location.line || !source) {
      return dispatch({
        type: "OUT_OF_SCOPE_LOCATIONS",
        locations: null
      });
    }

    const locations = await parser.getOutOfScopeLocations(
      source.toJS(),
      location
    );

    return dispatch({
      type: "OUT_OF_SCOPE_LOCATIONS",
      locations
    });
  };
}

export function clearPreview() {
  return ({ dispatch, getState, client }: ThunkArgs) => {
    const currentSelection = getPreview(getState());
    if (!currentSelection) {
      return;
    }

    return dispatch({
      type: "CLEAR_SELECTION"
    });
  };
}

function findBestMatch(symbols, tokenPos, token) {
  const { memberExpressions, identifiers } = symbols;
  const { line, column } = tokenPos;
  return identifiers.concat(memberExpressions).reduce((found, expression) => {
    const overlaps =
      expression.location.start.line == line &&
      expression.location.start.column <= column &&
      expression.location.end.column >= column;

    if (overlaps) {
      return expression;
    }

    return found;
  }, {});
}

export function setPreview(
  token: string,
  tokenPos: AstLocation,
  cursorPos: any
) {
  return async ({ dispatch, getState, client }: ThunkArgs) => {
    const currentSelection = getPreview(getState());
    if (currentSelection && currentSelection.updating) {
      return;
    }

    await dispatch({
      type: "SET_PREVIEW",
      [PROMISE]: (async function() {
        const source = getSelectedSource(getState());
        const _symbols = await parser.getSymbols(source.toJS());

        const found = findBestMatch(_symbols, tokenPos, token);
        if (!found) {
          return;
        }

        const { expression, location } = found;

        if (!expression) {
          return;
        }

        const selectedFrame = getSelectedFrame(getState());
        const { result } = await client.evaluate(expression, {
          frameId: selectedFrame.id
        });

        if (!result) {
          return;
        }

        return {
          expression,
          result,
          location,
          tokenPos,
          cursorPos
        };
      })()
    });
  };
}
<commit_msg>Fix preview for falsy values (#3960)<commit_after>// @flow

import {
  getSource,
  hasSymbols,
  getSelectedLocation,
  getSelectedSource,
  getSelectedFrame,
  getPreview
} from "../selectors";

import { PROMISE } from "../utils/redux/middleware/promise";
import * as parser from "../utils/parser";

import type { SourceId } from "debugger-html";
import type { ThunkArgs } from "./types";
import type { AstLocation } from "../utils/parser";

export function setSymbols(sourceId: SourceId) {
  return async ({ dispatch, getState }: ThunkArgs) => {
    const sourceRecord = getSource(getState(), sourceId);
    if (!sourceRecord) {
      return;
    }

    const source = sourceRecord.toJS();
    if (!source.text || hasSymbols(getState(), source)) {
      return;
    }

    const symbols = await parser.getSymbols(source);

    dispatch({
      type: "SET_SYMBOLS",
      source,
      symbols
    });
  };
}

export function setEmptyLines(sourceId: SourceId) {
  return async ({ dispatch, getState }: ThunkArgs) => {
    const sourceRecord = getSource(getState(), sourceId);
    if (!sourceRecord) {
      return;
    }

    const source = sourceRecord.toJS();
    if (!source.text) {
      return;
    }

    const emptyLines = await parser.getEmptyLines(source);

    dispatch({
      type: "SET_EMPTY_LINES",
      source,
      emptyLines
    });
  };
}

export function setOutOfScopeLocations() {
  return async ({ dispatch, getState }: ThunkArgs) => {
    const location = getSelectedLocation(getState());
    if (!location) {
      return;
    }

    const source = getSource(getState(), location.sourceId);

    if (!location.line || !source) {
      return dispatch({
        type: "OUT_OF_SCOPE_LOCATIONS",
        locations: null
      });
    }

    const locations = await parser.getOutOfScopeLocations(
      source.toJS(),
      location
    );

    return dispatch({
      type: "OUT_OF_SCOPE_LOCATIONS",
      locations
    });
  };
}

export function clearPreview() {
  return ({ dispatch, getState, client }: ThunkArgs) => {
    const currentSelection = getPreview(getState());
    if (!currentSelection) {
      return;
    }

    return dispatch({
      type: "CLEAR_SELECTION"
    });
  };
}

function findBestMatch(symbols, tokenPos, token) {
  const { memberExpressions, identifiers } = symbols;
  const { line, column } = tokenPos;
  return identifiers.concat(memberExpressions).reduce((found, expression) => {
    const overlaps =
      expression.location.start.line == line &&
      expression.location.start.column <= column &&
      expression.location.end.column >= column;

    if (overlaps) {
      return expression;
    }

    return found;
  }, {});
}

export function setPreview(
  token: string,
  tokenPos: AstLocation,
  cursorPos: any
) {
  return async ({ dispatch, getState, client }: ThunkArgs) => {
    const currentSelection = getPreview(getState());
    if (currentSelection && currentSelection.updating) {
      return;
    }

    await dispatch({
      type: "SET_PREVIEW",
      [PROMISE]: (async function() {
        const source = getSelectedSource(getState());
        const _symbols = await parser.getSymbols(source.toJS());

        const found = findBestMatch(_symbols, tokenPos, token);
        if (!found) {
          return;
        }

        const { expression, location } = found;

        if (!expression) {
          return;
        }

        const selectedFrame = getSelectedFrame(getState());
        const { result } = await client.evaluate(expression, {
          frameId: selectedFrame.id
        });

        if (result === undefined) {
          return;
        }

        return {
          expression,
          result,
          location,
          tokenPos,
          cursorPos
        };
      })()
    });
  };
}
<|endoftext|>


<commit_before>const request = require('request');
const exec = require('child_process').exec;
const discord = require('discord.js');

const time = require('../../lib/utils.js').time;

const githubCommits = 'https://api.github.com/repos/$repo/commits';
const githubContributors = 'https://api.github.com/repos/$repo/contributors';
const githubRepo = 'https://github.com/$repo';
const commitTemplate = '$username - $message';
const markdownLink = '[$text]($link)';
const description = 'Message cmd for available commands.';
let config;
const lastCommit = {};
const currentCommit = {};
let contributorsMessage = '';
const githubHeaders = {
  'User-Agent': 'TheAwesomeBot',
  'Accept': 'application/vnd.github.v3+json', // eslint-disable-line quote-props
};

function getLastCommit() {
  request({
    url: githubCommits.replace('$repo', config.repo),
    headers: githubHeaders,
  }, (err, response, body) => {
    if (err || response.statusCode !== 200) {
      lastCommit.link = 'https://github.com/404';
      lastCommit.message = 'Couldn\'t retrieve commit data.';
      return;
    }
    const commitData = JSON.parse(body);
    // TODO (sam): Instead of depending on nullness of the variable,
    // act according to github api docs
    if (commitData[0] == null) {
      lastCommit.message = 'Couldn\'t retrieve commit data.';
      return;
    }
    const commitMessage = commitData[0].commit.message.replace('\n\n', ' ')
      .replace('\n', ' ');
    lastCommit.link = commitData[0].html_url;
    lastCommit.username = commitData[0].author ? commitData[0].author.login : 'unkown';
    lastCommit.message = commitTemplate.replace('$username', lastCommit.username)
      .replace('$message', commitMessage);
  });
}

function getCurrentCommit() {
  exec('git show --oneline -s', (err, stdout) => {
    const gitOutput = stdout.replace('\n\n', '').replace('\n', '');
    currentCommit.shortSHA = gitOutput.split(' ')[0];

    request({
      url: githubCommits.replace('$repo', config.repo) + '/' + currentCommit.shortSHA,
      headers: githubHeaders,
    }, (error, response, body) => {
      if (error || response.statusCode !== 200) {
        currentCommit.link = 'https://github.com/404';
        return;
      }
      currentCommit.link = JSON.parse(body).html_url;
      currentCommit.username = JSON.parse(body).author ? JSON.parse(body).author.login : 'unkown';
      currentCommit.message = commitTemplate.replace('$username', currentCommit.username)
        .replace('$message', gitOutput.split(' ').slice(1).join(' '));
    });
  });
}

function getContributors() {
  request({
    url: githubContributors.replace('$repo', config.repo),
    headers: githubHeaders,
  }, (error, response, body) => {
    let jsonData = JSON.parse(body);
    jsonData = jsonData.slice(0, 10);

    jsonData.forEach((elem) => {
      contributorsMessage += markdownLink.replace('$text', elem.login).replace('$link', elem.html_url) + '\n';
    });
  });
}

function infoInit(bot) {
  config = bot.settings.info;
  // get current checked out commit from git
  getCurrentCommit();
  // get latest commit in git repo
  getLastCommit();
  getContributors();
}

function infoRun(bot, message, cmdArgs) {
  if (cmdArgs) {
    if (cmdArgs === 'contributors') {
      const contributorsEmbed = new discord.RichEmbed();
      contributorsEmbed.setColor('#4286f4')
        .setTitle('Top 10 contributors of AwesomeBot:')
        .setDescription(contributorsMessage);
      message.channel.sendEmbed(contributorsEmbed);
    }
  } else {
    const embed = new discord.RichEmbed();
    embed.setColor('#4286f4')
      .setAuthor('TheAwesomeBot', bot.client.user.avatarURL, githubRepo.replace('$repo', config.repo))
      .setFooter(description.replace('cmd', bot.settings.bot_cmd))
      .addField('Uptime', time.timeElapsed(bot.bootTime, new Date()))
      .addField('Latest Commit', markdownLink.replace('$text', lastCommit.message).replace('$link', lastCommit.link))
      .setDescription('An open source bot made with :heart:');
    // let the users know if bot is working on a rolled back commit
    if (currentCommit !== lastCommit) {
      embed.addField('Current Commit', markdownLink.replace('$text', currentCommit.message)
        .replace('$link', currentCommit.link));
    }
    message.channel.sendEmbed(embed);
  }
}

module.exports = {
  usage: [
    'info - displays information about bot',
    'info contributors - displays contributors',
  ],
  init: infoInit,
  run: infoRun,
};
<commit_msg>Safe guarding against malformed response<commit_after>const request = require('request');
const exec = require('child_process').exec;
const discord = require('discord.js');

const time = require('../../lib/utils.js').time;

const githubCommits = 'https://api.github.com/repos/$repo/commits';
const githubContributors = 'https://api.github.com/repos/$repo/contributors';
const githubRepo = 'https://github.com/$repo';
const commitTemplate = '$username - $message';
const markdownLink = '[$text]($link)';
const description = 'Message cmd for available commands.';
let config;
const lastCommit = {};
const currentCommit = {};
let contributorsMessage = '';
const githubHeaders = {
  'User-Agent': 'TheAwesomeBot',
  'Accept': 'application/vnd.github.v3+json', // eslint-disable-line quote-props
};

function getLastCommit() {
  request({
    url: githubCommits.replace('$repo', config.repo),
    headers: githubHeaders,
  }, (err, response, body) => {
    if (err || response.statusCode !== 200) {
      lastCommit.link = 'https://github.com/404';
      lastCommit.message = 'Couldn\'t retrieve commit data.';
      return;
    }
    const commitData = JSON.parse(body);
    // TODO (sam): Instead of depending on nullness of the variable,
    // act according to github api docs
    if (commitData[0] == null) {
      lastCommit.message = 'Couldn\'t retrieve commit data.';
      return;
    }
    const commitMessage = commitData[0].commit.message.replace('\n\n', ' ')
      .replace('\n', ' ');
    lastCommit.link = commitData[0].html_url;
    lastCommit.username = commitData[0].author ? commitData[0].author.login : 'unkown';
    lastCommit.message = commitTemplate.replace('$username', lastCommit.username)
      .replace('$message', commitMessage);
  });
}

function getCurrentCommit() {
  exec('git show --oneline -s', (err, stdout) => {
    const gitOutput = stdout.replace('\n\n', '').replace('\n', '');
    currentCommit.shortSHA = gitOutput.split(' ')[0];

    request({
      url: githubCommits.replace('$repo', config.repo) + '/' + currentCommit.shortSHA,
      headers: githubHeaders,
    }, (error, response, body) => {
      if (error || response.statusCode !== 200) {
        currentCommit.link = 'https://github.com/404';
        return;
      }
      currentCommit.link = JSON.parse(body).html_url;
      currentCommit.username = JSON.parse(body).author ? JSON.parse(body).author.login : 'unkown';
      currentCommit.message = commitTemplate.replace('$username', currentCommit.username)
        .replace('$message', gitOutput.split(' ').slice(1).join(' '));
    });
  });
}

function getContributors() {
  request({
    url: githubContributors.replace('$repo', config.repo),
    headers: githubHeaders,
  }, (error, response, body) => {
    let jsonData = JSON.parse(body);
    if (Array.isArray(jsonData) && jsonData.length >= 10) {
      jsonData = jsonData.slice(0, 10);
      contributorsMessage = jsonData.slice(0, 10).reduce((acc, cv) =>
        acc + markdownLink.replace('$text', cv.login).replace('$link', cv.html_url) + '\n'
      , '');
    } else {
      contributorsMessage = 'There was an error trying to get the contributors list :(';
    }
  });
}

function infoInit(bot) {
  config = bot.settings.info;
  // get current checked out commit from git
  getCurrentCommit();
  // get latest commit in git repo
  getLastCommit();
  getContributors();
}

function infoRun(bot, message, cmdArgs) {
  if (cmdArgs) {
    if (cmdArgs === 'contributors') {
      const contributorsEmbed = new discord.RichEmbed();
      contributorsEmbed.setColor('#4286f4')
        .setTitle('Top 10 contributors of AwesomeBot:')
        .setDescription(contributorsMessage);
      message.channel.sendEmbed(contributorsEmbed);
    }
  } else {
    const embed = new discord.RichEmbed();
    embed.setColor('#4286f4')
      .setAuthor('TheAwesomeBot', bot.client.user.avatarURL, githubRepo.replace('$repo', config.repo))
      .setFooter(description.replace('cmd', bot.settings.bot_cmd))
      .addField('Uptime', time.timeElapsed(bot.bootTime, new Date()))
      .addField('Latest Commit', markdownLink.replace('$text', lastCommit.message).replace('$link', lastCommit.link))
      .setDescription('An open source bot made with :heart:');
    // let the users know if bot is working on a rolled back commit
    if (currentCommit !== lastCommit) {
      embed.addField('Current Commit', markdownLink.replace('$text', currentCommit.message)
        .replace('$link', currentCommit.link));
    }
    message.channel.sendEmbed(embed);
  }
}

module.exports = {
  usage: [
    'info - displays information about bot',
    'info contributors - displays contributors',
  ],
  init: infoInit,
  run: infoRun,
};
<|endoftext|>


<commit_before>import Cookies from 'universal-cookie'
import * as types from '../types'
const cookie = new Cookies()
export const errorHandler = (dispatch, error, type) => {
    let errorMessage = error

    dispatch({
        type,
        payload: errorMessage
    })
}

export const loginUser = ({ email, password }) => dispatch => {
    const options = {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            email,
            password
        })
    }

    return fetch('/auth/login', options)
        .then(response => {
            if (response.status === 401) throw Error('An error occurred. Please verify your login credentials and try again.')
            return response.json()
        })
        .then(data => {
            cookie.set('token', data.token, { path: '/' })
            let fullName = (data.user.firstName + ' ' + data.user.lastName).toUpperCase()
            console.log('name', fullName)
            dispatch({ type: types.AUTH_USER, payload: fullName })
            window.location.href = '/bars'
        })
        .catch(error => {
            errorHandler(dispatch, error, types.AUTH_ERROR)
        })
}

export const registerUser = ({ email, firstName, lastName, password }) => dispatch => {
    const options = {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            email,
            firstName,
            lastName,
            password
        })
    }

    return fetch('/auth/register', options)
        .then(response => {
            if (response.status === 422) throw Error('Email is already in use.')
            return response.json()
        })
        .then(data => {
            cookie.set('token', data.token, { path: '/' })
            dispatch({ type: types.AUTH_USER })
            window.location.href = '/bars'
        })
        .catch((error) => {
            errorHandler(dispatch, error, types.AUTH_ERROR)
        })
}

export const logoutUser = () => dispatch => {
    dispatch({ type: types.UNAUTH_USER })
    cookie.remove('token', { path: '/' })

    window.location.href = '/login'
}

export const fetchUserProfile = () => dispatch => {
    const token = cookie.get('token')

    const options = {
        method: 'GET',
        headers: {
            'Authorization': token
        }
    }
    return fetch('/auth/dashboard', options)
        .then(response => response.json())
        .then(data => {
            console.log('profile fech', data)
            dispatch({
                type: types.FETCH_USER_PROFILE,
                payload: data.profile
            })
        })
}

export const addBarToUserProfile = (id) => dispatch => {
    const token = cookie.get('token')

    const options = {
        method: 'POST',
        headers: {
            'content-type': 'application/json',
            'Authorization': token
        },
        body: JSON.stringify({ id })
    }

    return fetch('/auth/addbar', options)
        .then(response => response.json())
        .then(data => {
            dispatch({
                type: types.FETCH_USER_PROFILE,
                payload: data.user
            })
        })
        .then(() => console.log('Done adding'))
}

export const removeBarFromUserProfile = (id) => dispatch => {
    const token = cookie.get('token')

    const options = {
        method: 'POST',
        headers: {
            'content-type': 'application/json',
            'Authorization': token
        },
        body: JSON.stringify({ id })
    }

    return fetch('/auth/removebar', options)
        .then(response => response.json())
        .then(data => {
            console.log('removing', data)
            dispatch({
                type: types.FETCH_USER_PROFILE,
                payload: data.user
            })
        })
        .then(() => console.log('Done remvoing'))
}

export const protectedTest = () => dispatch => {
    console.log(cookie.get('token'))
    return fetch('/auth/dashboard', { method: 'GET', headers: { 'Authorization': cookie.get('token') } })
        .then(response => response.json())
        .then(data => {
            dispatch({
                type: types.PROTECTED_TEST,
                payload: data
            })
        })
        .catch(error => {
            console.log('error', error)
            errorHandler(dispatch, error.response, types.AUTH_ERROR)
        })
}<commit_msg>remove console logs and add AUTH_USER dispatch when fetching profile data<commit_after>import Cookies from 'universal-cookie'
import * as types from '../types'
const cookie = new Cookies()
export const errorHandler = (dispatch, error, type) => {
    let errorMessage = error

    dispatch({
        type,
        payload: errorMessage
    })
}

export const loginUser = ({ email, password }) => dispatch => {
    const options = {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            email,
            password
        })
    }

    return fetch('/auth/login', options)
        .then(response => {
            if (response.status === 401) throw Error('An error occurred. Please verify your login credentials and try again.')
            return response.json()
        })
        .then(data => {
            cookie.set('token', data.token, { path: '/' })
            let fullName = (data.user.firstName + ' ' + data.user.lastName).toUpperCase()
            dispatch({ type: types.AUTH_USER, payload: fullName })
            window.location.href = '/bars'
        })
        .catch(error => {
            errorHandler(dispatch, error, types.AUTH_ERROR)
        })
}

export const registerUser = ({ email, firstName, lastName, password }) => dispatch => {
    const options = {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            email,
            firstName,
            lastName,
            password
        })
    }

    return fetch('/auth/register', options)
        .then(response => {
            if (response.status === 422) throw Error('Email is already in use.')
            return response.json()
        })
        .then(data => {
            cookie.set('token', data.token, { path: '/' })
            dispatch({ type: types.AUTH_USER })
            window.location.href = '/bars'
        })
        .catch((error) => {
            errorHandler(dispatch, error, types.AUTH_ERROR)
        })
}

export const logoutUser = () => dispatch => {
    dispatch({ type: types.UNAUTH_USER })
    cookie.remove('token', { path: '/' })

    window.location.href = '/login'
}

export const fetchUserProfile = () => dispatch => {
    const token = cookie.get('token')

    const options = {
        method: 'GET',
        headers: {
            'Authorization': token
        }
    }
    return fetch('/auth/dashboard', options)
        .then(response => response.json())
        .then(data => {
            dispatch({ type: types.AUTH_USER })
            dispatch({
                type: types.FETCH_USER_PROFILE,
                payload: data.profile
            })
        })
}

export const addBarToUserProfile = (id) => dispatch => {
    const token = cookie.get('token')

    const options = {
        method: 'POST',
        headers: {
            'content-type': 'application/json',
            'Authorization': token
        },
        body: JSON.stringify({ id })
    }

    return fetch('/auth/addbar', options)
        .then(response => response.json())
        .then(data => {
            dispatch({
                type: types.FETCH_USER_PROFILE,
                payload: data.user
            })
        })
}

export const removeBarFromUserProfile = (id) => dispatch => {
    const token = cookie.get('token')

    const options = {
        method: 'POST',
        headers: {
            'content-type': 'application/json',
            'Authorization': token
        },
        body: JSON.stringify({ id })
    }

    return fetch('/auth/removebar', options)
        .then(response => response.json())
        .then(data => {
            dispatch({
                type: types.FETCH_USER_PROFILE,
                payload: data.user
            })
        })
}

export const protectedTest = () => dispatch => {
    return fetch('/auth/dashboard', { method: 'GET', headers: { 'Authorization': cookie.get('token') } })
        .then(response => response.json())
        .then(data => {
            dispatch({
                type: types.PROTECTED_TEST,
                payload: data
            })
        })
        .catch(error => {
            errorHandler(dispatch, error.response, types.AUTH_ERROR)
        })
}<|endoftext|>


<commit_before>exports.names = ['maxlength', 'max', 'maxlenght'];
exports.hidden = false;
exports.enabled = true;
exports.matchStart = true;
exports.cd_all = 0;
exports.cd_user = 0;
exports.cd_manager = 0;
exports.min_role = PERMISSIONS.BOUNCER_PLUS;
exports.handler = function (data) {
	var input = data.message.split(' ');
	var command = _.first(input);
	var params = _.rest(input);
	if (params.length < 1) {
		modMessage(data, 'Current max song length: ' + sec_to_str(settings['maxlength']) + '.');
	}
	else if (params[0].indexOf(':') != -1){
		var time_with_colon = params[0].split(':');
		var new_minutes = time_with_colon[0];
		var new_seconds = time_with_colon[1];

		if (!isNaN(new_minutes) && !isNaN(new_seconds)) {
			var new_length = Math.floor(new_minutes * 60) + Math.floor(new_seconds);
			if (new_length >= 300) {
				set_setting('maxlength', new_length, data);
				modMessage(data, 'Max song length set to ' + sec_to_str(settings['maxlength']) + '.');
			}
			else {
				modMessage(data, 'You can't set the max song length below 5 minutes. :omgscoots:');
			}
	} else {
		var new_length = parseFloat(params);
		if (!isNaN(new_length)) {
			if (Math.floor(new_length * 60) >= 300) {
				set_setting('maxlength', Math.floor(new_length * 60), data);
				modMessage(data, 'Max song length set to ' + sec_to_str(settings['maxlength']) + '.');
			}
			else {
				modMessage(data, 'You can't set the max song length below 5 minutes. :omgscoots:');
			}
		}
	}
};
<commit_msg>fix broken syntax<commit_after>exports.names = ['maxlength', 'max', 'maxlenght'];
exports.hidden = false;
exports.enabled = true;
exports.matchStart = true;
exports.cd_all = 0;
exports.cd_user = 0;
exports.cd_manager = 0;
exports.min_role = PERMISSIONS.BOUNCER_PLUS;
exports.handler = function (data) {
	var input = data.message.split(' ');
	var command = _.first(input);
	var params = _.rest(input);
	if (params.length < 1) {
		modMessage(data, 'Current max song length: ' + sec_to_str(settings['maxlength']) + '.');
	}
	else if (params[0].indexOf(':') != -1){
		var time_with_colon = params[0].split(':');
		var new_minutes = time_with_colon[0];
		var new_seconds = time_with_colon[1];

		if (!isNaN(new_minutes) && !isNaN(new_seconds)) {
			var new_length = Math.floor(new_minutes * 60) + Math.floor(new_seconds);
			if (new_length >= 300) {
				set_setting('maxlength', new_length, data);
				modMessage(data, 'Max song length set to ' + sec_to_str(settings['maxlength']) + '.');
			}
			else {
				modMessage(data, 'You can\'t set the max song length below 5 minutes. :omgscoots:');
			}
	} else {
		var new_length = parseFloat(params);
		if (!isNaN(new_length)) {
			if (Math.floor(new_length * 60) >= 300) {
				set_setting('maxlength', Math.floor(new_length * 60), data);
				modMessage(data, 'Max song length set to ' + sec_to_str(settings['maxlength']) + '.');
			}
			else {
				modMessage(data, 'You can't set the max song length below 5 minutes. :omgscoots:');
			}
		}
	}
};
<|endoftext|>


<commit_before>var assign = require('object-assign');
var WinAppDispatcher = require('../dispatcher/WinAppDispatcher');
var EventEmitter = require('events').EventEmitter;
var assign = require('object-assign');

var WinAppWebApiUtils = require('../utils/WinAppWebApiUtils');
var WinAppObjectUtils = require('../utils/WinAppObjectUtils');
var WinAppConstants = require('../constants/WinAppConstants');
var ActionTypes = WinAppConstants.ActionTypes;

var WinSettings = {
    UserInfos:[],
    Preloads:[],
    SystemApps:[],
    CustomApps:[],
    SystemWins:[],
    CustomWins:[],
    SnapShot:{}
}
var WinSettingsStore = assign({},EventEmitter.prototype,{
    emitChange: function(event) {
        this.emit(event);
    },
    addChangeListener: function(event,callback) {
        this.on(event, callback);
    },
    removeChangeListener: function(event,callback) {
        this.removeListener(event, callback);
    },
    getTaskBars:function(){
        var sysApps = WinSettings.SystemApps;
        var cusApps = WinSettings.CustomApps;
        var bars = [];
        for(var i=0;i<sysApps.length;i++){
            var appWhere = sysApps[i].where;
            var appRender = sysApps[i].render;
            if(appWhere.indexOf("taskbar")>=0 && appRender == "Button"){
                bars.push(sysApps[i]);
            }
        }
        for(var i=0;i<cusApps.length;i++){
            var appWhere = cusApps[i].where;
            var appRender = cusApps[i].render;
            if(appWhere.indexOf("taskbar")>=0 && appRender == "Button"){
                bars.push(cusApps[i]);
            }
        }
        return bars;
    },
    getStartMenu:function(){
        var sysApps = WinSettings.SystemApps;
        var startMenu = { id:3,name:"开始菜单",image:"static/images/start.png",where:["taskbar"],render:"StartMenu",fixed:true};
        for(var i=0;i<sysApps.length;i++){
            var appWhere = sysApps[i].where;
            var appRender = sysApps[i].render;
            if(appWhere.indexOf("taskbar")>=0 && appRender == "StartMenu"){
                startMenu = sysApps[i];
            }
        }
        return startMenu;
    },
    getDesktopBars:function(){
        var sysApps = WinSettings.SystemApps;
        var cusApps = WinSettings.CustomApps;
        var bars = [];
        for(var i=0;i<sysApps.length;i++){
            var appWhere = sysApps[i].where;
            var appRender = sysApps[i].render;
            if(appWhere.indexOf("desktop")>=0 && appRender == "Button"){
                bars.push(sysApps[i]);
            }
        }
        for(var i=0;i<cusApps.length;i++){
            var appWhere = cusApps[i].where;
            var appRender = cusApps[i].render;
            if(appWhere.indexOf("desktop")>=0 && appRender == "Button"){
                bars.push(cusApps[i]);
            }
        }
        return bars;
    },
    getStartMenuBars:function(){
        var sysApps = WinSettings.SystemApps;
        var cusApps = WinSettings.CustomApps;
        var bars = [];
        for(var i=0;i<sysApps.length;i++){
            var appWhere = sysApps[i].where;
            var appRender = sysApps[i].render;
            if(appWhere.indexOf("startmenu")>=0 && appRender == "Button"){
                bars.push(sysApps[i]);
            }
        }
        for(var i=0;i<cusApps.length;i++){
            var appWhere = cusApps[i].where;
            var appRender = cusApps[i].render;
            if(appWhere.indexOf("startmenu")>=0 && appRender == "Button"){
                bars.push(cusApps[i]);
            }
        }
        return bars;
    },
    getWindows:function(){
        var SystemWins = WinSettings.SystemWins;
        var CustomWins = WinSettings.CustomWins;
        var windows = [];
        for(var i=0;i<SystemWins.length;i++){
            windows.push(SystemWins[i]);
        }
        for(var i=0;i<CustomWins.length;i++){
            windows.push(CustomWins[i]);
        }
        return windows;
    },
    getWindowById:function(id){
        var SystemWins = WinSettings.SystemWins;
        var CustomWins = WinSettings.CustomWins;
        var wins = SystemWins.filter(function(ele,pos){
            return ele.id == id;
        })
        if(wins.length>0){
            return wins[0];
        }
        var wins = CustomWins.filter(function(ele,pos){
            return ele.id == id;
        })
        if(wins.length>0){
            return wins[0];
        }else{
            return null;
        }
    },
    getStartMenuButtons:function(){
        return WinSettings.StartMenuButtons
    },
    getByIdAndType:function(id,type){
        var findObj = null;
        switch(type){
            case "SystemApp":
                var filterArr = WinSettings.SystemApps.filter(function(ele,pos){
                    return ele.id==id;
                });
                if(filterArr.length>0){
                    findObj = filterArr[0];
                }
                break;
            case "CustomApp":
                var filterArr = WinSettings.CustomApps.filter(function(ele,pos){
                    return ele.id==id;
                });
                if(filterArr.length>0){
                    findObj = filterArr[0];
                }
                break;
        }
        return findObj;
    },
    getAppById:function(id){
        var SystemApps = WinSettings.SystemApps;
        var CustomApps = WinSettings.CustomApps;
        var apps = SystemApps.filter(function(ele,pos){
            return ele.id == id;
        })
        if(apps.length>0){
            return apps[0];
        }
        var apps = CustomApps.filter(function(ele,pos){
            return ele.id == id;
        })
        if(apps.length>0){
            return apps[0];
        }else{
            return null;
        }
    },
    getSnapShot:function(){
        if(!isNull(WinSettings.SnapShot)){
            return WinSettings.SnapShot;
        }else{
            return {
                app:{},
                snapshots:[]
            };
        }
    },
    addWindow:function(win){
        win.id = win.app_id+"-"+Math.round(Math.random()*1000);
        if(win.type=="CustomWin"){
            WinSettings.CustomWins.push(win);
            var CustomApps = WinSettings.CustomApps;
            var apps = CustomApps.filter(function(ele,pos){
                return ele.id == win.app_id;
            })
            if(apps[0].windows==null) apps[0].windows = [];
            apps[0].windows[win.id] = {snapshot:null};
        }
        if(win.type=="SystemWin"){
            WinSettings.SystemWins.push(win);
            var SystemApps = WinSettings.SystemApps;
            var apps = SystemApps.filter(function(ele,pos){
                return ele.id == win.app_id;
            })
            if(apps[0].windows==null) apps[0].windows = [];
            apps[0].windows[win.id] = { snapshot:null };
        }

    },
    getLoginState:function(){
        return !!WinSettings.UserInfos.login;
    }
});

var isNull = WinAppObjectUtils.isNull;

WinSettingsStore.dispatchToken = WinAppDispatcher.register(function(action) {
    switch(action.type) {
        case ActionTypes.RECEIVE_WIN_SETTINGS:
          WinSettings = action.data;
          break;
        case ActionTypes.TOGGLE_WINDOW:
            var window = action.data;
            if(window.type=="SystemWin"){
                var findWins = WinSettings.SystemWins.filter(function(ele,pos){
                    return ele.id == window.id;
                });
                if(findWins.length>0){
                    findWins[0].show = !findWins[0].show;
                    WinSettingsStore.emitChange(WinAppConstants.EventTypes.WINDOWS);
                };
            }
            if(window.type=="CustomWin"){
                var findWins = WinSettings.CustomWins.filter(function(ele,pos){
                    return ele.id == window.id;
                });
                if(findWins.length>0){
                    findWins[0].show = !findWins[0].show;
                    WinSettingsStore.emitChange(WinAppConstants.EventTypes.WINDOWS);
                };
            }
            break;
        case ActionTypes.SHOW_WINDOW:
            var window = action.data;
            if(window.type=="SystemWin"){
                var findWins = WinSettings.SystemWins.filter(function(ele,pos){
                    return ele.id == window.id;
                });
                if(findWins.length>0){
                    findWins[0].show = true;
                    WinSettingsStore.emitChange(WinAppConstants.EventTypes.WINDOWS);
                };
            }
            if(window.type=="CustomWin"){
                var findWins = WinSettings.CustomWins.filter(function(ele,pos){
                    return ele.id == window.id;
                });
                if(findWins.length>0){
                    findWins[0].show = true;
                    WinSettingsStore.emitChange(WinAppConstants.EventTypes.WINDOWS);
                };
            }
            break;
        case ActionTypes.MIN_WINDOW:
            var window = action.data;
            if(window.type=="SystemWin"){
                var findWins = WinSettings.CustomWins.filter(function(ele,pos){
                    return ele.id == window.id;
                });
                var findApps = WinSettings.CustomApps.filter(function(ele,pos){
                    return ele.id == window.app_id;
                });
                if(findWins.length>0 && findApps.length>0){
                    findWins[0].show = false;
                    findApps[0].windows[window.id].snapshot = window.snapshot;
                    if(!findApps[0].config) findApps[0].config = {}
                    findApps[0].config.position={y:window.position.y,x:window.position.x};
                    findApps[0].width=window.width;
                    findApps[0].height=window.height;
                    WinSettingsStore.emitChange(WinAppConstants.EventTypes.WINDOWS);
                }
            }
            if(window.type=="CustomWin"){
                var findWins = WinSettings.CustomWins.filter(function(ele,pos){
                    return ele.id == window.id;
                });
                var findApps = WinSettings.CustomApps.filter(function(ele,pos){
                    return ele.id == window.app_id;
                });
                if(findWins.length>0 && findApps.length>0){
                    findWins[0].show = false;
                    findApps[0].windows[window.id].snapshot = window.snapshot;
                    if(!findApps[0].config) findApps[0].config = {}
                    findApps[0].config.position={y:window.position.y,x:window.position.x};
                    findApps[0].width=window.width;
                    findApps[0].height=window.height;
                    WinSettingsStore.emitChange(WinAppConstants.EventTypes.WINDOWS);
                }
            }
            break;
        case ActionTypes.CLOSE_WINDOW:
            var window = action.data;
            if(window.type=="SystemWin"){
                var m_pos = -1;
                var findWins = WinSettings.SystemWins.filter(function(ele,pos){
                    if(ele.id == window.id) m_pos=pos;
                    return ele.id == window.id;
                });
                var findApps = WinSettings.SystemApps.filter(function(ele,pos){
                    return ele.id == window.app_id;
                });
                if(findWins.length>0 && findApps.length>0){
                    if(findApps[0].windows[window.id]){
                        delete findApps[0].windows[window.id];
                        if(isNull(findApps[0].windows)){
                            findApps[0].windows = null;
                        }
                    }else{
                        findApps[0].window = null;
                    }
                    WinSettings.SystemWins.splice(m_pos,1);
                    if(!findApps[0].config) findApps[0].config = {}
                    findApps[0].config.position={y:window.position.y,x:window.position.x};
                    findApps[0].width=window.width;
                    findApps[0].height=window.height;
                    WinSettingsStore.emitChange(WinAppConstants.EventTypes.WINDOWS);
                    WinSettingsStore.emitChange(WinAppConstants.EventTypes.TASK_BARS);
                }
            }
            if(window.type=="CustomWin"){
                var m_pos = -1;
                var findWins = WinSettings.CustomWins.filter(function(ele,pos){
                    if(ele.id == window.id) m_pos=pos;
                    return ele.id == window.id;
                });
                var findApps = WinSettings.CustomApps.filter(function(ele,pos){
                    return ele.id == window.app_id;
                });
                if(findWins.length>0 && findApps.length>0){
                    if(findApps[0].windows[window.id]){
                        delete findApps[0].windows[window.id];
                        if(isNull(findApps[0].windows)){
                            findApps[0].windows = null;
                        }
                    }else{
                        findApps[0].window = null;
                    }
                    WinSettings.CustomWins.splice(m_pos,1);
                    if(!findApps[0].config) findApps[0].config = {};
                    findApps[0].config.position={y:window.position.y,x:window.position.x};
                    findApps[0].width=window.width;
                    findApps[0].height=window.height;
                    WinSettingsStore.emitChange(WinAppConstants.EventTypes.WINDOWS);
                    WinSettingsStore.emitChange(WinAppConstants.EventTypes.TASK_BARS);
                }
            }
            WinAppWebApiUtils.saveWinSettings(WinSettings);
            break;
        case ActionTypes.OPEN_WINDOW:
            var app = action.data;
            if(app.config){
                var config = app.config;
                config.app_id = app.id;
                config.image = app.image;
                config.show = true;
                config.fixed = app.fixed;
                WinSettingsStore.addWindow(config);
                WinSettingsStore.emitChange(WinAppConstants.EventTypes.WINDOWS);
                WinSettingsStore.emitChange(WinAppConstants.EventTypes.TASK_BARS);
            }
            WinAppWebApiUtils.saveWinSettings(WinSettings);
            break;
        case ActionTypes.SHOW_SNAP_SHOT:
            var snapShots = [];
            var window = action.data.window,
                windows =action.data.windows,
                app=action.data.app;
            if(!isNull(window)){
                snapShots.push(window);
            }
            if(!isNull(windows)){
                for(var w in windows){
                    windows[w].id = w;
                    snapShots.push(windows[w]);
                }
            }
            WinSettings.SnapShot ={
                snapshots:snapShots,
                app:app
            }
            WinSettingsStore.emitChange(WinAppConstants.EventTypes.SNAPSHOTS);
            break;
        case ActionTypes.USER_LOGIN:
            WinSettings.UserInfos.login = true;
            localStorage.setItem('winSettings',JSON.stringify(WinSettings));
            WinAppWebApiUtils.saveWinSettings(WinSettings);
//            WinSettingsStore.emitChange(WinAppConstants.EventTypes.USER);
            WinSettingsStore.emitChange(WinAppConstants.EventTypes.PAGES);

            break;
        default:
          // do nothing
    }

});

module.exports = WinSettingsStore;<commit_msg>[BUGFIX]登录成功记录session，无需重复登录<commit_after>var assign = require('object-assign');
var WinAppDispatcher = require('../dispatcher/WinAppDispatcher');
var EventEmitter = require('events').EventEmitter;
var assign = require('object-assign');

var WinAppWebApiUtils = require('../utils/WinAppWebApiUtils');
var WinAppObjectUtils = require('../utils/WinAppObjectUtils');
var WinAppConstants = require('../constants/WinAppConstants');
var ActionTypes = WinAppConstants.ActionTypes;

var WinSettings = {
    UserInfos:[],
    Preloads:[],
    SystemApps:[],
    CustomApps:[],
    SystemWins:[],
    CustomWins:[],
    SnapShot:{}
}
var WinSettingsStore = assign({},EventEmitter.prototype,{
    emitChange: function(event) {
        this.emit(event);
    },
    addChangeListener: function(event,callback) {
        this.on(event, callback);
    },
    removeChangeListener: function(event,callback) {
        this.removeListener(event, callback);
    },
    getTaskBars:function(){
        var sysApps = WinSettings.SystemApps;
        var cusApps = WinSettings.CustomApps;
        var bars = [];
        for(var i=0;i<sysApps.length;i++){
            var appWhere = sysApps[i].where;
            var appRender = sysApps[i].render;
            if(appWhere.indexOf("taskbar")>=0 && appRender == "Button"){
                bars.push(sysApps[i]);
            }
        }
        for(var i=0;i<cusApps.length;i++){
            var appWhere = cusApps[i].where;
            var appRender = cusApps[i].render;
            if(appWhere.indexOf("taskbar")>=0 && appRender == "Button"){
                bars.push(cusApps[i]);
            }
        }
        return bars;
    },
    getStartMenu:function(){
        var sysApps = WinSettings.SystemApps;
        var startMenu = { id:3,name:"开始菜单",image:"static/images/start.png",where:["taskbar"],render:"StartMenu",fixed:true};
        for(var i=0;i<sysApps.length;i++){
            var appWhere = sysApps[i].where;
            var appRender = sysApps[i].render;
            if(appWhere.indexOf("taskbar")>=0 && appRender == "StartMenu"){
                startMenu = sysApps[i];
            }
        }
        return startMenu;
    },
    getDesktopBars:function(){
        var sysApps = WinSettings.SystemApps;
        var cusApps = WinSettings.CustomApps;
        var bars = [];
        for(var i=0;i<sysApps.length;i++){
            var appWhere = sysApps[i].where;
            var appRender = sysApps[i].render;
            if(appWhere.indexOf("desktop")>=0 && appRender == "Button"){
                bars.push(sysApps[i]);
            }
        }
        for(var i=0;i<cusApps.length;i++){
            var appWhere = cusApps[i].where;
            var appRender = cusApps[i].render;
            if(appWhere.indexOf("desktop")>=0 && appRender == "Button"){
                bars.push(cusApps[i]);
            }
        }
        return bars;
    },
    getStartMenuBars:function(){
        var sysApps = WinSettings.SystemApps;
        var cusApps = WinSettings.CustomApps;
        var bars = [];
        for(var i=0;i<sysApps.length;i++){
            var appWhere = sysApps[i].where;
            var appRender = sysApps[i].render;
            if(appWhere.indexOf("startmenu")>=0 && appRender == "Button"){
                bars.push(sysApps[i]);
            }
        }
        for(var i=0;i<cusApps.length;i++){
            var appWhere = cusApps[i].where;
            var appRender = cusApps[i].render;
            if(appWhere.indexOf("startmenu")>=0 && appRender == "Button"){
                bars.push(cusApps[i]);
            }
        }
        return bars;
    },
    getWindows:function(){
        var SystemWins = WinSettings.SystemWins;
        var CustomWins = WinSettings.CustomWins;
        var windows = [];
        for(var i=0;i<SystemWins.length;i++){
            windows.push(SystemWins[i]);
        }
        for(var i=0;i<CustomWins.length;i++){
            windows.push(CustomWins[i]);
        }
        return windows;
    },
    getWindowById:function(id){
        var SystemWins = WinSettings.SystemWins;
        var CustomWins = WinSettings.CustomWins;
        var wins = SystemWins.filter(function(ele,pos){
            return ele.id == id;
        })
        if(wins.length>0){
            return wins[0];
        }
        var wins = CustomWins.filter(function(ele,pos){
            return ele.id == id;
        })
        if(wins.length>0){
            return wins[0];
        }else{
            return null;
        }
    },
    getStartMenuButtons:function(){
        return WinSettings.StartMenuButtons
    },
    getByIdAndType:function(id,type){
        var findObj = null;
        switch(type){
            case "SystemApp":
                var filterArr = WinSettings.SystemApps.filter(function(ele,pos){
                    return ele.id==id;
                });
                if(filterArr.length>0){
                    findObj = filterArr[0];
                }
                break;
            case "CustomApp":
                var filterArr = WinSettings.CustomApps.filter(function(ele,pos){
                    return ele.id==id;
                });
                if(filterArr.length>0){
                    findObj = filterArr[0];
                }
                break;
        }
        return findObj;
    },
    getAppById:function(id){
        var SystemApps = WinSettings.SystemApps;
        var CustomApps = WinSettings.CustomApps;
        var apps = SystemApps.filter(function(ele,pos){
            return ele.id == id;
        })
        if(apps.length>0){
            return apps[0];
        }
        var apps = CustomApps.filter(function(ele,pos){
            return ele.id == id;
        })
        if(apps.length>0){
            return apps[0];
        }else{
            return null;
        }
    },
    getSnapShot:function(){
        if(!isNull(WinSettings.SnapShot)){
            return WinSettings.SnapShot;
        }else{
            return {
                app:{},
                snapshots:[]
            };
        }
    },
    addWindow:function(win){
        win.id = win.app_id+"-"+Math.round(Math.random()*1000);
        if(win.type=="CustomWin"){
            WinSettings.CustomWins.push(win);
            var CustomApps = WinSettings.CustomApps;
            var apps = CustomApps.filter(function(ele,pos){
                return ele.id == win.app_id;
            })
            if(apps[0].windows==null) apps[0].windows = [];
            apps[0].windows[win.id] = {snapshot:null};
        }
        if(win.type=="SystemWin"){
            WinSettings.SystemWins.push(win);
            var SystemApps = WinSettings.SystemApps;
            var apps = SystemApps.filter(function(ele,pos){
                return ele.id == win.app_id;
            })
            if(apps[0].windows==null) apps[0].windows = [];
            apps[0].windows[win.id] = { snapshot:null };
        }

    },
    getLoginState:function(){
        return !!WinSettings.UserInfos.login;
    }
});

var isNull = WinAppObjectUtils.isNull;

WinSettingsStore.dispatchToken = WinAppDispatcher.register(function(action) {
    switch(action.type) {
        case ActionTypes.RECEIVE_WIN_SETTINGS:
          WinSettings = action.data;
            WinSettingsStore.emitChange(WinAppConstants.EventTypes.PAGES);
          break;
        case ActionTypes.TOGGLE_WINDOW:
            var window = action.data;
            if(window.type=="SystemWin"){
                var findWins = WinSettings.SystemWins.filter(function(ele,pos){
                    return ele.id == window.id;
                });
                if(findWins.length>0){
                    findWins[0].show = !findWins[0].show;
                    WinSettingsStore.emitChange(WinAppConstants.EventTypes.WINDOWS);
                };
            }
            if(window.type=="CustomWin"){
                var findWins = WinSettings.CustomWins.filter(function(ele,pos){
                    return ele.id == window.id;
                });
                if(findWins.length>0){
                    findWins[0].show = !findWins[0].show;
                    WinSettingsStore.emitChange(WinAppConstants.EventTypes.WINDOWS);
                };
            }
            break;
        case ActionTypes.SHOW_WINDOW:
            var window = action.data;
            if(window.type=="SystemWin"){
                var findWins = WinSettings.SystemWins.filter(function(ele,pos){
                    return ele.id == window.id;
                });
                if(findWins.length>0){
                    findWins[0].show = true;
                    WinSettingsStore.emitChange(WinAppConstants.EventTypes.WINDOWS);
                };
            }
            if(window.type=="CustomWin"){
                var findWins = WinSettings.CustomWins.filter(function(ele,pos){
                    return ele.id == window.id;
                });
                if(findWins.length>0){
                    findWins[0].show = true;
                    WinSettingsStore.emitChange(WinAppConstants.EventTypes.WINDOWS);
                };
            }
            break;
        case ActionTypes.MIN_WINDOW:
            var window = action.data;
            if(window.type=="SystemWin"){
                var findWins = WinSettings.CustomWins.filter(function(ele,pos){
                    return ele.id == window.id;
                });
                var findApps = WinSettings.CustomApps.filter(function(ele,pos){
                    return ele.id == window.app_id;
                });
                if(findWins.length>0 && findApps.length>0){
                    findWins[0].show = false;
                    findApps[0].windows[window.id].snapshot = window.snapshot;
                    if(!findApps[0].config) findApps[0].config = {}
                    findApps[0].config.position={y:window.position.y,x:window.position.x};
                    findApps[0].width=window.width;
                    findApps[0].height=window.height;
                    WinSettingsStore.emitChange(WinAppConstants.EventTypes.WINDOWS);
                }
            }
            if(window.type=="CustomWin"){
                var findWins = WinSettings.CustomWins.filter(function(ele,pos){
                    return ele.id == window.id;
                });
                var findApps = WinSettings.CustomApps.filter(function(ele,pos){
                    return ele.id == window.app_id;
                });
                if(findWins.length>0 && findApps.length>0){
                    findWins[0].show = false;
                    findApps[0].windows[window.id].snapshot = window.snapshot;
                    if(!findApps[0].config) findApps[0].config = {}
                    findApps[0].config.position={y:window.position.y,x:window.position.x};
                    findApps[0].width=window.width;
                    findApps[0].height=window.height;
                    WinSettingsStore.emitChange(WinAppConstants.EventTypes.WINDOWS);
                }
            }
            break;
        case ActionTypes.CLOSE_WINDOW:
            var window = action.data;
            if(window.type=="SystemWin"){
                var m_pos = -1;
                var findWins = WinSettings.SystemWins.filter(function(ele,pos){
                    if(ele.id == window.id) m_pos=pos;
                    return ele.id == window.id;
                });
                var findApps = WinSettings.SystemApps.filter(function(ele,pos){
                    return ele.id == window.app_id;
                });
                if(findWins.length>0 && findApps.length>0){
                    if(findApps[0].windows[window.id]){
                        delete findApps[0].windows[window.id];
                        if(isNull(findApps[0].windows)){
                            findApps[0].windows = null;
                        }
                    }else{
                        findApps[0].window = null;
                    }
                    WinSettings.SystemWins.splice(m_pos,1);
                    if(!findApps[0].config) findApps[0].config = {}
                    findApps[0].config.position={y:window.position.y,x:window.position.x};
                    findApps[0].width=window.width;
                    findApps[0].height=window.height;
                    WinSettingsStore.emitChange(WinAppConstants.EventTypes.WINDOWS);
                    WinSettingsStore.emitChange(WinAppConstants.EventTypes.TASK_BARS);
                }
            }
            if(window.type=="CustomWin"){
                var m_pos = -1;
                var findWins = WinSettings.CustomWins.filter(function(ele,pos){
                    if(ele.id == window.id) m_pos=pos;
                    return ele.id == window.id;
                });
                var findApps = WinSettings.CustomApps.filter(function(ele,pos){
                    return ele.id == window.app_id;
                });
                if(findWins.length>0 && findApps.length>0){
                    if(findApps[0].windows[window.id]){
                        delete findApps[0].windows[window.id];
                        if(isNull(findApps[0].windows)){
                            findApps[0].windows = null;
                        }
                    }else{
                        findApps[0].window = null;
                    }
                    WinSettings.CustomWins.splice(m_pos,1);
                    if(!findApps[0].config) findApps[0].config = {};
                    findApps[0].config.position={y:window.position.y,x:window.position.x};
                    findApps[0].width=window.width;
                    findApps[0].height=window.height;
                    WinSettingsStore.emitChange(WinAppConstants.EventTypes.WINDOWS);
                    WinSettingsStore.emitChange(WinAppConstants.EventTypes.TASK_BARS);
                }
            }
            WinAppWebApiUtils.saveWinSettings(WinSettings);
            break;
        case ActionTypes.OPEN_WINDOW:
            var app = action.data;
            if(app.config){
                var config = app.config;
                config.app_id = app.id;
                config.image = app.image;
                config.show = true;
                config.fixed = app.fixed;
                WinSettingsStore.addWindow(config);
                WinSettingsStore.emitChange(WinAppConstants.EventTypes.WINDOWS);
                WinSettingsStore.emitChange(WinAppConstants.EventTypes.TASK_BARS);
            }
            WinAppWebApiUtils.saveWinSettings(WinSettings);
            break;
        case ActionTypes.SHOW_SNAP_SHOT:
            var snapShots = [];
            var window = action.data.window,
                windows =action.data.windows,
                app=action.data.app;
            if(!isNull(window)){
                snapShots.push(window);
            }
            if(!isNull(windows)){
                for(var w in windows){
                    windows[w].id = w;
                    snapShots.push(windows[w]);
                }
            }
            WinSettings.SnapShot ={
                snapshots:snapShots,
                app:app
            }
            WinSettingsStore.emitChange(WinAppConstants.EventTypes.SNAPSHOTS);
            break;
        case ActionTypes.USER_LOGIN:
            WinSettings.UserInfos.login = true;
            localStorage.setItem('winSettings',JSON.stringify(WinSettings));
            WinAppWebApiUtils.saveWinSettings(WinSettings);
//            WinSettingsStore.emitChange(WinAppConstants.EventTypes.USER);
            WinSettingsStore.emitChange(WinAppConstants.EventTypes.PAGES);

            break;
        default:
          // do nothing
    }

});

module.exports = WinSettingsStore;<|endoftext|>


<commit_before>/**
 * @author Rob Taylor [manix84@gmail.com]
 */
define('utils/array/match', function () {

    /**
     * Are the arrays matching
     * @exports utils/array/match
     * @param {array} arrayA The first array to check against the second
     * @param {array} arrayB The second array to check against the first
     * @returns {boolean}
     */
    var match = function (arrayObjA, arrayObjB) {
        var i = 0,
            isArray = (Object.prototype.toString.call(arrayObjA) === '[objecy Array]');

        for (; i < arrayObjA.length; i++) {
            if ((isArray && !match(arrayObjA[i], arrayObjB[i])) ||
                    (isArray && arrayObjA[i] !== arrayObjB[i])) {
                return false;
            }
        }
        return true;
    };

    return match;
});
<commit_msg>Relocating array/match references.<commit_after>/**
 * @author Rob Taylor [manix84@gmail.com]
 */
define('array/match', function () {

    /**
     * Are the arrays matching
     * @exports array/match
     * @param {array} arrayA The first array to check against the second
     * @param {array} arrayB The second array to check against the first
     * @returns {boolean}
     */
    var match = function (arrayObjA, arrayObjB) {
        var i = 0,
            isArray = (Object.prototype.toString.call(arrayObjA) === '[objecy Array]');

        for (; i < arrayObjA.length; i++) {
            if ((isArray && !match(arrayObjA[i], arrayObjB[i])) ||
                    (isArray && arrayObjA[i] !== arrayObjB[i])) {
                return false;
            }
        }
        return true;
    };

    return match;
});
<|endoftext|>


<commit_before>"use strict";

$( document ).ready(function(){

  var app = WordsFinderApp();
  app.initialize();

});

var WordsFinderApp = function(){

  var matrix;
  var alphabet = 'abcdefghijklmnopqrstuvwxyz';
  var dimension;
  var dict_en = {};

  var directions = {
    'up':         [ 0, -1],
    'up-right':   [ 1, -1],
    'right':      [ 1,  0],
    'right-down': [ 1,  1],
    'down':       [ 0,  1],
    'down-left':  [-1,  1],
    'left':       [-1,  0],
    'left-up':    [-1, -1]
  };

  var initialize = function(){
    $("input").attr("maxlength", 1);
    fetchEnglishDictionary();
    registerEventListeners();
  };

  var registerEventListeners = function(){

    $("#randomizer").click(function(event){
      $('.results').hide();
      $.makeArray($('input')).forEach(function(el){
        var random = Math.ceil( (Math.random() * (alphabet.length - 1)) );
        $(el).val( alphabet[random] );
      });
    });

    $("#finder").click(function(event){

      $('#randomizer').attr('disabled', 'disabled');
      $('#finder').attr('disabled', 'disabled');
      $('.results').hide();
      $('.loading').show();

      setTimeout(function(){
        var timer = BenchmarkTimer();
        timer.start();
        var words = findWords();
        timer.stop();
        showWordsFound(words);
        $('.loading').hide();
        $('.benchmark span').html( timer.getTime() );
        $('#finder').removeAttr('disabled');
        $('#randomizer').removeAttr('disabled');
      }, 10);

      return false;
    });

    $('.words').on('mouseenter', 'span', function(event){
      var el = $(event.target);
      el.addClass('highlight-word');
      toggleLettersHighlight( el.data('positions'), true);
    });

    $('.words').on('mouseleave', 'span', function(event){
      var el = $(event.target);
      el.removeClass('highlight-word');
      toggleLettersHighlight( el.data('positions'), false);
    });
  };

  function findWords(){
    buildLetterMatrix();

    var words = findAllLetterCombinations();
    words = removeLongWords(words);
    words = removeDupes(words);
    words = keepExistingWords(words);
    words = sortWordsList(words);

    return words;
  }

  function findAllLetterCombinations(){
    var words = [];
    for(var i = 0; i < dimension; i++){
      for(var j = 0; j < dimension; j++){
        spread( words, Word([[i, j]]) );
      }
    }

    // max of 4-letter words for now (otherwise too slow)
    for(i = 0; i < 2; i++){
      words.forEach(function(e){
        spread( words, e );
      });
    }
    return words;
  }

  function buildLetterMatrix(){
    var letters = jQuery.makeArray($('input')).map(function(el){
      return $(el).val();
    });
    dimension = Math.sqrt( letters.length );
    matrix = new Array(dimension);
    for(var i=0; i < dimension; i++){
      matrix[i] = new Array(dimension);
      for(var j=0; j < dimension; j++){
        matrix[i][j] = letters[j*dimension + i];
      }
    }
  }

  function removeLongWords(words){
    return words.filter(function(w){
      return w.longEnough();
    });
  }

  function removeDupes(words){
    var set = [];
    var word;
    return words.filter(function(item) {
      word = item.getLetters(matrix);
      if( set.indexOf(word) == -1 ) {
        set.push( word );
        return true;
      }else{
        return false;
      }
    });
  }

  function keepExistingWords(words){
    return words.filter(function(item) {
      return dict_en.indexOf(item.getLetters(matrix)) != -1;
    });
  }

  function sortWordsList(words){
    return words.sort(function(item1, item2){
      if ( item1.getLetters(matrix) > item2.getLetters(matrix) ){
        return 1;
      }else{
        return -1;
      }
    });
  }

  function showWordsFound(words){
    $('.results').show();
    $('.results h2 span').html(words.length);
    $('.words').empty();
    var list = $('.words');
    var count = words.length;
    words.forEach(function(word){
      var word_el = $('<span />').data('positions', word.getPositions().toString().replace(/,/g, '') ).html( word.getLetters(matrix) );
      list.append(word_el);
      words.indexOf(word) == (count - 1) ? list.append('.') : list.append(', ');
    });
  }

  function fetchLetterElements( positions ){
    var inputs = $('input');
    var length = positions.length;
    var letterElements = [];
    for(var i = 0; i < length; i += 2){
      letterElements.push( $(inputs[parseInt(positions[i], 10) + dimension * parseInt(positions[i+1], 10)]) );
    }
    return letterElements;
  }

  function toggleLettersHighlight( positions, highlight ){
    positions = positions.toString();
    fetchLetterElements( positions ).map(function(el){
      el.toggleClass('highlight-letter', highlight);
    });
  }

  function move(word, direction){
    var current_position = word.getLastPosition();
    var new_position = [current_position[0] + direction[0], current_position[1] + direction[1]];
    if( insideMatrix(new_position) && !word.beenThere(new_position)){
      word.addPosition(new_position);
      return word;
    }
  }

  function insideMatrix(position){
    return (position[0] > -1 && position[1] > -1 && position[0] < dimension && position[1] < dimension );
  }

  function spread(words, word){
    for(var d in directions){
      var candidate = move( Word(word.getPositions()), directions[d] );
      if( candidate != undefined ){
        words.push( candidate );
      }
    }
  }

  function fetchEnglishDictionary(){
    $.get('/dict_en', function(response){
      dict_en = response;
      $('#finder').removeAttr('disabled');
    });
  }

  // export public interface
  return {
    initialize: initialize
  };
};

function Word(pos){
  var positions = pos.slice(0);
  var getPositions = function(){
    return positions;
  };
  var addPosition = function(position){
    positions.push(position);
  };
  var getLastPosition = function(){
    return positions[positions.length - 1];
  };
  var fillWithLetters = function(matrix){
    var chars = positions.map(function(e){
      return matrix[e[0]][e[1]];
    });
    return chars.join('');
  };
  var getLetters = function(matrix){
    if(!this.letters){
      this.letters = this.fillWithLetters(matrix);
    }
    return this.letters;
  };
  var beenThere = function(position){
    var found = false;
    positions.forEach(function(e){
      if(e[0] == position[0] && e[1] == position[1]){
        found = true;
      }
    });
    return found;
  };
  var longEnough = function(){
    return positions.length > 2;
  };

  // export public interface
  return {
    getPositions:     getPositions,
    addPosition:      addPosition,
    getLastPosition:  getLastPosition,
    fillWithLetters:  fillWithLetters,
    getLetters:       getLetters,
    beenThere:        beenThere,
    longEnough:       longEnough
  };
}
<commit_msg>refactoring: extracts code which does not belong in WordsFinderApp<commit_after>"use strict";

$( document ).ready(function(){

  var app = WordsFinderApp();
  app.initialize();

});

var WordsFinderApp = function(){
  var letterGrid;

  var initialize = function(){
    $("input").attr("maxlength", 1);
    letterGrid = LetterGrid();
    fetchEnglishDictionary();
    registerEventListeners();
  };

  var registerEventListeners = function(){

    $("#randomizer").click(function(event){
      $('.results').hide();
      $.makeArray($('input')).forEach(function(el){
        $(el).val( letterGrid.randomLetter() );
      });
    });

    $("#finder").click(function(event){
      $('#randomizer').attr('disabled', 'disabled');
      $('#finder').attr('disabled', 'disabled');
      $('.results').hide();
      $('.loading').show();

      setTimeout(function(){
        var timer = BenchmarkTimer();
        timer.start();
        var words = letterGrid.findWords();
        timer.stop();
        showWordsFound(words);
        $('.loading').hide();
        $('.benchmark span').html( timer.getTime() );
        $('#finder').removeAttr('disabled');
        $('#randomizer').removeAttr('disabled');
      }, 10);

      return false;
    });

    $('.words').on('mouseenter', 'span', function(event){
      var el = $(event.target);
      el.addClass('highlight-word');
      toggleLettersHighlight( el.data('positions'), true);
    });

    $('.words').on('mouseleave', 'span', function(event){
      var el = $(event.target);
      el.removeClass('highlight-word');
      toggleLettersHighlight( el.data('positions'), false);
    });
  };

  function showWordsFound(words){
    $('.results').show();
    $('.results h2 span').html(words.length);
    $('.words').empty();
    var list = $('.words');
    var count = words.length;
    words.forEach(function(word){
      var word_el = $('<span />').data('positions', word.getPositions().toString().replace(/,/g, '') ).html( word.getLetters(letterGrid.getLetterMatrix()) );
      list.append(word_el);
      words.indexOf(word) == (count - 1) ? list.append('.') : list.append(', ');
    });
  }

  function fetchEnglishDictionary(){
    $.get('/dict_en', function(response){
      letterGrid.setReferenceWordsList(response);
      $('#finder').removeAttr('disabled');
    });
  }

  // export public interface
  return {
    initialize: initialize
  };
};

function LetterGrid(){
  var letterMatrix;
  var alphabet = 'abcdefghijklmnopqrstuvwxyz';
  var dimension = 5;
  var referenceWordsList;

  var directions = {
    'up':         [ 0, -1],
    'up-right':   [ 1, -1],
    'right':      [ 1,  0],
    'right-down': [ 1,  1],
    'down':       [ 0,  1],
    'down-left':  [-1,  1],
    'left':       [-1,  0],
    'left-up':    [-1, -1]
  };

  function randomLetter(){
    var random = Math.ceil( (Math.random() * (alphabet.length - 1)) );
    return alphabet[random];
  }

  function setReferenceWordsList(wordsList){
    referenceWordsList = wordsList;
  }

  function findWords(){
    var words = findAllLetterCombinations();
    words = removeLongWords(words);
    words = removeDupes(words);
    words = keepExistingWords(words);
    words = sortWordsList(words);

    return words;
  }

  function findAllLetterCombinations(){
    var words = [];
    for(var i = 0; i < dimension; i++){
      for(var j = 0; j < dimension; j++){
        spread( words, Word([[i, j]]) );
      }
    }

    // max of 4-letter words for now (otherwise too slow)
    for(i = 0; i < 2; i++){
      words.forEach(function(e){
        spread( words, e );
      });
    }
    return words;
  }

  function getLetterMatrix(){
    if(!letterMatrix){
      buildLetterMatrix();
    }
    return letterMatrix;
  }

  function buildLetterMatrix(){
    var letters = jQuery.makeArray($('input')).map(function(el){
      return $(el).val();
    });
    // dimension = Math.sqrt( letters.length );
    letterMatrix = new Array(dimension);
    for(var i=0; i < dimension; i++){
      letterMatrix[i] = new Array(dimension);
      for(var j=0; j < dimension; j++){
        letterMatrix[i][j] = letters[j*dimension + i];
      }
    }
  }

  function removeLongWords(words){
    return words.filter(function(w){
      return w.longEnough();
    });
  }

  function removeDupes(words){
    var set = [];
    var word;
    return words.filter(function(item) {
      word = item.getLetters(getLetterMatrix());
      if( set.indexOf(word) == -1 ) {
        set.push( word );
        return true;
      }else{
        return false;
      }
    });
  }

  function keepExistingWords(words){
    return words.filter(function(item) {
      return referenceWordsList.indexOf(item.getLetters(getLetterMatrix())) != -1;
    });
  }

  function sortWordsList(words){
    return words.sort(function(item1, item2){
      if ( item1.getLetters(getLetterMatrix()) > item2.getLetters(getLetterMatrix()) ){
        return 1;
      }else{
        return -1;
      }
    });
  }

  function fetchLetterElements(positions){
    var inputs = $('input');
    var length = positions.length;
    var letterElements = [];
    for(var i = 0; i < length; i += 2){
      letterElements.push( $(inputs[parseInt(positions[i], 10) + dimension * parseInt(positions[i+1], 10)]) );
    }
    return letterElements;
  }

  function toggleLettersHighlight(positions, highlight){
    positions = positions.toString();
    fetchLetterElements( positions ).map(function(el){
      el.toggleClass('highlight-letter', highlight);
    });
  }

  function move(word, direction){
    var current_position = word.getLastPosition();
    var new_position = [current_position[0] + direction[0], current_position[1] + direction[1]];
    if( insideMatrix(new_position) && !word.beenThere(new_position)){
      word.addPosition(new_position);
      return word;
    }
  }

  function insideMatrix(position){
    return (position[0] > -1 && position[1] > -1 && position[0] < dimension && position[1] < dimension );
  }

  function spread(words, word){
    for(var d in directions){
      var candidate = move( Word(word.getPositions()), directions[d] );
      if( candidate != undefined ){
        words.push( candidate );
      }
    }
  }

  // export public interface
  return {
    setReferenceWordsList:  setReferenceWordsList,
    getLetterMatrix:        getLetterMatrix,
    findWords:              findWords,
    randomLetter:           randomLetter
  };
}

function Word(pos){
  var positions = pos.slice(0);

  var getPositions = function(){
    return positions;
  };

  var addPosition = function(position){
    positions.push(position);
  };

  var getLastPosition = function(){
    return positions[positions.length - 1];
  };

  var fillWithLetters = function(matrix){
    var chars = positions.map(function(e){
      return matrix[e[0]][e[1]];
    });
    return chars.join('');
  };

  var getLetters = function(matrix){
    if(!this.letters){
      this.letters = this.fillWithLetters(matrix);
    }
    return this.letters;
  };

  var beenThere = function(position){
    var found = false;
    positions.forEach(function(e){
      if(e[0] == position[0] && e[1] == position[1]){
        found = true;
      }
    });
    return found;
  };

  var longEnough = function(){
    return positions.length > 2;
  };

  // export public interface
  return {
    getPositions:     getPositions,
    addPosition:      addPosition,
    getLastPosition:  getLastPosition,
    fillWithLetters:  fillWithLetters,
    getLetters:       getLetters,
    beenThere:        beenThere,
    longEnough:       longEnough
  };
}
<|endoftext|>


<commit_before>const Discord = require('discord.js');

const app = require('../app');
const dbinfo = require('../dbinfo');

const db = app.db;
const addFooter = app.addFooter;
const encodeGrade = dbinfo.encodeGrade;
const decodeProgram = dbinfo.decodeProgram;
const decodeGrade = dbinfo.decodeGrade;
const decodeSeason = dbinfo.decodeSeason;
const decodeSeasonUrl = dbinfo.decodeSeasonUrl;

const rankEmojis = ['🥇', '🥈', '🥉'];
const pageSize = 10;
const previous = '🔺';
const next = '🔻';

const dynamicSkillsEmbed = async (message, skills, index = 0, reply, end) => {
	if (index >= skills.length) {
		index = 0;
	} else if (index < 0) {
		index = skills.length - pageSize;
	}
	let description = '';
	for (let i = index; i < skills.length && i < (index + pageSize); i++) {
		const skill = skills[i];
		let rank = skill.gradeRank;
		rank = (rank < 4) ? `${rankEmojis[rank - 1]}` : `**\`#${String(rank).padEnd(2)}\\`**`;
		const score = String(skill.score).padStart(3);
		const prog = String(skill.prog).padStart(3);
		const driver = String(skill.driver).padStart(3);
		const team = skill.team.id;
		description += `${rank}   \`\${score}\`   \`(\${prog} / \${driver})\`   [${team}](https://vexdb.io/teams/view/${team})\n`;
	}
	const prog = decodeProgram(skills[0].team.prog);
	const grade = decodeGrade(skills[0].team.grade);
	const season = decodeSeason(skills[0]._id.season);
	const seasonUrl = decodeSeasonUrl(skills[0]._id.season);
	const embed = new Discord.RichEmbed()
		.setColor('GOLD')
		.setAuthor(`${prog} ${grade} World Skills Standings`, null, `https://vexdb.io/skills/${prog}/${season.replace(/ /g, '_')}/Robot`)
		.setTitle(season)
		.setURL(seasonUrl)
		.setDescription(description);
	let time;
	try {
		if (!reply) {
			reply = await message.channel.send({embed: embed});
			await reply.react(previous);
			await reply.react(next);
			time = 30000;
			end = Date.now() + time;
		} else {
			reply = await reply.edit({embed: embed});
			time = end - Date.now();
		}
		const reactions = await reply.awaitReactions((reaction, user) => user.id === message.author.id && (reaction.emoji.name === previous || reaction.emoji.name === next), {max: 1, time: time});
		if (reactions.size) {
			index += (reactions.get(next) ? pageSize : -pageSize);
			dynamicSkillsEmbed(message, skills, index, reply, end);
		} else {
			reply.clearReactions();
			addFooter(message, embed, reply);
		}
	} catch (err) {
		console.error(err);
	}
};

module.exports = async (message, args) => {
	const arg = args ? args.replace(/\s+/g, '') : '';

	let grade = arg ? arg.toLowerCase() : 'h';
	let program;
	let season;
	let limit;
	if (['h', 'hs', 'high', 'highschool'].includes(grade)) {
		program = 'VRC';
		grade = 'High School';
		season = 119;
		limit = 35;
	} else if (['m', 'ms', 'mid', 'middle', 'middleschool'].includes(grade)) {
		program = 'VRC';
		grade = 'Middle School';
		season = 119;
		limit = 15;
	} else if (['c', 'u', 'college', 'uni', 'university', 'vexu'].includes(grade)) {
		program = 'VEXU';
		grade = 'College';
		season = 120;
		limit = 5;
	} else {
		message.reply('please enter a valid grade, such as **h**, **m**, or **c**.');
		return;
	}
	try {
		const skills = await db.collection('maxSkills')
			.find({'_id.season': season, 'team.grade': encodeGrade(grade)})
			.sort({'_id.rank': 1}).toArray();
		if (skills.length) {
			dynamicSkillsEmbed(message, skills);
		} else {
			message.reply(`no skills scores available for ${program} ${grade} In the Zone.`);
		}
	} catch (err) {
		console.error(err);
	}
};
<commit_msg>Minor visual tweak to the topskills command.<commit_after>const Discord = require('discord.js');

const app = require('../app');
const dbinfo = require('../dbinfo');

const db = app.db;
const addFooter = app.addFooter;
const encodeGrade = dbinfo.encodeGrade;
const decodeProgram = dbinfo.decodeProgram;
const decodeGrade = dbinfo.decodeGrade;
const decodeSeason = dbinfo.decodeSeason;
const decodeSeasonUrl = dbinfo.decodeSeasonUrl;

const rankEmojis = ['🥇', '🥈', '🥉'];
const pageSize = 10;
const previous = '🔺';
const next = '🔻';

const dynamicSkillsEmbed = async (message, skills, index = 0, reply, end) => {
	if (index >= skills.length) {
		index = 0;
	} else if (index < 0) {
		index = skills.length - pageSize;
	}
	let description = '';
	for (let i = index; i < skills.length && i < (index + pageSize); i++) {
		const skill = skills[i];
		let rank = skill.gradeRank;
		rank = (rank < 4) ? `${rankEmojis[rank - 1]}  ` : `**\`#${String(rank).padEnd(3)}\\`**`;
		const score = String(skill.score).padStart(3);
		const prog = String(skill.prog).padStart(3);
		const driver = String(skill.driver).padStart(3);
		const team = skill.team.id;
		description += `${rank}   \`\${score}\`   \`(\${prog} / \${driver})\`   [${team}](https://vexdb.io/teams/view/${team})\n`;
	}
	const prog = decodeProgram(skills[0].team.prog);
	const grade = decodeGrade(skills[0].team.grade);
	const season = decodeSeason(skills[0]._id.season);
	const seasonUrl = decodeSeasonUrl(skills[0]._id.season);
	const embed = new Discord.RichEmbed()
		.setColor('GOLD')
		.setAuthor(`${prog} ${grade} World Skills Standings`, null, `https://vexdb.io/skills/${prog}/${season.replace(/ /g, '_')}/Robot`)
		.setTitle(season)
		.setURL(seasonUrl)
		.setDescription(description);
	let time;
	try {
		if (!reply) {
			reply = await message.channel.send({embed: embed});
			await reply.react(previous);
			await reply.react(next);
			time = 30000;
			end = Date.now() + time;
		} else {
			reply = await reply.edit({embed: embed});
			time = end - Date.now();
		}
		const reactions = await reply.awaitReactions((reaction, user) => user.id === message.author.id && (reaction.emoji.name === previous || reaction.emoji.name === next), {max: 1, time: time});
		if (reactions.size) {
			index += (reactions.get(next) ? pageSize : -pageSize);
			dynamicSkillsEmbed(message, skills, index, reply, end);
		} else {
			reply.clearReactions();
			addFooter(message, embed, reply);
		}
	} catch (err) {
		console.error(err);
	}
};

module.exports = async (message, args) => {
	const arg = args ? args.replace(/\s+/g, '') : '';

	let grade = arg ? arg.toLowerCase() : 'h';
	let program;
	let season;
	let limit;
	if (['h', 'hs', 'high', 'highschool'].includes(grade)) {
		program = 'VRC';
		grade = 'High School';
		season = 119;
		limit = 35;
	} else if (['m', 'ms', 'mid', 'middle', 'middleschool'].includes(grade)) {
		program = 'VRC';
		grade = 'Middle School';
		season = 119;
		limit = 15;
	} else if (['c', 'u', 'college', 'uni', 'university', 'vexu'].includes(grade)) {
		program = 'VEXU';
		grade = 'College';
		season = 120;
		limit = 5;
	} else {
		message.reply('please enter a valid grade, such as **h**, **m**, or **c**.');
		return;
	}
	try {
		const skills = await db.collection('maxSkills')
			.find({'_id.season': season, 'team.grade': encodeGrade(grade)})
			.sort({'_id.rank': 1}).toArray();
		if (skills.length) {
			dynamicSkillsEmbed(message, skills);
		} else {
			message.reply(`no skills scores available for ${program} ${grade} In the Zone.`);
		}
	} catch (err) {
		console.error(err);
	}
};
<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');
var app = require('app');

// init_updater: Return true if need to exist.
// check_updates: Update if possible.

if (process.platform == 'darwin') {
  var autoUpdater = require('auto-updater');

  exports.init_updater = function () {
    autoUpdater.on('error', function (event, message) {
      console.log(message);
    });
    autoUpdater.on('checking-for-update', function () {
      console.log('Checking for update.');
    });
    autoUpdater.on('update-available', function () {
      console.log('Update available.');
    });
    autoUpdater.on('update-not-available', function () {
      console.log('Update not available.');
    });
    autoUpdater.on('update-downloaded', function (
        event, releaseNotes, releaseName, releaseDate, updateUrl, quitAndUpdate) {
      console.log('Update downloaded, quit and update.');
      quitAndUpdate();
    });
    autoUpdater.setFeedUrl('https://net-tsinghua.herokuapp.com/update/osx/' +
                           app.getVersion());
  };

  exports.check_updates = function () {
    autoUpdater.checkForUpdates();
  }
} else if (process.platform == 'win32') {
  var cp = require('child_process');
  // Based on code from http://www.mylifeforthecode.com/tag/windows-installer/.
  // FIXME: Check whether Update.exe exists.
  var updateDotExe = path.resolve(path.dirname(process.execPath),
                                  '..', 'Update.exe');

  function executeSquirrelCommand(args, done) {
    var child = cp.spawn(updateDotExe, args, { detached: true });
    child.on('close', function(code) {
      done();
    });
  }

  function install(done) {
    var target = path.basename(process.execPath);

    // Removing "Electron" shortcut from startup folder, if possible.
    try {
      fs.unlinkSync('%APPDATA%/Microsoft/Windows/Start Menu/Programs/Startup/Electron.lnk');
    } catch (err) {
      console.log('Unable to remove Electron.lnk from Startup folder: %s', err);
    }

    console.log('Creating shortcut.');
    executeSquirrelCommand(['--createShortcut', target,
                            '--shortcut-locations', 'Desktop,StartMenu,Startup'],
                           done);
  }

  function uninstall(done) {
    var target = path.basename(process.execPath);
    console.log('Removing shortcut.');
    executeSquirrelCommand(['--removeShortcut', target,
                            '--shortcut-locations', 'Desktop,StartMenu,Startup'],
                           done);
  }

  exports.init_updater = function() {
    var squirrelEvent = process.argv[1];
    switch (squirrelEvent) {
      case '--squirrel-install':
        console.log('App installed.');
        install(app.quit);
        return true;
      case '--squirrel-updated':
        console.log('App updated.');
        install(app.quit);
        return true;
      case '--squirrel-obsolete':
        console.log('About to update to a newer version, quit now.');
        app.quit();
        return true;
      case '--squirrel-uninstall':
        console.log('Uninstalling.');
        uninstall(app.quit);
        return true;
    }
  };

  exports.check_updates = function () {
    var child = cp.spawn(updateDotExe, [
        "--update",
        "https://net-tsinghua.herokuapp.com/update/win32/" + app.getVersion()
      ], { detached: true });
    child.on('close', function(code) {
      console.log('Updating is done.');
    });
  };
} else {  // Unsupported system.
  exports.init_updater = function () {};
  exports.check_updates = function () {};
}
<commit_msg>Fix path of Electron.lnk<commit_after>var fs = require('fs');
var path = require('path');
var app = require('app');

// init_updater: Return true if need to exist.
// check_updates: Update if possible.

if (process.platform == 'darwin') {
  var autoUpdater = require('auto-updater');

  exports.init_updater = function () {
    autoUpdater.on('error', function (event, message) {
      console.log(message);
    });
    autoUpdater.on('checking-for-update', function () {
      console.log('Checking for update.');
    });
    autoUpdater.on('update-available', function () {
      console.log('Update available.');
    });
    autoUpdater.on('update-not-available', function () {
      console.log('Update not available.');
    });
    autoUpdater.on('update-downloaded', function (
        event, releaseNotes, releaseName, releaseDate, updateUrl, quitAndUpdate) {
      console.log('Update downloaded, quit and update.');
      quitAndUpdate();
    });
    autoUpdater.setFeedUrl('https://net-tsinghua.herokuapp.com/update/osx/' +
                           app.getVersion());
  };

  exports.check_updates = function () {
    autoUpdater.checkForUpdates();
  }
} else if (process.platform == 'win32') {
  var cp = require('child_process');
  // Based on code from http://www.mylifeforthecode.com/tag/windows-installer/.
  // FIXME: Check whether Update.exe exists.
  var updateDotExe = path.resolve(path.dirname(process.execPath),
                                  '..', 'Update.exe');

  function executeSquirrelCommand(args, done) {
    var child = cp.spawn(updateDotExe, args, { detached: true });
    child.on('close', function(code) {
      done();
    });
  }

  function install(done) {
    var target = path.basename(process.execPath);

    // Removing "Electron" shortcut from startup folder, if possible.
    try {
      fs.unlinkSync(path.join(
        process.env.APPDATA,
        'Microsoft/Windows/Start Menu/Programs/Startup/Electron.lnk'));
    } catch (err) {
      console.log('Unable to remove Electron.lnk from Startup folder: %s', err);
    }

    console.log('Creating shortcut.');
    executeSquirrelCommand(['--createShortcut', target,
                            '--shortcut-locations', 'Desktop,StartMenu,Startup'],
                           done);
  }

  function uninstall(done) {
    var target = path.basename(process.execPath);
    console.log('Removing shortcut.');
    executeSquirrelCommand(['--removeShortcut', target,
                            '--shortcut-locations', 'Desktop,StartMenu,Startup'],
                           done);
  }

  exports.init_updater = function() {
    var squirrelEvent = process.argv[1];
    switch (squirrelEvent) {
      case '--squirrel-install':
        console.log('App installed.');
        install(app.quit);
        return true;
      case '--squirrel-updated':
        console.log('App updated.');
        install(app.quit);
        return true;
      case '--squirrel-obsolete':
        console.log('About to update to a newer version, quit now.');
        app.quit();
        return true;
      case '--squirrel-uninstall':
        console.log('Uninstalling.');
        uninstall(app.quit);
        return true;
    }
  };

  exports.check_updates = function () {
    var child = cp.spawn(updateDotExe, [
        "--update",
        "https://net-tsinghua.herokuapp.com/update/win32/" + app.getVersion()
      ], { detached: true });
    child.on('close', function(code) {
      console.log('Updating is done.');
    });
  };
} else {  // Unsupported system.
  exports.init_updater = function () {};
  exports.check_updates = function () {};
}
<|endoftext|>