<commit_before>require('dotenv').config();
const ua = require('universal-analytics');
const WebClient = require('@slack/client').WebClient;
const express = require('express');
const request = require('request');
const logger = require('morgan');
const sassMiddleware = require('node-sass-middleware');
const path = require('path');
const { IncomingWebhook } = require('@slack/client');
const Bot = require('./models/bot');
const bodyParser = require('body-parser');
const postInSlack = require('./lib/postInSlack');
const getLocation = require('./lib/getLocation');
const postMessage = require('./lib/slackWebClient').postMessage;
const weatherFor = require('./lib/weatherFor');
const sendHelp = require('./lib/sendHelp');
const SlackWebClient = require('./lib/slackWebClient');
const setUnits = require('./lib/setUnits');

const app = express();

app.use(logger('dev'));
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());

function clientErrorHandler (err, req, res, next) {
  if (req.xhr) {
    res.status(500).send({ error: 'Something failed!' })
  } else {
    next(err)
  }
}

function errorHandler (err, req, res, next) {
  res.status(500)
  res.render('error', { error: err })
}

app.use(clientErrorHandler)
app.use(errorHandler)

const srcPath = __dirname + '/sass';
const destPath = __dirname + '/../public/styles';

if (process.env.NODE_ENV != 'production') {
  app.use('/styles', sassMiddleware({
    src: srcPath,
    dest: destPath,
    debug: true,
    prefix: '/styles',
    outputStyle: 'compressed',
    outputStyle: 'expanded'
  }));
}

app.set('view engine', 'pug');

app.use('/icons', express.static('public/icons'))
app.use('/styles', express.static('public/styles'));
app.use('/robots.txt', express.static('public/robots.txt'));

app.get('/', (req, res) => {
  res.render('index');
});
app.get('/success', (req, res) => {
  res.render('success');
});
app.get('/error', (req, res) => {
  res.render('error');
});
app.get('/help', (req, res) => {
  res.render('help');
});

app.post('/weather', (req, res) => {
  const message = req.body;
  const location = message.text.replace(/<@.*>/, '').replace(/![\w]*/, '');
  const responseURL = message.response_url;

  if (message.token !== process.env.SLACK_VERIFICATION_TOKEN) {
    res.sendStatus(400);
    return;
  }

  Bot.findOne({ teamID: message.team_id })
    .then((bot) => {
      const visitor = ua(process.env.GA_ID, bot.teamName, { strictCidFormat: false, uid: bot.teamName });
      visitor.pageview('/weather', function(err) {
        if (err) { console.log(err); } // eslint-disable-line
      }).send();

      const units = bot.units || 'us';

      if (message.text.match(/help\s*$/) || location.match(/^(?![\s\S])/)) {
        res.status(200).send({ text: sendHelp() });
      } else if (message.text.match(/set\s*/)) {
        res.status(200).send({ text: setUnits(bot, message) });
      } else {
        getLocation(location)
          .then((coords) => {
            res.status(200).send({ text: `Getting weather for ${location}` });
            return weatherFor(coords.lat, coords.lng, coords.location, units);
          })
          .then((weather) => {
            postInSlack(responseURL, weather, units);
          })
          .catch((err) => {
            console.log(err);
            res.status(200).send(
              `Sorry, I could not find any location called ${location}. Can you be more specific?\n\n Just type "/forecast help" if you need help!`
            );
          });
      }
    })
    .catch((err) => {
      console.log(err);
      res.sendStatus(400);
    });
});

app.get('/auth/slack/callback', (req, res) => {
  const data = {
    form: {
      client_id: process.env.SLACK_CLIENT_ID,
      client_secret: process.env.SLACK_CLIENT_SECRET,
      redirect_uri: process.env.REDIRECT_URI,
      code: req.query.code
    }
  };
  request.post('https://slack.com/api/oauth.access', data, (error, response, body) => {
    if (!error && response.statusCode == 200) {
      const json = JSON.parse(body);
      const teamID = json.team_id;
      const teamName = json.team_name;
      const accessToken = json.access_token;
      Bot.findOne({ teamID })
        .then((existingBot) => {
          if ( existingBot ) {
            existingBot.teamID = teamID;
            existingBot.accessToken = accessToken;
            existingBot.teamName = teamName;
            existingBot.save()
              .then(() => {
                return res.redirect('/success');
              });
          } else {
            new Bot({ teamID, accessToken, teamName }).save()
              .then((bot) => {
                res.redirect('/success');
              })
              .catch((_err) => {
                console.log(_err);
                res.redirect('/error');
              });
          }
        })
        .catch((err) => {
          console.log(err);
          res.redirect('/error');
        });
    } else {
      console.log("OAuth error");
      console.log(response.body);
    }
  });
});

module.exports = app;
<commit_msg>User teamID for google uid<commit_after>require('dotenv').config();
const ua = require('universal-analytics');
const WebClient = require('@slack/client').WebClient;
const express = require('express');
const request = require('request');
const logger = require('morgan');
const sassMiddleware = require('node-sass-middleware');
const path = require('path');
const { IncomingWebhook } = require('@slack/client');
const Bot = require('./models/bot');
const bodyParser = require('body-parser');
const postInSlack = require('./lib/postInSlack');
const getLocation = require('./lib/getLocation');
const postMessage = require('./lib/slackWebClient').postMessage;
const weatherFor = require('./lib/weatherFor');
const sendHelp = require('./lib/sendHelp');
const SlackWebClient = require('./lib/slackWebClient');
const setUnits = require('./lib/setUnits');

const app = express();

app.use(logger('dev'));
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());

function clientErrorHandler (err, req, res, next) {
  if (req.xhr) {
    res.status(500).send({ error: 'Something failed!' })
  } else {
    next(err)
  }
}

function errorHandler (err, req, res, next) {
  res.status(500)
  res.render('error', { error: err })
}

app.use(clientErrorHandler)
app.use(errorHandler)

const srcPath = __dirname + '/sass';
const destPath = __dirname + '/../public/styles';

if (process.env.NODE_ENV != 'production') {
  app.use('/styles', sassMiddleware({
    src: srcPath,
    dest: destPath,
    debug: true,
    prefix: '/styles',
    outputStyle: 'compressed',
    outputStyle: 'expanded'
  }));
}

app.set('view engine', 'pug');

app.use('/icons', express.static('public/icons'))
app.use('/styles', express.static('public/styles'));
app.use('/robots.txt', express.static('public/robots.txt'));

app.get('/', (req, res) => {
  res.render('index');
});
app.get('/success', (req, res) => {
  res.render('success');
});
app.get('/error', (req, res) => {
  res.render('error');
});
app.get('/help', (req, res) => {
  res.render('help');
});

app.post('/weather', (req, res) => {
  const message = req.body;
  const location = message.text.replace(/<@.*>/, '').replace(/![\w]*/, '');
  const responseURL = message.response_url;

  if (message.token !== process.env.SLACK_VERIFICATION_TOKEN) {
    res.sendStatus(400);
    return;
  }

  Bot.findOne({ teamID: message.team_id })
    .then((bot) => {
      const visitor = ua(process.env.GA_ID, bot.teamName, { strictCidFormat: false, uid: bot.teamID });
      visitor.pageview('/weather', function(err) {
        if (err) { console.log(err); } // eslint-disable-line
      }).send();

      const units = bot.units || 'us';

      if (message.text.match(/help\s*$/) || location.match(/^(?![\s\S])/)) {
        res.status(200).send({ text: sendHelp() });
      } else if (message.text.match(/set\s*/)) {
        res.status(200).send({ text: setUnits(bot, message) });
      } else {
        getLocation(location)
          .then((coords) => {
            res.status(200).send({ text: `Getting weather for ${location}` });
            return weatherFor(coords.lat, coords.lng, coords.location, units);
          })
          .then((weather) => {
            postInSlack(responseURL, weather, units);
          })
          .catch((err) => {
            console.log(err);
            res.status(200).send(
              `Sorry, I could not find any location called ${location}. Can you be more specific?\n\n Just type "/forecast help" if you need help!`
            );
          });
      }
    })
    .catch((err) => {
      console.log(err);
      res.sendStatus(400);
    });
});

app.get('/auth/slack/callback', (req, res) => {
  const data = {
    form: {
      client_id: process.env.SLACK_CLIENT_ID,
      client_secret: process.env.SLACK_CLIENT_SECRET,
      redirect_uri: process.env.REDIRECT_URI,
      code: req.query.code
    }
  };
  request.post('https://slack.com/api/oauth.access', data, (error, response, body) => {
    if (!error && response.statusCode == 200) {
      const json = JSON.parse(body);
      const teamID = json.team_id;
      const teamName = json.team_name;
      const accessToken = json.access_token;
      Bot.findOne({ teamID })
        .then((existingBot) => {
          if ( existingBot ) {
            existingBot.teamID = teamID;
            existingBot.accessToken = accessToken;
            existingBot.teamName = teamName;
            existingBot.save()
              .then(() => {
                return res.redirect('/success');
              });
          } else {
            new Bot({ teamID, accessToken, teamName }).save()
              .then((bot) => {
                res.redirect('/success');
              })
              .catch((_err) => {
                console.log(_err);
                res.redirect('/error');
              });
          }
        })
        .catch((err) => {
          console.log(err);
          res.redirect('/error');
        });
    } else {
      console.log("OAuth error");
      console.log(response.body);
    }
  });
});

