<commit_before>/*jslint
 browser  : true,
 continue : true,
 devel    : true,
 indent   : 2,
 maxerr   : 50,
 nomen    : true,
 plusplus : true,
 regexp   : true,
 vars     : true,
 white    : true,
 todo     : true,
 node     : true
 */
'use strict';

var https = require('https');
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var port = process.env.PORT || 3000;
// var Translator = require('naver-translator');
var MsTranslator = require('mstranslator');

var ZH_CH = 'zh-CN';
var KO_KR = 'ko';
// var CLIENT_ID = process.env.NAVER_CLIENT_ID;
// var CLIENT_SECRET = process.env.NAVER_CLIENT_SECRET;
// var SEC_CLIENT_ID = process.env.NAVER_CLIENT_ID_2;
// var SEC_CLIENT_SECRET = process.env.NAVER_CLIENT_SECRET_2;
var MS_CLIENT_ID = process.env.MS_CLIENT_ID;
var MS_CLIENT_SECRET = process.env.MS_CLIENT_SECRET;

server.listen(port, function () {
  console.log('Server listening at port %d', port);
});

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

// Chatroom

var numUsers = 0;

io.on('connection', function (socket) {
  var addedUser = false;

  // when the client emits 'new message', this listens and executes
  socket.on('new message', function (/** @type {String} */data) {
    // we tell the client to execute 'new message'

    var koreanReg = /[가-힣]/g;
    // var chineseReg = /[\u4e00-\u9fa5]*/g;
    // var source = KO_KR;
    // var target = ZH_CH;
    var translateAvailable = true;

    if (koreanReg.test(data)) {
      // source = KO_KR;
      // target = ZH_CH;
      translateAvailable = false;
    }

    if (translateAvailable) {
      console.log('Use MS Translator');
      var translator = new MsTranslator({
        client_id : MS_CLIENT_ID,
        client_secret : MS_CLIENT_SECRET
      }, true);
      translator.detect({
          text : data
        },
        /**
         * @param {Object} error
         * @param {String} detectedResult
         */
        function (error, detectedResult) {
          if (error) {
            console.log('Language detect error', error);
          } else {
            console.log('Translator detected language : ', detectedResult);

            translator.translate({
              text : data, from : detectedResult, to : KO_KR
            }, function (error, translatedResult) {
              if (error) {
                console.log('Translate error', error);
              } else {
                console.log('Translated result : ', translatedResult);
                socket.broadcast.emit('new message', {
                  username : socket.username,
                  message : translatedResult + ' [ ' + data + ' ]'
                });
                socket.emit('new message', {
                  username : socket.username,
                  message : '[' + data + ']'
                });
              }
            });
          }
        });
    } else {
      console.log('no translate', data);
      socket.broadcast.emit('new message', {
        username : socket.username,
        message : data
      });
    }
  });

  // when the client emits 'add user', this listens and executes
  socket.on('add user', function (userData) {
    if (addedUser) {
      return;
    }

    // we store the username in the socket session for this client
    socket.username = userData.username;
    ++numUsers;
    addedUser = true;
    socket.emit('login', {
      numUsers : numUsers
    });
    // echo globally (all clients) that a person has connected
    socket.broadcast.emit('user joined', {
      username : socket.username,
      numUsers : numUsers
    });
  });

  // when the client emits 'typing', we broadcast it to others
  socket.on('typing', function () {
    socket.broadcast.emit('typing', {
      username : socket.username
    });
  });

  // when the client emits 'stop typing', we broadcast it to others
  socket.on('stop typing', function () {
    socket.broadcast.emit('stop typing', {
      username : socket.username
    });
  });

  // when the user disconnects.. perform this
  socket.on('disconnect', function () {
    if (addedUser) {
      --numUsers;

      // echo globally that this client has left
      socket.broadcast.emit('user left', {
        username : socket.username,
        numUsers : numUsers
      });
    }
  });
});
<commit_msg>내가 입력한 외국어가 나에게는 번역된것이 나와야 하는데 잘못 출력되는 문제 해결<commit_after>/*jslint
 browser  : true,
 continue : true,
 devel    : true,
 indent   : 2,
 maxerr   : 50,
 nomen    : true,
 plusplus : true,
 regexp   : true,
 vars     : true,
 white    : true,
 todo     : true,
 node     : true
 */
'use strict';

var https = require('https');
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var port = process.env.PORT || 3000;
// var Translator = require('naver-translator');
var MsTranslator = require('mstranslator');

var ZH_CH = 'zh-CN';
var KO_KR = 'ko';
// var CLIENT_ID = process.env.NAVER_CLIENT_ID;
// var CLIENT_SECRET = process.env.NAVER_CLIENT_SECRET;
// var SEC_CLIENT_ID = process.env.NAVER_CLIENT_ID_2;
// var SEC_CLIENT_SECRET = process.env.NAVER_CLIENT_SECRET_2;
var MS_CLIENT_ID = process.env.MS_CLIENT_ID;
var MS_CLIENT_SECRET = process.env.MS_CLIENT_SECRET;

server.listen(port, function () {
  console.log('Server listening at port %d', port);
});

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

// Chatroom

var numUsers = 0;

io.on('connection', function (socket) {
  var addedUser = false;

  // when the client emits 'new message', this listens and executes
  socket.on('new message', function (/** @type {String} */data) {
    // we tell the client to execute 'new message'

    var koreanReg = /[가-힣]/g;
    // var chineseReg = /[\u4e00-\u9fa5]*/g;
    // var source = KO_KR;
    // var target = ZH_CH;
    var translateAvailable = true;

    if (koreanReg.test(data)) {
      // source = KO_KR;
      // target = ZH_CH;
      translateAvailable = false;
    }

    if (translateAvailable) {
      console.log('Use MS Translator');
      var translator = new MsTranslator({
        client_id : MS_CLIENT_ID,
        client_secret : MS_CLIENT_SECRET
      }, true);
      translator.detect({
          text : data
        },
        /**
         * @param {Object} error
         * @param {String} detectedResult
         */
        function (error, detectedResult) {
          if (error) {
            console.log('Language detect error', error);
          } else {
            console.log('Translator detected language : ', detectedResult);

            translator.translate({
              text : data, from : detectedResult, to : KO_KR
            }, function (error, translatedResult) {
              if (error) {
                console.log('Translate error', error);
              } else {
                console.log('Translated result : ', translatedResult);
                socket.broadcast.emit('new message', {
                  username : socket.username,
                  message : translatedResult + ' [ ' + data + ' ]'
                });
                socket.emit('new message', {
                  username : socket.username,
                  message : '번역 : [' + translatedResult + ']'
                });
              }
            });
          }
        });
    } else {
      console.log('no translate', data);
      socket.broadcast.emit('new message', {
        username : socket.username,
        message : data
      });
    }
  });

  // when the client emits 'add user', this listens and executes
  socket.on('add user', function (userData) {
    if (addedUser) {
      return;
    }

    // we store the username in the socket session for this client
    socket.username = userData.username;
    ++numUsers;
    addedUser = true;
    socket.emit('login', {
      numUsers : numUsers
    });
    // echo globally (all clients) that a person has connected
    socket.broadcast.emit('user joined', {
      username : socket.username,
      numUsers : numUsers
    });
  });

  // when the client emits 'typing', we broadcast it to others
  socket.on('typing', function () {
    socket.broadcast.emit('typing', {
      username : socket.username
    });
  });

  // when the client emits 'stop typing', we broadcast it to others
  socket.on('stop typing', function () {
    socket.broadcast.emit('stop typing', {
      username : socket.username
    });
  });

  // when the user disconnects.. perform this
  socket.on('disconnect', function () {
    if (addedUser) {
      --numUsers;

      // echo globally that this client has left
      socket.broadcast.emit('user left', {
        username : socket.username,
        numUsers : numUsers
      });
    }
  });
});
<|endoftext|>


<commit_before>$(document).ready(function () {

    $.getJSON("/api/getQuote", function (data) {
        $(".quote").text(data[0].summary);
    });

    if (typeof $API === "undefined") {
        alert("Load this page into Johnny's Webview");
        return;
    }

    $(".close").on("click", $API.closeWindow);

    /* drag */
    var initialPos = {};
    var drag = false;
    $(".drag").on("mousedown", function (e) {
        drag = true;
        initialPos.x = e.pageX;
        initialPos.y = e.pageY;
    }).on("mousemove", function (e) {

        if (!drag) { return; }

        var current = $API.getWindowPosition();
        var winLeft, winTop;

        winLeft = current.left + (e.pageX - initialPos.x);
        winTop  = current.top + (e.pageY- initialPos.y);

        $API.setWindowPosition(winLeft, winTop);
    });

    $("body").on("mouseout mouseup", function () {
        drag = false;
        initial = {};
    });
});
<commit_msg>Update the quote.<commit_after>$(document).ready(function () {

    function updateQuote () {
        $.getJSON("/api/getQuote", function (data) {
            $(".quote").text(data[0].summary);
        });
    }

    updateQuote();
    setInterval(function () {
        updateQuote ();
    }, 20000);

    if (typeof $API === "undefined") {
        alert("Load this page into Johnny's Webview");
        return;
    }

    $(".close").on("click", $API.closeWindow);

    /* drag */
    var initialPos = {};
    var drag = false;
    $(".drag").on("mousedown", function (e) {
        drag = true;
        initialPos.x = e.pageX;
        initialPos.y = e.pageY;
    }).on("mousemove", function (e) {

        if (!drag) { return; }

        var current = $API.getWindowPosition();
        var winLeft, winTop;

        winLeft = current.left + (e.pageX - initialPos.x);
        winTop  = current.top + (e.pageY- initialPos.y);

        $API.setWindowPosition(winLeft, winTop);
    });

    $("body").on("mouseout mouseup", function () {
        drag = false;
        initial = {};
    });
});
<|endoftext|>


<commit_before>'use babel';

//import express from 'express'
var {allowUnsafeEval, allowUnsafeNewFunction} = require('loophole');
var _ = require('lodash');
var jsonutil = require('jsonutil');
var express = allowUnsafeEval(() => require('express'));
var bodyParser =  allowUnsafeEval(() => require('body-parser'));
var expressApp = express();
expressApp.use(bodyParser.json());
var http = require('http').Server(expressApp);
var io ;

export default class vMOTIF {

  constructor(eventBus){
    this.eventBus = eventBus;
    this.schemaMap = {};
    this.socketList = [];
    this.httpSockets = [];
    this.jsonSchemas = {};
    console.log("vMOTIF created with EventBus=" + eventBus);
  }

  isRunning(){
    return http.listening;
  }

  initialize(){
  }

  registerSchema(schema){
    console.log("Registering schema...");
  }

  unregisterSchema(schema){
    console.log("Unregistering schema...");

  }

  walkSync(dir, filelist) {
    var that = this;
    var fs = fs || require('fs'),
        files = fs.readdirSync(dir);
    filelist = filelist || [];
    files.forEach(function(file) {
      if (fs.statSync(dir + '/' + file).isDirectory()) {
        filelist = that.walkSync(dir + '/' + file, filelist);
      }
      else {
        if (that.fileExtension(file)==="mam"){
          filelist.push(dir + '/' + file);
        }
      }
    });
    return filelist;
  }

  fileExtension(fileName){
    var parts = _.split(fileName, ".");
    if (parts && parts.length > 0){
      return parts[parts.length-1];
    }
  }

