<commit_before>(function() {
  'use strict';

  /**
   * [hasVowels -- Checks if a string contain a vowel i.e (A E I O U)]
   * @return {Boolean} [Returns true if the a
   * String contains a vowel and false otherwise.]
   */
  String.prototype.hasVowels = function() {
    return /[aeiou]/i.test(this);
  };

  /**
   * [toUpper -- Capitalize all the charater in a string]
   * @return {[String]} [Returns the uppercased string]
   */
  String.prototype.toUpper = function() {
    return this.replace(/[a-z]/g, function(matchedLetter) {
      // Get the upper case charater by subtracting 32 from the
      // unicode value of the main charater.
      return String.fromCharCode(matchedLetter.charCodeAt() - 32);
    });
  };

  /**
   * [toLower -- Make a string lowercase]
   * @return {[String]} [Returns string with all alphabetic
   * characters converted to lowercase.]
   */
  String.prototype.toLower = function() {
    return this.replace(/[A-Z]/g, function(matchedLetter) {
      // Get the lower case charater by adding 32 to the
      // unicode value of the main charater.
      return String.fromCharCode(matchedLetter.charCodeAt() + 32);
    });
  };

  /**
   * [trimWord -- Strip whitespace from the beginning and end of a string]
   * @return {[String]} [returns a string with whitespace stripped
   * from the beginning and end]
   */
  String.prototype.trimWord = function() {
    return this.replace(/^\s+|\s+$/g, '');
  };

  /**
   * [ucFirst -- Make a string's first character uppercase]
   * @return {[String]} [Returns a string with the first character
   * capitalized, if that character is alphabetic]
   */
  String.prototype.ucFirst = function() {
    return this.replace(/^[a-z]/, function(matchedLetter) {
      return matchedLetter.toUpper();
    });
  };

  /**
   * [isQuestion -- Check if a String ends with a question mark]
   * @return {Boolean} [Return true if a string ends with
   * question mark or false otherwise]
   */
  String.prototype.isQuestion = function() {
    return /.[?]$/.test(this.trimWord());
  };

  /**
   * [removeSym -- Strip symbols from a string]
   * @return {[type]} [description]
   */
  String.prototype.removeSym = function() {
    return this.replace(/[,";:?!@#$%(^)&*()_+|.><{}±=-]/g, '');
  };

  /**
   * [trimWordEx -- Removes wihte spaces within and at the edges of a sentences]
   * @return {String} [A sentences separated with a single space]
   */
  String.prototype.trimWordEx = function() {
    return this.trimWord().replace(/\s+/g, ' ');
  };

  /**
   * [words -- Converts a string to an array of words]
   * @return {[Array]} [An array of the words in the string]
   */
  String.prototype.words = function() {
    if (this.length) {
      return this.removeSym().trimWordEx().split(/\s/);
    }

    return [];
  };

  /**
   * [wordCount -- Counts the number of the words in a string]
   * @return {[Integer]} [The number of words in a string]
   */
  String.prototype.wordCount = function() {
    return this.trimWordEx().words().length;
  };

  /**
   * [fromCurrency -- Converts a currency representation of a String to Number]
   * @return {[float]} [A number representation of the currency]
   */
  String.prototype.fromCurrency = function() {
    return parseFloat(this.replace(/[^\d.a-z]/ig, ''));
  };

  /**
   * [toCurrency -- Converts a number representation to money figures in String]
   * @return {[Mixed]} [A currency representation of the currency in String or
   * NaN if not s number]
   */
  String.prototype.toCurrency = function() {
    // Checks if number contain an alphabet or a symbol.
    if (/[a-z\s?_:\+()&%#@!~\-\$*]/i.test(this) === false) {
      var splitedNum = this.split(/\./);
      var decimalPart = null;

      // Regex groups number in theres without counsuming them.
      var regEx = /\B(?=(\d{3})+(?!\d))/g;

      if (splitedNum.length > 1) {
        // Save zero to realNumber if the first element in the
        // array of numbers contain multiple zeros
        var realNumber = parseInt(splitedNum[0]) === 0 ? '0' : splitedNum[0]
          .replace(regEx, ',');

        // Removes decimal number more than three digits.
        if (splitedNum[1].length >= 3) {
          decimalPart = splitedNum[1].substring(0, 2);
        } else {
          decimalPart = splitedNum[1];
        }

        return decimalPart ? (realNumber + '.' + decimalPart) : realNumber;
      }

      return this.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    }

    return NaN;
  };

})();
<commit_msg>Refactored the toCurrency function<commit_after>(function() {
  'use strict';

  /**
   * [hasVowels -- Checks if a string contain a vowel i.e (A E I O U)]
   * @return {Boolean} [Returns true if the a
   * String contains a vowel and false otherwise.]
   */
  String.prototype.hasVowels = function() {
    return /[aeiou]/i.test(this);
  };

  /**
   * [toUpper -- Capitalize all the charater in a string]
   * @return {[String]} [Returns the uppercased string]
   */
  String.prototype.toUpper = function() {
    return this.replace(/[a-z]/g, function(matchedLetter) {
      // Get the upper case charater by subtracting 32 from the
      // unicode value of the main charater.
      return String.fromCharCode(matchedLetter.charCodeAt() - 32);
    });
  };

  /**
   * [toLower -- Make a string lowercase]
   * @return {[String]} [Returns string with all alphabetic
   * characters converted to lowercase.]
   */
  String.prototype.toLower = function() {
    return this.replace(/[A-Z]/g, function(matchedLetter) {
      // Get the lower case charater by adding 32 to the
      // unicode value of the main charater.
      return String.fromCharCode(matchedLetter.charCodeAt() + 32);
    });
  };

  /**
   * [trimWord -- Strip whitespace from the beginning and end of a string]
   * @return {[String]} [returns a string with whitespace stripped
   * from the beginning and end]
   */
  String.prototype.trimWord = function() {
    return this.replace(/^\s+|\s+$/g, '');
  };

  /**
   * [ucFirst -- Make a string's first character uppercase]
   * @return {[String]} [Returns a string with the first character
   * capitalized, if that character is alphabetic]
   */
  String.prototype.ucFirst = function() {
    return this.replace(/^[a-z]/, function(matchedLetter) {
      return matchedLetter.toUpper();
    });
  };

  /**
   * [isQuestion -- Check if a String ends with a question mark]
   * @return {Boolean} [Return true if a string ends with
   * question mark or false otherwise]
   */
  String.prototype.isQuestion = function() {
    return /.[?]$/.test(this.trimWord());
  };

  /**
   * [removeSym -- Strip symbols from a string]
   * @return {[type]} [description]
   */
  String.prototype.removeSym = function() {
    return this.replace(/[,";:?!@#$%(^)&*()_+|.><{}±=-]/g, '');
  };

  /**
   * [trimWordEx -- Removes wihte spaces within and at the edges of a sentences]
   * @return {String} [A sentences separated with a single space]
   */
  String.prototype.trimWordEx = function() {
    return this.trimWord().replace(/\s+/g, ' ');
  };

  /**
   * [words -- Converts a string to an array of words]
   * @return {[Array]} [An array of the words in the string]
   */
  String.prototype.words = function() {
    if (this.length) {
      return this.removeSym().trimWordEx().split(/\s/);
    }

    return [];
  };

  /**
   * [wordCount -- Counts the number of the words in a string]
   * @return {[Integer]} [The number of words in a string]
   */
  String.prototype.wordCount = function() {
    return this.trimWordEx().words().length;
  };

  /**
   * [fromCurrency -- Converts a currency representation of a String to Number]
   * @return {[float]} [A number representation of the currency]
   */
  String.prototype.fromCurrency = function() {
    return parseFloat(this.replace(/[^\d.a-z]/ig, ''));
  };

  String.prototype.formatRealNumber = function() {
    // Save zero to realNumber if the first element in the
    // array of numbers contain multiple zeros
    return parseInt(this) === 0 ? '0' : this.groupNumber();
  };

  String.prototype.formatDecimal = function() {
    // Removes decimal number more than three digits.
    return this.length >= 3 ? this.substring(0, 2) : this;
  };

  String.prototype.groupNumber = function() {
    // Regex groups number in theres without counsuming them.
    return this.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  };

  /**
   * [toCurrency -- Converts a number representation to money figures in String]
   * @return {[Mixed]} [A currency representation of the currency in String or
   * NaN if not s number]
   */
  String.prototype.toCurrency = function() {
    // Checks if number contain an alphabet or a symbol.
    if (/[a-z\s?_:\+()&%#@!~\-\$*]/i.test(this) === false) {
      var splitedNum = this.split(/\./);
      return splitedNum.formatToCurrency();
    }

    return NaN;
  };

  Array.prototype.formatToCurrency = function() {
    if (this.length > 1) {
      var realNumber = this[0].formatRealNumber();
      var decimalPart = this[1].formatDecimal();

      return decimalPart ? (realNumber + '.' + decimalPart) : realNumber;
    }

    return this[0].groupNumber();
  };

})();
<|endoftext|>


<commit_before>"use strict";

var buttonStyle = {

  style: {
    background: '#EFEFEF',
    border: '1px solid #EFEFEF',
    borderBottomColor: '#D0D0D0',
    borderRadius: 2,
    boxSizing: 'border-box',
    color: '#555',
    cursor: 'pointer',
    display: 'inline-block',
    fontSize: 16,
    lineHeight: '26px',
    padding: '8px 12px 6px 12px',
    textAlign: 'center',
    textDecoration: 'none',
    verticalAlign: 'bottom'
  },

  hoverStyle: {
    background: '#F5F5F5',
    border: '1px solid #F5F5F5',
    borderBottomColor: '#D0D0D0',
    color: '#666'
  },

  focusStyle: {
    background: '#F5F5F5',
    border: '1px solid #F5F5F5',
    borderBottomColor: '#D0D0D0',
    color: '#666',
    outline: 0 // avoid default focus behaviour
  },

  activeStyle: {
    background: '#E8E8E8',
    border: '1px solid #E8E8E8',
    borderTopColor: '#CFCFCF',
    color: '#5C5C5C'
  },

  primaryStyle: {
    background: '#53C7F2',
    border: '1px solid #53C7F2',
    borderBottomColor: '#3C9CC0',
    borderRadius: 2,
    boxSizing: 'border-box',
    color:'#FAFAFA',
    cursor: 'pointer',
    display: 'inline-block',
    fontSize: 16,
    lineHeight: '26px',
    padding: '8px 12px 6px 12px',
    textAlign: 'center',
    textDecoration: 'none',
    verticalAlign: 'bottom'
  },

  primaryHoverStyle: {
    background: '#5FCDF5',
    border: '1px solid #5FCDF5',
    borderBottomColor: '#4FB4DA',
    color: '#FFF'
  },

  primaryFocusStyle: {
    background: '#5FCDF5',
    border: '1px solid #5FCDF5',
    borderBottomColor: '#4FB4DA',
    color: '#FFF',
    outline: 0 // avoid default focus behaviour
  },

  primaryActiveStyle: {
    background: '#4DBEE8',
    border: '1px solid #4DBEE8',
    borderTopColor: '#3B97BA',
    color: '#F5F5F5'
  }
};

export default buttonStyle;
<commit_msg>style(Button): improve colors for pressed state of primary button<commit_after>"use strict";

var buttonStyle = {

  style: {
    background: '#EFEFEF',
    border: '1px solid #EFEFEF',
    borderBottomColor: '#D0D0D0',
    borderRadius: 2,
    boxSizing: 'border-box',
    color: '#555',
    cursor: 'pointer',
    display: 'inline-block',
    fontSize: 16,
    lineHeight: '26px',
    padding: '8px 12px 6px 12px',
    textAlign: 'center',
    textDecoration: 'none',
    verticalAlign: 'bottom'
  },

  hoverStyle: {
    background: '#F5F5F5',
    border: '1px solid #F5F5F5',
    borderBottomColor: '#D0D0D0',
    color: '#666'
  },

  focusStyle: {
    background: '#F5F5F5',
    border: '1px solid #F5F5F5',
    borderBottomColor: '#D0D0D0',
    color: '#666',
    outline: 0 // avoid default focus behaviour
  },

  activeStyle: {
    background: '#E8E8E8',
    border: '1px solid #E8E8E8',
    borderTopColor: '#CFCFCF',
    color: '#5C5C5C'
  },

  primaryStyle: {
    background: '#53C7F2',
    border: '1px solid #53C7F2',
    borderBottomColor: '#3995B7',
    borderRadius: 2,
    boxSizing: 'border-box',
    color:'#FAFAFA',
    cursor: 'pointer',
    display: 'inline-block',
    fontSize: 16,
    lineHeight: '26px',
    padding: '8px 12px 6px 12px',
    textAlign: 'center',
    textDecoration: 'none',
    verticalAlign: 'bottom'
  },

  primaryHoverStyle: {
    background: '#5FCDF5',
    border: '1px solid #5FCDF5',
    borderBottomColor: '#4FB4DA',
    color: '#FFF'
  },

  primaryFocusStyle: {
    background: '#5FCDF5',
    border: '1px solid #5FCDF5',
    borderBottomColor: '#4FB4DA',
    color: '#FFF',
    outline: 0 // avoid default focus behaviour
  },

  primaryActiveStyle: {
    background: '#4DBEE8',
    border: '1px solid #4DBEE8',
    borderTopColor: '#3587A7',
    color: '#F5F5F5'
  }
};

export default buttonStyle;
<|endoftext|>


<commit_before>var express = require('express');
var path = require('path');
var logger = require('morgan');
var compression = require('compression');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var expressValidator = require('express-validator');
var dotenv = require('dotenv');
var mongoose = require('mongoose');
var jwt = require('jsonwebtoken');
var moment = require('moment');
var request = require('request');

// Load environment variables from .env file
dotenv.load();

// Models
var User = require('./models/User');

// Controllers
var userController = require('./controllers/user');
var contactController = require('./controllers/contact');
var uwController = require('./controllers/uw');
var app = express();

mongoose.connect(process.env.MONGODB);
mongoose.connection.on('error', function() {
  console.log('MongoDB Connection Error. Please make sure that MongoDB is running.');
  process.exit(1);
});
app.set('port', process.env.PORT || 3000);
app.use(compression());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(expressValidator());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(function(req, res, next) {
  req.isAuthenticated = function() {
    var token = (req.headers.authorization && req.headers.authorization.split(' ')[1]) || req.cookies.token;
    try {
      return jwt.verify(token, process.env.TOKEN_SECRET);
    } catch (err) {
      return false;
    }
  };

  if (req.isAuthenticated()) {
    var payload = req.isAuthenticated();
    User.findById(payload.sub, function(err, user) {
      req.user = user;
      next();
    });
  } else {
    next();
  }
});

app.post('/contact', contactController.contactPost);
app.put('/account', userController.ensureAuthenticated, userController.accountPut);
app.delete('/account', userController.ensureAuthenticated, userController.accountDelete);
app.post('/signup', userController.signupPost);
app.post('/login', userController.loginPost);
app.post('/forgot', userController.forgotPost);
app.post('/reset/:token', userController.resetPost);
app.get('/unlink/:provider', userController.ensureAuthenticated, userController.unlink);
app.post('/auth/facebook', userController.authFacebook);
app.get('/auth/facebook/callback', userController.authFacebookCallback);
app.post('/auth/google', userController.authGoogle);
app.get('/auth/google/callback', userController.authGoogleCallback);
app.get('/courses/:course_id', uwController.getCourseById);
app.get('/courses/:course_subject/:course_number', uwController.getCourseInfo);
app.get('/courses/:course_subject/:course_number/exams', uwController.getCourseExamSchedule);

app.get('*', function(req, res) {
  res.redirect('/#' + req.originalUrl);
});

// Production error handler
if (app.get('env') === 'production') {
  app.use(function(err, req, res, next) {
    console.error(err.stack);
    res.sendStatus(err.status || 500);
  });
}

app.listen(app.get('port'), function() {
  console.log('Express server listening on port ' + app.get('port'));
});

module.exports = app;
<commit_msg>Chat api<commit_after>var express = require('express');
var path = require('path');
var logger = require('morgan');
var compression = require('compression');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var expressValidator = require('express-validator');
var dotenv = require('dotenv');
var mongoose = require('mongoose');
var jwt = require('jsonwebtoken');
var moment = require('moment');
var request = require('request');

var mongojs = require('mongojs');
var db = mongojs('test',['test']);

// Load environment variables from .env file
dotenv.load();

// Models
var User = require('./models/User');

// Controllers
var userController = require('./controllers/user');
var contactController = require('./controllers/contact');

var uwController = require('./controllers/uw');

var app = express();

mongoose.connect(process.env.MONGODB);
mongoose.connection.on('error', function() {
  console.log('MongoDB Connection Error. Please make sure that MongoDB is running.');
  process.exit(1);
});
app.set('port', process.env.PORT || 3000);
app.use(compression());
app.use(logger('dev'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/json' }));
app.use(expressValidator());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use(function(req, res, next) {
  req.isAuthenticated = function() {
    var token = (req.headers.authorization && req.headers.authorization.split(' ')[1]) || req.cookies.token;
    try {
      return jwt.verify(token, process.env.TOKEN_SECRET);
    } catch (err) {
      return false;
    }
  };

  if (req.isAuthenticated()) {
    var payload = req.isAuthenticated();
    User.findById(payload.sub, function(err, user) {
      req.user = user;
      next();
    });
  } else {
    next();
  }
});

app.post('/contact', contactController.contactPost);
app.put('/account', userController.ensureAuthenticated, userController.accountPut);
app.delete('/account', userController.ensureAuthenticated, userController.accountDelete);
app.post('/signup', userController.signupPost);
app.post('/login', userController.loginPost);
app.post('/forgot', userController.forgotPost);
app.post('/reset/:token', userController.resetPost);
app.get('/unlink/:provider', userController.ensureAuthenticated, userController.unlink);
app.post('/auth/facebook', userController.authFacebook);
app.get('/auth/facebook/callback', userController.authFacebookCallback);
app.post('/auth/google', userController.authGoogle);
app.get('/auth/google/callback', userController.authGoogleCallback);
app.get('/courses/:course_id', uwController.getCourseById);
app.get('/courses/:course_subject/:course_number', uwController.getCourseInfo);
app.get('/courses/:course_subject/:course_number/exams', uwController.getCourseExamSchedule);

// API for home page

app.post('/send', function (req, res) {
  console.log("I received data!")
  console.log(req.body);
  db.test.insert(req.body, function (err, doc){
    res.json(doc);
  });
});

app.get('/getMes', function (req, res){
  console.log("I received a GET request!");
  db.test.find(function (err, docs){
    console.log(docs);
    res.json(docs);
  });
});

// API for home page

app.get('*', function(req, res) {
  res.redirect('/#' + req.originalUrl);
});

// Production error handler
if (app.get('env') === 'production') {
  app.use(function(err, req, res, next) {
    console.error(err.stack);
    res.sendStatus(err.status || 500);
  });
}

app.listen(app.get('port'), function() {
  console.log('Express server listening on port ' + app.get('port'));
});

module.exports = app;
<|endoftext|>


<commit_before>/* jshint esversion: 6 */
const myConfig = require('./config.json');
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const request = require('request');
const bodyParser = require('body-parser');
const Discord = require('discord.js');
const bot = new Discord.Client();
app.set('serverPort', myConfig.serverPort);
app.use(bodyParser.urlencoded({
  extended: true
}));
let botInvites = [];
app.use(bodyParser.json());

bot.on('message', message => {
  if (message.content === '!kern') {
    message.channel.sendMessage('https://clips.twitch.tv/MistyNiceBibimbapTheRinger');
  } else if (message.content === '!varcster') {
    message.channel.sendMessage('https://www.twitch.tv/videos/68214198');
  }
});

bot.on('ready', () => {
  console.log('I am ready!');
  let guild = bot.guilds.find(val => val.id === myConfig.guildID);
  if (guild.available) {
    guild.fetchInvites()
      .then(invites => {
        for (const invite of invites.array()) {
          if (invite.inviter && invite.inviter.id &&
            invite.inviter.id === myConfig.botID && invite.uses !== null &&
            invite.uses === 0)
            botInvites.push(invite.code);
        }
      })
      .catch(console.error);
  }
});
bot.on('guildMemberAdd', (member) => {
  let guild = bot.guilds.find(val => val.id === myConfig.guildID);
  if (guild.available) {
    guild.fetchInvites()
      .then(invites => {
        for (const invite of invites.array()) {
          for (var i = 0; i < botInvites.length; i++) {
            if (invite.code === botInvites[i] && invite.uses >= 1) {
              createApplicantUser(member, invite, i);
            }
          }
        }
      })
      .catch(console.error);
  }
});

const createApplicantUser = (member, invite, i) => {
  member.addRole(myConfig.applicantRoleID)
    .then((member) => {
      if (invite.channel) {
        invite.channel.overwritePermissions(member, {
         SEND_MESSAGES: true,
         READ_MESSAGES: true,
         EMBED_LINKS: true,
         READ_MESSAGE_HISTORY:true,
         ATTACH_FILES: true
        })
        .then(() => {
          member.setNickname(invite.channel.name)
            .then((applicant) => {
              invite.channel.sendMessage(`${applicant.user} Thanks for applying to revive. You can find your application here please feel free to ask any questions.`);
            })
            .catch(console.error);
        })
        .catch(console.error);
      }
    })
    .catch(console.error);
  invite.delete()
    .then(invite => {
      botInvites.splice(i,1);
    })
    .catch(console.error);
};

app.post('/createGuildApp', (req,res) => {
  const applicationData = {
    name:req.body.name,
    loc:req.body.loc,
    tag:req.body.tag,
    armory:req.body.armory,
    sscombat:req.body.sscombat,
    headset:req.body.headset,
    logs:req.body.logs,
    role:req.body.role,
    awp:req.body.awp,
    prog:req.body.prog,
    left:req.body.left,
    rotation:req.body.rotation,
    resources:req.body.resources,
    hear:req.body.hear,
    crit:req.body.crit,
    sit:req.body.sit,
    schedule:req.body.schedule,
    beta:req.body.beta,
    about:req.body.about,
    joke:req.body.joke
  };
  const applicationText = `**What is your Name, Age and Sex?**\n
━━━━━━━━━━━━━━━━━━━━━━━━\n
${applicationData.name}\n\n
**Provide the location you will primarily will be playing from and a speedtest.net screenshot from the Chicago server**\n
━━━━━━━━━━━━━━━━━━━━━━━━\n
${applicationData.loc}\n\n
**What is your Battle.net Tag**\n
━━━━━━━━━━━━━━━━━━━━━━━━\n
${applicationData.tag}\n\n
**Link to your main characters and alternate character's ADVANCED ARMORY**\n
━━━━━━━━━━━━━━━━━━━━━━━━\n
${applicationData.armory}\n\n
**Post a screenshot of your character in combat**\n
━━━━━━━━━━━━━━━━━━━━━━━━\n
${applicationData.sscombat}\n\n
**Do you have a functioning headset with microphone that you can use in Discord?**\n
━━━━━━━━━━━━━━━━━━━━━━━━\n
${applicationData.headset}\n\n
**Post your recent warcraft logs**\n
━━━━━━━━━━━━━━━━━━━━━━━━\n
${applicationData.logs}\n\n
**What role and spec are you applying for**\n
━━━━━━━━━━━━━━━━━━━━━━━━\n
${applicationData.role}\n\n
**List your Artifact Weapon points for all Specs **\n
━━━━━━━━━━━━━━━━━━━━━━━━\n
${applicationData.awp}\n\n
**List Pre Tier-19 Mythic/Heroic Progression Experiences**\n
━━━━━━━━━━━━━━━━━━━━━━━━\n
${applicationData.prog}\n\n
**Name your last TWO raiding guilds and the reason for leaving them?**\n
━━━━━━━━━━━━━━━━━━━━━━━━\n
${applicationData.left}\n\n
**Take us through your opening rotation on a SINGLE TARGET fight. (Healers Ignore this)**\n
━━━━━━━━━━━━━━━━━━━━━━━━\n
${applicationData.rotation}\n\n
**What resources do you use to improve yourself?**\n
━━━━━━━━━━━━━━━━━━━━━━━━\n
${applicationData.resources}\n\n
**How did you hear about us?**\n
━━━━━━━━━━━━━━━━━━━━━━━━\n
${applicationData.hear}\n\n
**How do you handle criticism and adult humor?**\n
━━━━━━━━━━━━━━━━━━━━━━━━\n
${applicationData.crit}\n\n
**You may be asked to sit on some fights for composition, gear, or general skill level how do you feel about that?**\n
━━━━━━━━━━━━━━━━━━━━━━━━\n
${applicationData.sit}\n\n
**Do you have any commitments or schedule changes that we should know about?**\n
━━━━━━━━━━━━━━━━━━━━━━━━\n
${applicationData.schedule}\n\n
**Are you willing to test new content in PTR/Alpha/Beta?**\n
━━━━━━━━━━━━━━━━━━━━━━━━\n
${applicationData.beta}\n\n
**Tell us a little bit about yourself. The more we know the better!**\n
━━━━━━━━━━━━━━━━━━━━━━━━\n
${applicationData.about}\n\n
**Tell us a joke**\n
━━━━━━━━━━━━━━━━━━━━━━━━\n
${applicationData.joke}\n\n`;
  let guild = bot.guilds.find(val => val.id === myConfig.guildID);
  let _this = this;
  if (guild.available) {
    const channel = applicationData.tag.replace('#','-');
    const permissions = [
      { id: '231944378577321984', type: 'role', deny: 0, allow: 3072 },
      { id: '291440686916698112', type: 'role', deny: 0, allow: 3072 },
      { id: '231933464201527298', type: 'role', deny: 1024, allow: 0 },
      {id: '231944387255336960',type: 'role',deny: 8192,allow: 3072 },
      {id: '231944378476658690',type:'role',deny:0,allow:3072},
      {id: '231948453737922580',type: 'role',deny: 8192,allow: 3072 }
    ];
    guild.createChannel(channel, 'text', permissions)
     .then(channel => {
       channel.createInvite({
         temporary: false,
         maxUses: 2
       }).then(invite => {
        botInvites.push(invite.code);
        res.send(invite.url);
       })
       .catch(console.error);
       channel.sendMessage(`@everyone New application please review.`).then(message => {
         channel.sendMessage(applicationText, {split:true})
         .then(message => {
         })
         .catch(console.error);
       }).catch(console.error());
     })
     .catch(console.error);
  }
});

app.get('/', (req,res) => {
  res.send("Revive-Discord-Bot");
});

app.get('/callback', (req,res) => {
  //Handle Discord Request URI?
});

bot.login(myConfig.discordKey);

server.listen(app.get('serverPort'));
console.log('Listening on port', app.get('serverPort'));<commit_msg>zesty<commit_after>/* jshint esversion: 6 */
const myConfig = require('./config.json');
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const request = require('request');
const bodyParser = require('body-parser');
const Discord = require('discord.js');
const bot = new Discord.Client();
app.set('serverPort', myConfig.serverPort);
app.use(bodyParser.urlencoded({
  extended: true
}));
let botInvites = [];
app.use(bodyParser.json());

bot.on('message', message => {
  if (message.content === '!kern') {
    message.channel.sendMessage('https://clips.twitch.tv/MistyNiceBibimbapTheRinger');
  } else if (message.content === '!varcster') {
    message.channel.sendMessage('https://www.twitch.tv/videos/68214198');
  } else if (message.content === '!zesty') {
    message.channel.sendMessage('https://clips.twitch.tv/SpoopyFreezingWrenOSsloth');
  }
});

bot.on('ready', () => {
  console.log('I am ready!');
  let guild = bot.guilds.find(val => val.id === myConfig.guildID);
  if (guild.available) {
    guild.fetchInvites()
      .then(invites => {
        for (const invite of invites.array()) {
          if (invite.inviter && invite.inviter.id &&
            invite.inviter.id === myConfig.botID && invite.uses !== null &&
            invite.uses === 0)
            botInvites.push(invite.code);
        }
      })
      .catch(console.error);
  }
});
bot.on('guildMemberAdd', (member) => {
  let guild = bot.guilds.find(val => val.id === myConfig.guildID);
  if (guild.available) {
    guild.fetchInvites()
      .then(invites => {
        for (const invite of invites.array()) {
          for (var i = 0; i < botInvites.length; i++) {
            if (invite.code === botInvites[i] && invite.uses >= 1) {
              createApplicantUser(member, invite, i);
            }
          }
        }
      })
      .catch(console.error);
  }
});

const createApplicantUser = (member, invite, i) => {
  member.addRole(myConfig.applicantRoleID)
    .then((member) => {
      if (invite.channel) {
        invite.channel.overwritePermissions(member, {
         SEND_MESSAGES: true,
         READ_MESSAGES: true,
         EMBED_LINKS: true,
         READ_MESSAGE_HISTORY:true,
         ATTACH_FILES: true
        })
        .then(() => {
          member.setNickname(invite.channel.name)
            .then((applicant) => {
              invite.channel.sendMessage(`${applicant.user} Thanks for applying to revive. You can find your application here please feel free to ask any questions.`);
            })
            .catch(console.error);
        })
        .catch(console.error);
      }
    })
    .catch(console.error);
  invite.delete()
    .then(invite => {
      botInvites.splice(i,1);
    })
    .catch(console.error);
};

app.post('/createGuildApp', (req,res) => {
  const applicationData = {
    name:req.body.name,
    loc:req.body.loc,
    tag:req.body.tag,
    armory:req.body.armory,
    sscombat:req.body.sscombat,
    headset:req.body.headset,
    logs:req.body.logs,
    role:req.body.role,
    awp:req.body.awp,
    prog:req.body.prog,
    left:req.body.left,
    rotation:req.body.rotation,
    resources:req.body.resources,
    hear:req.body.hear,
    crit:req.body.crit,
    sit:req.body.sit,
    schedule:req.body.schedule,
    beta:req.body.beta,
    about:req.body.about,
    joke:req.body.joke
  };
  const applicationText = `**What is your Name, Age and Sex?**\n
━━━━━━━━━━━━━━━━━━━━━━━━\n
${applicationData.name}\n\n
**Provide the location you will primarily will be playing from and a speedtest.net screenshot from the Chicago server**\n
━━━━━━━━━━━━━━━━━━━━━━━━\n
${applicationData.loc}\n\n
**What is your Battle.net Tag**\n
━━━━━━━━━━━━━━━━━━━━━━━━\n
${applicationData.tag}\n\n
**Link to your main characters and alternate character's ADVANCED ARMORY**\n
━━━━━━━━━━━━━━━━━━━━━━━━\n
${applicationData.armory}\n\n
**Post a screenshot of your character in combat**\n
━━━━━━━━━━━━━━━━━━━━━━━━\n
${applicationData.sscombat}\n\n
**Do you have a functioning headset with microphone that you can use in Discord?**\n
━━━━━━━━━━━━━━━━━━━━━━━━\n
${applicationData.headset}\n\n
**Post your recent warcraft logs**\n
━━━━━━━━━━━━━━━━━━━━━━━━\n
${applicationData.logs}\n\n
**What role and spec are you applying for**\n
━━━━━━━━━━━━━━━━━━━━━━━━\n
${applicationData.role}\n\n
**List your Artifact Weapon points for all Specs **\n
━━━━━━━━━━━━━━━━━━━━━━━━\n
${applicationData.awp}\n\n
**List Pre Tier-19 Mythic/Heroic Progression Experiences**\n
━━━━━━━━━━━━━━━━━━━━━━━━\n
${applicationData.prog}\n\n
**Name your last TWO raiding guilds and the reason for leaving them?**\n
━━━━━━━━━━━━━━━━━━━━━━━━\n
${applicationData.left}\n\n
**Take us through your opening rotation on a SINGLE TARGET fight. (Healers Ignore this)**\n
━━━━━━━━━━━━━━━━━━━━━━━━\n
${applicationData.rotation}\n\n
**What resources do you use to improve yourself?**\n
━━━━━━━━━━━━━━━━━━━━━━━━\n
${applicationData.resources}\n\n
**How did you hear about us?**\n
━━━━━━━━━━━━━━━━━━━━━━━━\n
${applicationData.hear}\n\n
**How do you handle criticism and adult humor?**\n
━━━━━━━━━━━━━━━━━━━━━━━━\n
${applicationData.crit}\n\n
**You may be asked to sit on some fights for composition, gear, or general skill level how do you feel about that?**\n
━━━━━━━━━━━━━━━━━━━━━━━━\n
${applicationData.sit}\n\n
**Do you have any commitments or schedule changes that we should know about?**\n
━━━━━━━━━━━━━━━━━━━━━━━━\n
${applicationData.schedule}\n\n
**Are you willing to test new content in PTR/Alpha/Beta?**\n
━━━━━━━━━━━━━━━━━━━━━━━━\n
${applicationData.beta}\n\n
**Tell us a little bit about yourself. The more we know the better!**\n
━━━━━━━━━━━━━━━━━━━━━━━━\n
${applicationData.about}\n\n
**Tell us a joke**\n
━━━━━━━━━━━━━━━━━━━━━━━━\n
${applicationData.joke}\n\n`;
  let guild = bot.guilds.find(val => val.id === myConfig.guildID);
  let _this = this;
  if (guild.available) {
    const channel = applicationData.tag.replace('#','-');
    const permissions = [
      { id: '231944378577321984', type: 'role', deny: 0, allow: 3072 },
      { id: '291440686916698112', type: 'role', deny: 0, allow: 3072 },
      { id: '231933464201527298', type: 'role', deny: 1024, allow: 0 },
      {id: '231944387255336960',type: 'role',deny: 8192,allow: 3072 },
      {id: '231944378476658690',type:'role',deny:0,allow:3072},
      {id: '231948453737922580',type: 'role',deny: 8192,allow: 3072 }
    ];
    guild.createChannel(channel, 'text', permissions)
     .then(channel => {
       channel.createInvite({
         temporary: false,
         maxUses: 2
       }).then(invite => {
        botInvites.push(invite.code);
        res.send(invite.url);
       })
       .catch(console.error);
       channel.sendMessage(`@everyone New application please review.`).then(message => {
         channel.sendMessage(applicationText, {split:true})
         .then(message => {
         })
         .catch(console.error);
       }).catch(console.error());
     })
     .catch(console.error);
  }
});

app.get('/', (req,res) => {
  res.send("Revive-Discord-Bot");
});

app.get('/callback', (req,res) => {
  //Handle Discord Request URI?
});

bot.login(myConfig.discordKey);

server.listen(app.get('serverPort'));
console.log('Listening on port', app.get('serverPort'));<|endoftext|>


<commit_before>var server_port = process.env.OPENSHIFT_NODEJS_PORT || 8080
var server_ip_address = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1'

server.listen(server_port,server_ip_address, function() {
    console.log( "Listening on " + server_ip_address +",port" + server_port )
});
<commit_msg>change server.js<commit_after>#!/usr/bin/env node

/**
 * Module dependencies.
 */

var app = require('../app');
var debug = require('debug')('myapp:server');
var http = require('http');

/**
 * Get port from environment and store in Express.
 */

/* var port = normalizePort(process.env.PORT || '3000');
 *
 */
var port = normalizePort(process.env.OPENSHIFT_NODEJS_PORT || '8080');
app.set('port', port);

/**
 * Create HTTP server.
 */

var server = http.createServer(app);

/**
 * Listen on provided port, on all network interfaces.
 */

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

/**
 * Normalize a port into a number, string, or false.
 */

function normalizePort(val) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
}

/**
 * Event listener for HTTP server "error" event.
 */

function onError(error) {
  if (error.syscall !== 'listen') {
    throw error;
  }

  var bind = typeof port === 'string'
    ? 'Pipe ' + port
    : 'Port ' + port;

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}

/**
 * Event listener for HTTP server "listening" event.
 */

function onListening() {
 /* var addr = server.address();
  * *
  */
  var addr = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1'
  var bind = typeof addr === 'string'
    ? 'pipe ' + addr
    : 'port ' + addr.port;
  debug('Listening on ' + bind);
}

var server_port = process.env.OPENSHIFT_NODEJS_PORT || 8080
var server_ip_address = process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1'

server.listen(server_port,server_ip_address, function() {
    console.log( "Listening on " + server_ip_address +",port" + server_port )
});
<|endoftext|>


<commit_before>(function () {
    'use strict';

    var MongoClient = require('mongodb').MongoClient, restify = require('restify'), assert = require('assert');//, ObjectId = require('mongodb').ObjectID;

    //Needs to impliment aggregate stuff (https://docs.mongodb.com/manual/reference/operator/aggregation/)
    //Need to impliment mapreduce stuff
    //Need to impliment projection stuff

    //Good source for operators:
    // https://docs.mongodb.com/manual/reference/operator/
    //I am making sure to not allow any operators that can change the documents
    // this is to ensure that this remains a query only server

    var acceptedRegex = "", sanatize, j, grabDbName, grabDocument,
            accepted$ = [
        "all", "and", "bitsAllClear", "bitsAllSet", "bitsAnyClear",
        "bitsAnySet", "collStats", "comment", "elemMatch",
        "eq", "exists", "explain", "geoIntersects", "geoWithin", "gt",
        "gte", "hint", "in", "limit", "lte", "match", "max", "maxScan",
        "maxTimeMS", "meta", "min", "mod", "natural", "ne", "near",
        "nearShpere", "nin", "nor", "not", "or", "orderby", "query",
        "regex", "returnKey", "showDiskLoc", "size", "skip", "slice",
        "snapshot", "text", "type", "where"
    ];

    for (j = 0; j < accepted$.length; j += 1) {
        acceptedRegex += "^\\$" + accepted$[j] + "$|";
    }
    acceptedRegex = acceptedRegex.replace(/\|$/, "");
    acceptedRegex = new RegExp(acceptedRegex, 'i');

    //define the query sanatize function
    //sanatize the query
    sanatize = function (query) {
        var keys, i;
        if (typeof query === "object") {
            keys = Object.keys(query);
            for (i = 0; i < keys.length; i += 1) {
                if (keys[i].match(/^\s*\$/)) {
                    //straight up kill it if it is not an accepted type
                    if (!keys[i].match(acceptedRegex)) {
                        delete query[keys[i]];
                    }
                } else if (typeof query[keys[i]] === "object") {
                    query[keys[i]] = sanatize(query[keys[i]]);
                }
            }
        } else {
            //If it is not an object then just query it all
            // should probably generate an error message
            query = {};
        }
        return query;
    };

    grabDbName = function (request, response) {
        var myDbName = request.params.db_name, query, fields, sort,
                collectionName = request.params.collection_name,
                url = 'mongodb://localhost:27017/' + myDbName;

        //Deal with the objects
        request.query.find = request.query.find || "{}";
        request.query.fields = request.query.fields || "-1";
        request.query.sort = request.query.sort || "[]";

        request.query.find = decodeURIComponent(request.query.find);
        request.query.fields = decodeURIComponent(request.query.fields);
        request.query.sort = decodeURIComponent(request.query.sort);

        //Objectify them
        query = JSON.parse(request.query.find);
        query = sanatize(query);
        fields = JSON.parse(request.query.fields);
        sort = JSON.parse(request.query.sort);

        //if there is a sort option, sanatize it
        if (sort.length > 0) {
            sanatize(sort);
        }

        //Start up connection and run the query
        MongoClient.connect(url, function (err, db) {
            assert.equal(null, err);
            var spec;
            var collection = db.collection(collectionName);
            console.log("Connected successfully to server");

            //options
            var limit = request.query.limit * 1 || 9000000; //9 mil more than enough
            var skip = request.query.skip * 1 || 0;
            var maxTimeMS = request.query.maxTimeMS * 1 || 1000 * 60 * 60; //1 hr

            //special stuff
            console.log(query, fields, sort);
            if (fields === -1) {
                spec = collection.find(query, {
                    limit: limit,
                    skip: skip,
                    maxTimeMS: maxTimeMS
                });
            } else {
                spec = collection.find(query, sanatize(fields), {
                    limit: limit,
                    skip: skip,
                    maxTimeMS: maxTimeMS
                });
            }

            //run the sort operation and then return the final result
            spec.sort(sort).toArray(function (err, docs) {
                assert.equal(err, null);
                console.log('Found docs');
               // console.log("Found the following records", docs);
                response.send(docs);
            });
        });
    };

    grabDocument = function (request, response) {
        var myDbName = request.params.db_name, fields,
                collectionName = request.params.collection_name,
                query = {id: decodeURIComponent(request.params.doc_id)},
                url = 'mongodb://localhost:27017/' + myDbName;

        //Deal with the objects
        myDbName = myDbName || 'kinome';
        request.query.fields = request.query.fields || "-1";
        request.query.fields = decodeURIComponent(request.query.fields);

        //Objectify them
        query = sanatize(query);
        fields = JSON.parse(request.query.fields);

        //Start up connection and run the query
        MongoClient.connect(url, function (err, db) {
            assert.equal(null, err);
            var spec;
            var collection = db.collection(collectionName);
            console.log("Connected successfully to server");

            //options
            var maxTimeMS = request.query.maxTimeMS * 1 || 1000 * 60 * 60; //1 hr

            //special stuff
            console.log(query, fields);
            if (fields === -1) {
                spec = collection.find({"_id": query.id}, {
                    maxTimeMS: maxTimeMS
                });
            } else {
                spec = collection.find({"_id": query.id}, sanatize(fields), {
                    maxTimeMS: maxTimeMS
                });
            }

            //run the sort operation and then return the final result
            spec.toArray(function (err, docs) {
                assert.equal(err, null);
                console.log('Found docs');
                //console.log("Found the following records", docs);
                //Only return the first object
                response.send(docs[0]);
            });
        });
    };

    //sets up the server stuff
    var server1 = restify.createServer({
        accept: ['application/json', 'image/tif', 'image/png']
    });
    server1.use(restify.queryParser());
    server1.use(restify.CORS({}));

    server1.get(/\/img\/kinome\/?.*/, restify.serveStatic({
        directory: "/var/www"
    }));

    //http://138.26.31.155:8000/img/kinome/631308613_W1_F1_T200_P154_I1313_A30.tif

    /*the following is for the internal db (accesible as a registered UAB user only)*/
    server1.get("/db/:db_name/:collection_name", grabDbName);
    server1.get("/db/:db_name/:collection_name/:doc_id", grabDocument);
    server1.listen(8000, function () {
        console.log('%s listening at %s', server1.name, server1.url);
    });

    // var server2 = restify.createServer({
    //     accept: ['application/json', 'image/tif', 'image/png']
    // });
    // server2.use(restify.queryParser());
    // server2.use(restify.CORS({}));

    // server2.get(/\/img\/kinome\/?.*/, restify.serveStatic({
    //     directory: "./server_imgs"
    // }));

    // /*The following is for the external db*/
    // server2.get("/db/1.0.0/:collection_name", grabDbName);
    // server2.get("/db/1.0.0/:collection_name/:doc_id", grabDocument);
    // server2.listen(80, function () {
    //     console.log('%s listening at %s', server2.name, server2.url);
    // });

}());
<commit_msg>add in server 2<commit_after>(function () {
    'use strict';

    var MongoClient = require('mongodb').MongoClient, restify = require('restify'), assert = require('assert');//, ObjectId = require('mongodb').ObjectID;

    //Needs to impliment aggregate stuff (https://docs.mongodb.com/manual/reference/operator/aggregation/)
    //Need to impliment mapreduce stuff
    //Need to impliment projection stuff

    //Good source for operators:
    // https://docs.mongodb.com/manual/reference/operator/
    //I am making sure to not allow any operators that can change the documents
    // this is to ensure that this remains a query only server

    var acceptedRegex = "", sanatize, j, grabDbName, grabDocument,
            accepted$ = [
        "all", "and", "bitsAllClear", "bitsAllSet", "bitsAnyClear",
        "bitsAnySet", "collStats", "comment", "elemMatch",
        "eq", "exists", "explain", "geoIntersects", "geoWithin", "gt",
        "gte", "hint", "in", "limit", "lte", "match", "max", "maxScan",
        "maxTimeMS", "meta", "min", "mod", "natural", "ne", "near",
        "nearShpere", "nin", "nor", "not", "or", "orderby", "query",
        "regex", "returnKey", "showDiskLoc", "size", "skip", "slice",
        "snapshot", "text", "type", "where"
    ];

    for (j = 0; j < accepted$.length; j += 1) {
        acceptedRegex += "^\\$" + accepted$[j] + "$|";
    }
    acceptedRegex = acceptedRegex.replace(/\|$/, "");
    acceptedRegex = new RegExp(acceptedRegex, 'i');

    //define the query sanatize function
    //sanatize the query
    sanatize = function (query) {
        var keys, i;
        if (typeof query === "object") {
            keys = Object.keys(query);
            for (i = 0; i < keys.length; i += 1) {
                if (keys[i].match(/^\s*\$/)) {
                    //straight up kill it if it is not an accepted type
                    if (!keys[i].match(acceptedRegex)) {
                        delete query[keys[i]];
                    }
                } else if (typeof query[keys[i]] === "object") {
                    query[keys[i]] = sanatize(query[keys[i]]);
                }
            }
        } else {
            //If it is not an object then just query it all
            // should probably generate an error message
            query = {};
        }
        return query;
    };

    grabDbName = function (request, response) {
        var myDbName = request.params.db_name, query, fields, sort,
                collectionName = request.params.collection_name,
                url = 'mongodb://localhost:27017/' + myDbName;

        //Deal with the objects
        request.query.find = request.query.find || "{}";
        request.query.fields = request.query.fields || "-1";
        request.query.sort = request.query.sort || "[]";

        request.query.find = decodeURIComponent(request.query.find);
        request.query.fields = decodeURIComponent(request.query.fields);
        request.query.sort = decodeURIComponent(request.query.sort);

        //Objectify them
        query = JSON.parse(request.query.find);
        query = sanatize(query);
        fields = JSON.parse(request.query.fields);
        sort = JSON.parse(request.query.sort);

        //if there is a sort option, sanatize it
        if (sort.length > 0) {
            sanatize(sort);
        }

        //Start up connection and run the query
        MongoClient.connect(url, function (err, db) {
            assert.equal(null, err);
            var spec;
            var collection = db.collection(collectionName);
            console.log("Connected successfully to server");

            //options
            var limit = request.query.limit * 1 || 9000000; //9 mil more than enough
            var skip = request.query.skip * 1 || 0;
            var maxTimeMS = request.query.maxTimeMS * 1 || 1000 * 60 * 60; //1 hr

            //special stuff
            console.log(query, fields, sort);
            if (fields === -1) {
                spec = collection.find(query, {
                    limit: limit,
                    skip: skip,
                    maxTimeMS: maxTimeMS
                });
            } else {
                spec = collection.find(query, sanatize(fields), {
                    limit: limit,
                    skip: skip,
                    maxTimeMS: maxTimeMS
                });
            }

            //run the sort operation and then return the final result
            spec.sort(sort).toArray(function (err, docs) {
                assert.equal(err, null);
                console.log('Found docs');
               // console.log("Found the following records", docs);
                response.send(docs);
            });
        });
    };

    grabDocument = function (request, response) {
        var myDbName = request.params.db_name, fields,
                collectionName = request.params.collection_name,
                query = {id: decodeURIComponent(request.params.doc_id)},
                url = 'mongodb://localhost:27017/' + myDbName;

        //Deal with the objects
        myDbName = myDbName || 'kinome';
        request.query.fields = request.query.fields || "-1";
        request.query.fields = decodeURIComponent(request.query.fields);

        //Objectify them
        query = sanatize(query);
        fields = JSON.parse(request.query.fields);

        //Start up connection and run the query
        MongoClient.connect(url, function (err, db) {
            assert.equal(null, err);
            var spec;
            var collection = db.collection(collectionName);
            console.log("Connected successfully to server");

            //options
            var maxTimeMS = request.query.maxTimeMS * 1 || 1000 * 60 * 60; //1 hr

            //special stuff
            console.log(query, fields);
            if (fields === -1) {
                spec = collection.find({"_id": query.id}, {
                    maxTimeMS: maxTimeMS
                });
            } else {
                spec = collection.find({"_id": query.id}, sanatize(fields), {
                    maxTimeMS: maxTimeMS
                });
            }

            //run the sort operation and then return the final result
            spec.toArray(function (err, docs) {
                assert.equal(err, null);
                console.log('Found docs');
                //console.log("Found the following records", docs);
                //Only return the first object
                response.send(docs[0]);
            });
        });
    };

    //sets up the server stuff
    var server1 = restify.createServer({
        accept: ['application/json', 'image/tif', 'image/png']
    });
    server1.use(restify.queryParser());
    server1.use(restify.CORS({}));

    server1.get(/\/img\/kinome\/?.*/, restify.serveStatic({
        directory: "/var/www"
    }));

    //http://138.26.31.155:8000/img/kinome/631308613_W1_F1_T200_P154_I1313_A30.tif

    /*the following is for the internal db (accesible as a registered UAB user only)*/
    server1.get("/db/:db_name/:collection_name", grabDbName);
    server1.get("/db/:db_name/:collection_name/:doc_id", grabDocument);
    server1.listen(8000, function () {
        console.log('%s listening at %s', server1.name, server1.url);
    });

    var server2 = restify.createServer({
        accept: ['application/json', 'image/tif', 'image/png']
    });
    server2.use(restify.queryParser());
    server2.use(restify.CORS({}));

    server2.get(/\/img\/kinome\/?.*/, restify.serveStatic({
        directory: "./server_imgs"
    }));

    /*The following is for the external db*/
    server2.get("/db/1.0.0/:collection_name", grabDbName);
    server2.get("/db/1.0.0/:collection_name/:doc_id", grabDocument);
    server2.listen(8080, function () {
        console.log('%s listening at %s', server2.name, server2.url);
    });

}());
<|endoftext|>


<commit_before>// TODO: Security still needs to be added to most endpoints

var express = require('express'),
    config = require('./lib/config'),
    docker = require('./lib/docker'),
    exec = require('child_process').exec,
    os = require('os');

var app = express();

//app.use(require('response-time')(5));
//app.use(require('connect-timeout')(10000));
app.use(require('body-parser')());

app.use(function(err, req, res, next) {
    console.log( err );
    err.request = req;
    res.send(500, { error: err })
});

app.get('/', function(req, res) {
    res.type( "text/plain" );
    res.send( 200, "Codewars Runner is live!" );
});

app.get('/version', function(req, res) {
    res.end(config.version);
});

app.get('/build', function(req, res) {
    exec('node build', function(err, stdout, stderr) {
        res.end(JSON.stringify({
           stdout: stdout,
           stderr: stderr
        }));
    });
});

// updates to the latest code and docker images
// responds to both get and post for backwards comparability and easier debugging.
getOrPost('/update', function(req, res)
{
    var updateSh = require('child_process').spawn('sh', [ 'setup/update.sh' ], {
        cwd: process.env.PWD
    });

    var buffer = [];

    updateSh.stdout.on('data', function(data)
    {
        buffer.push(data);
    });

    updateSh.on('exit', function (code)
    {
        buffer.push(code);
        res.end(buffer.join(''));
    });

    useTimeout(60000, res);
});

app.post('/run', function(req, res) {
    var image = req.body.image,
        taggedImage = docker.taggedImage(image);

    delete req.body.image;

    console.time(taggedImage);
    console.log(taggedImage);

    docker.run(image, 'run', req.body, function(error, data, stdout, stderr){
        console.timeEnd(taggedImage);

        json = safeParse(stdout);

        if (json) {
            json.freeMem = os.freemem();
            json.v = config.version;
            res.end(JSON.stringify(json));

        } else {
            console.warn('stdout did not return valid data, going with stderr');
            console.info(stderr);
            error = error || {};
            res.end(JSON.stringify({
                stdout: stdout,
                stderr: stderr || error.reason,
                statusCode: error.statusCode,
                failed: true,
                freeMem: os.freemem(),
                v: config.version,
                details: error.json
            }));
        }
    });

    useTimeout(10000, res);
});

app.get('/status', function(req, res) {
    docker.run(null, 'run', {l: 'javascript', c: 'console.log(1+1)'}, function(err, data, stdout, stderr) {
        res.end(JSON.stringify({
            healthy: stdout.indexOf('stdout":"2\\n",') > 0,
            freeMem: os.freemem(),
            version: config.version,
            dryRun: {
                error: err && err.toString(),
                data: data,
                stdout: stdout,
                stderr: stderr
            }
        }));
    });

    useTimeout(5000, res);
});

function useTimeout(timeout, res) {
    setTimeout(function() {
        res.end(JSON.stringify({
            failed: true,
            reason: 'Response timed out, took longer than ' + timeout + 'ms'
        }));
    }, timeout);
}

function safeParse(json) {
    try
    {
        return json ? JSON.parse(json) : null;
    }
    catch(ex)
    {
        console.log(ex);
        return null
    }
}

function getOrPost(route, cb) {
    app.get(route, cb);
    app.post(route, cb);
}

// for testing only
//app.post('/run', function(req, res) {
//    var image = req.body.image || 'codewars/cli-runner';
//    delete req.body.image;
//
//    docker.runCmd(image, 'run', req.body, function(error, out){
//        console.log(out);
//        res.end(out);
//    });
//});

server = app.listen(8080, function() {
    console.log('Listening on port %d', server.address().port);
});
<commit_msg>added stderr to output<commit_after>// TODO: Security still needs to be added to most endpoints

var express = require('express'),
    config = require('./lib/config'),
    docker = require('./lib/docker'),
    exec = require('child_process').exec,
    os = require('os');

var app = express();

//app.use(require('response-time')(5));
//app.use(require('connect-timeout')(10000));
app.use(require('body-parser')());

app.use(function(err, req, res, next) {
    console.log( err );
    err.request = req;
    res.send(500, { error: err })
});

app.get('/', function(req, res) {
    res.type( "text/plain" );
    res.send( 200, "Codewars Runner is live!" );
});

app.get('/version', function(req, res) {
    res.end(config.version);
});

app.get('/build', function(req, res) {
    exec('node build', function(err, stdout, stderr) {
        res.end(JSON.stringify({
           stdout: stdout,
           stderr: stderr
        }));
    });
});

// updates to the latest code and docker images
// responds to both get and post for backwards comparability and easier debugging.
getOrPost('/update', function(req, res)
{
    var updateSh = require('child_process').spawn('sh', [ 'setup/update.sh' ], {
        cwd: process.env.PWD
    });

    var buffer = [];

    updateSh.stdout.on('data', function(data)
    {
        buffer.push(data);
    });

    updateSh.stderr.on('data', function(data)
    {
        buffer.push(data);
    });

    updateSh.on('exit', function (code)
    {
        buffer.push(code);
        res.end(buffer.join(''));
    });

    useTimeout(60000, res);
});

app.post('/run', function(req, res) {
    var image = req.body.image,
        taggedImage = docker.taggedImage(image);

    delete req.body.image;

    console.time(taggedImage);
    console.log(taggedImage);

    docker.run(image, 'run', req.body, function(error, data, stdout, stderr){
        console.timeEnd(taggedImage);

        json = safeParse(stdout);

        if (json) {
            json.freeMem = os.freemem();
            json.v = config.version;
            res.end(JSON.stringify(json));

        } else {
            console.warn('stdout did not return valid data, going with stderr');
            console.info(stderr);
            error = error || {};
            res.end(JSON.stringify({
                stdout: stdout,
                stderr: stderr || error.reason,
                statusCode: error.statusCode,
                failed: true,
                freeMem: os.freemem(),
                v: config.version,
                details: error.json
            }));
        }
    });

    useTimeout(10000, res);
});

app.get('/status', function(req, res) {
    docker.run(null, 'run', {l: 'javascript', c: 'console.log(1+1)'}, function(err, data, stdout, stderr) {
        res.end(JSON.stringify({
            healthy: stdout.indexOf('stdout":"2\\n",') > 0,
            freeMem: os.freemem(),
            version: config.version,
            dryRun: {
                error: err && err.toString(),
                data: data,
                stdout: stdout,
                stderr: stderr
            }
        }));
    });

    useTimeout(5000, res);
});

function useTimeout(timeout, res) {
    setTimeout(function() {
        res.end(JSON.stringify({
            failed: true,
            reason: 'Response timed out, took longer than ' + timeout + 'ms'
        }));
    }, timeout);
}

function safeParse(json) {
    try
    {
        return json ? JSON.parse(json) : null;
    }
    catch(ex)
    {
        console.log(ex);
        return null
    }
}

function getOrPost(route, cb) {
    app.get(route, cb);
    app.post(route, cb);
}

// for testing only
//app.post('/run', function(req, res) {
//    var image = req.body.image || 'codewars/cli-runner';
//    delete req.body.image;
//
//    docker.runCmd(image, 'run', req.body, function(error, out){
//        console.log(out);
//        res.end(out);
//    });
//});

server = app.listen(8080, function() {
    console.log('Listening on port %d', server.address().port);
});
<|endoftext|>


<commit_before>// Rendering styles

import {StyleParser} from './style_parser';
import FeatureSelection from '../selection';
import ShaderProgram from '../gl/shader_program';
import VBOMesh from '../gl/vbo_mesh';
import Builders from './builders';
import Texture from '../gl/texture';
import Material from '../material';
import {MethodNotImplemented} from '../utils/errors';
import shaderSources from '../gl/shader_sources'; // built-in shaders

import log from 'loglevel';

// Base class

export var Style = {
    init () {
        if (this.initialized) {
            return;
        }

        if (!this.isBuiltIn()) {
            this.built_in = false; // explicitly set to false to avoid any confusion
        }

        this.defines = this.defines || {};          // #defines to be injected into the shaders
        this.shaders = this.shaders || {};          // shader customization via scene definition (uniforms, defines, blocks, etc.)
        this.selection = this.selection || false;   // flag indicating if this style supports feature selection
        this.compiling = false;                     // programs are currently compiling
        this.compiled = false;                      // programs are finished compiling
        this.program = null;                        // GL program reference (for main render pass)
        this.selection_program = null;              // GL program reference for feature selection render pass
        this.feature_style = {};                    // style for feature currently being parsed, shared to lessen GC/memory thrash
        this.textures = this.textures || {};

        this.material = new Material();
        this.material.inject(this);

        this.initialized = true;
    },

    destroy () {
        if (this.program) {
            this.program.destroy();
            this.program = null;
        }

        if (this.selection_program) {
            this.selection_program.destroy();
            this.selection_program = null;
        }

        this.gl = null;
        this.initialized = false;
    },

    isBuiltIn () {
        return this.hasOwnProperty('built_in') && this.built_in;
    },

    /*** Style parsing and geometry construction ***/

    // Returns an object to hold feature data (for a tile or other object)
    startData () {
        return {
            vertex_data: null,
            uniforms: null,
            order: { min: Infinity, max: -Infinity } // reset to track order range within tile
        };
    },

    // Finalizes an object holding feature data (for a tile or other object)
    endData (tile_data) {
        if (tile_data.vertex_data) {
            // Only keep final byte buffer
            tile_data.vertex_data.end();
            tile_data.vertex_data = tile_data.vertex_data.buffer;
        }
        return Promise.resolve(tile_data);
    },

    addFeature (feature, rule, context, tile_data) {
        let style = this.parseFeature(feature, rule, context);

        // Skip feature?
        if (!style) {
            return;
        }

        // Track min/max order range
        if (style.order < tile_data.order.min) {
            tile_data.order.min = style.order;
        }
        if (style.order > tile_data.order.max) {
            tile_data.order.max = style.order;
        }

        // First feature in this render style?
        if (!tile_data.vertex_data) {
            tile_data.vertex_data = this.vertex_layout.createVertexData();
        }

        this.buildGeometry(feature.geometry, style, tile_data.vertex_data);
    },

    buildGeometry (geometry, style, vertex_data) {
        if (geometry.type === 'Polygon') {
            this.buildPolygons([geometry.coordinates], style, vertex_data);
        }
        else if (geometry.type === 'MultiPolygon') {
            this.buildPolygons(geometry.coordinates, style, vertex_data);
        }
        else if (geometry.type === 'LineString') {
            this.buildLines([geometry.coordinates], style, vertex_data);
        }
        else if (geometry.type === 'MultiLineString') {
            this.buildLines(geometry.coordinates, style, vertex_data);
        }
        else if (geometry.type === 'Point') {
            this.buildPoints([geometry.coordinates], style, vertex_data);
        }
        else if (geometry.type === 'MultiPoint') {
            this.buildPoints(geometry.coordinates, style, vertex_data);
        }
    },

    parseFeature (feature, rule_style, context) {
        try {
            var style = this.feature_style;

            // Calculate order if it was not cached
            style.order = rule_style.order;
            if (typeof style.order !== 'number') {
                style.order = StyleParser.calculateOrder(style.order, context);
            }

            // Feature selection (only if style supports it)
            var selectable = false;
            style.interactive = rule_style.interactive;
            if (this.selection) {
                if (typeof style.interactive === 'function') {
                    selectable = style.interactive(context);
                }
                else {
                    selectable = style.interactive;
                }
            }

            // If feature is marked as selectable
            if (selectable) {
                style.selection_color = FeatureSelection.makeColor(feature);
            }
            else {
                style.selection_color = FeatureSelection.defaultColor;
            }

            // Subclass implementation
            this._parseFeature(feature, rule_style, context);

            return style;
        }
        catch(error) {
            log.error('Style.parseFeature: style parsing error', feature, error);
        }
    },

    _parseFeature (feature, rule_style, context) {
        throw new MethodNotImplemented('_parseFeature');
    },

    // Build functions are no-ops until overriden
    buildPolygons () {},
    buildLines () {},
    buildPoints () {},

    /*** Texture management ***/

    // Prefix texture name with style name
    textureName (name) {
        return this.name + '_' + name;
    },

    setupTextureUniforms () {
        var num_textures = Object.keys(this.textures).length;

        // Set a default texture flag
        if (this.textures.default) {
            this.defines['HAS_DEFAULT_TEXTURE'] = true;
        }

        // Provide a built-in uniform array of textures
        if (num_textures > 0) {
            var tex_id = 0;
            this.defines['NUM_TEXTURES'] = num_textures.toString(); // force string to avoid auto-conversion to float
            this.shaders.uniforms = this.shaders.uniforms || {};
            this.shaders.uniforms.u_textures = [];

            for (var name in this.textures) {
                var texture = this.textures[name];
                texture.name = this.textureName(name);
                texture.id = tex_id++; // give every texture a unique id local to this style

                // Consistently map named textures to the same array index in the texture uniform
                this.shaders.uniforms.u_textures[texture.id] = texture.name;

                // Provide a #define mapping each texture back to its name in the stylesheet
                this.defines[`texture_${name}`] = `u_textures[${texture.id}]`;
            }
        }
    },

    // Preload any textures with explicit configuration in the 'textures' field
    // (textures can also be initialized on the fly via uniform setters if they don't require any additional configuration)
    // NOTE: this is only run in the main thread, since workers don't use any GL resources
    preloadTextures () {
        if (this.textures) {
            for (var name in this.textures) {
                var { url, filtering, repeat, sprites } = this.textures[name];
                var texture = new Texture(this.gl, this.textureName(name), { sprites });

                texture.load(url, { filtering, repeat });
            }
        }
    },

    // Pre-calc sprite regions for a texture sprite in UV [0, 1] space
    calculateTextureSprites (name) {
        var texture = Texture.textures[this.textureName(name)];
        if (texture.sprites) {
            this.texture_sprites = this.texture_sprites || {};
            this.texture_sprites[name] = {};

            for (var s in texture.sprites) {
                var sprite = texture.sprites[s];

                // Map [0, 0] to [1, 1] coords to the appropriate sprite sub-area of the texture
                this.texture_sprites[name][s] = Builders.getTexcoordsForSprite(
                    [sprite[0], sprite[1]],
                    [sprite[2], sprite[3]],
                    [texture.width, texture.height]
                );
            }
        }
    },

    // Set optional scale to use for texture coordinates (default is [0, 1])
    setTexcoordScale (style) {
        // Get sprite sub-area if necessary
        if (this.textures && style.sprite) {
            // Use default texture if available, otherwise texture must be specified
            var tex;
            if (this.textures.default) {
                tex = 'default';
            }
            else {
                tex = style.texture;
            }

            if (!tex) {
                log.error(`Style: in style '${this.name}', must specify texture to use for sprite '${style.sprite}', must be one of [${Object.keys(this.textures).join(', ')}]`);
            }
            else {
                // Lazily calculate sprite UVs the first time they are encountered
                if (!this.texture_sprites || !this.texture_sprites[tex]) {
                    this.calculateTextureSprites(tex);
                }
                this.texcoord_scale = this.texture_sprites[tex] && this.texture_sprites[tex][style.sprite];
            }
        }
    },

    /*** GL state and rendering ***/

    setGL (gl) {
        this.gl = gl;
        this.setupTextureUniforms();
        this.preloadTextures();
    },

    makeMesh (vertex_data, { uniforms } = {}) {
        return new VBOMesh(this.gl, vertex_data, this.vertex_layout, { uniforms });
    },

    compile () {
        if (!this.gl) {
            throw(new Error(`style.compile(): skipping for ${this.name} because no GL context`));
        }

        if (this.compiling) {
            throw(new Error(`style.compile(): skipping for ${this.name} because style is already compiling`));
        }
        this.compiling = true;
        this.compiled = false;

        // Build defines & for selection (need to create a new object since the first is stored as a reference by the program)
        var defines = this.buildDefineList();
        if (this.selection) {
            var selection_defines = Object.assign({}, defines);
            selection_defines['FEATURE_SELECTION'] = true;
        }

        // Get any custom code transforms, uniform dependencies, etc.
        var transforms = (this.shaders && this.shaders.transforms);
        var uniforms = (this.shaders && this.shaders.uniforms);

        // Create shaders
        try {
            this.program = new ShaderProgram(
                this.gl,
                shaderSources[this.vertex_shader_key],
                shaderSources[this.fragment_shader_key],
                {
                    name: this.name,
                    defines,
                    uniforms,
                    transforms
                }
            );

            if (this.selection) {
                this.selection_program = new ShaderProgram(
                    this.gl,
                    shaderSources[this.vertex_shader_key],
                    shaderSources['gl/shaders/selection_fragment'],
                    {
                        name: (this.name + ' (selection)'),
                        defines: selection_defines,
                        uniforms,
                        transforms
                    }
                );
            }
            else {
                this.selection_program = null;
            }
        }
        catch(error) {
            this.compiling = false;
            this.compiled = false;
            throw(new Error(`style.compile(): style ${this.name} error:`, error));
        }

        this.compiling = false;
        this.compiled = true;
    },

    // Add a shader transform
    addShaderTransform (key, ...transforms) {
        this.shaders.transforms = this.shaders.transforms || {};
        this.shaders.transforms[key] = this.shaders.transforms[key] || [];
        this.shaders.transforms[key].push(...transforms);
    },

    /** TODO: could probably combine and generalize this with similar method in ShaderProgram
     * (list of define objects that inherit from each other)
     */
    buildDefineList () {
        // Add any custom defines to built-in style defines
        var defines = {}; // create a new object to avoid mutating a prototype value that may be shared with other styles
        if (this.defines != null) {
            for (var d in this.defines) {
                defines[d] = this.defines[d];
            }
        }
        if (this.shaders != null && this.shaders.defines != null) {
            for (d in this.shaders.defines) {
                defines[d] = this.shaders.defines[d];
            }
        }
        return defines;

    },

    // Setup any GL state for rendering
    setup () {
        this.setUniforms();
        this.material.setupProgram(ShaderProgram.current);
    },

    // Set style uniforms on currently bound program
    setUniforms () {
        var program = ShaderProgram.current;
        if (!program) {
            return;
        }

        program.setUniforms(this.shaders && this.shaders.uniforms, true); // reset texture unit to 0
    },

    update () {
        // Style-specific animation
        // if (typeof this.animation === 'function') {
        //     this.animation();
        // }
    }
};
<commit_msg>add remove and replace transform methods for styles<commit_after>// Rendering styles

import {StyleParser} from './style_parser';
import FeatureSelection from '../selection';
import ShaderProgram from '../gl/shader_program';
import VBOMesh from '../gl/vbo_mesh';
import Builders from './builders';
import Texture from '../gl/texture';
import Material from '../material';
import {MethodNotImplemented} from '../utils/errors';
import shaderSources from '../gl/shader_sources'; // built-in shaders

import log from 'loglevel';

// Base class

export var Style = {
    init () {
        if (this.initialized) {
            return;
        }

        if (!this.isBuiltIn()) {
            this.built_in = false; // explicitly set to false to avoid any confusion
        }

        this.defines = this.defines || {};          // #defines to be injected into the shaders
        this.shaders = this.shaders || {};          // shader customization via scene definition (uniforms, defines, blocks, etc.)
        this.selection = this.selection || false;   // flag indicating if this style supports feature selection
        this.compiling = false;                     // programs are currently compiling
        this.compiled = false;                      // programs are finished compiling
        this.program = null;                        // GL program reference (for main render pass)
        this.selection_program = null;              // GL program reference for feature selection render pass
        this.feature_style = {};                    // style for feature currently being parsed, shared to lessen GC/memory thrash
        this.textures = this.textures || {};

        this.material = new Material();
        this.material.inject(this);

        this.initialized = true;
    },

    destroy () {
        if (this.program) {
            this.program.destroy();
            this.program = null;
        }

        if (this.selection_program) {
            this.selection_program.destroy();
            this.selection_program = null;
        }

        this.gl = null;
        this.initialized = false;
    },

    isBuiltIn () {
        return this.hasOwnProperty('built_in') && this.built_in;
    },

    /*** Style parsing and geometry construction ***/

    // Returns an object to hold feature data (for a tile or other object)
    startData () {
        return {
            vertex_data: null,
            uniforms: null,
            order: { min: Infinity, max: -Infinity } // reset to track order range within tile
        };
    },

    // Finalizes an object holding feature data (for a tile or other object)
    endData (tile_data) {
        if (tile_data.vertex_data) {
            // Only keep final byte buffer
            tile_data.vertex_data.end();
            tile_data.vertex_data = tile_data.vertex_data.buffer;
        }
        return Promise.resolve(tile_data);
    },

    addFeature (feature, rule, context, tile_data) {
        let style = this.parseFeature(feature, rule, context);

        // Skip feature?
        if (!style) {
            return;
        }

        // Track min/max order range
        if (style.order < tile_data.order.min) {
            tile_data.order.min = style.order;
        }
        if (style.order > tile_data.order.max) {
            tile_data.order.max = style.order;
        }

        // First feature in this render style?
        if (!tile_data.vertex_data) {
            tile_data.vertex_data = this.vertex_layout.createVertexData();
        }

        this.buildGeometry(feature.geometry, style, tile_data.vertex_data);
    },

    buildGeometry (geometry, style, vertex_data) {
        if (geometry.type === 'Polygon') {
            this.buildPolygons([geometry.coordinates], style, vertex_data);
        }
        else if (geometry.type === 'MultiPolygon') {
            this.buildPolygons(geometry.coordinates, style, vertex_data);
        }
        else if (geometry.type === 'LineString') {
            this.buildLines([geometry.coordinates], style, vertex_data);
        }
        else if (geometry.type === 'MultiLineString') {
            this.buildLines(geometry.coordinates, style, vertex_data);
        }
        else if (geometry.type === 'Point') {
            this.buildPoints([geometry.coordinates], style, vertex_data);
        }
        else if (geometry.type === 'MultiPoint') {
            this.buildPoints(geometry.coordinates, style, vertex_data);
        }
    },

    parseFeature (feature, rule_style, context) {
        try {
            var style = this.feature_style;

            // Calculate order if it was not cached
            style.order = rule_style.order;
            if (typeof style.order !== 'number') {
                style.order = StyleParser.calculateOrder(style.order, context);
            }

            // Feature selection (only if style supports it)
            var selectable = false;
            style.interactive = rule_style.interactive;
            if (this.selection) {
                if (typeof style.interactive === 'function') {
                    selectable = style.interactive(context);
                }
                else {
                    selectable = style.interactive;
                }
            }

            // If feature is marked as selectable
            if (selectable) {
                style.selection_color = FeatureSelection.makeColor(feature);
            }
            else {
                style.selection_color = FeatureSelection.defaultColor;
            }

            // Subclass implementation
            this._parseFeature(feature, rule_style, context);

            return style;
        }
        catch(error) {
            log.error('Style.parseFeature: style parsing error', feature, error);
        }
    },

    _parseFeature (feature, rule_style, context) {
        throw new MethodNotImplemented('_parseFeature');
    },

    // Build functions are no-ops until overriden
    buildPolygons () {},
    buildLines () {},
    buildPoints () {},

    /*** Texture management ***/

    // Prefix texture name with style name
    textureName (name) {
        return this.name + '_' + name;
    },

    setupTextureUniforms () {
        var num_textures = Object.keys(this.textures).length;

        // Set a default texture flag
        if (this.textures.default) {
            this.defines['HAS_DEFAULT_TEXTURE'] = true;
        }

        // Provide a built-in uniform array of textures
        if (num_textures > 0) {
            var tex_id = 0;
            this.defines['NUM_TEXTURES'] = num_textures.toString(); // force string to avoid auto-conversion to float
            this.shaders.uniforms = this.shaders.uniforms || {};
            this.shaders.uniforms.u_textures = [];

            for (var name in this.textures) {
                var texture = this.textures[name];
                texture.name = this.textureName(name);
                texture.id = tex_id++; // give every texture a unique id local to this style

                // Consistently map named textures to the same array index in the texture uniform
                this.shaders.uniforms.u_textures[texture.id] = texture.name;

                // Provide a #define mapping each texture back to its name in the stylesheet
                this.defines[`texture_${name}`] = `u_textures[${texture.id}]`;
            }
        }
    },

    // Preload any textures with explicit configuration in the 'textures' field
    // (textures can also be initialized on the fly via uniform setters if they don't require any additional configuration)
    // NOTE: this is only run in the main thread, since workers don't use any GL resources
    preloadTextures () {
        if (this.textures) {
            for (var name in this.textures) {
                var { url, filtering, repeat, sprites } = this.textures[name];
                var texture = new Texture(this.gl, this.textureName(name), { sprites });

                texture.load(url, { filtering, repeat });
            }
        }
    },

    // Pre-calc sprite regions for a texture sprite in UV [0, 1] space
    calculateTextureSprites (name) {
        var texture = Texture.textures[this.textureName(name)];
        if (texture.sprites) {
            this.texture_sprites = this.texture_sprites || {};
            this.texture_sprites[name] = {};

            for (var s in texture.sprites) {
                var sprite = texture.sprites[s];

                // Map [0, 0] to [1, 1] coords to the appropriate sprite sub-area of the texture
                this.texture_sprites[name][s] = Builders.getTexcoordsForSprite(
                    [sprite[0], sprite[1]],
                    [sprite[2], sprite[3]],
                    [texture.width, texture.height]
                );
            }
        }
    },

    // Set optional scale to use for texture coordinates (default is [0, 1])
    setTexcoordScale (style) {
        // Get sprite sub-area if necessary
        if (this.textures && style.sprite) {
            // Use default texture if available, otherwise texture must be specified
            var tex;
            if (this.textures.default) {
                tex = 'default';
            }
            else {
                tex = style.texture;
            }

            if (!tex) {
                log.error(`Style: in style '${this.name}', must specify texture to use for sprite '${style.sprite}', must be one of [${Object.keys(this.textures).join(', ')}]`);
            }
            else {
                // Lazily calculate sprite UVs the first time they are encountered
                if (!this.texture_sprites || !this.texture_sprites[tex]) {
                    this.calculateTextureSprites(tex);
                }
                this.texcoord_scale = this.texture_sprites[tex] && this.texture_sprites[tex][style.sprite];
            }
        }
    },

    /*** GL state and rendering ***/

    setGL (gl) {
        this.gl = gl;
        this.setupTextureUniforms();
        this.preloadTextures();
    },

    makeMesh (vertex_data, { uniforms } = {}) {
        return new VBOMesh(this.gl, vertex_data, this.vertex_layout, { uniforms });
    },

    compile () {
        if (!this.gl) {
            throw(new Error(`style.compile(): skipping for ${this.name} because no GL context`));
        }

        if (this.compiling) {
            throw(new Error(`style.compile(): skipping for ${this.name} because style is already compiling`));
        }
        this.compiling = true;
        this.compiled = false;

        // Build defines & for selection (need to create a new object since the first is stored as a reference by the program)
        var defines = this.buildDefineList();
        if (this.selection) {
            var selection_defines = Object.assign({}, defines);
            selection_defines['FEATURE_SELECTION'] = true;
        }

        // Get any custom code transforms, uniform dependencies, etc.
        var transforms = (this.shaders && this.shaders.transforms);
        var uniforms = (this.shaders && this.shaders.uniforms);

        // Create shaders
        try {
            this.program = new ShaderProgram(
                this.gl,
                shaderSources[this.vertex_shader_key],
                shaderSources[this.fragment_shader_key],
                {
                    name: this.name,
                    defines,
                    uniforms,
                    transforms
                }
            );

            if (this.selection) {
                this.selection_program = new ShaderProgram(
                    this.gl,
                    shaderSources[this.vertex_shader_key],
                    shaderSources['gl/shaders/selection_fragment'],
                    {
                        name: (this.name + ' (selection)'),
                        defines: selection_defines,
                        uniforms,
                        transforms
                    }
                );
            }
            else {
                this.selection_program = null;
            }
        }
        catch(error) {
            this.compiling = false;
            this.compiled = false;
            throw(new Error(`style.compile(): style ${this.name} error:`, error));
        }

        this.compiling = false;
        this.compiled = true;
    },

    // Add a shader transform
    addShaderTransform (key, ...transforms) {
        this.shaders.transforms = this.shaders.transforms || {};
        this.shaders.transforms[key] = this.shaders.transforms[key] || [];
        this.shaders.transforms[key].push(...transforms);
    },

    // Remove all shader transforms for key
    removeShaderTransform (key) {
        if (this.shaders.transforms) {
            this.shaders.transforms[key] = null;
        }
    },

    replaceShaderTransform (key, ...transforms) {
        this.removeShaderTransform(key);
        this.addShaderTransform(key, ...transforms);
    },

    /** TODO: could probably combine and generalize this with similar method in ShaderProgram
     * (list of define objects that inherit from each other)
     */
    buildDefineList () {
        // Add any custom defines to built-in style defines
        var defines = {}; // create a new object to avoid mutating a prototype value that may be shared with other styles
        if (this.defines != null) {
            for (var d in this.defines) {
                defines[d] = this.defines[d];
            }
        }
        if (this.shaders != null && this.shaders.defines != null) {
            for (d in this.shaders.defines) {
                defines[d] = this.shaders.defines[d];
            }
        }
        return defines;

    },

    // Setup any GL state for rendering
    setup () {
        this.setUniforms();
        this.material.setupProgram(ShaderProgram.current);
    },

    // Set style uniforms on currently bound program
    setUniforms () {
        var program = ShaderProgram.current;
        if (!program) {
            return;
        }

        program.setUniforms(this.shaders && this.shaders.uniforms, true); // reset texture unit to 0
    },

    update () {
        // Style-specific animation
        // if (typeof this.animation === 'function') {
        //     this.animation();
        // }
    }
};
<|endoftext|>


<commit_before>var
  AWS = require("aws-sdk"),
  awsRegion = "us-west-2",
  sqs = {},
  Hapi = require('hapi'),
  Good = require('good'),
  queueUri = 'https://sqs.us-west-2.amazonaws.com/621392439615/a_sample';

var server = new Hapi.Server(process.env.PORT || 3000);

server.route({
  method: 'GET',
  path: '/',
  handler: function (request, reply) {
    reply('Hello, world!');
  }
});

function sendSqsMessage(nameParam) {
  "use strict";

  AWS.config.update({
    accessKeyId: process.env.AWS_ACCESS_KEY_ID,
    secretAccessKey: process.env.AWS_SECRET_KEY,
    region: awsRegion
  });
  sqs = new AWS.SQS();

  var params = {
    MessageBody: "Hello " + nameParam,
    QueueUrl: queueUri,
    DelaySeconds: 0
  };

  sqs.sendMessage(params, function (err, data) {
    if (err) {
      server.log("Error: ", err);
    } // an error occurred
    else {
      server.log('Victory, message sent for ' + encodeURIComponent(request.params.name) + '!');
    };
  });
}

server.route({
  method: 'GET',
  path: '/{name}',
  handler: function (request, reply) {
    sendSqsMessage(encodeURIComponent(request.params.name));
    reply('Your message ' + encodeURIComponent(request.params.name) + ' has been sent to queue!');
  }
});

server.pack.register(Good, function (err) {
  if (err) {
    throw err; // something bad happened loading the plugin
  }

  server.start(function () {
    server.log('info', 'Server running at: ' + server.info.uri);
  });
});
<commit_msg>Updated queue URI.<commit_after>var
  AWS = require("aws-sdk"),
  awsRegion = "us-west-2",
  sqs = {},
  Hapi = require('hapi'),
  Good = require('good'),
  queueUri = 'https://sqs.us-west-2.amazonaws.com/621392439615/sample';

var server = new Hapi.Server(process.env.PORT || 3000);

server.route({
  method: 'GET',
  path: '/',
  handler: function (request, reply) {
    reply('Hello, world!');
  }
});

function sendSqsMessage(nameParam) {
  "use strict";

  AWS.config.update({
    accessKeyId: process.env.AWS_ACCESS_KEY_ID,
    secretAccessKey: process.env.AWS_SECRET_KEY,
    region: awsRegion
  });
  sqs = new AWS.SQS();

  var params = {
    MessageBody: "Hello " + nameParam,
    QueueUrl: queueUri,
    DelaySeconds: 0
  };

  sqs.sendMessage(params, function (err, data) {
    if (err) {
      server.log("Error: ", err);
    } // an error occurred
    else {
      server.log('Victory, message sent for ' + encodeURIComponent(request.params.name) + '!');
    };
  });
}

server.route({
  method: 'GET',
  path: '/{name}',
  handler: function (request, reply) {
    sendSqsMessage(encodeURIComponent(request.params.name));
    reply('Your message ' + encodeURIComponent(request.params.name) + ' has been sent to queue!');
  }
});

server.pack.register(Good, function (err) {
  if (err) {
    throw err; // something bad happened loading the plugin
  }

  server.start(function () {
    server.log('info', 'Server running at: ' + server.info.uri);
  });
});
<|endoftext|>