module.exports = app;
<|endoftext|>


<commit_before>// Copyright (c) 2016 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var errors = require('./errors');
var assert = require('assert');
var ReadResult = require('bufrw').ReadResult;

var readRes = new ReadResult();

function TChannelServiceNameHandler(options) {
    if (!(this instanceof TChannelServiceNameHandler)) {
        return new TChannelServiceNameHandler(options);
    }
    var self = this;

    assert(typeof options === 'object', 'options required');

    self.channel = options.channel;
    assert(typeof self.channel === 'object', 'expected options.tchannel to be object');

    self.isBusy = options.isBusy || null;
    if (self.isBusy) {
        assert(typeof self.isBusy === 'function', 'expected options.isBusy to be function');
    }
}

TChannelServiceNameHandler.prototype.type = 'tchannel.service-name-handler';

TChannelServiceNameHandler.prototype.handleLazily = function handleLazily(conn, reqFrame) {
    var self = this;

    var res = reqFrame.bodyRW.lazy.poolReadService(readRes, reqFrame);
    if (res.err) {
        // TODO: stat?
        self.channel.logger.warn('failed to lazy read frame serviceName', conn.extendLogInfo({
            error: res.err
        }));
        // TODO: protocol error instead?
        conn.sendLazyErrorFrameForReq(reqFrame, 'BadRequest', 'failed to read serviceName');
        return false;
    }

    var serviceName = res.value;
    if (!serviceName) {
        // TODO: reqFrame.extendLogInfo would be nice, especially if it added
        // things like callerName and arg1
        self.channel.logger.warn('missing service name in lazy frame', conn.extendLogInfo({}));
        conn.sendLazyErrorFrameForReq(reqFrame, 'BadRequest', 'missing serviceName');
        return false;
    }

    var chan = self.channel.subChannels[serviceName];

    if (chan && chan.handler.handleLazily) {
        return chan.handler.handleLazily(conn, reqFrame);
    } else {
        return false;
    }
};

TChannelServiceNameHandler.prototype.handleRequest = function handleRequest(req, buildRes) {
    var self = this;

    if (self.isBusy) {
        var busyInfo = self.isBusy();
        if (busyInfo) {
            buildRes().sendError('Busy', busyInfo);
            return;
        }
    }

    if (!req.serviceName) {
        buildRes().sendError('BadRequest', 'no service name given');
        return;
    }
    var chan = self.channel.subChannels[req.serviceName];
    if (chan) {
        chan.handler.handleRequest(req, buildRes);
    } else {
        self.handleDefault(req, buildRes);
    }
};

TChannelServiceNameHandler.prototype.handleDefault = function handleDefault(req, buildRes) {
    var err = errors.NoServiceHandlerError({serviceName: req.serviceName});
    buildRes().sendError('BadRequest', err.message);
};

TChannelServiceNameHandler.prototype.register = function register() {
    throw errors.TopLevelRegisterError();
};

module.exports = TChannelServiceNameHandler;
<commit_msg>pass req through to `isBusy()`<commit_after>// Copyright (c) 2016 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var errors = require('./errors');
var assert = require('assert');
var ReadResult = require('bufrw').ReadResult;

var readRes = new ReadResult();

function TChannelServiceNameHandler(options) {
    if (!(this instanceof TChannelServiceNameHandler)) {
        return new TChannelServiceNameHandler(options);
    }
    var self = this;

    assert(typeof options === 'object', 'options required');

    self.channel = options.channel;
    assert(typeof self.channel === 'object', 'expected options.tchannel to be object');

    self.isBusy = options.isBusy || null;
    if (self.isBusy) {
        assert(typeof self.isBusy === 'function', 'expected options.isBusy to be function');
    }
}

TChannelServiceNameHandler.prototype.type = 'tchannel.service-name-handler';

TChannelServiceNameHandler.prototype.handleLazily = function handleLazily(conn, reqFrame) {
    var self = this;

    var res = reqFrame.bodyRW.lazy.poolReadService(readRes, reqFrame);
    if (res.err) {
        // TODO: stat?
        self.channel.logger.warn('failed to lazy read frame serviceName', conn.extendLogInfo({
            error: res.err
        }));
        // TODO: protocol error instead?
        conn.sendLazyErrorFrameForReq(reqFrame, 'BadRequest', 'failed to read serviceName');
        return false;
    }

    var serviceName = res.value;
    if (!serviceName) {
        // TODO: reqFrame.extendLogInfo would be nice, especially if it added
        // things like callerName and arg1
        self.channel.logger.warn('missing service name in lazy frame', conn.extendLogInfo({}));
        conn.sendLazyErrorFrameForReq(reqFrame, 'BadRequest', 'missing serviceName');
        return false;
    }

    var chan = self.channel.subChannels[serviceName];

    if (chan && chan.handler.handleLazily) {
        return chan.handler.handleLazily(conn, reqFrame);
    } else {
        return false;
    }
};

TChannelServiceNameHandler.prototype.handleRequest = function handleRequest(req, buildRes) {
    var self = this;

    if (self.isBusy) {
        var busyInfo = self.isBusy(req);
        if (busyInfo) {
            buildRes().sendError('Busy', busyInfo);
            return;
        }
    }

    if (!req.serviceName) {
        buildRes().sendError('BadRequest', 'no service name given');
        return;
    }
    var chan = self.channel.subChannels[req.serviceName];
    if (chan) {
        chan.handler.handleRequest(req, buildRes);
    } else {
        self.handleDefault(req, buildRes);
    }
};

TChannelServiceNameHandler.prototype.handleDefault = function handleDefault(req, buildRes) {
    var err = errors.NoServiceHandlerError({serviceName: req.serviceName});
    buildRes().sendError('BadRequest', err.message);
};

TChannelServiceNameHandler.prototype.register = function register() {
    throw errors.TopLevelRegisterError();
};

module.exports = TChannelServiceNameHandler;
<|endoftext|>


<commit_before>const Base  = require('yeoman-generator').Base;
const yosay = require('yosay');
const chalk = require('chalk');

module.exports = class AppGenerator extends Base {

  /**
   * Constructor.
   */
  constructor (...args) {
    super(...args);
  }

  /**
   * Display a welcome message.
   */
  welcome () {
    this.log(yosay(
      `Welcome to the ${chalk.red('Webpack Angular')} generator!`
    ));
  }
}
<commit_msg>:art: Refactoring<commit_after><|endoftext|>