  start(){
    console.log("Starting...");
    var that=this;

    this.jsonSchemas = {};
    //Get the list of current project MAM files
    console.log("Loading project files...");
    var projectFolders = atom.project.getPaths();
    var fileList = this.walkSync(projectFolders[0]);
    for (i=0;i<fileList.length;i++){
      try {
        var jsonSchema = jsonutil.readFileSync(fileList[i]);
        this.jsonSchemas[jsonSchema.uri] = jsonSchema;
      } catch (e){
        console.log("Error loading file " + fileList[i] + ": " + e);
      }
    }

    expressApp.post('/json', function(request,res){
      console.log("MOTIF request "+ request.body);
      try {
        var dom = request.body.req.dom;
        var app = request.body.req.app;
        var srv = request.body.req.srv;
        var op = request.body.req.op;
        var uri = "/" + dom + "/" + app + "/" + srv + "/" + op;
        if (that.jsonSchemas[uri] && that.jsonSchemas[uri].response){
          var reqSchemaResponseExample = that.jsonSchemas[uri].response.example;
          if (reqSchemaResponseExample){
            var jsonResp = {
                "dom" : dom,
                "app" : app,
                "srv" : srv,
                "op" : op,
                "header" : reqSchemaResponseExample
            };
            res.json(jsonResp);
          } else {
            res.status(500).send('Operation ' + uri +' example not defined');
          }
        } else {
          res.status(500).send('Operation ' + uri +' not defined');
        }
      } catch (e) {
        res.status(500).send('Invalid protocol: ' + e);
      }
    });

    http.on('connection',function(socket){
      var thisSocket = socket;
      console.log('HTTP socket opened ' + socket);
      that.httpSockets.push(socket);

      // Remove the socket when it closes
      thisSocket.on('close', function () {
        console.log('HTTP socket closed ' + that.thisSocket);
        delete that.thisSocket;
        that.httpSockets.splice(that.httpSockets.indexOf(socket), 1);
      });

    });

    var port = atom.config.get('motif-mam-tools.MockServerPort');
    http.listen(port, function(){
      console.log('VMOTIF listening on port ' + http.address().port);
      that.eventBus.publish("VMOTIF_STARTED", { 'status' : 'started'});
    });
  }

  stop(){
    console.log("Stopping VMOTIF...");
    this.httpSockets.forEach(function(socket){
      socket.destroy();
    })
    http.close();
    this.eventBus.publish("VMOTIF_STOPPED", { 'status' : 'stopped'});
    console.log("VMOTIF stopped.");
  }

}
<commit_msg>Added request validation in VMotif<commit_after>'use babel';

//import express from 'express'
var {allowUnsafeEval, allowUnsafeNewFunction} = require('loophole');
var _ = require('lodash');
var jsonutil = require('jsonutil');
var express = allowUnsafeEval(() => require('express'));
var bodyParser =  allowUnsafeEval(() => require('body-parser'));
var expressApp = express();
expressApp.use(bodyParser.json());
var http = require('http').Server(expressApp);
var io ;

export default class vMOTIF {

  constructor(eventBus){
    this.eventBus = eventBus;
    this.schemaMap = {};
    this.socketList = [];
    this.httpSockets = [];
    this.jsonSchemas = {};
    console.log("vMOTIF created with EventBus=" + eventBus);
  }

  isRunning(){
    return http.listening;
  }

  initialize(){
  }

  registerSchema(schema){
    console.log("Registering schema...");
  }

  unregisterSchema(schema){
    console.log("Unregistering schema...");

  }

  walkSync(dir, filelist) {
    var that = this;
    var fs = fs || require('fs'),
        files = fs.readdirSync(dir);
    filelist = filelist || [];
    files.forEach(function(file) {
      if (fs.statSync(dir + '/' + file).isDirectory()) {
        filelist = that.walkSync(dir + '/' + file, filelist);
      }
      else {
        if (that.fileExtension(file)==="mam"){
          filelist.push(dir + '/' + file);
        }
      }
    });
    return filelist;
  }

  fileExtension(fileName){
    var parts = _.split(fileName, ".");
    if (parts && parts.length > 0){
      return parts[parts.length-1];
    }
  }

  start(){
    console.log("Starting...");
    var that=this;

    this.jsonSchemas = {};
    //Get the list of current project MAM files
    console.log("Loading project files...");
    var projectFolders = atom.project.getPaths();
    var fileList = this.walkSync(projectFolders[0]);
    for (i=0;i<fileList.length;i++){
      try {
        var jsonSchema = jsonutil.readFileSync(fileList[i]);
        this.jsonSchemas[jsonSchema.uri] = jsonSchema;
      } catch (e){
        console.log("Error loading file " + fileList[i] + ": " + e);
      }
    }

    expressApp.post('/json', function(request,res){
      console.log("MOTIF request "+ request.body);
      try {
        var dom = request.body.req.dom;
        var app = request.body.req.app;
        var srv = request.body.req.srv;
        var op = request.body.req.op;
        var header = request.body.req.header;
        var uri = "/" + dom + "/" + app + "/" + srv + "/" + op;
        if (that.jsonSchemas[uri]){
          var requestSchema = that.jsonSchemas[uri];

           var mamRequestSchema =  require("./schemas/motif.request.schema.json");
          //validate the request
          var Ajv = require('ajv');
          var ajv = new Ajv(); // options can be passed, e.g. {allErrors: true}
          allowUnsafeEval(() => allowUnsafeNewFunction(() => ajv.addSchema(mamRequestSchema, mamRequestSchema.id)));
          allowUnsafeEval(() => allowUnsafeNewFunction(() => ajv.addSchema(requestSchema, "__temp")));
          var valid = allowUnsafeEval(() => allowUnsafeNewFunction(() => ajv.validate('__temp', header)));
          if (valid){
            if (requestSchema.response && requestSchema.response.example){
              var jsonResp = {
                  "dom" : dom,
                  "app" : app,
                  "srv" : srv,
                  "op" : op,
                  "header" : requestSchema.response.example
              };
              res.json(jsonResp);
            } else {
              res.status(500).send('Operation ' + uri +' response example not defined');
            }
          } else {
            res.status(500).send('Invalid request (schema validation error): ' + ajv.errorsText());
          }
          ajv.removeSchema("__temp");
          ajv.removeSchema(mamRequestSchema.id);
          ajv = undefined;
        } else {
          res.status(500).send('Operation ' + uri +' not defined');
        }

        /**
        if (that.jsonSchemas[uri] && that.jsonSchemas[uri].response){
          var reqSchemaResponseExample = that.jsonSchemas[uri].response.example;
          if (reqSchemaResponseExample){
            var jsonResp = {
                "dom" : dom,
                "app" : app,
                "srv" : srv,
                "op" : op,
                "header" : reqSchemaResponseExample
            };
            res.json(jsonResp);
          } else {
            res.status(500).send('Operation ' + uri +' example not defined');
          }
        } else {
          res.status(500).send('Operation ' + uri +' not defined');
        }
        **/
      } catch (e) {
        res.status(500).send('Invalid protocol: ' + e);
      }
    });

    http.on('connection',function(socket){
      var thisSocket = socket;
      console.log('HTTP socket opened ' + socket);
      that.httpSockets.push(socket);

      // Remove the socket when it closes
      thisSocket.on('close', function () {
        console.log('HTTP socket closed ' + that.thisSocket);
        delete that.thisSocket;
        that.httpSockets.splice(that.httpSockets.indexOf(socket), 1);
      });

    });

    var port = atom.config.get('motif-mam-tools.MockServerPort');
    http.listen(port, function(){
      console.log('VMOTIF listening on port ' + http.address().port);
      that.eventBus.publish("VMOTIF_STARTED", { 'status' : 'started'});
    });
  }

  stop(){
    console.log("Stopping VMOTIF...");
    this.httpSockets.forEach(function(socket){
      socket.destroy();
    })
    http.close();
    this.eventBus.publish("VMOTIF_STOPPED", { 'status' : 'stopped'});
    console.log("VMOTIF stopped.");
  }

}
<|endoftext|>


<commit_before>var _redirect = function(paths){
  var path = paths.shift();
  if (!path) {
    return;
  }

  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function(){
    if(xhr.readyState == 4) {
      if(xhr.status == 200) {
        location.href = path;
      } else {
        if(paths) {
          _redirect(paths);
        }
      }
    }
  };
  xhr.open("GET", path, true);
  xhr.send();
};
_redirect([
  "/0.3.2/index.html",
  "/dist/index.html"
]);
<commit_msg>fix: initial version<commit_after>var _redirect = function(paths){
  var path = paths.shift();
  if (!path) {
    return;
  }

  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function(){
    if(xhr.readyState == 4) {
      if(xhr.status == 200) {
        location.href = path;
      } else {
        if(paths) {
          _redirect(paths);
        }
      }
    }
  };
  xhr.open("GET", path, true);
  xhr.send();
};
_redirect([
  "/0.3.3/index.html",
  "/dist/index.html"
]);
<|endoftext|>


<commit_before>var http = require('http');
var express = require('express');
var path = require('path');

var favicon = require('serve-favicon');
var logger = require('morgan');
var methodOverride = require('method-override');
var bodyParser = require('body-parser');
var multer = require('multer');
var errorHandler = require('errorhandler');

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(favicon(__dirname + '/public/images/star200.png'));
app.use(logger('dev'));
app.use(methodOverride());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(multer());
app.use(express.static(path.join(__dirname, 'public')));

// error handling middleware should be loaded after the loading the routes
if ('development' == app.get('env')) {
  app.use(errorHandler());
}

app.get('/', function(req,res) {
  console.log('TREEEEES!')
  res.sendfile("./public/treeworker.html");
});

var server = http.createServer(app);
server.listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});<commit_msg>Index route fixed<commit_after>var http = require('http');
var express = require('express');
var path = require('path');

var favicon = require('serve-favicon');
var logger = require('morgan');
var methodOverride = require('method-override');
var bodyParser = require('body-parser');
var multer = require('multer');
var errorHandler = require('errorhandler');

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(favicon(__dirname + '/public/images/star200.png'));
app.use(logger('dev'));
app.use(methodOverride());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(multer());
app.use(express.static(path.join(__dirname, 'public')));

// error handling middleware should be loaded after the loading the routes
if ('development' == app.get('env')) {
  app.use(errorHandler());
}

var server = http.createServer(app);
server.listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});<|endoftext|>


<commit_before>/*
  index.js
*/

$(document).ready(function() {

  // Assume root data source endpoint is local unless explicitly overridden.
  // This makes local front-end dev/test a bit easier from my laptop.
  //
  window.dataSourceUrl = location.origin;
  if($.urlParam('dataSourceUrl')) {
    window.dataSourceUrl = $.urlParam('dataSourceUrl');
  }

  initGauges();
  initHistory();

  // Initiate websocket connection for sensor and location updates
  //
  (function websocketConnect() {
    var host = window.dataSourceUrl.replace(/^http/, 'ws');
    console.log('Websocket host:', host);
    var ws = new WebSocket(host);
    ws.onmessage = function(event) {
      var eventData = JSON.parse(event.data);

      switch(eventData.id) {
        case 1:
          //console.log('Received new sensor data:', eventData.data);
          $.sensorData = eventData.data;
          drawGauges(eventData.data);
          updateMap();
          $('#node-version').text(eventData.data.app.engine);
          $('#raw-data-json').text(JSON.stringify(eventData.data, null, 2));
          break;

        case 2:
          //console.log('Received new location data:', eventData.data);
          $('#raw-location-json').text(JSON.stringify(eventData.data, null, 2));
        break;
      }
    };
  })();

});

$.urlParam = function(name) {
  var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
  return results == null ? null : decodeURI(results[1]) || null;
}
<commit_msg>remove debug line<commit_after>/*
  index.js
*/