<commit_before>jQuery(function () {

    function renderDataPoint(service, dataPointId) {
        jQuery.ajax('http://tos-dr.info/points/' + dataPointId + '.json', {success:function (dataPoint) {
            var badge, icon, sign;
            if (dataPoint.tosdr.point == 'good') {
                badge = 'badge-success';
                icon = 'plus';
                sign = '+';
            } else if (dataPoint.tosdr.point == 'mediocre') {
                badge = 'badge-warning';
                icon = 'minus';
                sign = '-';
            } else if (dataPoint.tosdr.point == 'alert') {
                badge = 'badge-important';
                icon = 'remove';
                sign = '×';
            } else if (dataPoint.tosdr.point == 'not bad') {
                badge = 'badge-neutral';
                icon = 'arrow-right';
                sign = '→';
            } else {
                badge = '';
                icon = 'question-sign';
                sign = '?';
            }
            document.getElementById('popup-point-' + service + '-' + dataPointId).innerHTML =
                '

' + sign + ' ' + dataPoint.name + '

'
                    + dataPoint.tosdr.tldr + '

';
            $('#popup-point-' + service + '-' + dataPointId).html(
                '

' + sign + ' ' + dataPoint.name + ' Discussion

'
                    + dataPoint.tosdr.tldr + '

');
        }});
    }

    var NOT_RATED_TEXT = "We haven't sufficiently reviewed the terms yet. Please contribute to our group: tosdr@googlegroups.com.";
    var RATING_TEXT = {
        0:NOT_RATED_TEXT,
        "false":NOT_RATED_TEXT,
        "A":"The terms of service treat you fairly, respect your rights and follows the best practices.",
        "B":"The terms of services are fair towards the user but they could be improved.",
        "C":"The terms of service are okay but some issues need your consideration.",
        "D":"The terms of service are very uneven or there are some important issues that need your attention.",
        "E":"The terms of service raise very serious concerns."
    };

    function renderPopup(name) {
        var service = JSON.parse(localStorage[name]);
        renderPopupHtml(name, service.name, service.url, service.tosdr.rated, RATING_TEXT[service.tosdr.rated],
            service.points, service.links);
    }

    function isEmpty(map) {
        for (var key in map) {
            if (map.hasOwnProperty(key)) {
                return false;
            }
        }
        return true;
    }

    function renderPopupHtml(name, longName, domain, verdict, ratingText, points, links) {
        var headerHtml = '
'
            + ''
            + '
' + longName + '  Rating from Terms of Service; Didn’t Read'
            + '<button id="closeButton" data-dismiss="modal" class="close pull-right" type="button">×</button>

';
        var classHtml = '
'
            + (verdict ? 'Class ' + verdict : 'No Class Yet') + '
' + ratingText + '

';
        var pointsHtml = '';
        for (var i = 0; i < points.length; i++) {
            pointsHtml += '

';
        }
        var bodyHtml = '
' + classHtml + '

' + pointsHtml + '

';

        // Add Links
        if (isEmpty(links)) {
            bodyHtml += '
 Get Involved
';
        } else {
            bodyHtml += '

Read the Terms

';
            for (var i in links) {
                bodyHtml += '
' + (links[i].name ? links[i].name : i) + '
';
            }
            bodyHtml += '

';
        }

        bodyHtml += '
';

        $('#page').html(headerHtml + bodyHtml);
        for (var i = 0; i < points.length; i++) {
            renderDataPoint(name, points[i]);
        }
    }

    var serviceName = window.location.hash.substr(1);
    renderPopup(serviceName);

    $('#closeButton,.close').click(function () {
        window.close();
    });
});
<commit_msg>removed service logo as its already on website and added tosdr logo<commit_after>jQuery(function () {

    function renderDataPoint(service, dataPointId) {
        jQuery.ajax('http://tos-dr.info/points/' + dataPointId + '.json', {success:function (dataPoint) {
            var badge, icon, sign;
            if (dataPoint.tosdr.point == 'good') {
                badge = 'badge-success';
                icon = 'thumbs-up';
                sign = '+';
            } else if (dataPoint.tosdr.point == 'mediocre') {
                badge = 'badge-warning';
                icon = 'thumbs-down';
                sign = '-';
            } else if (dataPoint.tosdr.point == 'alert') {
                badge = 'badge-important';
                icon = 'remove';
                sign = '×';
            } else if (dataPoint.tosdr.point == 'not bad') {
                badge = 'badge-neutral';
                icon = 'arrow-right';
                sign = '→';
            } else {
                badge = '';
                icon = 'question-sign';
                sign = '?';
            }
            document.getElementById('popup-point-' + service + '-' + dataPointId).innerHTML =
                '

' + sign + ' ' + dataPoint.name + '

'
                    + dataPoint.tosdr.tldr + '

';
            $('#popup-point-' + service + '-' + dataPointId).html(
                '

' + sign + ' ' + dataPoint.name + ' Discussion

'
                    + dataPoint.tosdr.tldr + '

');
        }});
    }

    var NOT_RATED_TEXT = "We haven't sufficiently reviewed the terms yet. Please contribute to our group: tosdr@googlegroups.com.";
    var RATING_TEXT = {
        0:NOT_RATED_TEXT,
        "false":NOT_RATED_TEXT,
        "A":"The terms of service treat you fairly, respect your rights and follows the best practices.",
        "B":"The terms of services are fair towards the user but they could be improved.",
        "C":"The terms of service are okay but some issues need your consideration.",
        "D":"The terms of service are very uneven or there are some important issues that need your attention.",
        "E":"The terms of service raise very serious concerns."
    };

    function renderPopup(name) {
        var service = JSON.parse(localStorage[name]);
        renderPopupHtml(name, service.name, service.url, service.tosdr.rated, RATING_TEXT[service.tosdr.rated],
            service.points, service.links);
    }

    function isEmpty(map) {
        for (var key in map) {
            if (map.hasOwnProperty(key)) {
                return false;
            }
        }
        return true;
    }

    function renderPopupHtml(name, longName, domain, verdict, ratingText, points, links) {
        var headerHtml = '
'
            + '
'
            + 'Rating from Terms of Service; Didn’t Read'
            + '<button id="closeButton" data-dismiss="modal" class="close pull-right" type="button">×</button>

';
        var classHtml = '
'
            + (verdict ? 'Class ' + verdict : 'No Class Yet') + '
' + ratingText + '

';
        var pointsHtml = '';
        for (var i = 0; i < points.length; i++) {
            pointsHtml += '

';
        }
        var bodyHtml = '
' + classHtml + '

' + pointsHtml + '

';

        // Add Links
        if (isEmpty(links)) {
            bodyHtml += '
 Get Involved
';
        } else {
            bodyHtml += '

Read the Terms

';
            for (var i in links) {
                bodyHtml += '
' + (links[i].name ? links[i].name : i) + '
';
            }
            bodyHtml += '

';
        }

        bodyHtml += '
';

        $('#page').html(headerHtml + bodyHtml);
        for (var i = 0; i < points.length; i++) {
            renderDataPoint(name, points[i]);
        }
    }

    var serviceName = window.location.hash.substr(1);
    renderPopup(serviceName);

    $('#closeButton,.close').click(function () {
        window.close();
    });
});
<|endoftext|>


<commit_before>var gl;

var mvMatrix;
var perspectiveMatrix;

var shaderProgram;

var shapes;
var tanks;
var projectiles;
var player;
var multiplayer;
var terrain;

var degreesToRadians = Math.PI / 180.0;

//
// start()
//
// Called when the canvas is created to get the ball rolling.
//
function start() {
    var canvas = document.getElementById("glcanvas");
    initWebGL(canvas); // Initialize the GL context

    // Only continue if WebGL is available and working
    if ( gl ) {
        gl.clearColor(0.2, 0.7, 1.0, 1.0);  // Clear to sky blue
        gl.clearDepth(1.0);                 // Clear everything
        gl.enable(gl.DEPTH_TEST);           // Enable depth testing
        gl.depthFunc(gl.LEQUAL);            // Near things obscure far things

        initShaders();
        initTextures();
        initSounds();

        Math.seedrandom("I am Ozymandius, King of asdasdaac");

        terrain = new Terrain();

        shapes = [
            terrain,
            new Square({x: terrain.displacement.horizontal, y: terrain.displacement.vertical, z: terrain.displacement.horizontal}, {x: 0, y: 0, z: 0}, {x: 1000, y: 1, z: 1000}),
            new Sphere({x: terrain.displacement.horizontal, y: 0, z: terrain.displacement.horizontal} , {x: 0, y: 0, z: 0}, {x: 300, y: 300, z: 300}, textures.sky),
        ];

        shapes[2].lighting = false;

        tanks = [];

        projectiles = [];

        multiplayer = new Multiplayer();
        multiplayer.initConnection();

        player = new Player(new Tank({x: 300, y: 15, z: 250}, 0)); // To prevent an error later

        initInputEventHandler();

        // Set up periodic updates:
        setInterval(drawScene, 30);
        setInterval(multiplayer.receiveTankUpdate, 30);
    }
}

//
// initWebGL()
//
// Initialize WebGL, returning the GL context or null if
// WebGL isn't available or could not be initialized.
//
function initWebGL(canvas) {
    gl = null;

    try {
        // Try to grab the standard context. If it fails, fallback to experimental.
        gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl");
    }
    catch(e) {}

    // If we don't have a GL context, give up now
    if ( !gl ) {
        alert("Unable to initialize WebGL. Your browser may not support it.");
    }
}

// drawScene()
//
// Draw the scene.
//
function drawScene() {
    // Clear the canvas before we start drawing on it.
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

    // Establish the perspective with which we want to view the
    // scene. Our field of view is 60 degrees, with a width/height
    // ratio of 800:450 (16:9), and we only want to see objects between 0.1 units
    // and 500 units away from the camera.
    perspectiveMatrix = makePerspective(60, 800.0/450.0, 1, 500.0);

    // Set the drawing position to the "identity" point, which is
    // the center of the scene.
    loadIdentity();

    // Save the current matrix.
    mvPushMatrix();

    player.update();

    // Remove projectiles if they are no longer active:
    for (i = 0; i < projectiles.length; i++) {
        if ( projectiles[i].is_alive === false ) {
            projectiles.splice(i, 1);
        }
    }

    items = shapes.concat(tanks); // Since a tank may have been added...
    items = items.concat(projectiles);
    for (var i = 0; i < items.length; i++)
        items[i].draw();

    // Restore the original matrix
    mvPopMatrix();
}

//
// updateTank
// Moves the given tank to the given orientation.
//
function updateTank(tank_id, tank_position, tank_rotation, tank_turret_rotation)
{
    for (var i = 0; i < tanks.length; i++) {
        if ( tanks[i].id == tank_id ) {
            tanks[i].setPositionAndRotation(tank_position, tank_rotation, tank_turret_rotation);
            tanks[i].adaptToTerrain();
            return true;
        }
    }
}

// randString
// Generates a random 24 character string
//
function randString()
{
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    for( var i=0; i < 24; i++ )
        text += possible.charAt(Math.floor(Math.random() * possible.length));

    return text;
}

// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(offset) {
  this.splice(this.indexOf(offset, 1));
};
<commit_msg>disabled lighting on the ocean<commit_after>var gl;

var mvMatrix;
var perspectiveMatrix;

var shaderProgram;

var shapes;
var tanks;
var projectiles;
var player;
var multiplayer;
var terrain;

var degreesToRadians = Math.PI / 180.0;

//
// start()
//
// Called when the canvas is created to get the ball rolling.
//
function start() {
    var canvas = document.getElementById("glcanvas");
    initWebGL(canvas); // Initialize the GL context

    // Only continue if WebGL is available and working
    if ( gl ) {
        gl.clearColor(0.2, 0.7, 1.0, 1.0);  // Clear to sky blue
        gl.clearDepth(1.0);                 // Clear everything
        gl.enable(gl.DEPTH_TEST);           // Enable depth testing
        gl.depthFunc(gl.LEQUAL);            // Near things obscure far things

        initShaders();
        initTextures();
        initSounds();

        Math.seedrandom("I am Ozymandius, King of asdasdaac");

        terrain = new Terrain();

        shapes = [
            terrain,
            new Square({x: terrain.displacement.horizontal, y: terrain.displacement.vertical, z: terrain.displacement.horizontal}, {x: 0, y: 0, z: 0}, {x: 1000, y: 1, z: 1000}),
            new Sphere({x: terrain.displacement.horizontal, y: 0, z: terrain.displacement.horizontal} , {x: 0, y: 0, z: 0}, {x: 300, y: 300, z: 300}, textures.sky),
        ];

        shapes[1].lighting = shapes[2].lighting = false;

        tanks = [];

        projectiles = [];

        multiplayer = new Multiplayer();
        multiplayer.initConnection();

        player = new Player(new Tank({x: 300, y: 15, z: 250}, 0)); // To prevent an error later

        initInputEventHandler();

        // Set up periodic updates:
        setInterval(drawScene, 30);
        setInterval(multiplayer.receiveTankUpdate, 30);
    }
}

//
// initWebGL()
//
// Initialize WebGL, returning the GL context or null if
// WebGL isn't available or could not be initialized.
//
function initWebGL(canvas) {
    gl = null;

    try {
        // Try to grab the standard context. If it fails, fallback to experimental.
        gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl");
    }
    catch(e) {}

    // If we don't have a GL context, give up now
    if ( !gl ) {
        alert("Unable to initialize WebGL. Your browser may not support it.");
    }
}

// drawScene()
//
// Draw the scene.
//
function drawScene() {
    // Clear the canvas before we start drawing on it.
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

    // Establish the perspective with which we want to view the
    // scene. Our field of view is 60 degrees, with a width/height
    // ratio of 800:450 (16:9), and we only want to see objects between 0.1 units
    // and 500 units away from the camera.
    perspectiveMatrix = makePerspective(60, 800.0/450.0, 1, 500.0);

    // Set the drawing position to the "identity" point, which is
    // the center of the scene.
    loadIdentity();

    // Save the current matrix.
    mvPushMatrix();

    player.update();

    // Remove projectiles if they are no longer active:
    for (i = 0; i < projectiles.length; i++) {
        if ( projectiles[i].is_alive === false ) {
            projectiles.splice(i, 1);
        }
    }

    items = shapes.concat(tanks); // Since a tank may have been added...
    items = items.concat(projectiles);
    for (var i = 0; i < items.length; i++)
        items[i].draw();

    // Restore the original matrix
    mvPopMatrix();
}

//
// updateTank
// Moves the given tank to the given orientation.
//
function updateTank(tank_id, tank_position, tank_rotation, tank_turret_rotation)
{
    for (var i = 0; i < tanks.length; i++) {
        if ( tanks[i].id == tank_id ) {
            tanks[i].setPositionAndRotation(tank_position, tank_rotation, tank_turret_rotation);
            tanks[i].adaptToTerrain();
            return true;
        }
    }
}

// randString
// Generates a random 24 character string
//
function randString()
{
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    for( var i=0; i < 24; i++ )
        text += possible.charAt(Math.floor(Math.random() * possible.length));

    return text;
}

// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(offset) {
  this.splice(this.indexOf(offset, 1));
};
<|endoftext|>


<commit_before>var core = require('./index.js');

function createConnection (opts) {
  var coreConnection = core.createConnection(opts);
  var Promise = opts.Promise || global.Promise;
  if (!Promise) {
    throw new Error('no Promise implementation available.' +
      'Use promise-enabled node version or pass userland Promise' +
      ' implementation as parameter, for example: { Promise: require(\'es6-promise\').Promise }');
  }
  return new Promise(function (resolve, reject) {
    coreConnection.once('connect', function (connectParams) {
      resolve(new PromiseConnection(coreConnection, Promise));
    });
    coreConnection.once('error', reject);
  });
}

function PromiseConnection (connection, promiseImpl) {
  this.connection = connection;
  this.Promise = promiseImpl;
}

PromiseConnection.prototype.release = function () {
  this.connection.release();
};

function makeDoneCb (resolve, reject) {
  return function (err, rows, fields) {
    if (err) {
      reject(err);
    } else {
      resolve([rows, fields]);
    }
  };
}

PromiseConnection.prototype.query = function (query, params) {
  var c = this.connection;
  return new this.Promise(function (resolve, reject) {
    var done = makeDoneCb(resolve, reject);
    if (params) {
      c.query(query, params, done);
    } else {
      c.query(query, done);
    }
  });
};

PromiseConnection.prototype.execute = function (query, params) {
  var c = this.connection;
  return new this.Promise(function (resolve, reject) {
    var done = makeDoneCb(resolve, reject);
    if (params) {
      c.execute(query, params, done);
    } else {
      c.execute(query, done);
    }
  });
};

PromiseConnection.prototype.end = function () {
  var c = this.connection;
  return new this.Promise(function (resolve, reject) {
    c.end(function () {
      resolve();
    });
  });
};

PromiseConnection.prototype.beginTransaction = function () {
  var c = this.connection;
  return new this.Promise(function (resolve, reject) {
    var done = makeDoneCb(resolve, reject);
    c.beginTransaction(done);
  });
};

PromiseConnection.prototype.commit = function () {
  var c = this.connection;
  return new this.Promise(function (resolve, reject) {
    var done = makeDoneCb(resolve, reject);
    c.commit(done);
  });
};

PromiseConnection.prototype.rollback = function () {
  var c = this.connection;
  return new this.Promise(function (resolve, reject) {
    var done = makeDoneCb(resolve, reject);
    c.rollback(done);
  });
};

PromiseConnection.prototype.ping = function () {
  var c = this.connection;
  return new this.Promise(function (resolve, reject) {
    c.ping(resolve);
  });
};

PromiseConnection.prototype.connect = function () {
  var c = this.connection;
  return new this.Promise(function (resolve, reject) {
    c.connect(function (error, param) {
      if (error) {
        reject(error);
      } else {
        resolve(param);
      }
    });
  });
};

PromiseConnection.prototype.prepare = function () {
  var c = this.connection;
  return new this.Promise(function (resolve, reject) {
    c.prepare(function (error, statement) {
      if (error) {
        reject(error);
      } else {
        resolve(statement);
      }
    });
  });
};

// note: the callback of "changeUser" is not called on success
// hence there is no possibility to call "resolve"

// patching PromiseConnection
// create facade functions for prototype functions on "Connection" that are not yet
// implemented with PromiseConnection

// proxy synchronous functions only
(function (functionsToWrap) {

  for (var i = 0; functionsToWrap && i < functionsToWrap.length; i++) {
    var func = functionsToWrap[i];

    if (
      typeof core.Connection.prototype[func] === 'function'
      && PromiseConnection.prototype[func] === undefined
    ) {
      PromiseConnection.prototype[func] = (function factory (funcName) {
        return function () {
          return core.Connection
            .prototype[funcName].apply(this.connection, arguments);
        };
      })(func);
    }
  }

})([
// synchronous functions
  'close',
  'createBinlogStream',
  'destroy',
  'escape',
  'escapeId',
  'format',
  'pause',
  'pipe',
  'resume',
  'unprepare'
]);

function createPool (opts) {
  var corePool = core.createPool(opts);
  var Promise = opts.Promise || global.Promise || require('es6-promise');

  var promisePool = {
    getConnection: function () {
      return new Promise(function (resolve, reject) {
        corePool.getConnection(function (err, coreConnection) {
          if (err) {
            reject(err);
          } else {
            resolve(new PromiseConnection(coreConnection, Promise));
          }
        });
      });
    },

    query: function (sql, args) {
      return new Promise(function (resolve, reject) {
        var done = makeDoneCb(resolve, reject);
        if (args) {
          corePool.query(sql, args, done);
        } else {
          corePool.query(sql, done);
        }
      });
    },

    execute: function (sql, values) {
      return new Promise(function (resolve, reject) {
        corePool.execute(sql, values, makeDoneCb(resolve, reject));
      });
    },

    end: function () {
      return new Promise(function (resolve, reject) {
        corePool.end(function (err) {
          if (err) {
            reject(err);
          } else {
            resolve();
          }
        });
      });
    }
  };

  return promisePool;
}

module.exports.createConnection = createConnection;
module.exports.createPool = createPool;
<commit_msg>use bluebird instead of es6-promise<commit_after>var core = require('./index.js');

function createConnection (opts) {
  var coreConnection = core.createConnection(opts);
  var Promise = opts.Promise || global.Promise;
  if (!Promise) {
    throw new Error('no Promise implementation available.' +
      'Use promise-enabled node version or pass userland Promise' +
      ' implementation as parameter, for example: { Promise: require(\'bluebird\') }');
  }
  return new Promise(function (resolve, reject) {
    coreConnection.once('connect', function (connectParams) {
      resolve(new PromiseConnection(coreConnection, Promise));
    });
    coreConnection.once('error', reject);
  });
}

function PromiseConnection (connection, promiseImpl) {
  this.connection = connection;
  this.Promise = promiseImpl;
}

PromiseConnection.prototype.release = function () {
  this.connection.release();
};

function makeDoneCb (resolve, reject) {
  return function (err, rows, fields) {
    if (err) {
      reject(err);
    } else {
      resolve([rows, fields]);
    }
  };
}