$(document).ready(function() {

  // Assume root data source endpoint is local unless explicitly overridden.
  // This makes local front-end dev/test a bit easier from my laptop.
  //
  window.dataSourceUrl = location.origin;
  if($.urlParam('dataSourceUrl')) {
    window.dataSourceUrl = $.urlParam('dataSourceUrl');
  }

  initGauges();
  initHistory();

  // Initiate websocket connection for sensor and location updates
  //
  (function websocketConnect() {
    var host = window.dataSourceUrl.replace(/^http/, 'ws');
    //console.log('Websocket host:', host);
    var ws = new WebSocket(host);
    ws.onmessage = function(event) {
      var eventData = JSON.parse(event.data);

      switch(eventData.id) {
        case 1:
          //console.log('Received new sensor data:', eventData.data);
          $.sensorData = eventData.data;
          drawGauges(eventData.data);
          updateMap();
          $('#node-version').text(eventData.data.app.engine);
          $('#raw-data-json').text(JSON.stringify(eventData.data, null, 2));
          break;

        case 2:
          //console.log('Received new location data:', eventData.data);
          $('#raw-location-json').text(JSON.stringify(eventData.data, null, 2));
        break;
      }
    };
  })();

});

$.urlParam = function(name) {
  var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
  return results == null ? null : decodeURI(results[1]) || null;
}
<|endoftext|>


<commit_before>var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var favicon = require('serve-favicon');
var express = require('express');
var logger = require('morgan');
var path = require('path');
var ejs = require('ejs');
var fs = require('fs');

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('.html', ejs.__express);
app.set('view engine', 'html');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

var root_path = process.argv[2];
var listFile = 'E:/list.html';
var fileTypes = 'png,jpg,gif,bmp';
var listFileContent = '<!doctype html>\n\n\n<meta charset="utf-8">\n<title>Image Files</title>\n\n\n
\n' + getAllFiles(root_path).join('\n') + '\n
\n\n';

fs.readFile(listFile, function(err, data) {

    if (err && err.errno == 33) {

        fs.open(listFile, 'w', 0666, function(e, fd) {

            if (e) { console.log(e); };

            fs.write(fd, listFileContent, 0, 'utf8', function(e) {
                if (e) { console.log(e); };
                fs.closeSync(fd);
            });

        });

    } else {

        fs.writeFile(listFile, listFileContent, function(e) {
            if (e) { console.log(e); };
            console.log('All Done, My Lord !');
        });

    };

});