PromiseConnection.prototype.query = function (query, params) {
  var c = this.connection;
  return new this.Promise(function (resolve, reject) {
    var done = makeDoneCb(resolve, reject);
    if (params) {
      c.query(query, params, done);
    } else {
      c.query(query, done);
    }
  });
};

PromiseConnection.prototype.execute = function (query, params) {
  var c = this.connection;
  return new this.Promise(function (resolve, reject) {
    var done = makeDoneCb(resolve, reject);
    if (params) {
      c.execute(query, params, done);
    } else {
      c.execute(query, done);
    }
  });
};

PromiseConnection.prototype.end = function () {
  var c = this.connection;
  return new this.Promise(function (resolve, reject) {
    c.end(function () {
      resolve();
    });
  });
};

PromiseConnection.prototype.beginTransaction = function () {
  var c = this.connection;
  return new this.Promise(function (resolve, reject) {
    var done = makeDoneCb(resolve, reject);
    c.beginTransaction(done);
  });
};

PromiseConnection.prototype.commit = function () {
  var c = this.connection;
  return new this.Promise(function (resolve, reject) {
    var done = makeDoneCb(resolve, reject);
    c.commit(done);
  });
};

PromiseConnection.prototype.rollback = function () {
  var c = this.connection;
  return new this.Promise(function (resolve, reject) {
    var done = makeDoneCb(resolve, reject);
    c.rollback(done);
  });
};

PromiseConnection.prototype.ping = function () {
  var c = this.connection;
  return new this.Promise(function (resolve, reject) {
    c.ping(resolve);
  });
};

PromiseConnection.prototype.connect = function () {
  var c = this.connection;
  return new this.Promise(function (resolve, reject) {
    c.connect(function (error, param) {
      if (error) {
        reject(error);
      } else {
        resolve(param);
      }
    });
  });
};

PromiseConnection.prototype.prepare = function () {
  var c = this.connection;
  return new this.Promise(function (resolve, reject) {
    c.prepare(function (error, statement) {
      if (error) {
        reject(error);
      } else {
        resolve(statement);
      }
    });
  });
};

// note: the callback of "changeUser" is not called on success
// hence there is no possibility to call "resolve"

// patching PromiseConnection
// create facade functions for prototype functions on "Connection" that are not yet
// implemented with PromiseConnection

// proxy synchronous functions only
(function (functionsToWrap) {

  for (var i = 0; functionsToWrap && i < functionsToWrap.length; i++) {
    var func = functionsToWrap[i];

    if (
      typeof core.Connection.prototype[func] === 'function'
      && PromiseConnection.prototype[func] === undefined
    ) {
      PromiseConnection.prototype[func] = (function factory (funcName) {
        return function () {
          return core.Connection
            .prototype[funcName].apply(this.connection, arguments);
        };
      })(func);
    }
  }

})([
// synchronous functions
  'close',
  'createBinlogStream',
  'destroy',
  'escape',
  'escapeId',
  'format',
  'pause',
  'pipe',
  'resume',
  'unprepare'
]);

function createPool (opts) {
  var corePool = core.createPool(opts);
  var Promise = opts.Promise || global.Promise || require('bluebird');

  var promisePool = {
    getConnection: function () {
      return new Promise(function (resolve, reject) {
        corePool.getConnection(function (err, coreConnection) {
          if (err) {
            reject(err);
          } else {
            resolve(new PromiseConnection(coreConnection, Promise));
          }
        });
      });
    },

    query: function (sql, args) {
      return new Promise(function (resolve, reject) {
        var done = makeDoneCb(resolve, reject);
        if (args) {
          corePool.query(sql, args, done);
        } else {
          corePool.query(sql, done);
        }
      });
    },

    execute: function (sql, values) {
      return new Promise(function (resolve, reject) {
        corePool.execute(sql, values, makeDoneCb(resolve, reject));
      });
    },

    end: function () {
      return new Promise(function (resolve, reject) {
        corePool.end(function (err) {
          if (err) {
            reject(err);
          } else {
            resolve();
          }
        });
      });
    }
  };

  return promisePool;
}

module.exports.createConnection = createConnection;
module.exports.createPool = createPool;
<|endoftext|>


<commit_before>/*
 * Websensor video stabilization project
 * https://github.com/jessenie-intel/websensor-video
 *
 * Copyright (c) 2017 Jesse Nieminen
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
*/

'use strict';

var constraints = {audio: true,video: {  width: { min: 640, ideal: 640, max: 640 },  height: { min: 480, ideal: 480, max: 480 }}};
var mediaRecorder = null;
var chunks = [];
var videoData = null;
var interval = null;

var accel_sensor = null;
var orientation_sensor = null;
var sensorfreq = 60;

//var roll = null;
//var pitch = null;
//var yaw = null;
var accel = {"x": null, "y": null, "z": null};
var ori = {"roll": null, "pitch": null, "yaw": null, "time": null};
var oriInitial = {"roll": null, "pitch": null, "yaw": null, "time": null};
var initialoriobtained = false;
var orientationData = [];       //array to store all the orientation data
var frameData = {"data": null, "time": null, "ori": null};
var dataArray = [];     //array to store all the combined data
var dataArray2 = [];     //array to store all the combined data

var time = null;
var timestamps = [];
var nFrame = 0; //frame number with which we can combine timestamp and frame data

//canvas
var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');

//video element
var videoElement = document.querySelector('video');
videoElement.controls = false;

var ref = null;

class AbsOriSensor {
        constructor() {
        const sensor = new AbsoluteOrientationSensor({ frequency: sensorfreq });
        const mat4 = new Float32Array(16);
        const euler = new Float32Array(3);
        sensor.onreading = () => {
                sensor.populateMatrix(mat4);
                toEulerianAngle(sensor.quaternion, euler);      //From quaternion to Eulerian angles
                this.roll = euler[0];
                this.pitch = euler[1];
                this.yaw = euler[2];
                this.timestamp = sensor.timestamp;
                if (this.onreading) this.onreading();
        };
        sensor.onactivate = () => {
                if (this.onactivate) this.onactivate();
        };
        const start = () => sensor.start();
        Object.assign(this, { start });
        }
}

//WINDOWS 10 HAS DIFFERENT CONVENTION: Yaw z, pitch x, roll y
function toEulerianAngle(quat, out)
{
        const ysqr = quat[1] ** 2;

        // Roll (x-axis rotation).
        const t0 = 2 * (quat[3] * quat[0] + quat[1] * quat[2]);
        const t1 = 1 - 2 * (ysqr + quat[0] ** 2);
        out[0] = Math.atan2(t0, t1);
        // Pitch (y-axis rotation).
        let t2 = 2 * (quat[3] * quat[1] - quat[2] * quat[0]);
        t2 = t2 > 1 ? 1 : t2;
        t2 = t2 < -1 ? -1 : t2;
        out[1] = Math.asin(t2);
        // Yaw (z-axis rotation).
        const t3 = 2 * (quat[3] * quat[2] + quat[0] * quat[1]);
        const t4 = 1 - 2 * (ysqr + quat[2] ** 2);
        out[2] = Math.atan2(t3, t4);
        return out;
}

function errorCallback(error){
	console.log("error: ", error);
}

function startDemo () {
		navigator.getUserMedia(constraints, startRecording, errorCallback);
}

function startRecording(stream) {

                try {
                //Initialize sensors
                /*accel_sensor = new Accelerometer();
                accel_sensor.onreading = () => {
                        accel = {"x": accel_sensor.x, "y": accel_sensor.y, "z": accel_sensor.z};
                };
                accel_sensor.onactivate = () => {
                };
                accel_sensor.start();*/
                orientation_sensor = new AbsOriSensor();
                orientation_sensor.onreading = () => {
                        let roll = orientation_sensor.roll;
                        let pitch = orientation_sensor.pitch;
                        let yaw = orientation_sensor.yaw;
                        time = orientation_sensor.timestamp;
                        if(!initialoriobtained) //obtain initial orientation
                        {
                                oriInitial = {"roll": orientation_sensor.roll, "pitch": orientation_sensor.pitch, "yaw": orientation_sensor.yaw, "time": orientation_sensor.timestamp};
                                initialoriobtained = true;
                        }
                        ori = {"roll": orientation_sensor.roll, "pitch": orientation_sensor.pitch, "yaw": orientation_sensor.yaw, "time": orientation_sensor.timestamp};
                };
                orientation_sensor.onactivate = () => {
                };
                orientation_sensor.start();
                }
                catch(err) {
                        console.log(err.message);
                        console.log("Your browser doesn't seem to support generic sensors. If you are running Chrome, please enable it in about:flags.");
                        //this.innerHTML = "Your browser doesn't seem to support generic sensors. If you are running Chrome, please enable it in about:flags";
                }
	        //var options = {mimeType: 'video/webm;codecs=vp9'};
		//mediaRecorder = new MediaRecorder(stream, options);
		mediaRecorder = new MediaRecorder(stream);

	        mediaRecorder.start(10);

	        var url = window.URL;
	        videoElement.src = url ? url.createObjectURL(stream) : stream;
                //videoElement.play();

	        mediaRecorder.ondataavailable = function(e) {
                        //console.log("Data available", e);
                        //console.log(time);
                        timestamps.push(time);
                        frameData.time = time;
		        chunks.push(e.data);
                        frameData.data = e.data;
                        orientationData.push(ori);
                        frameData.ori = ori;
                        var b = new Object;     //need to push by value
                        Object.assign(b, frameData);
                        dataArray.push(b);
	        };

	        mediaRecorder.onerror = function(e){
		        console.log('Error: ', e);
	        };

	        mediaRecorder.onstart = function(){
                        console.log("Recording started", mediaRecorder.state);
	        };

	        mediaRecorder.onstop = function(){
		        var blob = new Blob(chunks, {type: "video/webm"});
		        chunks = [];

		        var videoURL = window.URL.createObjectURL(blob);

		        videoElement.src = videoURL;
                        //videoElement.load();

                        //resize canvas
videoElement.addEventListener('loadedmetadata', function() {
  canvas.width = videoElement.videoWidth;
  canvas.height = videoElement.videoHeight;
});

                        /*//Read blob data so we can stabilize the video
                        var reader = new FileReader();
                         reader.onload = function(event){
                                let text = reader.result;
                                console.log(text);
                          };
                        reader.readAsText(blob, "video/webm");*/
                        //console.log(orientationData);
                        //console.log(timestamps);
                        //console.log(dataArray);
/*
var blobUrl = URL.createObjectURL(blob);
var x = new XMLHttpRequest();
// set x.responseType = 'blob' if you want to get a Blob object:
// x.responseType = 'blob';
x.onload = function() {
    alert(x.responseText);
};
console.log(x.open('get', blobUrl));*/
                        readFrameData(blob, orientationData);    //reads the video into dataArray2
                        /*videoElement.onended = function() {
                                alert("The video has ended");
                                cancelAnimationFrame(ref);
                        };*/
                        //ctx.clearRect(0, 0, canvas.width, canvas.height);
                        //stabilize(dataArray2);        //now we can operate on it
                        //interval=window.setInterval(stabilize,20);
	        };

	        mediaRecorder.onpause = function(){
	        }

	        mediaRecorder.onresume = function(){
	        }

	        mediaRecorder.onwarning = function(e){
	        };
}

function stopRecording(){
	mediaRecorder.stop();
        //Now stabilize
	videoElement.controls = true;
}
//Idea: copy video to canvas, operate on the video, and then use the canvas with the stabilized video as source for the video element
function readFrameData(blob, oriArray) {     //Read video data from blob to object form with pixel data we can operate on
        console.log("frame");

        //console.log(orientationData);
        //console.log(oriInitial);
        //console.log(timestamps[nFrame] - timestamps[0], videoElement.currentTime);
        //while(!videoElement.ended)
        //{
        let x = 0;
        let y = 0;
        let oriDiff = null;
                //videoElement.playbackRate = 0.5;        //fix playback being too fast
                let ori = orientationData[nFrame];
                if(ori !== undefined)
                {
                        oriDiff = {"roll": ori.roll-oriInitial.roll, "pitch": ori.pitch-oriInitial.pitch, "yaw": ori.yaw-oriInitial.yaw};
                        x = videoElement.videoWidth*(oriDiff.yaw/(2*Math.Pi));
                        y = videoElement.videoWidth*(oriDiff.roll/(2*Math.Pi));     //each 2pi means 1 video height
                }
                else
                {
                        x = 0;
                        y = 0;
                }
                let widthR = 100;
                let heightR = 100;
                ctx.drawImage(videoElement,0,0, videoElement.videoWidth, videoElement.videoHeight);
                /*ctx.beginPath();
                ctx.rect(x,y,widthR,heightR);
                ctx.stroke();*/

                //ctx.drawImage(videoElement, 0, 0);
                let imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
                /*let pixeldataArray = [];
                //loop through every pixel
                for(let i=0; i<imageData.data.length; i = i+4)
                {
                        let pixeldata = {"red": imageData.data[i], "green":imageData.data[i+1], "blue": imageData.data[i+2], "alpha":imageData.data[i+3]};
                        //pixeldataArray.push(pixeldata);
                }
                //pixeldataArray.push(imageData);*/
                if(ori !== undefined) {
                        let timestamp = dataArray[nFrame].time;
                        let frameData2 = {"imagedata": imageData, "time": timestamp, "oridiff": oriDiff};
                        dataArray2.push(frameData2);
                        //console.log(pixeldataArray);
                        //newImageData.data = data;
                    // Draw the pixels onto the visible canvas
                    //ctx.putImageData(newImageData,0,0);
                        //ctx.putImageData(imageData, 0, 0)
                        //xD
                }
        //}
                nFrame = nFrame + 1;
                ref = requestAnimationFrame(readFrameData);
        /*
        if(dataArray2.length === timestamps.length)     //now we have read the whole blob - should use callback here instead of if condition
        {
                console.log("ended");
                cancelAnimationFrame(ref);
                console.log(dataArray2);
                stabilize(dataArray2);
        } */
        if(nFrame >= orientationData.length-1)
        {
                //cancelAnimationFrame(ref);
        }
}

function stabilize(dataArrayArg) { //Create a stabilized video from the pixel data given as input
        let frame = dataArrayArg[0];      //first frame
        console.log(frame);
        //ctx.drawImage(frame.imagedata,0,0, videoElement.videoWidth, videoElement.videoHeight);
        //ctx.putImageData(frame.imagedata, 0, 0);
}
<commit_msg>Working on reacting to sensor input<commit_after>/*
 * Websensor video stabilization project
 * https://github.com/jessenie-intel/websensor-video
 *
 * Copyright (c) 2017 Jesse Nieminen
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
*/

'use strict';

var constraints = {audio: true,video: {  width: { min: 640, ideal: 640, max: 640 },  height: { min: 480, ideal: 480, max: 480 }}};
var mediaRecorder = null;
var chunks = [];
var videoData = null;
var interval = null;

var accel_sensor = null;
var orientation_sensor = null;
var sensorfreq = 60;

//var roll = null;
//var pitch = null;
//var yaw = null;
var accel = {"x": null, "y": null, "z": null};
var ori = {"roll": null, "pitch": null, "yaw": null, "time": null};
var oriInitial = {"roll": null, "pitch": null, "yaw": null, "time": null};
var initialoriobtained = false;
var orientationData = [];       //array to store all the orientation data
var frameData = {"data": null, "time": null, "ori": null};
var dataArray = [];     //array to store all the combined data
var dataArray2 = [];     //array to store all the combined data

var time = null;
var timestamps = [];
var nFrame = 0; //frame number with which we can combine timestamp and frame data

//canvas
var canvas = document.querySelector('canvas');
var ctx = canvas.getContext('2d');

//video element
var videoElement = document.querySelector('video');
videoElement.controls = false;

var ref = null;

class AbsOriSensor {
        constructor() {
        const sensor = new AbsoluteOrientationSensor({ frequency: sensorfreq });
        const mat4 = new Float32Array(16);
        const euler = new Float32Array(3);
        sensor.onreading = () => {
                sensor.populateMatrix(mat4);
                toEulerianAngle(sensor.quaternion, euler);      //From quaternion to Eulerian angles
                this.roll = euler[0];
                this.pitch = euler[1];
                this.yaw = euler[2];
                this.timestamp = sensor.timestamp;
                if (this.onreading) this.onreading();
        };
        sensor.onactivate = () => {
                if (this.onactivate) this.onactivate();
        };
        const start = () => sensor.start();
        Object.assign(this, { start });
        }
}

//WINDOWS 10 HAS DIFFERENT CONVENTION: Yaw z, pitch x, roll y
function toEulerianAngle(quat, out)
{
        const ysqr = quat[1] ** 2;

        // Roll (x-axis rotation).
        const t0 = 2 * (quat[3] * quat[0] + quat[1] * quat[2]);
        const t1 = 1 - 2 * (ysqr + quat[0] ** 2);
        out[0] = Math.atan2(t0, t1);
        // Pitch (y-axis rotation).
        let t2 = 2 * (quat[3] * quat[1] - quat[2] * quat[0]);
        t2 = t2 > 1 ? 1 : t2;
        t2 = t2 < -1 ? -1 : t2;
        out[1] = Math.asin(t2);
        // Yaw (z-axis rotation).
        const t3 = 2 * (quat[3] * quat[2] + quat[0] * quat[1]);
        const t4 = 1 - 2 * (ysqr + quat[2] ** 2);
        out[2] = Math.atan2(t3, t4);
        return out;
}

function errorCallback(error){
	console.log("error: ", error);
}

function startDemo () {
		navigator.getUserMedia(constraints, startRecording, errorCallback);
}