function getAllFiles(root) {

    var res = [],
        files = fs.readdirSync(root);

    files.forEach(function(file) {
        var pathname = root + '/' + file;
        if ( pathname.indexOf('System Volume Information') == -1 && pathname.indexOf('$Recycle') == -1 && pathname.indexOf('.sys') == -1 && pathname.indexOf('MSOCache') == -1 && pathname.indexOf('latest_stat.xml') == -1 && pathname.indexOf('CrashReports') == -1 && pathname.indexOf('Microsoft') == -1 && pathname.indexOf('ElevatedDiagnostics') == -1 && pathname.indexOf('Windows') == -1 ) {

            var stat = fs.lstatSync(pathname);

            if (!stat.isDirectory()) {
                if (isFileType(file, fileTypes)) {
                    res.push('
' + file + '
');
                };
            } else {
                res = res.concat(getAllFiles(pathname));
            };

        };

    });

    return res;

}

function isFileType(filename, types) {
    var reg = /,/;
    types = types.split(reg);
    var pattern = '\.(';
    for (var i = 0; i < types.length; i++) {
        if (0 != i) { pattern += '|'; };
        pattern += types[i].trim();
    };
    pattern += ')$';
    return new RegExp(pattern, 'i').test(filename);
}

module.exports = app;<commit_msg>Bug Fix<commit_after>var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var favicon = require('serve-favicon');
var express = require('express');
var logger = require('morgan');
var path = require('path');
var ejs = require('ejs');
var fs = require('fs');

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('.html', ejs.__express);
app.set('view engine', 'html');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

var root_path = process.argv[2];
var listFile = 'E:/list.html';
var fileTypes = 'png,jpg,gif,bmp';
var listFileContent = '<!doctype html>\n\n\n<meta charset="utf-8">\n<title>Image Files</title>\n\n\n
\n' + getAllFiles(root_path).join('\n') + '\n
\n\n';

fs.readFile(listFile, function(err, data) {

    if (err && err.errno == 33) {

        fs.open(listFile, 'w', 0666, function(e, fd) {

            if (e) { console.log(e); };

            fs.write(fd, listFileContent, 0, 'utf8', function(e) {
                if (e) { console.log(e); };
                fs.closeSync(fd);
            });

        });

    } else {

        fs.writeFile(listFile, listFileContent, function(e) {
            if (e) { console.log(e); };
            console.log('All Done, My Lord !');
        });

    };

});

function getAllFiles(root) {

    var res = [],
        files = fs.readdirSync(root);

    files.forEach(function(file) {
        var pathname = root + '/' + file;
        if ( pathname.indexOf('System Volume Information') == -1 && pathname.indexOf('$Recycle') == -1 && pathname.indexOf('$RECYCLE') == -1 && pathname.indexOf('.sys') == -1 && pathname.indexOf('MSOCache') == -1 && pathname.indexOf('latest_stat.xml') == -1 && pathname.indexOf('CrashReports') == -1 && pathname.indexOf('Microsoft') == -1 && pathname.indexOf('ElevatedDiagnostics') == -1 && pathname.indexOf('Windows') == -1 ) {

            var stat = fs.lstatSync(pathname);

            if (!stat.isDirectory()) {
                if (isFileType(file, fileTypes)) {
                    res.push('
' + file + '
');
                };
            } else {
                res = res.concat(getAllFiles(pathname));
            };

        };

    });

    return res;

}

function isFileType(filename, types) {
    var reg = /,/;
    types = types.split(reg);
    var pattern = '\.(';
    for (var i = 0; i < types.length; i++) {
        if (0 != i) { pattern += '|'; };
        pattern += types[i].trim();
    };
    pattern += ')$';
    return new RegExp(pattern, 'i').test(filename);
}

module.exports = app;<|endoftext|>


<commit_before>window.myDay = {

};

window.myDay.loadClubs = function(target, callback) {
	window.api.get("myDay/clubs/getAll", function(data) {
		//data.clubs
		for (var clubIndex in data.clubs) {
			var club = data.clubs[clubIndex];
			var option = $('<option></option>');
				option.val(club.clubId);
				option.text(club.name);
			target.append(option);
		};
		callback();
	});
};

$(document).ready(function() {
	window.myDay.loadClubs($(".myDay-club-select"), function() {
		$(".myDay-club-select").chosen();
	});
	$("#myDay").on("tabOpened", function() {

	});
	$("#myDay-welcome-submit").click(function() {
		if ($("input[name=sleepHrs]").val().trim() == ""` || $("input[name=WakeUpTime]").val().trim() == ""` || $("input[name=Address]").val().trim() == ""`)
		{
		swal("You did something wrong, are all your forms filled out?")
		}
		else {
		swal("Yay! Now we will calculate your schedule.", "success")
		}
		var prefs = {};
		prefs.sleep = $("input[name=sleepHrs]").val();
		prefs.wake = $("input[name=WakeUpTime]").val();
		prefs.address = $("input[name=Address]").val();
		prefs.clubs = "notsureifthisworkssoimputtingastringhere";
		prefs.schoolId = 42;
		window.api.post("myDay/info/set", prefs, function(resp) {});
	});
});
<commit_msg>fix little bug<commit_after>window.myDay = {

};

window.myDay.loadClubs = function(target, callback) {
	window.api.get("myDay/clubs/getAll", function(data) {
		//data.clubs
		for (var clubIndex in data.clubs) {
			var club = data.clubs[clubIndex];
			var option = $('<option></option>');
				option.val(club.clubId);
				option.text(club.name);
			target.append(option);
		};
		callback();
	});
};

$(document).ready(function() {
	window.myDay.loadClubs($(".myDay-club-select"), function() {
		$(".myDay-club-select").chosen();
	});
	$("#myDay").on("tabOpened", function() {

	});
	$("#myDay-welcome-submit").click(function() {
		if ($("input[name=sleepHrs]").val().trim() == "" || $("input[name=WakeUpTime]").val().trim() == "" || $("input[name=Address]").val().trim() == "")
		{
		swal("You did something wrong, are all your forms filled out?")
		}
		else {
		swal("Yay! Now we will calculate your schedule.", "success")
		}
		var prefs = {};
		prefs.sleep = $("input[name=sleepHrs]").val();
		prefs.wake = $("input[name=WakeUpTime]").val();
		prefs.address = $("input[name=Address]").val();
		prefs.clubs = "notsureifthisworkssoimputtingastringhere";
		prefs.schoolId = 42;
		window.api.post("myDay/info/set", prefs, function(resp) {});
	});
});
<|endoftext|>


<commit_before>'use strict';

var path = require('path'),
    _ = require('lodash'),
    exerciser = require('workshopper-exercise'),
    filecheck = require('workshopper-exercise/filecheck'),
    execute = require('workshopper-exercise/execute'),
    jsdiff = require("diff"),
    colorsTmpl = require('workshopper/node_modules/colors-tmpl');

function stringify(obj) {
    var string = JSON.stringify(obj, null, " ");
    if (typeof string === 'undefined') {
        string = 'undefined';
    }

    // reduce a few linebreaks
    string = string.replace(/([^,])[\r\n]+/g, "$1");
    string = string.replace(/\{  "/g, '{ "');

    // For templating-erercises (html-code line breaks)
    string = string.replace(/\\n/g, "\n");

    return string;
}

function clean(str) {
    if (!str) {
        return void 0;
    }

    if (typeof str !== "string") {
        return str;
    }

    return str.replace(/\r?\n|\r/g, '').replace(/(\s)+/g, '$1');
}

function line(n, sep) {
    n = n || 20;
    sep = sep || '-';
    return (new Array(n)).join(sep);
}

function diffsould(shouldbe, output) {

    var diff = jsdiff.diffWords(output, shouldbe);
    var string = "";

    diff.forEach(function (part) {
        // green for additions, red for deletions, white right
        var color = part.added ? 'green' : part.removed ? 'red' : 'white';
        string = string + colorsTmpl("{" + color + "}" + part.value + "{/" + color + "}");
    });

    return string;
}

function logcompare(input, output, shouldbe) {
    console.log([
        line(),
        'Input',
        line(),
        stringify(input),
        line(),
        'Output:\n' + diffsould(stringify(output), stringify(shouldbe)),
        line(),
        'Output should be:\n' + stringify(shouldbe),
        line()
    ].join('\n'));
}

module.exports = function (tests, run) {
    var exercise = _.compose(execute, filecheck)(exerciser());

    exercise.addProcessor(function (mode, callback) {
        var isRunMode = mode === 'run', self = this, usersolution, result;

        try {
            usersolution = require(path.resolve(process.cwd(), this.args[0]));
        } catch (e) {
            var message = (e.code !== 'MODULE_NOT_FOUND' ? 'Could not find your file. Make sure the path is correct.'
                            : 'You need to install all of the dependencies you are using in your solution (e.g. lodash)');

            this.emit('fail', message);
            return callback(null, false);
        }

        if (typeof usersolution !== 'function') {
            this.emit('fail', 'You should always return a function using the module.exports object.');
            return callback(null, false);
        }

        if (isRunMode) {
            try {
                result = usersolution(run.json);
            } catch (e) { }

            var expected = run.expect;
            if ('string' === typeof expected && exercise.i18n.has(expected)) {
                expected = exercise.__(expected);
            }

            logcompare(run.json, result, expected);

            if (!result || !_.isEqual(clean(result), clean(expected))) {
                this.emit('fail', 'Test');
                return callback(null, false);
            }

            this.emit('pass', 'Test');
            return callback(null, true);
        }

        var allPassed = _(tests).map(function (item, element) {
            var isCorrect;
            var shouldbe = item.shouldbe;
            if ('string' === typeof shouldbe && exercise.i18n.has(shouldbe)) {
                shouldbe = exercise.__(shouldbe);
            }

            try {
                isCorrect = _.isEqual(clean(shouldbe), clean(usersolution(item.input)));
            } catch (e) { }

            if (!isCorrect) {
                self.emit('fail', element);
                logcompare(item.input, usersolution(item.input), shouldbe);
                return false;
            }

            self.emit('pass', element);
            return true;
        }).every();

        return callback(null, allPassed);
    });

    return exercise;
};
<commit_msg>g11n: shield i18n lookups of random strings against corner case in i18n-core.<commit_after>'use strict';

var path = require('path'),
    _ = require('lodash'),
    exerciser = require('workshopper-exercise'),
    filecheck = require('workshopper-exercise/filecheck'),
    execute = require('workshopper-exercise/execute'),
    jsdiff = require("diff"),
    colorsTmpl = require('workshopper/node_modules/colors-tmpl');

function stringify(obj) {
    var string = JSON.stringify(obj, null, " ");
    if (typeof string === 'undefined') {
        string = 'undefined';
    }

    // reduce a few linebreaks
    string = string.replace(/([^,])[\r\n]+/g, "$1");
    string = string.replace(/\{  "/g, '{ "');

    // For templating-erercises (html-code line breaks)
    string = string.replace(/\\n/g, "\n");

    return string;
}

function clean(str) {
    if (!str) {
        return void 0;
    }

    if (typeof str !== "string") {
        return str;
    }

    return str.replace(/\r?\n|\r/g, '').replace(/(\s)+/g, '$1');
}

function line(n, sep) {
    n = n || 20;
    sep = sep || '-';
    return (new Array(n)).join(sep);
}

function diffsould(shouldbe, output) {

    var diff = jsdiff.diffWords(output, shouldbe);
    var string = "";

    diff.forEach(function (part) {
        // green for additions, red for deletions, white right
        var color = part.added ? 'green' : part.removed ? 'red' : 'white';
        string = string + colorsTmpl("{" + color + "}" + part.value + "{/" + color + "}");
    });

    return string;
}

function logcompare(input, output, shouldbe) {
    console.log([
        line(),
        'Input',
        line(),
        stringify(input),
        line(),
        'Output:\n' + diffsould(stringify(output), stringify(shouldbe)),
        line(),
        'Output should be:\n' + stringify(shouldbe),
        line()
    ].join('\n'));
}

module.exports = function (tests, run) {
    var exercise = _.compose(execute, filecheck)(exerciser());

    function i18nSafeHas(key) {
        try {
            return exercise.i18n.has(key);
        } catch (e) {
            // There's a corner case in i18n-core for keys with no '.' anywhere,
            // which can happen for us due to missing trans and parent traversal.
            return false;
        }
    }

    exercise.addProcessor(function (mode, callback) {
        var isRunMode = mode === 'run', self = this, usersolution, result;

        try {
            usersolution = require(path.resolve(process.cwd(), this.args[0]));
        } catch (e) {
            var message = (e.code !== 'MODULE_NOT_FOUND' ? 'Could not find your file. Make sure the path is correct.'
                            : 'You need to install all of the dependencies you are using in your solution (e.g. lodash)');

            this.emit('fail', message);
            return callback(null, false);
        }

        if (typeof usersolution !== 'function') {
            this.emit('fail', 'You should always return a function using the module.exports object.');
            return callback(null, false);
        }

        if (isRunMode) {
            try {
                result = usersolution(run.json);
            } catch (e) { }

            var expected = run.expect;
            if ('string' === typeof expected && i18nSafeHas(expected)) {
                expected = exercise.__(expected);
            }

            logcompare(run.json, result, expected);

            if (!result || !_.isEqual(clean(result), clean(expected))) {
                this.emit('fail', 'Test');
                return callback(null, false);
            }

            this.emit('pass', 'Test');
            return callback(null, true);
        }

        var allPassed = _(tests).map(function (item, element) {
            var isCorrect;
            var shouldbe = item.shouldbe;
            if ('string' === typeof shouldbe && i18nSafeHas(shouldbe)) {
                shouldbe = exercise.__(shouldbe);
            }

            try {
                isCorrect = _.isEqual(clean(shouldbe), clean(usersolution(item.input)));
            } catch (e) { }

            if (!isCorrect) {
                self.emit('fail', element);
                logcompare(item.input, usersolution(item.input), shouldbe);
                return false;
            }

            self.emit('pass', element);
            return true;
        }).every();

        return callback(null, allPassed);
    });

    return exercise;
};
<|endoftext|>


<commit_before>var config = require('./config');
var request = require('request');
var wallpaper = require('wallpaper');
var $ = require('cheerio');
var exec = require('child_process').exec;

request('http://photography.nationalgeographic.com/photography/photo-of-the-day/', function(err,resp,rawHtml){

	var html = $.load(rawHtml);

	html(".primary_photo img").map(function(i,link){

		var src = $(link).attr('src');

		var url = "http:" + src;

		var location = __dirname + "/Images/photo-of-the-day.jpg ";

		exec("wget -O " + location + " " + url, function (error, stdout, stderr) {

			if (err) throw err;

		  console.log('stdout: ' + stdout);
		  console.log('stderr: ' + stderr);

			wallpaper.set("./Images/photo-of-the-day.jpg", function(err) {

				if (err) throw err;

				console.log("Background image is set!");

			});

		});

	});

});
<commit_msg>random image from https://unsplash.com/ now will be a gb<commit_after>var config = require('./config');
var request = require('request');
var wallpaper = require('wallpaper');
var $ = require('cheerio');
var exec = require('child_process').exec;

request('https://unsplash.com/', function(err,resp,rawHtml){

	var html = $.load(rawHtml);

	var photos = [];

	html(".photo img").map(function(i,link){

		var src = $(link).attr('src');

		photos.push(src);

	});

	console.log(photos.length);

		var photoID = Math.floor(Math.random() * 19) + 0

		console.log("photoID: " + photoID);

		var url = photos[photoID];

		var location = __dirname + "/Images/photo-of-the-day_" + photoID + ".jpg";

		console.log("Staring photo download from " + url + " ...");

		exec("wget -O " + location + " " + url, function (error, stdout, stderr) {

			if (err) throw err;

		  console.log('stdout: ' + stdout);
		  console.log('stderr: ' + stderr);

			console.log("Downloaded!");

			console.log("Setting photo as desktop background!");

			wallpaper.set("./Images/photo-of-the-day_" + photoID + ".jpg", function(err) {

				if (err) throw err;

				console.log("Background photo is set!");

			});

		});

});
<|endoftext|>


<commit_before>YUI().use('css-mediaquery', 'rework', 'rework-pure-grids', function (Y) {
    'use strict';

    var exported   = Y.Env._exported,
        rework     = Y.config.global.rework,
        pureGrids  = exported['rework-pure-grids'],
        mediaQuery = exported['css-mediaquery'];

    var css = rework('').use(pureGrids.units({
        mediaQueries: {
            med: 'screen and (min-width: 48em)',
            lrg: 'screen and (min-width: 75em)'
        }
    })).toString();

    console.log(mediaQuery.parse('screen and (min-width: 48em)'));
    console.log(css);
});
<commit_msg>add a console.log() for easy viewing server payload<commit_after>YUI().use('css-mediaquery', 'rework', 'rework-pure-grids', function (Y) {
    'use strict';

    var exported   = Y.Env._exported,
        rework     = Y.config.global.rework,
        pureGrids  = exported['rework-pure-grids'],
        mediaQuery = exported['css-mediaquery'];

    var css = rework('').use(pureGrids.units({
        mediaQueries: {
            med: 'screen and (min-width: 48em)',
            lrg: 'screen and (min-width: 75em)'
        }
    })).toString();

    console.log(mediaQuery.parse('screen and (min-width: 48em)'));
    console.log(css);
    console.log(app.start.query);
});
<|endoftext|>


<commit_before>'use strict'

let https = require('https')
var express = require('express')
var app = express()
var server = require('http').Server(app)
var bodyParser = require('body-parser')
var io = require('socket.io')(server)

var cookieParser = require('cookie-parser');
var cookieEncrypter = require('cookie-encrypter');
var port = process.env.PORT || 4000
startServer()

const githubApplication = {
  client_id: process.env.GITHUB_APPLICATION_CLIENT_ID,
  redirect_uri: process.env.GITHUB_APPLICATION_REDIRECT_URI,
  client_secret: process.env.GITHUB_APPLICATION_CLIENT_SECRET
};

const cookieParams = {
  httpOnly: true,
  signed: true,
  maxAge: 300000,
};

const cookieSecretKey = process.env.COOKIE_SECRET;

app.use(bodyParser.json())
app.use(cookieParser(cookieSecretKey));
app.use(cookieEncrypter(cookieSecretKey));

app.get('/githuboauthcallback', function(req, res) {
  let postRequest = https.request({
    hostname: 'github.com',
    method: 'POST',
    path: '/login/oauth/access_token',
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    },
  }, (response) => {
    console.log(`Got access_token response: ${response.statusCode}`);
    let body = '';
    response.on('data', (d) => body += d);
    response.on('end', () => {
      const json = JSON.parse(body);
      res.cookie('token', json.access_token, cookieParams);
      res.redirect(req.signedCookies.redirect);
    });
  }).on('error', (e) => {
    console.log(`Got error: ${e}`);
    res.end();
  });

  postRequest.write(JSON.stringify({
    client_id: githubApplication.client_id,
    client_secret: githubApplication.client_secret,
    redirect_uri: githubApplication.redirect_uri,
    code: req.query.code,
  }));
  postRequest.end();
});

app.post('/github', function (req, res) {
  res.send({status: 200})

  const org = req.body.name.split('/')[0]
  const repo = req.body.name.split('/')[1]

  const options = {
    hostname: 'api.github.com',
    path: `/repos/${org}/${repo}/commits/${req.body.sha}/status`,
    headers: {
      'Authorization': `token ${process.env.GITHUB_OAUTH_TOKEN}`,
      'User-Agent': 'hookmaster'
    }
  }

  https.get(options, (res) => {
    console.log(`Got response: ${res.statusCode}`)
    let body = ''
    res.on('data', (d) => body += d)
    res.on('end', () => {
      // not sure which branch to use... just pick the first
      const branch = req.body.branches.length && req.body.branches[0].name
      const combinedStatus = JSON.parse(body).state;
      if (!branch) return

      pushBuildUpdateToClient({
        repo: repo,
        outcome: combinedStatus,
        branch: branch,
        author: req.body.commit.commit.author.name,
        coauthor: req.body.commit.commit.committer.name,
        timestamp: (new Date()).getTime()
      })
    })
  }).on('error', (e) => {
    console.log(`Got error: ${e}`)
  })
})

const r1 = express.Router();
r1.get('/:orgName/:repo', authenticate)

const r2 = express.Router();
r2.use('/:orgName/:repo', express.static('dist'))

app.use(r1, r2);

app.get('/logout', (req, res) => {
  res.clearCookie('token')
  res.clearCookie('redirect')
  res.send('logged out')
})

app.get('/:org?', (req, res) => {
  res.send("Use buildmaster.com/orgname/reponame")
})

function authenticate (req, res, next) {
  console.log('authenticate...')
  if(req.signedCookies.token) {
    console.log('user is authenticated')
    next()
  } else {
    console.log('need to authenticate')
    res.cookie('redirect', req.originalUrl, cookieParams)
    res.redirect('https://github.com/login/oauth/authorize?scope=repo&client_id=' + githubApplication.client_id + '&redirect_uri=' + encodeURIComponent(githubApplication.redirect_uri));
  }
}

function pushBuildUpdateToClient (buildData) {
  console.log(buildData)
  io.sockets.emit('action', {type: 'message', data: buildData})
}

function startServer () {
  server.listen(port, function () {
    console.log('Express server is up and running!')
  })
}
<commit_msg>nicer<commit_after>'use strict'

let https = require('https')
var express = require('express')
var app = express()
var server = require('http').Server(app)
var bodyParser = require('body-parser')
var io = require('socket.io')(server)

var cookieParser = require('cookie-parser');
var cookieEncrypter = require('cookie-encrypter');
var port = process.env.PORT || 4000
startServer()

const githubApplication = {
  client_id: process.env.GITHUB_APPLICATION_CLIENT_ID,
  redirect_uri: process.env.GITHUB_APPLICATION_REDIRECT_URI,
  client_secret: process.env.GITHUB_APPLICATION_CLIENT_SECRET
};

const cookieParams = {
  httpOnly: true,
  signed: true,
  maxAge: 300000,
};

const cookieSecretKey = process.env.COOKIE_SECRET;

app.use(bodyParser.json())
app.use(cookieParser(cookieSecretKey));
app.use(cookieEncrypter(cookieSecretKey));

app.get('/githuboauthcallback', function(req, res) {
  let postRequest = https.request({
    hostname: 'github.com',
    method: 'POST',
    path: '/login/oauth/access_token',
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    },
  }, (response) => {
    console.log(`Got access_token response: ${response.statusCode}`);
    let body = '';
    response.on('data', (d) => body += d);
    response.on('end', () => {
      const json = JSON.parse(body);
      res.cookie('token', json.access_token, cookieParams);
      res.redirect(req.signedCookies.redirect);
    });
  }).on('error', (e) => {
    console.log(`Got error: ${e}`);
    res.end();
  });

  postRequest.write(JSON.stringify({
    client_id: githubApplication.client_id,
    client_secret: githubApplication.client_secret,
    redirect_uri: githubApplication.redirect_uri,
    code: req.query.code,
  }));
  postRequest.end();
});

app.post('/github', function (req, res) {
  res.send({status: 200})

  const org = req.body.name.split('/')[0]
  const repo = req.body.name.split('/')[1]

  const options = {
    hostname: 'api.github.com',
    path: `/repos/${org}/${repo}/commits/${req.body.sha}/status`,
    headers: {
      'Authorization': `token ${process.env.GITHUB_OAUTH_TOKEN}`,
      'User-Agent': 'hookmaster'
    }
  }

  https.get(options, (res) => {
    console.log(`Got response: ${res.statusCode}`)
    let body = ''
    res.on('data', (d) => body += d)
    res.on('end', () => {
      // not sure which branch to use... just pick the first
      const branch = req.body.branches.length && req.body.branches[0].name
      const combinedStatus = JSON.parse(body).state;
      if (!branch) return

      pushBuildUpdateToClient({
        repo: repo,
        outcome: combinedStatus,
        branch: branch,
        author: req.body.commit.commit.author.name,
        coauthor: req.body.commit.commit.committer.name,
        timestamp: (new Date()).getTime()
      })
    })
  }).on('error', (e) => {
    console.log(`Got error: ${e}`)
  })
})

app.get('/:orgName/:repo', authenticate)
app.use('/:orgName/:repo', express.static('dist'))

app.get('/logout', (req, res) => {
  res.clearCookie('token')
  res.clearCookie('redirect')
  res.send('logged out')
})

app.get('/:org?', (req, res) => {
  res.send("Use buildmaster.com/orgname/reponame")
})

function authenticate (req, res, next) {
  console.log('authenticate...')
  if(req.signedCookies.token) {
    console.log('user is authenticated')
    next()
  } else {
    console.log('need to authenticate')
    res.cookie('redirect', req.originalUrl, cookieParams)
    res.redirect('https://github.com/login/oauth/authorize?scope=repo&client_id=' + githubApplication.client_id + '&redirect_uri=' + encodeURIComponent(githubApplication.redirect_uri));
  }
}

function pushBuildUpdateToClient (buildData) {
  console.log(buildData)
  io.sockets.emit('action', {type: 'message', data: buildData})
}

function startServer () {
  server.listen(port, function () {
    console.log('Express server is up and running!')
  })
}
<|endoftext|>


<commit_before>/****************************************************************************
 * app.js
 * openacousticdevices.info
 * June 2017
 *****************************************************************************/

'use strict';

/*global document, Uint8Array*/
/*jslint bitwise: true*/

var audiomoth = require('audiomoth-hid');

var ui = require('./ui.js');
var timeHandler = require('./timePeriods.js');
var saveLoad = require('./saveLoad.js');
var lifeDisplay = require('./lifeDisplay.js');

var electron = require('electron');
var dialog = electron.remote.dialog;

/* UI components */

var ledCheckbox = document.getElementById('led-checkbox');

var recordingDurationInput = document.getElementById('recording-duration-input');
var sleepDurationInput = document.getElementById('sleep-duration-input');

var configureButton = document.getElementById('configure-button');

var startTimeInput = document.getElementById('start-time-input');
var endTimeInput = document.getElementById('end-time-input');

/* Setting parameters */

var configurations = [{
    clockDivider: 4,
    acquisitionCycles: 16,
    oversampleRate: 1,
    sampleRate: 256000,
    sampleRateDivider: 32,
    current: 10.5
}, {
    clockDivider: 4,
    acquisitionCycles: 16,
    oversampleRate: 1,
    sampleRate: 256000,
    sampleRateDivider: 16,
    current: 12.0
}, {
    clockDivider: 4,
    acquisitionCycles: 16,
    oversampleRate: 1,
    sampleRate: 256000,
    sampleRateDivider: 8,
    current: 12.5
}, {
    clockDivider: 4,
    acquisitionCycles: 16,
    oversampleRate: 1,
    sampleRate: 384000,
    sampleRateDivider: 8,
    current: 13.5
}, {
    clockDivider: 4,
    acquisitionCycles: 16,
    oversampleRate: 1,
    sampleRate: 384000,
    sampleRateDivider: 4,
    current: 17.5
}, {
    clockDivider: 4,
    acquisitionCycles: 16,
    oversampleRate: 1,
    sampleRate: 384000,
    sampleRateDivider: 2,
    current: 24.5
}, {
    clockDivider: 4,
    acquisitionCycles: 16,
    oversampleRate: 1,
    sampleRate: 384000,
    sampleRateDivider: 1,
    current: 39.0
}];

function errorOccurred(err) {

    console.error(err);

    ui.disableDisplay();

}

/* Request, receive and handle AudioMoth information packet */

function getAudioMothPacket() {

    var id, date, batteryState;

    audiomoth.getPacket(function (err, packet) {

        if (err) {

            errorOccurred(err);

        } else if (packet === null) {

            ui.disableDisplay();

        } else {

            date = audiomoth.convertFourBytesFromBufferToDate(packet, 1);

            id = audiomoth.convertEightBytesFromBufferToID(packet, 1 + 4);

            batteryState = audiomoth.convertOneByteFromBufferToBatteryState(packet, 1 + 4 + 8);

            ui.enableDisplayAndShowTime(date);

            ui.updateIdDisplay(id);

            ui.updateBatteryDisplay(batteryState);

        }

        setTimeout(getAudioMothPacket, 1000);

    });

}

/* Write bytes into a buffer for transmission */

function writeLittleEndianBytes(buffer, start, byteCount, value) {
    var i;

    for (i = 0; i < byteCount; i += 1) {
        buffer[start + i] = (value >> (i * 8)) & 255;
    }
}

/* Submit configuration packet and configure device */

function configureDevice() {

    var packet, index, date, configuration, i, timePeriods;

    /* Build configuration packet */

    packet = new Uint8Array(62);
    index = 0;

    date = new Date();
    writeLittleEndianBytes(packet, index, 4, date.valueOf() / 1000);
    index += 4;

    packet[index] = parseInt(ui.getSelectedRadioValue("gain-radio"), 10);
    index += 1;

    configuration = configurations[parseInt(ui.getSelectedRadioValue("sample-rate-radio"), 10)];

    packet[index] = configuration.clockDivider;
    index += 1;
    packet[index] = configuration.acquisitionCycles;
    index += 1;
    packet[index] = configuration.oversampleRate;
    index += 1;
    writeLittleEndianBytes(packet, index, 4, configuration.sampleRate);
    index += 4;
    packet[index] = configuration.sampleRateDivider;
    index += 1;

    writeLittleEndianBytes(packet, index, 2, sleepDurationInput.value);
    index += 2;
    writeLittleEndianBytes(packet, index, 2, recordingDurationInput.value);
    index += 2;

    if (ledCheckbox.checked) {

        packet[index] = 0x01;

    } else {

        packet[index] = 0x00;

    }
    index += 1;

    timePeriods = timeHandler.getTimePeriods();
    packet[index] = timePeriods.length;
    index += 1;

    for (i = 0; i < timePeriods.length; i += 1) {

        writeLittleEndianBytes(packet, index, 2, timePeriods[i].startMins);
        index += 2;
        writeLittleEndianBytes(packet, index, 2, timePeriods[i].endMins);
        index += 2;

    }

    /* Send packet to device */

    audiomoth.setPacket(packet, function (err, data) {

        var j, matches, showError;

        showError = function () {
            dialog.showErrorBox("Configuration failed.", "Configuration was not applied to AudioMoth\nPlease reconnect device and try again.");
        };

        if (err || data === null || data.length === 0) {

            showError();

        } else {

            matches = true;

            for (j = 0; j < Math.min(packet.length, data.length - 1); j += 1) {
                if (packet[j] !== data[j + 1]) {
                    console.log(packet[j] + ' - ' + data[j + 1]);
                    matches = false;
                    break;
                }
            }

            if (matches) {

                configureButton.style.color = "green";
                setTimeout(function () {
                    configureButton.style.color = "";
                }, 1000);

            } else {

                showError();

            }

        }

    });

}

/* Initiliase lifeDisplay configuration data */

lifeDisplay.setConfigurationData(configurations);

/* Initialise UI elements */

ui.drawTimeLabels();

timeHandler.updateTimeList();

ui.updateCanvasTimer();

ui.disableDisplay();

ui.initialiseDisplay();

ui.addRadioButtonListeners();

setTimeout(getAudioMothPacket, 1000);

configureButton.addEventListener('click', function () {
    ui.checkInputs(configureDevice);
});<commit_msg>Add missing spacing<commit_after>/****************************************************************************
 * app.js
 * openacousticdevices.info
 * June 2017
 *****************************************************************************/

'use strict';

/*global document, Uint8Array*/
/*jslint bitwise: true*/

var audiomoth = require('audiomoth-hid');

var ui = require('./ui.js');
var timeHandler = require('./timePeriods.js');
var saveLoad = require('./saveLoad.js');
var lifeDisplay = require('./lifeDisplay.js');

var electron = require('electron');
var dialog = electron.remote.dialog;

/* UI components */

var ledCheckbox = document.getElementById('led-checkbox');

var recordingDurationInput = document.getElementById('recording-duration-input');
var sleepDurationInput = document.getElementById('sleep-duration-input');

var configureButton = document.getElementById('configure-button');

var startTimeInput = document.getElementById('start-time-input');
var endTimeInput = document.getElementById('end-time-input');

/* Setting parameters */

var configurations = [{
    clockDivider: 4,
    acquisitionCycles: 16,
    oversampleRate: 1,
    sampleRate: 256000,
    sampleRateDivider: 32,
    current: 10.5
}, {
    clockDivider: 4,
    acquisitionCycles: 16,
    oversampleRate: 1,
    sampleRate: 256000,
    sampleRateDivider: 16,
    current: 12.0
}, {
    clockDivider: 4,
    acquisitionCycles: 16,
    oversampleRate: 1,
    sampleRate: 256000,
    sampleRateDivider: 8,
    current: 12.5
}, {
    clockDivider: 4,
    acquisitionCycles: 16,
    oversampleRate: 1,
    sampleRate: 384000,
    sampleRateDivider: 8,
    current: 13.5
}, {
    clockDivider: 4,
    acquisitionCycles: 16,
    oversampleRate: 1,
    sampleRate: 384000,
    sampleRateDivider: 4,
    current: 17.5
}, {
    clockDivider: 4,
    acquisitionCycles: 16,
    oversampleRate: 1,
    sampleRate: 384000,
    sampleRateDivider: 2,
    current: 24.5
}, {
    clockDivider: 4,
    acquisitionCycles: 16,
    oversampleRate: 1,
    sampleRate: 384000,
    sampleRateDivider: 1,
    current: 39.0
}];

function errorOccurred(err) {

    console.error(err);

    ui.disableDisplay();

}

/* Request, receive and handle AudioMoth information packet */

function getAudioMothPacket() {

    var id, date, batteryState;

    audiomoth.getPacket(function (err, packet) {

        if (err) {

            errorOccurred(err);

        } else if (packet === null) {

            ui.disableDisplay();

        } else {

            date = audiomoth.convertFourBytesFromBufferToDate(packet, 1);

            id = audiomoth.convertEightBytesFromBufferToID(packet, 1 + 4);

            batteryState = audiomoth.convertOneByteFromBufferToBatteryState(packet, 1 + 4 + 8);

            ui.enableDisplayAndShowTime(date);

            ui.updateIdDisplay(id);

            ui.updateBatteryDisplay(batteryState);

        }

        setTimeout(getAudioMothPacket, 1000);

    });

}

/* Write bytes into a buffer for transmission */

function writeLittleEndianBytes(buffer, start, byteCount, value) {

    var i;

    for (i = 0; i < byteCount; i += 1) {

        buffer[start + i] = (value >> (i * 8)) & 255;

    }

}

/* Submit configuration packet and configure device */

function configureDevice() {

    var packet, index, date, configuration, i, timePeriods;

    /* Build configuration packet */

    packet = new Uint8Array(62);
    index = 0;

    date = new Date();
    writeLittleEndianBytes(packet, index, 4, date.valueOf() / 1000);
    index += 4;

    packet[index] = parseInt(ui.getSelectedRadioValue("gain-radio"), 10);
    index += 1;

    configuration = configurations[parseInt(ui.getSelectedRadioValue("sample-rate-radio"), 10)];

    packet[index] = configuration.clockDivider;
    index += 1;
    packet[index] = configuration.acquisitionCycles;
    index += 1;
    packet[index] = configuration.oversampleRate;
    index += 1;
    writeLittleEndianBytes(packet, index, 4, configuration.sampleRate);
    index += 4;
    packet[index] = configuration.sampleRateDivider;
    index += 1;

    writeLittleEndianBytes(packet, index, 2, sleepDurationInput.value);
    index += 2;
    writeLittleEndianBytes(packet, index, 2, recordingDurationInput.value);
    index += 2;

    if (ledCheckbox.checked) {

        packet[index] = 0x01;

    } else {

        packet[index] = 0x00;

    }
    index += 1;

    timePeriods = timeHandler.getTimePeriods();
    packet[index] = timePeriods.length;
    index += 1;

    for (i = 0; i < timePeriods.length; i += 1) {

        writeLittleEndianBytes(packet, index, 2, timePeriods[i].startMins);
        index += 2;
        writeLittleEndianBytes(packet, index, 2, timePeriods[i].endMins);
        index += 2;

    }

    /* Send packet to device */

    audiomoth.setPacket(packet, function (err, data) {

        var j, matches, showError;

        showError = function () {
            dialog.showErrorBox("Configuration failed.", "Configuration was not applied to AudioMoth\nPlease reconnect device and try again.");
        };

        if (err || data === null || data.length === 0) {

            showError();

        } else {

            matches = true;

            for (j = 0; j < Math.min(packet.length, data.length - 1); j += 1) {

                if (packet[j] !== data[j + 1]) {

                    console.log(packet[j] + ' - ' + data[j + 1]);
                    matches = false;

                    break;

                }

            }

            if (matches) {

                configureButton.style.color = "green";

                setTimeout(function () {
                    configureButton.style.color = "";
                }, 1000);

            } else {

                showError();

            }

        }

    });

}

/* Initiliase lifeDisplay configuration data */

lifeDisplay.setConfigurationData(configurations);

/* Initialise UI elements */

ui.drawTimeLabels();

timeHandler.updateTimeList();

ui.updateCanvasTimer();

ui.disableDisplay();

ui.initialiseDisplay();

ui.addRadioButtonListeners();

setTimeout(getAudioMothPacket, 1000);

configureButton.addEventListener('click', function () {
    ui.checkInputs(configureDevice);
});<|endoftext|>


<commit_before>import assignIn from 'lodash/assignIn';

import {
  DISPATCH_TYPE,
  STATE_TYPE,
  PATCH_STATE_TYPE,
  DIFF_STATUS_UPDATED,
  DIFF_STATUS_REMOVED,
} from '../constants';

const backgroundErrPrefix = '\nLooks like there is an error in the background page. ' +
  'You might want to inspect your background page for more details.\n';

class Store {
  /**
   * Creates a new Proxy store
   * @param  {object} options An object of form {portName, state, extensionId}, where `portName` is a required string and defines the name of the port for state transition changes, `state` is the initial state of this store (default `{}`) `extensionId` is the extension id as defined by chrome when extension is loaded (default `''`)
   */
  constructor({portName, state = {}, extensionId = ''}) {
    if (!portName) {
      throw new Error('portName is required in options');
    }

    this.portName = portName;
    this.readyResolved = false;
    this.readyPromise = new Promise(resolve => this.readyResolve = resolve);

    this.extensionId = extensionId; // keep the extensionId as an instance variable
    this.port = chrome.runtime.connect(this.extensionId, {name: portName});
    this.listeners = [];
    this.state = state;

    this.port.onMessage.addListener(message => {
      switch (message.type) {
        case STATE_TYPE:
          this.replaceState(message.payload);

          if (!this.readyResolved) {
            this.readyResolved = true;
            this.readyResolve();
          }
          break;

        case PATCH_STATE_TYPE:
          this.patchState(message.payload);
          break;

        default:
          // do nothing
      }
    });

    this.dispatch = this.dispatch.bind(this); // add this context to dispatch
  }

  /**
  * Returns a promise that resolves when the store is ready. Optionally a callback may be passed in instead.
  * @param [function] callback An optional callback that may be passed in and will fire when the store is ready.
  * @return {object} promise A promise that resolves when the store has established a connection with the background page.
  */
  ready(cb = null) {
    if (cb !== null) {
      return this.readyPromise.then(cb);
    }

    return this.readyPromise;
  }

  /**
   * Subscribes a listener function for all state changes
   * @param  {function} listener A listener function to be called when store state changes
   * @return {function}          An unsubscribe function which can be called to remove the listener from state updates
   */
  subscribe(listener) {
    this.listeners.push(listener);

    return () => {
      this.listeners = this.listeners.filter((l) => l !== listener);
    };
  }

  /**
   * Replaces the state for only the keys in the updated state. Notifies all listeners of state change.
   * @param {object} state the new (partial) redux state
   */
  patchState(difference) {
    const state = Object.assign({}, this.state);

    difference.forEach(({change, key, value}) => {
      if (change === DIFF_STATUS_UPDATED) {
        state[key] = value;
      } else if (change === DIFF_STATUS_REMOVED) {
        Reflect.deleteProperty(state, key);
      }
    });

    this.state = state;

    this.listeners.forEach((l) => l());
  }

  /**
   * Replace the current state with a new state. Notifies all listeners of state change.
   * @param  {object} state The new state for the store
   */
  replaceState(state) {
    this.state = state;

    this.listeners.forEach((l) => l());
  }

  /**
   * Get the current state of the store
   * @return {object} the current store state
   */
  getState() {
    return this.state;
  }

  /**
   * Dispatch an action to the background using messaging passing
   * @param  {object} data The action data to dispatch
   * @return {Promise}     Promise that will resolve/reject based on the action response from the background
   */
  dispatch(data) {
    return new Promise((resolve, reject) => {
      chrome.runtime.sendMessage(
        this.extensionId,
        {
          type: DISPATCH_TYPE,
          portName: this.portName,
          payload: data
        }, (resp) => {
          const {error, value} = resp;

          if (error) {
            const bgErr = new Error(`${backgroundErrPrefix}${error}`);

            reject(assignIn(bgErr, error));
          } else {
            resolve(value && value.payload);
          }
        });
    });
  }
}

export default Store;
<commit_msg>Use switch instead of if else<commit_after>import assignIn from 'lodash/assignIn';

import {
  DISPATCH_TYPE,
  STATE_TYPE,
  PATCH_STATE_TYPE,
  DIFF_STATUS_UPDATED,
  DIFF_STATUS_REMOVED,
} from '../constants';

const backgroundErrPrefix = '\nLooks like there is an error in the background page. ' +
  'You might want to inspect your background page for more details.\n';

class Store {
  /**
   * Creates a new Proxy store
   * @param  {object} options An object of form {portName, state, extensionId}, where `portName` is a required string and defines the name of the port for state transition changes, `state` is the initial state of this store (default `{}`) `extensionId` is the extension id as defined by chrome when extension is loaded (default `''`)
   */
  constructor({portName, state = {}, extensionId = ''}) {
    if (!portName) {
      throw new Error('portName is required in options');
    }

    this.portName = portName;
    this.readyResolved = false;
    this.readyPromise = new Promise(resolve => this.readyResolve = resolve);

    this.extensionId = extensionId; // keep the extensionId as an instance variable
    this.port = chrome.runtime.connect(this.extensionId, {name: portName});
    this.listeners = [];
    this.state = state;

    this.port.onMessage.addListener(message => {
      switch (message.type) {
        case STATE_TYPE:
          this.replaceState(message.payload);

          if (!this.readyResolved) {
            this.readyResolved = true;
            this.readyResolve();
          }
          break;

        case PATCH_STATE_TYPE:
          this.patchState(message.payload);
          break;

        default:
          // do nothing
      }
    });

    this.dispatch = this.dispatch.bind(this); // add this context to dispatch
  }

  /**
  * Returns a promise that resolves when the store is ready. Optionally a callback may be passed in instead.
  * @param [function] callback An optional callback that may be passed in and will fire when the store is ready.
  * @return {object} promise A promise that resolves when the store has established a connection with the background page.
  */
  ready(cb = null) {
    if (cb !== null) {
      return this.readyPromise.then(cb);
    }

    return this.readyPromise;
  }

  /**
   * Subscribes a listener function for all state changes
   * @param  {function} listener A listener function to be called when store state changes
   * @return {function}          An unsubscribe function which can be called to remove the listener from state updates
   */
  subscribe(listener) {
    this.listeners.push(listener);

    return () => {
      this.listeners = this.listeners.filter((l) => l !== listener);
    };
  }

  /**
   * Replaces the state for only the keys in the updated state. Notifies all listeners of state change.
   * @param {object} state the new (partial) redux state
   */
  patchState(difference) {
    const state = Object.assign({}, this.state);

    difference.forEach(({change, key, value}) => {
      switch (change) {
        case DIFF_STATUS_UPDATED:
          state[key] = value;
          break;

        case DIFF_STATUS_REMOVED:
          Reflect.deleteProperty(state, key);
          break;

        default:
          // do nothing
      }
    });

    this.state = state;

    this.listeners.forEach((l) => l());
  }

  /**
   * Replace the current state with a new state. Notifies all listeners of state change.
   * @param  {object} state The new state for the store
   */
  replaceState(state) {
    this.state = state;

    this.listeners.forEach((l) => l());
  }

  /**
   * Get the current state of the store
   * @return {object} the current store state
   */
  getState() {
    return this.state;
  }

  /**
   * Dispatch an action to the background using messaging passing
   * @param  {object} data The action data to dispatch
   * @return {Promise}     Promise that will resolve/reject based on the action response from the background
   */
  dispatch(data) {
    return new Promise((resolve, reject) => {
      chrome.runtime.sendMessage(
        this.extensionId,
        {
          type: DISPATCH_TYPE,
          portName: this.portName,
          payload: data
        }, (resp) => {
          const {error, value} = resp;

          if (error) {
            const bgErr = new Error(`${backgroundErrPrefix}${error}`);

            reject(assignIn(bgErr, error));
          } else {
            resolve(value && value.payload);
          }
        });
    });
  }
}

export default Store;
<|endoftext|>


<commit_before>define(function (require) {
  // we need to load the css ourselves
  require('plugins/para_vis/para_vis.less');

  // we also need to load the controller and used by the template
  require('plugins/para_vis/para_vis_controller.js');

  // register the provider with the visTypes registry
  require('ui/registry/vis_types').register(ParaVisProvider);

  function ParaVisProvider(Private) {
    const TemplateVisType = Private(require('ui/template_vis_type/TemplateVisType'));
    const Schemas = Private(require('ui/Vis/Schemas'));

    // return the visType object, which kibana will use to display and configure new
    // Vis object of this type.
    return new TemplateVisType({
      name: 'para',
      title: 'Paragraph Generator',
      description: 'Create custom paragraphs/blocks of text with the addition of automatica paramters.',
      icon: 'fa-calculator',
      template: require('plugins/para_vis/para_vis.html'),
      params: {
        defaults: {
          handleNoResults: true,
          fontSize: 60
        },
        editor: require('plugins/para_vis/para_vis_params.html')
      },
      schemas: new Schemas([
        {
          group: 'paras',
          name: 'para',
          title: 'Paragraph Generator',
          min: 1,
          defaults: [
            { type: 'count', schema: 'para' }
          ]
        }
      ])
    });
  }

  // export the provider so that the visType can be required with Private()
  return ParaVisProvider;
});
<commit_msg>Changes made to para_vis.js<commit_after>define(function (require) {
  // we need to load the css ourselves
  require('plugins/Kibana_ParagraphGenerator/para_vis.less');

  // we also need to load the controller and used by the template
  require('plugins/Kibana_ParagraphGenerator/para_vis_controller.js');

  // register the provider with the visTypes registry
  require('ui/registry/vis_types').register(ParaVisProvider);

  function ParaVisProvider(Private) {
    const TemplateVisType = Private(require('ui/template_vis_type/TemplateVisType'));
    const Schemas = Private(require('ui/Vis/Schemas'));

    // return the visType object, which kibana will use to display and configure new
    // Vis object of this type.
    return new TemplateVisType({
      name: 'para',
      title: 'Paragraph Generator',
      description: 'Create custom paragraphs/blocks of text with the addition of automatica paramters.',
      icon: 'fa-calculator',
      template: require('plugins/Kibana_ParagraphGenerator/para_vis.html'),
      params: {
        defaults: {
          handleNoResults: true,
          fontSize: 60
        },
        editor: require('plugins/Kibana_ParagraphGenerator/para_vis_params.html')
      },
      schemas: new Schemas([
        {
          group: 'paras',
          name: 'para',
          title: 'Paragraph Generator',
          min: 1,
          defaults: [
            { type: 'count', schema: 'para' }
          ]
        }
      ])
    });
  }

  // export the provider so that the visType can be required with Private()
  return ParaVisProvider;
});
<|endoftext|>


<commit_before>'use strict';

var hoursOp = ['6 AM: ', '7am: ', '8am: ', '9am: ', '10am: ', '11am: ', '12pm: ', '1pm: ', '2pm: ', '3pm: ', '4pm: ', '5pm: ', '6pm: ', '7pm: '],

function CookieStore(name, minCust, maxCust, avgCookies, ) {
  this.name = name;
  this.minCust = minCust;
  this.maxCust = maxCust;
  this.avgCookies = avgCookies;
  this.avgSimCookies = [];

  this.randCust = function() {
    return Math.floor(Math.random() * (this.maxNumCust - this.minNumCust) + this.minNumCust);
    };
  this.eachHrSales = function() {
    for (var i = 0; i < 14; i++) {
      var hrSales = Math.ceil(this.randCust() * this.avgCookies);
      this.avgSimCookies.push(Math.ceil(eachHrSales(i)))
      }
    };

  eachHrSales: function () {
    this.avgSimCookies = [];
  for (var i = 0; i < 2; i++) {
    var hrSales = Math.ceil(this.randCust() * this.avgNumCookiesCust);
    this.avgSimCookies.push(Math.ceil.(eachHrSales));
    console.log(eachHrSales);
    }
  },

  salesReport: function () {
    for (var i = 0; i < this.hoursOp.length; i++) {
    var pikeRandomSales = this.eachHrSales();
    this.avgSimCookies.push(this.hoursOp[i] + pikeRandomSales + ' cookies');
    console.log(this.eachHrSales());

    var listItems = document.create.Element('li');
    listItems.innerText = "Total: " + this.total + 'cookies';
    list.appendChild(listItems);

//    this.total+=pikeRandomSales;
    }
  },
};

firstPike.salesReport();

var salesReport = document.createElement('li');
firstPikeSalesReport.innerText = this.hoursOp[i] + this.avgSimCookies[i] + '.'; // <--- if you want to change the inner text
firstPikeSalesReport.appendChild(newLi);*/
console.log(firstPike.total);

var listFirstPike = document.getElementById('firstPikeSalesReport');
var listFirstPikeMerge = document.createElement('li');
firstPikeSalesReport.appendChild(listFirstPikeMerge);
<commit_msg>changes to constructor function<commit_after>'use strict';

var hours = ['6 AM: ', '7am: ', '8am: ', '9am: ', '10am: ', '11am: ', '12pm: ', '1pm: ', '2pm: ', '3pm: ', '4pm: ', '5pm: ', '6pm: ', '7pm: '],

function CookieStore(name, minCust, maxCust, avgCookies, ) {
  this.name = name;
  this.minCust = minCust;
  this.maxCust = maxCust;
  this.avgCookies = avgCookies;
  this.avgSimCookies = [];

  this.randCust = function() {
    return Math.floor(Math.random() * (this.maxNumCust - this.minNumCust) + this.minNumCust);
    };
  this.eachHrSales = function() {
    for (var i = 0; i < 14; i++) {
      var hrSales = Math.ceil(this.randCust() * this.avgCookies);
      this.avgSimCookies.push(Math.ceil(eachHrSales(i)))
      }
    };

  eachHrSales: function () {
    this.avgSimCookies = [];
  for (var i = 0; i < 2; i++) {
    var hrSales = Math.ceil(this.randCust() * this.avgNumCookiesCust);
    this.avgSimCookies.push(Math.ceil.(eachHrSales));
    console.log(eachHrSales);
    }
  },

  salesReport: function () {
    for (var i = 0; i < this.hoursOp.length; i++) {
    var pikeRandomSales = this.eachHrSales();
    this.avgSimCookies.push(this.hoursOp[i] + pikeRandomSales + ' cookies');
    console.log(this.eachHrSales());

    var listItems = document.create.Element('li');
    listItems.innerText = "Total: " + this.total + 'cookies';
    list.appendChild(listItems);

//    this.total+=pikeRandomSales;
    }
  },
};

firstPike.salesReport();

var salesReport = document.createElement('li');
firstPikeSalesReport.innerText = this.hoursOp[i] + this.avgSimCookies[i] + '.'; // <--- if you want to change the inner text
firstPikeSalesReport.appendChild(newLi);*/
console.log(firstPike.total);

var listFirstPike = document.getElementById('firstPikeSalesReport');
var listFirstPikeMerge = document.createElement('li');
firstPikeSalesReport.appendChild(listFirstPikeMerge);
<|endoftext|>


<commit_before>import Vue from "vue";
import Vuex from "vuex";
import vuexI18n from "vuex-i18n";
import axios from "axios";
// eslint-disable-next-line
// import router from '@/router'

Vue.use(Vuex);

const lang = {
  en: {
    location: "./i18n/English.json",
    strings: require("./i18n/English.json"),
    loaded: true
  },
  "zh-Hans": {
    location: "/i18n/ChineseSimplified.json",
    strings: null,
    loaded: false
  },
  "zh-Hant": {
    location: "/i18n/ChineseTraditional.json",
    strings: null,
    loaded: false
  },
  fr: {
    location: "/i18n/French.json",
    strings: null,
    loaded: false
  },
  de: {
    location: "/i18n/German.json",
    strings: null,
    loaded: false
  },
  ja: {
    location: "/i18n/Japanese.json",
    strings: null,
    loaded: false
  },
  ko: {
    location: "/i18n/Korean.json",
    strings: null,
    loaded: false
  },
  pt: {
    location: "/i18n/Portuguese.json",
    strings: null,
    loaded: false
  },
  ru: {
    location: "/i18n/Russian.json",
    strings: null,
    loaded: false
  },
  es: {
    location: "/i18n/Spanish.json",
    strings: null,
    loaded: false
  },
  th: {
    location: "/i18n/Thai.json",
    strings: null,
    loaded: false
  },
  vi: {
    location: "/i18n/Vietnamese.json",
    strings: null,
    loaded: false
  }
};

const state = {
  locale: "en",
  artifactID: "1",
  heroID: "1",
  data: require("@/data.json"),
  star: 0,
  level: 0
};

const getters = {
  getArtifactList: function() {
    var artifacts = {};
    for (var artifact in lang[state.locale].strings["artifact"]) {
      artifacts[
        lang[state.locale].strings["artifact"][artifact]["name"]
      ] = artifact;
    }
    return artifacts;
  },
  getHeroList: function() {
    var heroes = {};
    for (var hero in lang[state.locale].strings["hero"]) {
      heroes[lang[state.locale].strings["hero"][hero]["name"]] = hero;
    }
    return heroes;
  },
  getArtifact: function() {
    return {
      image: require("@/components/artifact/images/" +
        state.artifactID +
        ".png"),
      name: Vue.i18n.translate("artifact." + state.artifactID + ".name"),
      description: Vue.i18n.translate(
        "artifact." + state.artifactID + ".description"
      )
    };
  },
  getHero: function() {
    var prefix = "hero." + state.heroID;
    return {
      image: require("@/components/hero/images/" + state.heroID + "/hero.png"),
      name: Vue.i18n.translate(prefix + ".name"),
      subtitle: Vue.i18n.translate(prefix + ".subtitle"),
      class: Vue.i18n.translate("ui." + h.getClass()),
      description: Vue.i18n.translate(prefix + ".description"),
      t5: {
        light: Vue.i18n.translate(prefix + ".t5.light"),
        dark: Vue.i18n.translate(prefix + ".t5.dark")
      },
      attributes: {
        image: require("@/components/hero/images/classes/" +
          h.getClass() +
          ".png"),
        stats: h.getClassStats().attributes
      },
      treasure: {
        image: require("@/components/hero/images/" + state.heroID + "/UT.png"),
        name: Vue.i18n.translate(prefix + ".s3.ut.name"),
        description: Vue.i18n.translate(prefix + ".s3.ut.description")
      },
      weapon: {
        image: require("@/components/hero/images/" + state.heroID + "/UW.png"),
        name: Vue.i18n.translate(prefix + ".uw.name"),
        description: Vue.i18n.translate(prefix + ".uw.description")
      },
      s1: h.getSkill(prefix + ".s1", "s1"),
      s2: h.getSkill(prefix + ".s2", "s2"),
      s3: h.getSkill(prefix + ".s3", "s3"),
      s4: h.getSkill(prefix + ".s4", "s4")
    };
  },
  getUAtk: function() {
    return h.getUnique(h.getClassStats().uatk);
  },
  getUHP: function() {
    return h.getUnique(11500);
  }
};

const actions = {};

const mutations = {
  setArtifactID: function(state, newID) {
    state.artifactID = newID;
  },
  setHeroID: function(state, newID) {
    state.heroID = newID;
  },
  setLocale: function(state, locale) {
    h.changeLocale(locale);
    Vue.i18n.set(locale);
    state.locale = locale;
  },
  starChange: function(state, newStar) {
    state.star = Number(newStar);
  },
  levelChange: function(state, newlevel) {
    // need to set the value twice to ensure the input value is refreshed
    state.level = Number(newlevel);
    state.level = h.levelValidation(newlevel);
  }
};

const h = {
  getClass: function() {
    return state.data.hero[state.heroID].class;
  },
  getClassStats: function() {
    return state.data.class[h.getClass()];
  },
  getSkill: function(prefix, skillNum) {
    var s = state.data.hero[state.heroID][skillNum];
    return {
      image: require("@/components/hero/images/" +
        state.heroID +
        "/" +
        skillNum +
        ".png"),
      name: Vue.i18n.translate(prefix + ".name"),
      description: Vue.i18n.translate(prefix + ".description", s.description),
      //description: "Vue.i18n.translate(prefix + '.description')",
      transcendence: {
        light: Vue.i18n.translate(prefix + ".light"),
        dark: Vue.i18n.translate(prefix + ".dark")
      },
      books: [
        Vue.i18n.translate(prefix + ".books.0", s.books[0]),
        Vue.i18n.translate(prefix + ".books.1", s.books[1]),
        Vue.i18n.translate(prefix + ".books.2", s.books[2])
      ]
    };
  },
  getUnique: function(baseVal) {
    return Math.floor(
      (Math.floor(
        (state.data.scaling.star[state.star] *
          state.data.scaling.level[state.level]) /
          1000
      ) *
        baseVal) /
        1000
    );
  },
  levelValidation: function(level) {
    level = Number(level);
    var minLevel = 0;
    var maxLevel = 90;
    var newLevel = h.numberWithinBounds(minLevel, maxLevel, level);
    return newLevel;
  },
  numberWithinBounds: function(min, max, number) {
    return number < min ? min : number > max ? max : number;
  },
  changeLocale: function(locale) {
    if (!lang[locale].loaded) {
      lang[locale].loaded = true;
      return new Promise(resolve => {
        axios.get(lang[locale].location).then(result => {
          resolve(
            (lang[locale].strings = result.data),
            Vue.i18n.add(locale, result.data),
            (state.locale = locale)
          );
        });
      });
    }
  }
};

const store = new Vuex.Store({
  state,
  getters,
  actions,
  mutations
});

// Vue.use(vuexI18n.plugin, store)

// only ask for translation ONCE from the server as all the strings are in a single JSON
// would otherwise FLOOD the server with requests for the JSON

Vue.use(vuexI18n.plugin, store, {
  moduleName: "i18n",
  onTranslationNotFound(locale) {
    return h.changeLocale(locale);
  }
});

Vue.i18n.add("en", lang.en.strings);

Vue.i18n.set(navigator.language.split("-")[0]);
Vue.i18n.fallback("en");

export default store;
<commit_msg>Fix bugs regarding locale loading and new heroes.<commit_after>import Vue from "vue";
import Vuex from "vuex";
import vuexI18n from "vuex-i18n";
import axios from "axios";
// eslint-disable-next-line
// import router from '@/router'

Vue.use(Vuex);

const lang = {
  en: {
    location: "./i18n/English.json",
    strings: require("./i18n/English.json"),
    loaded: true
  },
  "zh-Hans": {
    location: "/i18n/ChineseSimplified.json",
    strings: null,
    loaded: false
  },
  "zh-Hant": {
    location: "/i18n/ChineseTraditional.json",
    strings: null,
    loaded: false
  },
  fr: {
    location: "/i18n/French.json",
    strings: null,
    loaded: false
  },
  de: {
    location: "/i18n/German.json",
    strings: null,
    loaded: false
  },
  ja: {
    location: "/i18n/Japanese.json",
    strings: null,
    loaded: false
  },
  ko: {
    location: "/i18n/Korean.json",
    strings: null,
    loaded: false
  },
  pt: {
    location: "/i18n/Portuguese.json",
    strings: null,
    loaded: false
  },
  ru: {
    location: "/i18n/Russian.json",
    strings: null,
    loaded: false
  },
  es: {
    location: "/i18n/Spanish.json",
    strings: null,
    loaded: false
  },
  th: {
    location: "/i18n/Thai.json",
    strings: null,
    loaded: false
  },
  vi: {
    location: "/i18n/Vietnamese.json",
    strings: null,
    loaded: false
  }
};

const state = {
  locale: "en",
  artifactID: "1",
  heroID: "1",
  data: require("@/data.json"),
  star: 0,
  level: 0
};

const getters = {
  getArtifactList: function() {
    var artifacts = {};
    for (var artifact in lang[state.locale].strings["artifact"]) {
      artifacts[
        lang[state.locale].strings["artifact"][artifact]["name"]
      ] = artifact;
    }
    return artifacts;
  },
  getHeroList: function() {
    var heroes = {};
    for (var hero in lang[state.locale].strings["hero"]) {
      if (lang[state.locale].strings["hero"][hero]["name"] !== "") {
        heroes[lang[state.locale].strings["hero"][hero]["name"]] = hero;
      }
    }
    return heroes;
  },
  getArtifact: function() {
    return {
      image: require("@/components/artifact/images/" +
        state.artifactID +
        ".png"),
      name: Vue.i18n.translate("artifact." + state.artifactID + ".name"),
      description: Vue.i18n.translate(
        "artifact." + state.artifactID + ".description"
      )
    };
  },
  getHero: function() {
    var prefix = "hero." + state.heroID;
    return {
      image: require("@/components/hero/images/" + state.heroID + "/hero.png"),
      name: Vue.i18n.translate(prefix + ".name"),
      subtitle: Vue.i18n.translate(prefix + ".subtitle"),
      class: Vue.i18n.translate("ui." + h.getClass()),
      description: Vue.i18n.translate(prefix + ".description"),
      t5: {
        light: Vue.i18n.translate(prefix + ".t5.light"),
        dark: Vue.i18n.translate(prefix + ".t5.dark")
      },
      attributes: {
        image: require("@/components/hero/images/classes/" +
          h.getClass() +
          ".png"),
        stats: h.getClassStats().attributes
      },
      treasure: {
        image: require("@/components/hero/images/" + state.heroID + "/UT.png"),
        name: Vue.i18n.translate(prefix + ".s3.ut.name"),
        description: Vue.i18n.translate(prefix + ".s3.ut.description")
      },
      weapon: {
        image: require("@/components/hero/images/" + state.heroID + "/UW.png"),
        name: Vue.i18n.translate(prefix + ".uw.name"),
        description: Vue.i18n.translate(prefix + ".uw.description")
      },
      s1: h.getSkill(prefix + ".s1", "s1"),
      s2: h.getSkill(prefix + ".s2", "s2"),
      s3: h.getSkill(prefix + ".s3", "s3"),
      s4: h.getSkill(prefix + ".s4", "s4")
    };
  },
  getUAtk: function() {
    return h.getUnique(h.getClassStats().uatk);
  },
  getUHP: function() {
    return h.getUnique(11500);
  }
};

const actions = {};

const mutations = {
  setArtifactID: function(state, newID) {
    state.artifactID = newID;
  },
  setHeroID: function(state, newID) {
    state.heroID = newID;
  },
  setLocale: async function(state, locale) {
    locale = h.parseLocale(locale);
    await h.changeLocale(locale);
    Vue.i18n.set(locale);
    state.locale = locale;
  },
  starChange: function(state, newStar) {
    state.star = Number(newStar);
  },
  levelChange: function(state, newlevel) {
    // need to set the value twice to ensure the input value is refreshed
    state.level = Number(newlevel);
    state.level = h.levelValidation(newlevel);
  }
};

const h = {
  getClass: function() {
    return state.data.hero[state.heroID].class;
  },
  getClassStats: function() {
    return state.data.class[h.getClass()];
  },
  getSkill: function(prefix, skillNum) {
    var s = state.data.hero[state.heroID][skillNum];
    return {
      image: require("@/components/hero/images/" +
        state.heroID +
        "/" +
        skillNum +
        ".png"),
      name: Vue.i18n.translate(prefix + ".name"),
      description: Vue.i18n.translate(prefix + ".description", s.description),
      //description: "Vue.i18n.translate(prefix + '.description')",
      transcendence: {
        light: Vue.i18n.translate(prefix + ".light"),
        dark: Vue.i18n.translate(prefix + ".dark")
      },
      books: [
        Vue.i18n.translate(prefix + ".books.0", s.books[0]),
        Vue.i18n.translate(prefix + ".books.1", s.books[1]),
        Vue.i18n.translate(prefix + ".books.2", s.books[2])
      ]
    };
  },
  getUnique: function(baseVal) {
    return Math.floor(
      (Math.floor(
        (state.data.scaling.star[state.star] *
          state.data.scaling.level[state.level]) /
          1000
      ) *
        baseVal) /
        1000
    );
  },
  levelValidation: function(level) {
    level = Number(level);
    var minLevel = 0;
    var maxLevel = 90;
    var newLevel = h.numberWithinBounds(minLevel, maxLevel, level);
    return newLevel;
  },
  numberWithinBounds: function(min, max, number) {
    return number < min ? min : number > max ? max : number;
  },
  changeLocale: async function(locale) {
    if (!lang[locale].loaded) {
      lang[locale].loaded = true;
      var result = await axios(lang[locale].location);
      lang[locale].strings = result.data;
      Vue.i18n.add(locale, result.data);
    }
  },
  parseLocale: function(locale) {
    var l = locale.split("-");
    if (l[0].toLowerCase() === "zh") {
      var tradtional = ["TW", "HK", "HANT"]
      if (l.length > 1 && l[1].toUpperCase() in tradtional) {
        return "zh-Hant";
      } else {
        return "zh-Hans";
      }
    } else if (l[0].toLowerCase() in lang) {
      return l[0].toLowerCase();
    } else {
      return "en";
    }
  }
};

const store = new Vuex.Store({
  state,
  getters,
  actions,
  mutations
});

// Vue.use(vuexI18n.plugin, store)

// only ask for translation ONCE from the server as all the strings are in a single JSON
// would otherwise FLOOD the server with requests for the JSON

Vue.use(vuexI18n.plugin, store, {
  moduleName: "i18n",
  onTranslationNotFound(locale) {
    return h.changeLocale(locale);
  }
});

Vue.i18n.add("en", lang.en.strings);
Vue.i18n.set("en");
store.commit("setLocale", navigator.language);
Vue.i18n.fallback("en");

export default store;
<|endoftext|>