function startRecording(stream) {

                try {
                //Initialize sensors
                /*accel_sensor = new Accelerometer();
                accel_sensor.onreading = () => {
                        accel = {"x": accel_sensor.x, "y": accel_sensor.y, "z": accel_sensor.z};
                };
                accel_sensor.onactivate = () => {
                };
                accel_sensor.start();*/
                orientation_sensor = new AbsOriSensor();
                orientation_sensor.onreading = () => {
                        let roll = orientation_sensor.roll;
                        let pitch = orientation_sensor.pitch;
                        let yaw = orientation_sensor.yaw;
                        time = orientation_sensor.timestamp;
                        if(!initialoriobtained) //obtain initial orientation
                        {
                                oriInitial = {"roll": orientation_sensor.roll, "pitch": orientation_sensor.pitch, "yaw": orientation_sensor.yaw, "time": orientation_sensor.timestamp};
                                initialoriobtained = true;
                        }
                        ori = {"roll": orientation_sensor.roll, "pitch": orientation_sensor.pitch, "yaw": orientation_sensor.yaw, "time": orientation_sensor.timestamp};
                };
                orientation_sensor.onactivate = () => {
                };
                orientation_sensor.start();
                }
                catch(err) {
                        console.log(err.message);
                        console.log("Your browser doesn't seem to support generic sensors. If you are running Chrome, please enable it in about:flags.");
                        //this.innerHTML = "Your browser doesn't seem to support generic sensors. If you are running Chrome, please enable it in about:flags";
                }
	        //var options = {mimeType: 'video/webm;codecs=vp9'};
		//mediaRecorder = new MediaRecorder(stream, options);
		mediaRecorder = new MediaRecorder(stream);

	        mediaRecorder.start(10);

	        var url = window.URL;
	        videoElement.src = url ? url.createObjectURL(stream) : stream;
                //videoElement.play();

	        mediaRecorder.ondataavailable = function(e) {
                        //console.log("Data available", e);
                        //console.log(time);
                        timestamps.push(time);
                        frameData.time = time;
		        chunks.push(e.data);
                        frameData.data = e.data;
                        orientationData.push(ori);
                        frameData.ori = ori;
                        var b = new Object;     //need to push by value
                        Object.assign(b, frameData);
                        dataArray.push(b);
	        };

	        mediaRecorder.onerror = function(e){
		        console.log('Error: ', e);
	        };

	        mediaRecorder.onstart = function(){
                        console.log("Recording started", mediaRecorder.state);
	        };

	        mediaRecorder.onstop = function(){
		        var blob = new Blob(chunks, {type: "video/webm"});
		        chunks = [];

		        var videoURL = window.URL.createObjectURL(blob);

		        videoElement.src = videoURL;
                        //videoElement.load();

                        //resize canvas
videoElement.addEventListener('loadedmetadata', function() {
  canvas.width = videoElement.videoWidth;
  canvas.height = videoElement.videoHeight;
});

                        /*//Read blob data so we can stabilize the video
                        var reader = new FileReader();
                         reader.onload = function(event){
                                let text = reader.result;
                                console.log(text);
                          };
                        reader.readAsText(blob, "video/webm");*/
                        //console.log(orientationData);
                        //console.log(timestamps);
                        //console.log(dataArray);
/*
var blobUrl = URL.createObjectURL(blob);
var x = new XMLHttpRequest();
// set x.responseType = 'blob' if you want to get a Blob object:
// x.responseType = 'blob';
x.onload = function() {
    alert(x.responseText);
};
console.log(x.open('get', blobUrl));*/
                        readFrameData(blob, orientationData);    //reads the video into dataArray2
                        /*videoElement.onended = function() {
                                alert("The video has ended");
                                cancelAnimationFrame(ref);
                        };*/
                        //ctx.clearRect(0, 0, canvas.width, canvas.height);
                        //stabilize(dataArray2);        //now we can operate on it
                        //interval=window.setInterval(stabilize,20);
	        };

	        mediaRecorder.onpause = function(){
	        }

	        mediaRecorder.onresume = function(){
	        }

	        mediaRecorder.onwarning = function(e){
	        };
}

function stopRecording(){
	mediaRecorder.stop();
        //Now stabilize
	videoElement.controls = true;
}
//Idea: copy video to canvas, operate on the video, and then use the canvas with the stabilized video as source for the video element
function readFrameData(blob, oriArray) {     //Read video data from blob to object form with pixel data we can operate on
        console.log("frame");

        //console.log(orientationData);
        //console.log(oriInitial);
        //console.log(timestamps[nFrame] - timestamps[0], videoElement.currentTime);
        //while(!videoElement.ended)
        //{
        let x = 0;
        let y = 0;
        let oriDiff = null;
                //videoElement.playbackRate = 0.5;        //fix playback being too fast
                let ori = orientationData[nFrame];
                if(ori !== undefined)
                {
                        oriDiff = {"roll": ori.roll-oriInitial.roll, "pitch": ori.pitch-oriInitial.pitch, "yaw": ori.yaw-oriInitial.yaw};
                        x = videoElement.videoWidth*(oriDiff.yaw/(2*Math.Pi));
                        y = videoElement.videoWidth*(oriDiff.roll/(2*Math.Pi));     //each 2pi means 1 video height
                }
                else
                {
                        x = 0;
                        y = 0;
                }
                let widthR = 100;
                let heightR = 100;
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                ctx.drawImage(videoElement,0,0, videoElement.videoWidth, videoElement.videoHeight);
                ctx.beginPath();
                ctx.rect(x,y,widthR,heightR);
                ctx.stroke();

                //ctx.drawImage(videoElement, 0, 0);
                let imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
                /*let pixeldataArray = [];
                //loop through every pixel
                for(let i=0; i<imageData.data.length; i = i+4)
                {
                        let pixeldata = {"red": imageData.data[i], "green":imageData.data[i+1], "blue": imageData.data[i+2], "alpha":imageData.data[i+3]};
                        //pixeldataArray.push(pixeldata);
                }
                //pixeldataArray.push(imageData);*/
                if(ori !== undefined) {
                        let timestamp = dataArray[nFrame].time;
                        let frameData2 = {"imagedata": imageData, "time": timestamp, "oridiff": oriDiff};
                        dataArray2.push(frameData2);
                        //console.log(pixeldataArray);
                        //newImageData.data = data;
                    // Draw the pixels onto the visible canvas
                    //ctx.putImageData(newImageData,0,0);
                        //ctx.putImageData(imageData, 0, 0)
                        //xD
                }
        //}
                nFrame = nFrame + 1;
                ref = requestAnimationFrame(readFrameData);
        /*
        if(dataArray2.length === timestamps.length)     //now we have read the whole blob - should use callback here instead of if condition
        {
                console.log("ended");
                cancelAnimationFrame(ref);
                console.log(dataArray2);
                stabilize(dataArray2);
        } */
        if(nFrame >= orientationData.length-1)
        {
                //cancelAnimationFrame(ref);
        }
}

function stabilize(dataArrayArg) { //Create a stabilized video from the pixel data given as input
        let frame = dataArrayArg[0];      //first frame
        console.log(frame);
        //ctx.drawImage(frame.imagedata,0,0, videoElement.videoWidth, videoElement.videoHeight);
        //ctx.putImageData(frame.imagedata, 0, 0);
}
<|endoftext|>


<commit_before>var imageContainerMargin = 70;  // Margin + padding
var currentBox = 0;
var scrollPosition = 0;

// This watches for the scrollable container
$('div#contents').scroll(function() {
  scrollPosition = $(this).scrollTop();
});

// This highlights selected GeoJSON polygons marked with Flag = 1; values not listed in ranges below display as the last color (white)
function getFillColor(d) {
  return  d == 1 ? 'red' :
          'white';
}

function style(feature) {
  return {
    color: 'blue',
    fillColor: getFillColor(feature.properties.Flag),
    weight: 2,
    fillOpacity: 0.2
  };
}

// This adds data as a new layer to the map
function refreshLayer(data, map, coord, zoom) {
  var dataLayer = L.geoJson(data, {
      style: style,
      //onEachFeature: onEachFeature // future option to show town name on click or hover
  });
  dataLayer.addTo(map);
  map.setView([coord[1], coord[0]], zoom);
}

function initMap() {
  // Although all coordinates and zoom are pulled from map.geojson, insert initial data here for smooth startup
  var map = L.map('map', {
    center: [0, 0],
    zoom: 5,
    scrollWheelZoom: false
  });

  // This customizes link to view source code; add your own GitHub repository
  map.attributionControl
  .setPrefix('View code on GitHub, created with Leaflet');

  // Legend control layers - global variable with (null, null) allows indiv layers to be added inside functions below
  // See style.css code that intentionally hides legend control in this version
  var controlLayers = L.control.layers( null, null, {
    position: "bottomright",
    collapsed: false // false = open by default
  }).addTo(map);

  // This displays the default tile layer
  var lightAll = new L.tileLayer('http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png', {
    attribution: '© OpenStreetMap contributors, © CartoDB'
  }).addTo(map);
  controlLayers.addBaseLayer(lightAll, 'default');

  // tileLayer.WMS as a baselayer - see http://leafletjs.com/reference.html#tilelayer-wms
  // UConn MAGIC WMS settings - see http://geoserver.lib.uconn.edu:8080/geoserver/web/?wicket:bookmarkablePage=:org.geoserver.web.demo.MapPreviewPage
  var map1795 = new L.tileLayer.wms("http://geoserver.lib.uconn.edu:8080/geoserver/MAGIC/wms?", {
    layers: 'MAGIC:Connecticut_Doolittle_1795',
    format: 'image/png',
    version: '1.1.0',
    transparent: true,
    attribution: '1795 MAGIC UConn'
  });
  controlLayers.addBaseLayer(map1795, '1795 map');

  var map1811 = new L.tileLayer.wms("http://geoserver.lib.uconn.edu:8080/geoserver/MAGIC/wms?", {
    layers: 'MAGIC:1811_Warren',
    format: 'image/png',
    version: '1.1.0',
    transparent: true,
    attribution: '1811 MAGIC UConn'
  });
  controlLayers.addBaseLayer(map1811, '1811 map');

  var map1855 = new L.tileLayer.wms("http://geoserver.lib.uconn.edu:8080/geoserver/MAGIC/wms?", {
    layers: 'MAGIC:HartfordCounty_Woodford_1855',
    format: 'image/png',
    version: '1.1.0',
    transparent: true,
    attribution: '1855 MAGIC UConn'
  });
  map1855.addTo(map);
  controlLayers.addBaseLayer(map1855, '1855 map');

  // This loads the GeoJSON map data file from a local folder
  $.getJSON('map.geojson', function(data) {
    var geojson = L.geoJson(data, {
      onEachFeature: function (feature, layer) {
        (function(layer, properties) {

          // This creates the contents of each chapter from the GeoJSON data. Unwanted items can be removed, and new ones can be added
          var chapter = $('

', {
            text: feature.properties['chapter'],
            class: 'chapter-header'
          });

          // images and source credits been commented-out from this version
          // var image = $('', {
          //   src: feature.properties['image'],
          // });

          // var source = $('', {
          //   text: feature.properties['source-credit'],
          //   href: feature.properties['source-link'],
          //   target: "_blank",
          //   class: 'source'
          // });

          var description = $('

', {
            text: feature.properties['description'],
            class: 'description'
          });

          var container = $('

', {
            id: 'container' + feature.properties['id'],
            class: 'image-container'
          });

          // var imgHolder = $('
</div', {
          //   class: 'img-holder'
          // });
          //
          // imgHolder.append(image);

          // imgHolder.append(image);
          // container.append(chapter).append(imgHolder).append(source).append(description);

          container.append(chapter).append(description);
          $('#contents').append(container);

          var i;
          var areaTop = -100;
          var areaBottom = 0;

          // Calculating total height of blocks above active
          for (i = 1; i < feature.properties['id']; i++) {
            areaTop += $('div#container' + i).height() + imageContainerMargin;
          }

          areaBottom = areaTop + $('div#container' + feature.properties['id']).height();

          $('div#contents').scroll(function() {
            if ($(this).scrollTop() >= areaTop && $(this).scrollTop() < areaBottom) {
              if (feature.properties['id'] != currentBox) {
                currentBox = feature.properties['id'];

                $('.image-container').removeClass("inFocus").addClass("outFocus");
                $('div#container' + feature.properties['id']).addClass("inFocus").removeClass("outFocus");

                // This removes all layers except the default base layer; change name if necessary
                map.eachLayer(function (layer) {
                  if (layer != lightAll) {
                    map.removeLayer(layer);
                  }
                });

                // This adds another data layer
                $.getJSON(feature.properties['layer'], function(data) {
                  var coord = feature.geometry['coordinates'];
                  var zoom = feature.properties['zoom'];
                  refreshLayer(data, map, coord, zoom);
                });

                // This loads the tile layer from map.geojson by imitating a click to the legend control span
                var tile = feature.properties['tile'];
                $($('span:contains(" ' + tile + '")').get(0)).siblings("input").click();
              }
            }
          });

        })(layer, feature.properties);
      }
    });

    $('#contents').append("

Top
");

  });
}

initMap();

$("div#contents").animate({ scrollTop: 5 });
<commit_msg>set initial center & zoom<commit_after>var imageContainerMargin = 70;  // Margin + padding
var currentBox = 0;
var scrollPosition = 0;

// This watches for the scrollable container
$('div#contents').scroll(function() {
  scrollPosition = $(this).scrollTop();
});

// This highlights selected GeoJSON polygons marked with Flag = 1; values not listed in ranges below display as the last color (white)
function getFillColor(d) {
  return  d == 1 ? 'red' :
          'white';
}

function style(feature) {
  return {
    color: 'blue',
    fillColor: getFillColor(feature.properties.Flag),
    weight: 2,
    fillOpacity: 0.2
  };
}

// This adds data as a new layer to the map
function refreshLayer(data, map, coord, zoom) {
  var dataLayer = L.geoJson(data, {
      style: style,
      //onEachFeature: onEachFeature // future option to show town name on click or hover
  });
  dataLayer.addTo(map);
  map.setView([coord[1], coord[0]], zoom);
}

function initMap() {
  // Although all coordinates and zoom are pulled from map.geojson, insert initial data here for smooth startup
  var map = L.map('map', {
    center: [41.79, -72.717],
    zoom: 10,
    scrollWheelZoom: false
  });

  // This customizes link to view source code; add your own GitHub repository
  map.attributionControl
  .setPrefix('View code on GitHub, created with Leaflet');

  // Legend control layers - global variable with (null, null) allows indiv layers to be added inside functions below
  // See style.css code that intentionally hides legend control in this version
  var controlLayers = L.control.layers( null, null, {
    position: "bottomright",
    collapsed: false // false = open by default
  }).addTo(map);

  // This displays the default tile layer
  var lightAll = new L.tileLayer('http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png', {
    attribution: '© OpenStreetMap contributors, © CartoDB'
  }).addTo(map);
  controlLayers.addBaseLayer(lightAll, 'default');

  // tileLayer.WMS as a baselayer - see http://leafletjs.com/reference.html#tilelayer-wms
  // UConn MAGIC WMS settings - see http://geoserver.lib.uconn.edu:8080/geoserver/web/?wicket:bookmarkablePage=:org.geoserver.web.demo.MapPreviewPage
  var map1795 = new L.tileLayer.wms("http://geoserver.lib.uconn.edu:8080/geoserver/MAGIC/wms?", {
    layers: 'MAGIC:Connecticut_Doolittle_1795',
    format: 'image/png',
    version: '1.1.0',
    transparent: true,
    attribution: '1795 MAGIC UConn'
  });
  controlLayers.addBaseLayer(map1795, '1795 map');

  var map1811 = new L.tileLayer.wms("http://geoserver.lib.uconn.edu:8080/geoserver/MAGIC/wms?", {
    layers: 'MAGIC:1811_Warren',
    format: 'image/png',
    version: '1.1.0',
    transparent: true,
    attribution: '1811 MAGIC UConn'
  });
  controlLayers.addBaseLayer(map1811, '1811 map');

  var map1855 = new L.tileLayer.wms("http://geoserver.lib.uconn.edu:8080/geoserver/MAGIC/wms?", {
    layers: 'MAGIC:HartfordCounty_Woodford_1855',
    format: 'image/png',
    version: '1.1.0',
    transparent: true,
    attribution: '1855 MAGIC UConn'
  });
  map1855.addTo(map);
  controlLayers.addBaseLayer(map1855, '1855 map');

  // This loads the GeoJSON map data file from a local folder
  $.getJSON('map.geojson', function(data) {
    var geojson = L.geoJson(data, {
      onEachFeature: function (feature, layer) {
        (function(layer, properties) {

          // This creates the contents of each chapter from the GeoJSON data. Unwanted items can be removed, and new ones can be added
          var chapter = $('

', {
            text: feature.properties['chapter'],
            class: 'chapter-header'
          });

          // images and source credits been commented-out from this version
          // var image = $('', {
          //   src: feature.properties['image'],
          // });

          // var source = $('', {
          //   text: feature.properties['source-credit'],
          //   href: feature.properties['source-link'],
          //   target: "_blank",
          //   class: 'source'
          // });

          var description = $('

', {
            text: feature.properties['description'],
            class: 'description'
          });

          var container = $('

', {
            id: 'container' + feature.properties['id'],
            class: 'image-container'
          });

          // var imgHolder = $('
</div', {
          //   class: 'img-holder'
          // });
          //
          // imgHolder.append(image);

          // imgHolder.append(image);
          // container.append(chapter).append(imgHolder).append(source).append(description);

          container.append(chapter).append(description);
          $('#contents').append(container);

          var i;
          var areaTop = -100;
          var areaBottom = 0;

          // Calculating total height of blocks above active
          for (i = 1; i < feature.properties['id']; i++) {
            areaTop += $('div#container' + i).height() + imageContainerMargin;
          }

          areaBottom = areaTop + $('div#container' + feature.properties['id']).height();

          $('div#contents').scroll(function() {
            if ($(this).scrollTop() >= areaTop && $(this).scrollTop() < areaBottom) {
              if (feature.properties['id'] != currentBox) {
                currentBox = feature.properties['id'];

                $('.image-container').removeClass("inFocus").addClass("outFocus");
                $('div#container' + feature.properties['id']).addClass("inFocus").removeClass("outFocus");

                // This removes all layers except the default base layer; change name if necessary
                map.eachLayer(function (layer) {
                  if (layer != lightAll) {
                    map.removeLayer(layer);
                  }
                });

                // This adds another data layer
                $.getJSON(feature.properties['layer'], function(data) {
                  var coord = feature.geometry['coordinates'];
                  var zoom = feature.properties['zoom'];
                  refreshLayer(data, map, coord, zoom);
                });

                // This loads the tile layer from map.geojson by imitating a click to the legend control span
                var tile = feature.properties['tile'];
                $($('span:contains(" ' + tile + '")').get(0)).siblings("input").click();
              }
            }
          });

        })(layer, feature.properties);
      }
    });

    $('#contents').append("

Top
");

  });
}

initMap();

$("div#contents").animate({ scrollTop: 5 });
<|endoftext|>