<commit_before>// register service worker

if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/sw-test/sw.js', {
    scope: '/*'
  }).then(function() {
    // registration worked
    console.log('Registration succeeded.');
  }).catch(function() {
    // registration failed
    console.log('Registration failed.');
  });
}

// function for loading each image via XHR

function imgLoad(imgJSON) {
// return a promise for an image loading
return new Promise(function(resolve, reject) {
  var request = new XMLHttpRequest();
  request.open('GET', imgJSON.url);
  request.responseType = 'blob';

  request.onload = function() {
	    if (request.status == 200) {
	      var arrayResponse = [];
	      arrayResponse[0] = request.response;
	      arrayResponse[1] = imgJSON;
	      resolve(arrayResponse);
	    } else {
	      reject(Error('Image didn\'t load successfully; error code:' + request.statusText));
	    }
  };

    request.onerror = function() {
      reject(Error('There was a network error.'));
  };

  // Send the request
  request.send();
  });
};

var imgSection = document.querySelector('section');

window.onload = function() {

  // load each set of image, alt text, name and caption
  for(i = 0; i<=Gallery.images.length-1; i++) {
    imgLoad(Gallery.images[i]).then(function(arrayResponse) {

      var myImage = document.createElement('img');
      var myFigure = document.createElement('figure');
      var myCaption = document.createElement('caption');
      var imageURL = window.URL.createObjectURL(arrayResponse[0]);

	  myImage.src = imageURL;
      myImage.setAttribute('alt', arrayResponse[1].alt);
      myCaption.innerHTML = '' + arrayResponse[1].name + ': Taken by ' + arrayResponse[1].credit;

      imgSection.appendChild(myFigure);
      myFigure.appendChild(myImage);
      myFigure.appendChild(myCaption);

	}, function(Error) {
	  console.log(Error);
	});
  };

};

<commit_msg>adding error printout to register failure callback to get more information on why registration is failing<commit_after>// register service worker

if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/sw-test/sw.js', {
    scope: '/*'
  }).then(function() {
    // registration worked
    console.log('Registration succeeded.');
  }).catch(function(error) {
    // registration failed
    console.log('Registration failed with ' + error);
  });
}

// function for loading each image via XHR

function imgLoad(imgJSON) {
// return a promise for an image loading
return new Promise(function(resolve, reject) {
  var request = new XMLHttpRequest();
  request.open('GET', imgJSON.url);
  request.responseType = 'blob';

  request.onload = function() {
	    if (request.status == 200) {
	      var arrayResponse = [];
	      arrayResponse[0] = request.response;
	      arrayResponse[1] = imgJSON;
	      resolve(arrayResponse);
	    } else {
	      reject(Error('Image didn\'t load successfully; error code:' + request.statusText));
	    }
  };

    request.onerror = function() {
      reject(Error('There was a network error.'));
  };

  // Send the request
  request.send();
  });
};

var imgSection = document.querySelector('section');

window.onload = function() {

  // load each set of image, alt text, name and caption
  for(i = 0; i<=Gallery.images.length-1; i++) {
    imgLoad(Gallery.images[i]).then(function(arrayResponse) {

      var myImage = document.createElement('img');
      var myFigure = document.createElement('figure');
      var myCaption = document.createElement('caption');
      var imageURL = window.URL.createObjectURL(arrayResponse[0]);

	  myImage.src = imageURL;
      myImage.setAttribute('alt', arrayResponse[1].alt);
      myCaption.innerHTML = '' + arrayResponse[1].name + ': Taken by ' + arrayResponse[1].credit;

      imgSection.appendChild(myFigure);
      myFigure.appendChild(myImage);
      myFigure.appendChild(myCaption);

	}, function(Error) {
	  console.log(Error);
	});
  };

};

<|endoftext|>


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

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

var httpServer = require('http').Server(app);
var io = require('socket.io')(httpServer);
httpServer.listen(43000);

// Connect to mongo
app.locals.db = require('mongoskin').db('mongodb://localhost:27017/trckr');

// Connected clients
app.locals.clients = [];

// Store clients for later
io.on('connection', function(socket){
  app.locals.clients.push(socket);

  getLastPoint(function(point) {
    emitPoint(point);
  });

  socket.on('disconnect', function(){
    // delete the client
  });
});

var getLastPoint = function(cb) {
  app.locals.db.collection('points').find({command: "BR00"}).sort({timestamp: -1}).limit(1).toArray(function(err, result) {
    if (err) throw err;
    cb(result[0]);
  });
};

var emitPoint = function(point) {
  for (var i = 0, len = app.locals.clients.length; i < len; i++) {
    app.locals.clients[i].emit('location', JSON.stringify(point));
  }
};

var savePoint = function(point) {
  app.locals.db.collection('points').insert([point], function(err, result) {
    debug('save result', err, result);
  });
};

var saveHeartbeat = function(heartbeat) {
  app.locals.db.collection('heartbeats').insert([heartbeat], function(err, result) {
    debug('save result', err, result);
  });
};

// Look away
var convertLatLng = function(input) {
  var degreesLength = input.length === 10 ? 3 : 2,
      degrees = input.slice(0, degreesLength),
      minutes = input.slice(degreesLength, input.length);
  minutes = (Number(minutes)/60)*100;
  minutes = minutes < 10 ? '0' + minutes : minutes;
  minutes = String(minutes).replace('.', '');

  return parseFloat(Number(degrees + '.' + minutes).toFixed(5));
}

var server = net.createServer(function (socket) {
  socket.on('data', function(data) {

    // Determin message type
    var msgType = null;

    if(data.length === 36) {
      msgType = 'heartbeat';
    } else if (data.length === 80) {
      msgType = 'location';
    } else {
      // Unknown message type
      throw 'Unknown message type for message' + data.toString();
      return;
    }

    // Trim leading and trailing parens
    data = data.slice(1,data.length-1);

    if(msgType === 'location') {
      /**
       * Example record:
       * (027042854711BR00150117A5702.5470N00955.1263E000.61648574.770000000000L00000000)
       *
       * 027042854711     # imei                        12 chars
       * BR00             # command                      4 chars
       * 150117           # date yy/mm/dd                6 chars
       * A                # A=valid GPS data, V=invalid  1 char
       * 5702.5470        # lat                          9 chars
       * N                # lat indicator                1 char
       * 00955.1263       # long                        10 chars
       * E                # long indicator               1 char
       * 000.6            # speed, km/hour               5 chars
       * 164857           # time hh/mm/ss                6 chars
       * 4.7700           # orientation, deb             6 chars
       * 00000000         # status                       8 chars
       * L                # always L ?                   1 char
       * 00000000         # mean milage ?                8 chars
       */
      var rec = {};
      rec.imei          = data.toString('ascii',  0, 12);
      rec.command       = data.toString('ascii', 12, 16);
      rec.year          = data.toString('ascii', 16, 18);
      rec.month         = data.toString('ascii', 18, 20);
      rec.day           = data.toString('ascii', 20, 22);
      rec.status        = data.toString('ascii', 22, 23);
      rec.lat           = convertLatLng(data.toString('ascii', 23, 32));
      rec.latIndicator  = data.toString('ascii', 32, 33);
      rec.lng           = convertLatLng(data.toString('ascii', 33, 43));
      rec.lngIndicator  = data.toString('ascii', 43, 44);
      rec.speed         = data.toString('ascii', 44, 49);
      rec.hour          = data.toString('ascii', 49, 51);
      rec.minute        = data.toString('ascii', 51, 53);
      rec.second        = data.toString('ascii', 53, 55);
      rec.orientation   = data.toString('ascii', 55, 61);
      rec.status        = data.toString('ascii', 61, 69);
      rec.l             = data.toString('ascii', 69, 70);
      rec.milage        = data.toString('ascii', 70, 78);

      rec.timestamp     = new Date(Date.UTC(
        parseInt(rec.year, 10) + 2000, // Otherwise Data defaults to 19xx
        parseInt(rec.month) - 1, // Month is zero based, because Javascript
        parseInt(rec.day),
        parseInt(rec.hour),
        parseInt(rec.minute),
        parseInt(rec.second)
      ));

      savePoint(rec);
      emitPoint(rec);
    } else if (msgType === 'heartbeat') {
      /**
       * Example record: (027042854711BP00000027042854711HSO)
       *
       * 027042854711       # imei            12 chars
       * BP00               # record type      4 chars
       * 000027042854711    # device id       15 chars
       * HSO                # message body     3 chars
       */
      var rec = {};
      rec.imei          = data.toString('ascii',  0, 12);
      rec.command       = data.toString('ascii', 12, 16);
      rec.deviceId      = data.toString('ascii', 16, 31);
      rec.body          = data.toString('ascii', 31, 34);

      saveHeartbeat(rec);
    }
    socket.end();
  });
});

server.listen(43510);

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

app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

// Mount folders with static assets to /static
app.use('/static', express.static(path.join(__dirname, 'public')));
app.use('/static', express.static(path.join(__dirname, 'bower_components')));

// Define route(s)
app.use('/', routes);

// 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: {}
    });
});

module.exports = app;
<commit_msg>If multiple messages are concatinated, split by ")(" and handle each part seperatly.<commit_after>var express = require('express');
var app = express();
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var net = require('net');
var debug = require('debug')('app');

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

var httpServer = require('http').Server(app);
var io = require('socket.io')(httpServer);
httpServer.listen(43000);

// Connect to mongo
app.locals.db = require('mongoskin').db('mongodb://localhost:27017/trckr');

// Connected clients
app.locals.clients = [];

// Store clients for later
io.on('connection', function(socket){
  app.locals.clients.push(socket);

  getLastPoint(function(point) {
    emitPoint(point);
  });

  socket.on('disconnect', function(){
    // delete the client
  });
});

var getLastPoint = function(cb) {
  app.locals.db.collection('points').find({command: "BR00"}).sort({timestamp: -1}).limit(1).toArray(function(err, result) {
    if (err) throw err;
    cb(result[0]);
  });
};

var emitPoint = function(point) {
  for (var i = 0, len = app.locals.clients.length; i < len; i++) {
    app.locals.clients[i].emit('location', JSON.stringify(point));
  }
};

var savePoint = function(point) {
  app.locals.db.collection('points').insert([point], function(err, result) {
    debug('save result', err, result);
  });
};

var saveHeartbeat = function(heartbeat) {
  app.locals.db.collection('heartbeats').insert([heartbeat], function(err, result) {
    debug('save result', err, result);
  });
};

// Look away
var convertLatLng = function(input) {
  var degreesLength = input.length === 10 ? 3 : 2,
      degrees = input.slice(0, degreesLength),
      minutes = input.slice(degreesLength, input.length);
  minutes = (Number(minutes)/60)*100;
  minutes = minutes < 10 ? '0' + minutes : minutes;
  minutes = String(minutes).replace('.', '');

  return parseFloat(Number(degrees + '.' + minutes).toFixed(5));
}

var server = net.createServer(function (socket) {
  socket.on('data', function(data) {

    // Determin message type
    var msgType = null;

    // Trim leading and trailing parens
    data = data.slice(1,data.length-1);

    // Split string by ")(" (if messages are concatinated)
    var arr = data.toString().split(")(");

    // for each element run the following
    arr.forEach(function(data) {

      if(data.length === 34) {
        msgType = 'heartbeat';
      } else if (data.length === 78) {
        msgType = 'location';
      } else {
        // Unknown message type
        throw 'Unknown message type for message' + data.toString();
        return;
      }

      if(msgType === 'location') {
        /**
         * Example record:
         * (027042854711BR00150117A5702.5470N00955.1263E000.61648574.770000000000L00000000)
         *
         * 027042854711     # imei                        12 chars
         * BR00             # command                      4 chars
         * 150117           # date yy/mm/dd                6 chars
         * A                # A=valid GPS data, V=invalid  1 char
         * 5702.5470        # lat                          9 chars
         * N                # lat indicator                1 char
         * 00955.1263       # long                        10 chars
         * E                # long indicator               1 char
         * 000.6            # speed, km/hour               5 chars
         * 164857           # time hh/mm/ss                6 chars
         * 4.7700           # orientation, deb             6 chars
         * 00000000         # status                       8 chars
         * L                # always L ?                   1 char
         * 00000000         # mean milage ?                8 chars
         */
        var rec = {};
        rec.imei          = data.substring(0, 12);
        rec.command       = data.substring(12, 16);
        rec.year          = data.substring(16, 18);
        rec.month         = data.substring(18, 20);
        rec.day           = data.substring(20, 22);
        rec.status        = data.substring(22, 23);
        rec.lat           = convertLatLng(data.substring(23, 32));
        rec.latIndicator  = data.substring(32, 33);
        rec.lng           = convertLatLng(data.substring(33, 43));
        rec.lngIndicator  = data.substring(43, 44);
        rec.speed         = data.substring(44, 49);
        rec.hour          = data.substring(49, 51);
        rec.minute        = data.substring(51, 53);
        rec.second        = data.substring(53, 55);
        rec.orientation   = data.substring(55, 61);
        rec.status        = data.substring(61, 69);
        rec.l             = data.substring(69, 70);
        rec.milage        = data.substring(70, 78);

        rec.timestamp     = new Date(Date.UTC(
          parseInt(rec.year, 10) + 2000, // Otherwise Data defaults to 19xx
          parseInt(rec.month) - 1, // Month is zero based, because Javascript
          parseInt(rec.day),
          parseInt(rec.hour),
          parseInt(rec.minute),
          parseInt(rec.second)
        ));

        savePoint(rec);
        emitPoint(rec);
      } else if (msgType === 'heartbeat') {
        /**
         * Example record: (027042854711BP00000027042854711HSO)
         *
         * 027042854711       # imei            12 chars
         * BP00               # record type      4 chars
         * 000027042854711    # device id       15 chars
         * HSO                # message body     3 chars
         */
        var rec = {};
        rec.imei          = data.substring( 0, 12);
        rec.command       = data.substring(12, 16);
        rec.deviceId      = data.substring(16, 31);
        rec.body          = data.substring(31, 34);

        saveHeartbeat(rec);
      }
    });
    socket.end();
  });
});

server.listen(43510);

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

app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

// Mount folders with static assets to /static
app.use('/static', express.static(path.join(__dirname, 'public')));
app.use('/static', express.static(path.join(__dirname, 'bower_components')));

// Define route(s)
app.use('/', routes);

// 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: {}
    });
});

module.exports = app;
<|endoftext|>


<commit_before>
'use strict';

console.log('Launching…');

// Pseudo-constants:
var PREFIX = 'stubs/'
,   SUFFIX = '.sh'
,   STEPS = [
      'retrieve-resources'
    , 'third-party-checker'
    , 'specberus'
    , 'link-checker'
    , 'parse-metadata'
    , 'publish'
    ]
;

var Promise = require('promise');

var meta = require('./package.json')
,   express = require('express')
,   ejs = require('ejs')
,   spawn = require('child_process').spawn
,   app = express()
,   port = 3000
,   requests = {}
;

app.use(express.compress());
app.use(express.bodyParser({}));

app.set('view engine', 'ejs');
app.engine('.html', ejs.renderFile);

if (process.env.NODE_ENV === 'production') {
  app.set('views', __dirname + '/dist/views');
  app.use(express.static(__dirname + '/dist/assets'));
} else {
  app.set('views', __dirname + '/views');
  app.use(express.static(__dirname + '/assets'));
}

// Index Page
app.get('/', function(request, response, next) {
  response.render('index.html');
});

// API methods

app.get('/api/version', function(req, res) {
  res.send(meta.name +
    ' version ' + meta.version +
    ' running on ' + process.platform +
    ' and listening on port ' + port +
    '. The server time is ' + new Date().toLocaleTimeString() + '.');
});

app.get('/api/status', function(req, res) {
  var result
  ,   url = req.body ? req.body.url : null
  ,   entry
  ;
  if (url) {
    if (requests[url]) {
      res.json(requests[url]);
    }
    else {
      res.send(500, {error: 'Request of URL ' + url + ' does not exist.'});
    }
  }
  else {
    result = {'requests': {}};
    for (entry in requests) {
      result.requests[entry] = requests[entry];
    }
    res.json(result);
  }
});

app.post('/api/request', function(req, res) {
  var url = req.body ? req.body.url : null
  ,   decision = req.body ? req.body.decision : null
  ;
  if (!url || !decision) {
    res.send(500, {error: 'Missing parameters {url, decision}.'});
  }
  else {
    if (requests[url]) {
      res.send('Spec at ' + url + ' is yet pending validation OR has been already submitted. Check “/api/status”.');
    }
    else {
      requests[url] = {'decision': decision, 'stage': -1, 'jobs': {}, 'errors': []};
      orchestrate(url);
      res.send(200, 'Spec at ' + url + ' (decision: ' + decision + ') added to the queue.');
    }
  }
});

function dumpLine(data) {
  console.log(data);
}

function retrieve(url) {
  return new Promise(function (resolve, reject) {
    var job = spawn('stubs/retrieve-resources.sh', [url]);

    job.on('exit', function (innerCode, innerSignal) {
      if (innerCode === 0) {
        resolve(url);
      }
      else {
        reject("retrieve step failed.");
      }
    });
  });

}

function specberus(url) {
  return new Promise(function (resolve, reject) {
    var job = spawn('stubs/specberus.sh', [url]);

    job.on('exit', function (innerCode, innerSignal) {
      if (innerCode === 0) {
        resolve(url);
      }
      else {
        reject("specberus step failed.");
      }
    });
  });
}

function orchestrate(url) {
  var spec = requests[url];

  spec.jobs['retrieve-resources'] = {};
  spec.jobs['retrieve-resources'].status = 'pending';

  retrieve(url).then(
    function (url) {
      spec.jobs['retrieve-resources'].status = 'ok';

      spec.jobs['specberus'] = {};
      spec.jobs['specberus'].status = 'pending';
      return specberus(url);
    },
    function (err) {
      spec.jobs['retrieve-resources'].status = 'failure';
      spec.errors.push(err);
    }
  ).then(
    function (url) {
      spec.jobs['specberus'].status = 'ok';
    },
    function (err) {
      spec.jobs['specberus'].status = 'failure';
      spec.errors.push(err);
    }
  );

}

function processJob(url, code, signal) {
  var spec
  ,   job;
  if (requests[url]) {
    spec = requests[url];
    if (code && 0 !== code) {
      spec.jobs[STEPS[spec.stage]].status = 'failure';
      spec.errors.push(STEPS[spec.stage] + ' failed with code ' + code + '.');
    }
    else if (spec.stage >= -1 && spec.stage < STEPS.length - 1) {
      if (spec.stage !== -1) {
        spec.jobs[STEPS[spec.stage]].status = 'ok';
      }
      spec.stage ++;
      spec.jobs[STEPS[spec.stage]] = {};
      spec.jobs[STEPS[spec.stage]].status = 'pending';
      job = spawn(PREFIX + STEPS[spec.stage] + SUFFIX, [url]);
      /* job.stdout.on('data', dumpLine);
      job.stderr.on('data', dumpLine); */
      job.on('exit', function(innerCode, innerSignal) {
        processJob(url, innerCode, innerSignal);
      });
    }
    else if (STEPS.length - 1 === spec.stage) {
      spec.jobs[STEPS[spec.stage]].status = 'ok';
      console.log('Spec at ' + url + ' (decision: ' + spec.decision + ') has finished.');
      requests[url].time = new Date().toLocaleTimeString('en-GB');
    }
  }
  else {
    console.error('Cannot find spec at "' + url + '".');
  }
}

app.listen(process.env.PORT || port);

console.log(meta.name +
  ' version ' + meta.version +
  ' running on ' + process.platform +
  ' and listening on port ' + port +
  '. The server time is ' + new Date().toLocaleTimeString() + '.');

// EOF

<commit_msg>Pass Error in reject arguments rather than strings<commit_after>
'use strict';

console.log('Launching…');

// Pseudo-constants:
var PREFIX = 'stubs/'
,   SUFFIX = '.sh'
,   STEPS = [
      'retrieve-resources'
    , 'third-party-checker'
    , 'specberus'
    , 'link-checker'
    , 'parse-metadata'
    , 'publish'
    ]
;

var Promise = require('promise');

var meta = require('./package.json')
,   express = require('express')
,   ejs = require('ejs')
,   spawn = require('child_process').spawn
,   app = express()
,   port = 3000
,   requests = {}
;

app.use(express.compress());
app.use(express.bodyParser({}));

app.set('view engine', 'ejs');
app.engine('.html', ejs.renderFile);

if (process.env.NODE_ENV === 'production') {
  app.set('views', __dirname + '/dist/views');
  app.use(express.static(__dirname + '/dist/assets'));
} else {
  app.set('views', __dirname + '/views');
  app.use(express.static(__dirname + '/assets'));
}

// Index Page
app.get('/', function(request, response, next) {
  response.render('index.html');
});

// API methods

app.get('/api/version', function(req, res) {
  res.send(meta.name +
    ' version ' + meta.version +
    ' running on ' + process.platform +
    ' and listening on port ' + port +
    '. The server time is ' + new Date().toLocaleTimeString() + '.');
});

app.get('/api/status', function(req, res) {
  var result
  ,   url = req.body ? req.body.url : null
  ,   entry
  ;
  if (url) {
    if (requests[url]) {
      res.json(requests[url]);
    }
    else {
      res.send(500, {error: 'Request of URL ' + url + ' does not exist.'});
    }
  }
  else {
    result = {'requests': {}};
    for (entry in requests) {
      result.requests[entry] = requests[entry];
    }
    res.json(result);
  }
});

app.post('/api/request', function(req, res) {
  var url = req.body ? req.body.url : null
  ,   decision = req.body ? req.body.decision : null
  ;
  if (!url || !decision) {
    res.send(500, {error: 'Missing parameters {url, decision}.'});
  }
  else {
    if (requests[url]) {
      res.send('Spec at ' + url + ' is yet pending validation OR has been already submitted. Check “/api/status”.');
    }
    else {
      requests[url] = {'decision': decision, 'stage': -1, 'jobs': {}, 'errors': []};
      orchestrate(url);
      res.send(200, 'Spec at ' + url + ' (decision: ' + decision + ') added to the queue.');
    }
  }
});

function dumpLine(data) {
  console.log(data);
}

function retrieve(url) {
  return new Promise(function (resolve, reject) {
    var job = spawn('stubs/retrieve-resources.sh', [url]);

    job.on('exit', function (innerCode, innerSignal) {
      if (innerCode === 0) {
        resolve(url);
      }
      else {
        reject(new Error("retrieve-resources step failed with code " + innerCode));
      }
    });
  });
}

function specberus(url) {
  return new Promise(function (resolve, reject) {
    var job = spawn('stubs/specberus.sh', [url]);

    job.on('exit', function (innerCode, innerSignal) {
      if (innerCode === 0) {
        resolve(url);
      }
      else {
        reject(new Error("specberus step failed with code " + innerCode));
      }
    });
  });
}

function orchestrate(url) {
  var spec = requests[url];

  spec.jobs['retrieve-resources'] = {};
  spec.jobs['retrieve-resources'].status = 'pending';

  retrieve(url).then(
    function (url) {
      spec.jobs['retrieve-resources'].status = 'ok';

      spec.jobs['specberus'] = {};
      spec.jobs['specberus'].status = 'pending';
      return specberus(url);
    },
    function (err) {
      spec.jobs['retrieve-resources'].status = 'failure';
      spec.errors.push(err.toString());
    }
  ).then(
    function (url) {
      spec.jobs['specberus'].status = 'ok';
    },
    function (err) {
      spec.jobs['specberus'].status = 'failure';
      spec.errors.push(err.toString());
    }
  );

}

function processJob(url, code, signal) {
  var spec
  ,   job;
  if (requests[url]) {
    spec = requests[url];
    if (code && 0 !== code) {
      spec.jobs[STEPS[spec.stage]].status = 'failure';
      spec.errors.push(STEPS[spec.stage] + ' failed with code ' + code + '.');
    }
    else if (spec.stage >= -1 && spec.stage < STEPS.length - 1) {
      if (spec.stage !== -1) {
        spec.jobs[STEPS[spec.stage]].status = 'ok';
      }
      spec.stage ++;
      spec.jobs[STEPS[spec.stage]] = {};
      spec.jobs[STEPS[spec.stage]].status = 'pending';
      job = spawn(PREFIX + STEPS[spec.stage] + SUFFIX, [url]);
      /* job.stdout.on('data', dumpLine);
      job.stderr.on('data', dumpLine); */
      job.on('exit', function(innerCode, innerSignal) {
        processJob(url, innerCode, innerSignal);
      });
    }
    else if (STEPS.length - 1 === spec.stage) {
      spec.jobs[STEPS[spec.stage]].status = 'ok';
      console.log('Spec at ' + url + ' (decision: ' + spec.decision + ') has finished.');
      requests[url].time = new Date().toLocaleTimeString('en-GB');
    }
  }
  else {
    console.error('Cannot find spec at "' + url + '".');
  }
}

app.listen(process.env.PORT || port);

console.log(meta.name +
  ' version ' + meta.version +
  ' running on ' + process.platform +
  ' and listening on port ' + port +
  '. The server time is ' + new Date().toLocaleTimeString() + '.');

// EOF

<|endoftext|>


<commit_before>#!/usr/bin/env node

var colors = require('colors');
var program = require('commander');
var moment = require('moment');
var momentRelative = require('moment-relative');
var parseMessyTime = require('parse-messy-time');

program
	.version(require('./package.json').version)
	.option('-c, --countdown', 'Display a countdown')
	.option('-v, --verbose', 'Be verbose. Specify multiple times for increasing verbosity', function(i, v) { return v + 1 }, 0)
	.parse(process.argv);

if (!program.args.length) {
	console.log('No time specified');
	process.exit(1);
}

// Try parse with moment
var time = program.args.join(' ');
if (program.verbose > 1) console.log(colors.blue('[Coma]'), 'Trying to parse', time);

// Main time parser {{{
var parsedTime = function(time) {
	// Parse with moment
	var parsedMoment = moment(time);
	if (parsedMoment.isValid()) return parsedMoment.toDate(time);

	// Parse with moment-relative
	try {
		var parsedMomentRelative = momentRelative()
		parsedMomentRelative.relative(time);
		if (parsedMomentRelative.isValid()) return parsedMomentRelative.toDate(time);
	} catch (e) {
		// Ignore moment-relatives weird parsing errors and continue
	}

	// Parse with parse-messy-time
	var parsedMessyTime = parseMessyTime(time);
	if (parsedMessyTime) return parsedMessyTime;

	return false;
}(time);
// }}}

// Sanity check that the date is valid {{{
if (!parsedTime) {
	console.log(colors.blue('[Coma]'), colors.red('ERROR'), 'Cannot parse date:', time);
	process.exit(1);
} else if (parsedTime < (new Date)) {
	console.log(colors.blue('[Coma]'), colors.red('ERROR'), 'Date', colors.cyan(parsedTime.toString()), 'is in the past');
	process.exit(1);
}
// }}}

if (program.verbose > 1) console.log(colors.blue('[Coma]'), 'Sleeping until', colors.cyan(parsedTime.toString()));
if (program.verbose) console.log(colors.blue('[Coma]'), 'Sleeping', colors.cyan(moment.duration(parsedTime.getTime() - (new Date).getTime(), 'milliseconds').humanize()));

setInterval(function() {
	var now = (new Date);
	if (parsedTime < now) {
		if (program.verbose) console.log(colors.blue('[Coma]'), colors.bold.green('Completed!'));
		process.exit(0);
	} else if (program.countdown) {
		var momentD = moment.duration(parsedTime.getTime() - now.getTime(), 'milliseconds');

		console.log(colors.blue('[Coma]'), 'Remaining time', colors.cyan(
			momentD.humanize()
		));
	}
}, 1000);
<commit_msg>BUGFIX: Moment no longer throws depreciation errors<commit_after>#!/usr/bin/env node

var colors = require('colors');
var program = require('commander');
var moment = require('moment');
var momentRelative = require('moment-relative');
var parseMessyTime = require('parse-messy-time');

program
	.version(require('./package.json').version)
	.option('-c, --countdown', 'Display a countdown')
	.option('-v, --verbose', 'Be verbose. Specify multiple times for increasing verbosity', function(i, v) { return v + 1 }, 0)
	.parse(process.argv);

if (!program.args.length) {
	console.log('No time specified');
	process.exit(1);
}

// Try parse with moment
var time = program.args.join(' ');
if (program.verbose > 1) console.log(colors.blue('[Coma]'), 'Trying to parse', time);

// Main time parser {{{
var parsedTime = function(time) {
	// Parse with moment
	try {
		var parsedRawDate = Date.parse(time);
		var parsedMoment = moment(parsedRawDate);
		if (parsedMoment.isValid()) return parsedMoment.toDate(time);
	} catch (e) {
		console.log('C!');
		// Ignore moment complaints and try next method
	}

	// Parse with moment-relative
	try {
		var parsedMomentRelative = momentRelative()
		parsedMomentRelative.relative(time);
		if (parsedMomentRelative.isValid()) return parsedMomentRelative.toDate(time);
	} catch (e) {
		// Ignore moment-relatives weird parsing errors and continue
	}

	// Parse with parse-messy-time
	var parsedMessyTime = parseMessyTime(time);
	if (parsedMessyTime) return parsedMessyTime;

	return false;
}(time);
// }}}

// Sanity check that the date is valid {{{
if (!parsedTime) {
	console.log(colors.blue('[Coma]'), colors.red('ERROR'), 'Cannot parse date:', time);
	process.exit(1);
} else if (parsedTime < (new Date)) {
	console.log(colors.blue('[Coma]'), colors.red('ERROR'), 'Date', colors.cyan(parsedTime.toString()), 'is in the past');
	process.exit(1);
}
// }}}

if (program.verbose > 1) console.log(colors.blue('[Coma]'), 'Sleeping until', colors.cyan(parsedTime.toString()));
if (program.verbose) console.log(colors.blue('[Coma]'), 'Sleeping', colors.cyan(moment.duration(parsedTime.getTime() - (new Date).getTime(), 'milliseconds').humanize()));

setInterval(function() {
	var now = (new Date);
	if (parsedTime < now) {
		if (program.verbose) console.log(colors.blue('[Coma]'), colors.bold.green('Completed!'));
		process.exit(0);
	} else if (program.countdown) {
		var momentD = moment.duration(parsedTime.getTime() - now.getTime(), 'milliseconds');

		console.log(colors.blue('[Coma]'), 'Remaining time', colors.cyan(
			momentD.humanize()
		));
	}
}, 1000);
<|endoftext|>


<commit_before>'use strict';

// var percent = [];
var arrayAllImg = [];
var totalClicks = 0;
var clickLim = 3;

var arrayAllImg = [
  new Image('bag' , 'assets/bag.jpg'),
  new Image('bathroom' , 'assets/bathroom.jpg'),
  new Image('boots' , 'assets/boots.jpg'),
  new Image('banana' , 'assets/banana.jpg'),
  new Image('breakfast' , 'assets/breakfast.jpg'),
  new Image('bubblegum' , 'assets/bubblegum.jpg'),
  new Image('chair' , 'assets/chair.jpg'),
  new Image('cthulhu' , 'assets/cthulhu.jpg'),
  new Image('dog duck' , 'assets/dog-duck.jpg'),
  new Image('dragon' , 'assets/dragon.jpg'),
  new Image('pen' , 'assets/pen.jpg'),
  new Image('pet sweep' , 'assets/pet-sweep.jpg'),
  new Image('scissors' , 'assets/scissors.jpg'),
  new Image('shark' , 'assets/shark.jpg'),
  new Image('sweep' , 'assets/sweep.png'),
  new Image('tauntaun' , 'assets/tauntaun.jpg'),
  new Image('unicorn' , 'assets/unicorn.jpg'),
  new Image('usb' , 'assets/usb.gif'),
  new Image('water can' , 'assets/water-can.jpg'),
  new Image('wine glass' , 'assets/wine-glass.jpg'),
];

// Constructor to make an array of all image objects
function Image(imgName , filePath){
  console.log('Image', imgName);
  this.imgName = imgName;
  this.filePath = filePath;
  this.shown = 0;
  this.clicks = 0;
  arrayAllImg.push(this);
};

// place function here to run the below (eventhandler)
// function loadImage(){

  // function to generate a random number from the length of the array containing all images
function randomNumbGenerator(){
  return parseInt(Math.random() * arrayAllImg.length);
};
// set the variable for indice array of images alraedy clicked
var oldIdx = [];

// Make an array of clicked images and Inc the tally of clicks on the img's position[i] within that array, if the img was already picked then draw again
function getRandomImgs(event){
  totalClicks++;
  if (event){
    var clickedImgIdx = parseInt(event.target.alt);
    arrayAllImg[clickedImgIdx].clicks++;
  }
    // get all the imgTag that have the class of clickable
  var imgTag = document.getElementsByClassName('clickable');
  // this array holds the random indexes
  var randomIdx = [];

    // for each div to fill with an img, genterate a random index position. The imgTag length depends on how many className 'clickable' elements are listed in html
  for (var i = 0; i < imgTag.length; i++){
    var idx = randomNumbGenerator();
    while (randomIdx.indexOf(idx) !== -1 || oldIdx.indexOf(idx) !== -1){
        // check for duplicate displayed imgages on same draw or if the image was just seen...run function again to pick a diff image
      idx = randomNumbGenerator();
    }
    // generate a # to represent the position in the array
    randomIdx[i] = idx;
  }
  // kept the newly generated Idx to compare for duplicates on the next click
  oldIdx = randomIdx;
    // create a variable for an array of items to be displayed and once it has been displayed then increase the number of times shown.
  var productsToBeDisplayed = [];
  for (var i = 0; i < randomIdx.length; i++){
    var thisIdx = randomIdx[i];
    productsToBeDisplayed[i] = arrayAllImg[thisIdx];
    arrayAllImg[thisIdx].shown++;
  }
    // Loop through the imgTag in html and find the tags to fill the src with the filePath and the and the index of that corresponding product in the 'alt' attribute of the img.
    // according to the random position in the array, fill the src of the imgTag with a filePath and store the index corresponding to that product in the 'alt' attribute of the image.

  for (var i = 0; i < imgTag.length; i++){
    imgTag[i].setAttribute('src' , productsToBeDisplayed[i].filePath);
    imgTag[i].setAttribute('alt' , randomIdx[i]);
  }
    // Remove event handler when clickLim is reached
  if (totalClicks >= clickLim) {
    for (var i = 0; i < imgTag.length; i++) {
      imgTag[i].removeEventListener('click' , getRandomImgs);
      // createStoreData();
      // storeData(i);
    }
      // select the id click-info in html and create unordered list as a child element below it
    var clickInfo = document.getElementById('click-info');
    var ul = document.createElement('ul');
    clickInfo.appendChild(ul);

    // for each of the images, list its clicked and shown info
    for (var i = 0; i < arrayAllImg.length; i++) {
      var thisImage = arrayAllImg[i];
      var li = document.createElement('li');
      var fillerInfo = '';
      fillerInfo += thisImage.imgName;
      if (thisImage.shown === 0){
        fillerInfo += ' | Click Rate: None';
      } else {
        console.log('NAME:  ', thisImage.imgName);
        console.log('thisImage.clicks: ', thisImage.clicks);
        console.log('thisImage.shown: ', thisImage.shown);
        fillerInfo += ' | Click Rate: ' + (thisImage.clicks / thisImage.shown * 100) + '%';
      }
      li.innerText = fillerInfo;
      ul.appendChild(li);
    }
  }
}

getRandomImgs();
// compensating for the extra click added by calling the above function when page initially loads
totalClicks--;

// event listener for clicks - call the getRandomImgs function when someone clicks on an imgTag item
var imgTag = document.getElementsByClassName('clickable');
for (var i = 0; i < imgTag.length; i++) {
  imgTag[i].addEventListener('click' , getRandomImgs);
}

  // checking the work
function productsShown() {
  for (var i = 0; i < arrayAllImg.length; i++) {
    console.log(arrayAllImg[i].imgName + 'shown' + arrayAllImg[i].shown + 'times.');
    console.log(arrayAllImg[i].imgName + 'clicked' + arrayAllImg[i].clicks + 'times.');
  }
}
localStorage.setItem('arrayAllImg', JSON.stringify(arrayAllImg));
var holder =JSON.parse(localStorage.getItem('arrayAllImg'));
console.log(holder);
console.log(holder[0].shown);

var table = document.getElementById('table');
var tr = document.createElement('tr');
table.appendChild(tr);
for (var i = 0; i < holder.length; i++) {
  var td = document.createElement('td');
  td.innerText = holder[i].shown;
  tr.appendChild(td);
}
var tr2 = document.createElement('tr');
table.appendChild(tr2);
for (var i = 0; i < holder.length; i++) {
    var td = document.createElement('td');
    td.innerText = holder[i].clicks;
    tr2.appendChild(td);
}

var canvas = document.getElementById('chart');
var ctx = canvas.getContext('2d');
<commit_msg>updates to local storage for clicks and shown<commit_after>'use strict';

// var percent = [];
var holder = JSON.parse(localStorage.getItem('arrayAllImg'));
console.log(holder);
console.log(holder[0].shown);

var arrayAllImg = [];
var totalClicks = 0;
var clickLim = 3;

var arrayAllImg = [
  new Image('bag' , 'assets/bag.jpg'),
  new Image('bathroom' , 'assets/bathroom.jpg'),
  new Image('boots' , 'assets/boots.jpg'),
  new Image('banana' , 'assets/banana.jpg'),
  new Image('breakfast' , 'assets/breakfast.jpg'),
  new Image('bubblegum' , 'assets/bubblegum.jpg'),
  new Image('chair' , 'assets/chair.jpg'),
  new Image('cthulhu' , 'assets/cthulhu.jpg'),
  new Image('dog duck' , 'assets/dog-duck.jpg'),
  new Image('dragon' , 'assets/dragon.jpg'),
  new Image('pen' , 'assets/pen.jpg'),
  new Image('pet sweep' , 'assets/pet-sweep.jpg'),
  new Image('scissors' , 'assets/scissors.jpg'),
  new Image('shark' , 'assets/shark.jpg'),
  new Image('sweep' , 'assets/sweep.png'),
  new Image('tauntaun' , 'assets/tauntaun.jpg'),
  new Image('unicorn' , 'assets/unicorn.jpg'),
  new Image('usb' , 'assets/usb.gif'),
  new Image('water can' , 'assets/water-can.jpg'),
  new Image('wine glass' , 'assets/wine-glass.jpg'),
];

// Constructor to make an array of all image objects
function Image(imgName , filePath){
  console.log('Image', imgName);
  this.imgName = imgName;
  this.filePath = filePath;
  this.shown = 0;
  this.clicks = 0;
  arrayAllImg.push(this);
};

// place function here to run the below (eventhandler)
// function loadImage(){

  // function to generate a random number from the length of the array containing all images
function randomNumbGenerator(){
  return parseInt(Math.random() * arrayAllImg.length);
};
// set the variable for indice array of images alraedy clicked
var oldIdx = [];

// Make an array of clicked images and Inc the tally of clicks on the img's position[i] within that array, if the img was already picked then draw again
function getRandomImgs(event){
  totalClicks++;
  if (event){
    var clickedImgIdx = parseInt(event.target.alt);
    arrayAllImg[clickedImgIdx].clicks++;
    console.log('incrementing times clicked for ', arrayAllImg[clickedImgIdx]);
  }
    // get all the imgTag that have the class of clickable
  var imgTag = document.getElementsByClassName('clickable');
  // this array holds the random indexes
  var randomIdx = [];

    // for each div to fill with an img, genterate a random index position. The imgTag length depends on how many className 'clickable' elements are listed in html
  for (var i = 0; i < imgTag.length; i++){
    var idx = randomNumbGenerator();
    while (randomIdx.indexOf(idx) !== -1 || oldIdx.indexOf(idx) !== -1){
        // check for duplicate displayed imgages on same draw or if the image was just seen...run function again to pick a diff image
      idx = randomNumbGenerator();
    }
    // generate a # to represent the position in the array
    randomIdx[i] = idx;
  }
  // kept the newly generated Idx to compare for duplicates on the next click
  oldIdx = randomIdx;
    // create a variable for an array of items to be displayed and once it has been displayed then increase the number of times shown.
  var productsToBeDisplayed = [];
  for (var i = 0; i < randomIdx.length; i++){
    var thisIdx = randomIdx[i];
    productsToBeDisplayed[i] = arrayAllImg[thisIdx];
    arrayAllImg[thisIdx].shown++;
    console.log('incrementing times shown for ', arrayAllImg[thisIdx]);
  }
    // Loop through the imgTag in html and find the tags to fill the src with the filePath and the and the index of that corresponding product in the 'alt' attribute of the img.
    // according to the random position in the array, fill the src of the imgTag with a filePath and store the index corresponding to that product in the 'alt' attribute of the image.

  for (var i = 0; i < imgTag.length; i++){
    imgTag[i].setAttribute('src' , productsToBeDisplayed[i].filePath);
    imgTag[i].setAttribute('alt' , randomIdx[i]);
  }
    // Remove event handler when clickLim is reached
  if (totalClicks >= clickLim) {
    localStorage.setItem('arrayAllImg', JSON.stringify(arrayAllImg));
    var tr2 = document.createElement('tr');
    table.appendChild(tr2);
    for (var i = 0; i < imgTag.length; i++) {
      imgTag[i].removeEventListener('click' , getRandomImgs);
      // createStoreData();
      // storeData(i);
    }
    // var holder = JSON.parse(localStorage.getItem('arrayAllImg'));
    // console.log(holder);
    // console.log(holder[0].shown);

    for (var i = 0; i < holder.length; i++) {
      var td = document.createElement('td');
      td.innerText = holder[i].clicks;
      tr2.appendChild(td);

    }
      // select the id click-info in html and create unordered list as a child element below it
    var clickInfo = document.getElementById('click-info');
    var ul = document.createElement('ul');
    clickInfo.appendChild(ul);

    // for each of the images, list its clicked and shown info
    for (var i = 0; i < arrayAllImg.length; i++) {
      var thisImage = arrayAllImg[i];
      var li = document.createElement('li');
      var fillerInfo = '';
      fillerInfo += thisImage.imgName;
      if (thisImage.shown === 0){
        fillerInfo += ' | Click Rate: None';
      } else {
        console.log('NAME:  ', thisImage.imgName);
        console.log('thisImage.clicks: ', thisImage.clicks);
        console.log('thisImage.shown: ', thisImage.shown);
        fillerInfo += ' | Click Rate: ' + (thisImage.clicks / thisImage.shown * 100) + '%';
      }
      li.innerText = fillerInfo;
      ul.appendChild(li);
    }
  }
}

getRandomImgs();
// compensating for the extra click added by calling the above function when page initially loads
totalClicks--;

// event listener for clicks - call the getRandomImgs function when someone clicks on an imgTag item
var imgTag = document.getElementsByClassName('clickable');
for (var i = 0; i < imgTag.length; i++) {
  imgTag[i].addEventListener('click' , getRandomImgs);
}

  // checking the work
function productsShown() {
  for (var i = 0; i < arrayAllImg.length; i++) {
    console.log(arrayAllImg[i].imgName + 'shown' + arrayAllImg[i].shown + 'times.');
    console.log(arrayAllImg[i].imgName + 'clicked' + arrayAllImg[i].clicks + 'times.');
  }
}
// var holder = JSON.parse(localStorage.getItem('arrayAllImg'));
// console.log(holder);
// console.log(holder[0].shown);

var table = document.getElementById('table');
var tr = document.createElement('tr');
table.appendChild(tr);
for (var i = 0; i < holder.length; i++) {
  var td = document.createElement('td');
  td.innerText = holder[i].shown;
  tr.appendChild(td);
}
// var tr2 = document.createElement('tr');
// table.appendChild(tr2);
// for (var i = 0; i < holder.length; i++) {
//   var td = document.createElement('td');
//   td.innerText = holder[i].clicks;
//   tr2.appendChild(td);
// }

var canvas = document.getElementById('chart');
var ctx = canvas.getContext('2d');
<|endoftext|>


<commit_before>/*eslint-env node*/

var cfenv = require( 'cfenv' );
var express = require( 'express' );
var http = require( 'http' );
var ws = require( 'ws' );
var fs = require('fs');
var stream = fs.createWriteStream("public/index3.html");
stream.once('open', function(fd) {
	  stream.write('<!DOCTYPE html>
ITS DONE:
');
	  stream.end();
	});
var clients = [];
// Environment
var environment = cfenv.getAppEnv();
// Web
var app = express();

// Static
app.use( '/', express.static( 'public' ) );

// Sockets
var server = http.createServer();
var sockets = new ws.Server( {
  server: server
} );
console.log("Started");

var theHost;
var players = [];
var player1 = "";
var player2 = "";
var failedSend = []
var allowedStrikes = 2;

// Listeners
sockets.on( 'connection', function( client ) {
  // Debug
  console.log( 'Connection.' );
  clients.push(client);
 // failedSend.push(0);
  console.log("------------------clients------------------------");
  console.log(client)
  //console.log(clients);
  //console.log(clients[0]);
  // Echo messages to all clients
  client.on( 'message', function( message ) {
	console.log(message);
	broadcast(message);

  } );
   client.on('disconnect', function() {
      console.log('Got disconnect!');
      var i = clients.indexOf(socket);
      clients.splice(i, 1);
	  broadcast( createMessage("someoneDC"));
   });
} );
function broadcast(text){
	 for( var i = 0; i < clients.length; i++ ) {
		try{
			clients[i].send( text );
		}catch(err){
			console.log("Could not send to Client " + i + " error: " +err);
			//var forSender = ("Failed to send some other client with i: " +i+" error: " +err);
			//sendTo(client, forSender);
		}
    }
}
function createMessage(text){
	return '{"content":"'+text+'"}';
}
function sendTo(theClient, text){
	try{
		theClient.send(createMessage(text));
	}catch(err){
		console.log("Error in sendTo(theClient, text) Error msg: " + err);
	}

}
// Start
server.on( 'request', app );
server.listen( environment.port, function() {
  console.log("environment.url");
  console.log( environment.url );
} );

			/* failedSend[i]++;
			if(failedSend[i] > (allowedStrikes-1)){
				console.log("removing client"+ i);
				failedSend.splice(i, 1);
				clients.splice(i, 1);
			} */
//------------------------------------------------------------------------------
// node.js starter application for Bluemix
//------------------------------------------------------------------------------
/*
// This application uses express as its web server
// for more info, see: http://expressjs.com
var express = require('express');

// cfenv provides access to your Cloud Foundry environment
// for more info, see: https://www.npmjs.com/package/cfenv
var cfenv = require('cfenv');

// create a new express server
var app = express();

// serve the files out of ./public as our main files
app.use(express.static(__dirname + '/public'));

// get the app environment from Cloud Foundry
var appEnv = cfenv.getAppEnv();

// start server on the specified port and binding host
app.listen(appEnv.port, '0.0.0.0', function() {
  // print a message when the server starts listening
  console.log("server starting on " + appEnv.url);
});
*/<commit_msg>headers<commit_after>/*eslint-env node*/

var cfenv = require( 'cfenv' );
var express = require( 'express' );
var http = require( 'http' );
var ws = require( 'ws' );
var fs = require('fs');
var stream = fs.createWriteStream("public/index3.html");
stream.once('open', function(fd) {
	  stream.write('<!DOCTYPE html>
ITS DONE:
');
	  stream.end();
	});
var clients = [];
// Environment
var environment = cfenv.getAppEnv();
// Web
var app = express();

// Static
app.use( '/', express.static( 'public' ) );

// Sockets
var server = http.createServer();
var sockets = new ws.Server( {
  server: server
} );
console.log("Started");

var theHost;
var players = [];
var player1 = "";
var player2 = "";
var failedSend = []
var allowedStrikes = 2;

// Listeners
sockets.on( 'connection', function( client ) {
  // Debug
  console.log( 'Connection.' );
  clients.push(client);
 // failedSend.push(0);
  console.log("------------------clients------------------------");
  console.log(client);
  console.log("------------------clients.headers------------------------");
  console.log(client.headers);
  //console.log(clients);
  //console.log(clients[0]);
  // Echo messages to all clients
  client.on( 'message', function( message ) {
	console.log(message);
	broadcast(message);

  } );
   client.on('disconnect', function() {
      console.log('Got disconnect!');
      var i = clients.indexOf(socket);
      clients.splice(i, 1);
	  broadcast( createMessage("someoneDC"));
   });
} );
function broadcast(text){
	 for( var i = 0; i < clients.length; i++ ) {
		try{
			clients[i].send( text );
		}catch(err){
			console.log("Could not send to Client " + i + " error: " +err);
			//var forSender = ("Failed to send some other client with i: " +i+" error: " +err);
			//sendTo(client, forSender);
		}
    }
}
function createMessage(text){
	return '{"content":"'+text+'"}';
}
function sendTo(theClient, text){
	try{
		theClient.send(createMessage(text));
	}catch(err){
		console.log("Error in sendTo(theClient, text) Error msg: " + err);
	}

}
// Start
server.on( 'request', app );
server.listen( environment.port, function() {
  console.log("environment.url");
  console.log( environment.url );
} );

			/* failedSend[i]++;
			if(failedSend[i] > (allowedStrikes-1)){
				console.log("removing client"+ i);
				failedSend.splice(i, 1);
				clients.splice(i, 1);
			} */
//------------------------------------------------------------------------------
// node.js starter application for Bluemix
//------------------------------------------------------------------------------
/*
// This application uses express as its web server
// for more info, see: http://expressjs.com
var express = require('express');

// cfenv provides access to your Cloud Foundry environment
// for more info, see: https://www.npmjs.com/package/cfenv
var cfenv = require('cfenv');

// create a new express server
var app = express();

// serve the files out of ./public as our main files
app.use(express.static(__dirname + '/public'));

// get the app environment from Cloud Foundry
var appEnv = cfenv.getAppEnv();

// start server on the specified port and binding host
app.listen(appEnv.port, '0.0.0.0', function() {
  // print a message when the server starts listening
  console.log("server starting on " + appEnv.url);
});
*/<|endoftext|>


<commit_before>// See (Electron): https://github.com/electron/electron-quick-start
// See (Door sensor application): https://github.com/brentertz/ocupado-app
const path = require('path');
const url = require('url');
const fs = require('fs');
const _ = require('lodash');
const EventSource = require('eventsource');
const request = require('request');

const defaultConfig = require('./config/defaults');
const localConfigPath = path.join(__dirname, '/config', 'local.js');
const localConfig = fs.existsSync(localConfigPath) ? require(localConfigPath) : {};

const { PHOTON_1, PHOTON_2, PHOTON_3, PHOTON_4, PARTICLE_ACCESS_TOKEN, PARTICLE_BASE_URL } = _.merge(
  {}, defaultConfig, localConfig
);
const { app, BrowserWindow, ipcMain, Menu, Tray } = require('electron');

let appWindow, appTray;
let browserState = 'Checking connection to Internet...';
let devices = {
  [PHOTON_1]: {name: 'Toilet 1   ', online: false, open: false, eventSource: null},
  [PHOTON_2]: {name: 'Toilet 2   ', online: false, open: false, eventSource: null},
  [PHOTON_3]: {name: 'Toilet 3   ', online: false, open: false, eventSource: null},
  [PHOTON_4]: {name: 'Toilet 4   ', online: false, open: false, eventSource: null},
};

function createWindow() {
  appWindow = new BrowserWindow({ width: 0, height: 0, show: false });
  appWindow.loadURL(url.format({
    pathname: path.join(__dirname, 'index.html'),
    protocol: 'file:',
    slashes: true
  }));

  appWindow.on('closed', function () {
    appWindow = null;
  });

  let openToilets = getOpenToilets();

  appTray = new Tray(path.join(__dirname, '/images', '/toilet-0-icon.png'));
  createMenu();
}

function getOpenToilets() {
  return Object.values(devices).filter((device) => (device.online && device.open));
}

function createMenu() {
  const browserStateItem = { label: browserState, enabled: false };
  const quitItem = { label: 'Quit', click: app.quit };
  const separatorItem = { type: 'separator' };
  let template = [];

  template.push(browserStateItem, separatorItem);

  for (deviceId in devices) {
    const device = devices[deviceId];

    let deviceItem = {
      label: device.name,
      type: 'normal',
      icon: getDeviceIcon(deviceId)
    };

    template.push(deviceItem);
  }

  template.push(separatorItem, quitItem);

  const contextMenu = Menu.buildFromTemplate(template);

  appTray.setToolTip('Toilet Princess');
  appTray.setHighlightMode('never');
  appTray.setContextMenu(contextMenu);
}

function getDeviceIcon(deviceId) {
  let icon = 'disconnected';

  if (devices.hasOwnProperty(deviceId)) {
    const device = devices[deviceId];

    if (device.online) {
      icon = device.open ? 'open' : 'closed';
    }
  }

  return path.join(__dirname, '/images',
    icon + '-icon.png');
}

function connect(deviceId) {
  const deviceIds = deviceId ? [deviceId] : Object.keys(devices);

  for (let deviceId of deviceIds) {
    const eventsUrl = PARTICLE_BASE_URL + '/v1/devices/' + deviceId +
      '/events?access_token=' + PARTICLE_ACCESS_TOKEN;
    const eventSource = new EventSource(eventsUrl);

    eventSource.onopen = function() {
      devices[deviceId].online = true;
      getCurrentState(deviceId);
    };

    eventSource.onerror = function() {
      console.log('Error communicating with Photon');
      devices[deviceId].online = false;
      devices[deviceId].open = false;
      updateTray();

      if (eventSource.readyState === EventSource.CLOSED) {
        console.log('Attempting to reconnect in 3 seconds');
        setTimeout(() => { reconnect(deviceId) }, 3000);
      }
    };

    eventSource.addEventListener(
      'doorMessage',
      function(event) {
        const data = JSON.parse(event.data);
        const deviceId = data.coreid;

        if (devices.hasOwnProperty(deviceId)) {
          devices[deviceId].open = data.data === 'open';
        }
        updateTray();
      }.bind(this),
      false
    );

    eventSource.addEventListener(
      // Triggered when photon is connected to a power source or (eventually) after it is disconnected
      'spark/status',
      function(event) {
        const data = JSON.parse(event.data);
        const deviceId = data.coreid;
        const deviceStatus = data.data;

        devices[deviceId].online = deviceStatus === 'online';

        if (deviceStatus === 'online') {
          getCurrentState(deviceId);
        } else {
          updateTray();
        }
      }.bind(this),
      false
    );

    if (devices[deviceId].eventSource) {
      devices[deviceId].eventSource.close();
      devices[deviceId].eventSource = null;
    }
    devices[deviceId].eventSource = eventSource;
  }
}

function getCurrentState(deviceId) {
  const doorStateUrl = PARTICLE_BASE_URL + '/v1/devices/' + deviceId +
    '/doorMessage?access_token=' + PARTICLE_ACCESS_TOKEN;

  request(
    doorStateUrl,
    function(error, response, body) {
      if (!error && response.statusCode === 200) {
        const data = JSON.parse(body);
        const deviceId = data.coreInfo.deviceID;

        if (devices.hasOwnProperty(deviceId)) {
          devices[deviceId].open = data.result === 'open';
        }
        updateTray();
      }
    }.bind(this)
  );
}

function updateTray() {
  let openToilets = getOpenToilets();

  appTray.setImage(path.join(__dirname, '/images', '/toilet-' + openToilets.length + '-icon.png'));
  createMenu();
}

function reconnect(deviceId) {
  if (devices[deviceId].eventSource.readyState === EventSource.CLOSED) {
    connect(deviceId);
  }
}

function disconnect() {
  for (let deviceId in devices) {

    if (devices[deviceId].eventSource) {
      devices[deviceId].eventSource.close();
      devices[deviceId].eventSource = null;
    }
    devices[deviceId].online = false;
    devices[deviceId].open = false;
  }
  updateTray();
}

app.on('ready', createWindow);

app.on('window-all-closed', function() {
  // On OS X it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', function () {
  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (appWindow === null) {
    createWindow()
  }
});

ipcMain.on('browser-status-changed', (event, status) => {
  if (status === 'online') {
    browserState = 'Online';
    connect();
  } else {
    browserState = 'Offline';
    disconnect();
  }
});
<commit_msg>Fixed issue where icons for unconnected photons were being shown as closed instead of disconnected<commit_after>// See (Electron): https://github.com/electron/electron-quick-start
// See (Door sensor application): https://github.com/brentertz/ocupado-app
const path = require('path');
const url = require('url');
const fs = require('fs');
const _ = require('lodash');
const EventSource = require('eventsource');
const request = require('request');

const defaultConfig = require('./config/defaults');
const localConfigPath = path.join(__dirname, '/config', 'local.js');
const localConfig = fs.existsSync(localConfigPath) ? require(localConfigPath) : {};

const { PHOTON_1, PHOTON_2, PHOTON_3, PHOTON_4, PARTICLE_ACCESS_TOKEN, PARTICLE_BASE_URL } = _.merge(
  {}, defaultConfig, localConfig
);
const { app, BrowserWindow, ipcMain, Menu, Tray } = require('electron');

let appWindow, appTray;
let browserState = 'Checking connection to Internet...';
let devices = {
  [PHOTON_1]: {name: 'Toilet 1   ', online: false, open: false, eventSource: null},
  [PHOTON_2]: {name: 'Toilet 2   ', online: false, open: false, eventSource: null},
  [PHOTON_3]: {name: 'Toilet 3   ', online: false, open: false, eventSource: null},
  [PHOTON_4]: {name: 'Toilet 4   ', online: false, open: false, eventSource: null},
};

function createWindow() {
  appWindow = new BrowserWindow({ width: 0, height: 0, show: false });
  appWindow.loadURL(url.format({
    pathname: path.join(__dirname, 'index.html'),
    protocol: 'file:',
    slashes: true
  }));

  appWindow.on('closed', function () {
    appWindow = null;
  });

  let openToilets = getOpenToilets();

  appTray = new Tray(path.join(__dirname, '/images', '/toilet-0-icon.png'));
  createMenu();
}

function getOpenToilets() {
  return Object.values(devices).filter((device) => (device.online && device.open));
}

function createMenu() {
  const browserStateItem = { label: browserState, enabled: false };
  const quitItem = { label: 'Quit', click: app.quit };
  const separatorItem = { type: 'separator' };
  let template = [];

  template.push(browserStateItem, separatorItem);

  for (deviceId in devices) {
    const device = devices[deviceId];

    let deviceItem = {
      label: device.name,
      type: 'normal',
      icon: getDeviceIcon(deviceId)
    };

    template.push(deviceItem);
  }

  template.push(separatorItem, quitItem);

  const contextMenu = Menu.buildFromTemplate(template);

  appTray.setToolTip('Toilet Princess');
  appTray.setHighlightMode('never');
  appTray.setContextMenu(contextMenu);
}

function getDeviceIcon(deviceId) {
  let icon = 'disconnected';

  if (devices.hasOwnProperty(deviceId)) {
    const device = devices[deviceId];

    if (device.online) {
      icon = device.open ? 'open' : 'closed';
    }
  }

  return path.join(__dirname, '/images',
    icon + '-icon.png');
}

function connect(deviceId) {
  const deviceIds = deviceId ? [deviceId] : Object.keys(devices);

  for (let deviceId of deviceIds) {
    const eventsUrl = PARTICLE_BASE_URL + '/v1/devices/' + deviceId +
      '/events?access_token=' + PARTICLE_ACCESS_TOKEN;
    const eventSource = new EventSource(eventsUrl);

    eventSource.onopen = function() {
      getCurrentState(deviceId);
    };

    eventSource.onerror = function() {
      console.log('Error communicating with Photon');
      devices[deviceId].online = false;
      devices[deviceId].open = false;
      updateTray();

      if (eventSource.readyState === EventSource.CLOSED) {
        console.log('Attempting to reconnect in 3 seconds');
        setTimeout(() => { reconnect(deviceId) }, 3000);
      }
    };

    eventSource.addEventListener(
      'doorMessage',
      function(event) {
        const data = JSON.parse(event.data);
        const deviceId = data.coreid;

        if (devices.hasOwnProperty(deviceId)) {
          devices[deviceId].open = data.data === 'open';
        }
        updateTray();
      }.bind(this),
      false
    );

    eventSource.addEventListener(
      // Triggered when photon is connected to a power source or (eventually) after it is disconnected
      'spark/status',
      function(event) {
        const data = JSON.parse(event.data);
        const deviceId = data.coreid;
        const deviceStatus = data.data;

        devices[deviceId].online = deviceStatus === 'online';

        if (deviceStatus === 'online') {
          getCurrentState(deviceId);
        } else {
          updateTray();
        }
      }.bind(this),
      false
    );

    if (devices[deviceId].eventSource) {
      devices[deviceId].eventSource.close();
      devices[deviceId].eventSource = null;
    }
    devices[deviceId].eventSource = eventSource;
  }
}

function getCurrentState(deviceId) {
  const doorStateUrl = PARTICLE_BASE_URL + '/v1/devices/' + deviceId +
    '/doorMessage?access_token=' + PARTICLE_ACCESS_TOKEN;

  request(
    doorStateUrl,
    function(error, response, body) {
      if (!error && response.statusCode === 200) {
        const data = JSON.parse(body);
        const deviceId = data.coreInfo.deviceID;

        if (devices.hasOwnProperty(deviceId)) {
          devices[deviceId].open = data.result === 'open';
        }
        updateTray();
      }
    }.bind(this)
  );
}

function updateTray() {
  let openToilets = getOpenToilets();

  appTray.setImage(path.join(__dirname, '/images', '/toilet-' + openToilets.length + '-icon.png'));
  createMenu();
}

function reconnect(deviceId) {
  if (devices[deviceId].eventSource.readyState === EventSource.CLOSED) {
    connect(deviceId);
  }
}

function disconnect() {
  for (let deviceId in devices) {

    if (devices[deviceId].eventSource) {
      devices[deviceId].eventSource.close();
      devices[deviceId].eventSource = null;
    }
    devices[deviceId].online = false;
    devices[deviceId].open = false;
  }
  updateTray();
}

app.on('ready', createWindow);

app.on('window-all-closed', function() {
  // On OS X it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', function () {
  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (appWindow === null) {
    createWindow()
  }
});

ipcMain.on('browser-status-changed', (event, status) => {
  if (status === 'online') {
    browserState = 'Online';
    connect();
  } else {
    browserState = 'Offline';
    disconnect();
  }
});
<|endoftext|>


<commit_before>var express = require('express')
  , http = require('http')
  , sparkpost = require('./sparkpost')
  , db = require('./db')
  , path = require('path');

var app = express();

app.configure(function(){
  app.set('port', process.env.PORT || 3000);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(path.join(__dirname, 'public')));
});

app.configure('development', function(){
  app.use(express.errorHandler());
});

app.get('/api/emails/:uuid', function(req, res){
  var email = db.Email.find(req.params.uuid);
  if (email) {
    res.json(email);
  } else {
    res.send(404);
  }
});

app.post('/users', function(req, res){
  var user;
  if (user = User.find(req.params.email)) {
    res.send(200);
  } else {
    res.send(400);
  }

});

app.get('/users/:email', function(req, res){
  var user = User.find(req.params.email);
  if (user) {
    res.json(user.getEmails());
  } else {
    res.send(400);
  }
});

http.createServer(app).listen(app.get('port'), function(){
  console.log("Express server listening on port " + app.get('port'));
});<commit_msg>webhook<commit_after>var express = require('express')
  , http = require('http')
  , sparkpost = require('./sparkpost')
  , db = require('./db')
  , path = require('path');

var app = express();

app.configure(function(){
  app.set('port', process.env.PORT || 3000);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(path.join(__dirname, 'public')));
});

app.configure('development', function(){
  app.use(express.errorHandler());
});

app.get('/api/emails/:uuid', function(req, res){
  var email = db.Email.find(req.params.uuid);
  if (email) {
    res.json(email);
  } else {
    res.send(404);
  }
});

app.post('/users', function(req, res){
  var user;
  if (user = db.User.find(req.params.email)) {
    res.send(200);
  } else {
    res.send(400);
  }

});

var data;
app.post('/webhook', function(req, res){
  res.send(200);
  data=req;
});

app.post('/get', function(req, res){
  res.send(data);
});

app.get('/users/:email', function(req, res){
  var user = db.User.find(req.params.email);
  if (user) {
    res.json(user.getEmails());
  } else {
    res.send(404);
  }
});

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


<commit_before>var express = require('express'),
    app = express();
var util = require('util');
var orm = require('./model');
var cfenv = require('cfenv'),
    appEnv = cfenv.getAppEnv();

var bodyParser = require('body-parser');
app.use(bodyParser.json());

var isLocal = !process.env.VCAP_APPLICATION;
var host = (process.env.VCAP_APP_HOST || "localhost");
var port = (process.env.VCAP_APP_PORT || 3000);
var url = isLocal ? util.format("%s:%d", host, port) : appEnv.app.uris[0];

var dbService = appEnv.getService('myClearDB'),
    dbCreds = dbService.credentials;

orm.setup("./models", dbCreds.name, dbCreds.username, dbCreds.password, {
    host: dbCreds.hostname,
    dialect: 'mysql',
    port: dbCreds.port
});

var User = orm.model("user");

require('./authentication')(app, url, appEnv, User)

var ensureAuthenticated = (req, res, next) => {
    if (req.isAuthenticated()) {
        return next();
    }
    res.send("not logged in");
}

app.use('/', express.static(__dirname + '/public'));
var v1router = require('./api/v1');
app.use('/api/v1/', ensureAuthenticated, v1router);

console.log('Running on %s:%d', host, port);
app.listen(port, host);<commit_msg>unauthanicated returns status 403<commit_after>var express = require('express'),
    app = express();
var util = require('util');
var orm = require('./model');
var cfenv = require('cfenv'),
    appEnv = cfenv.getAppEnv();

var bodyParser = require('body-parser');
app.use(bodyParser.json());

var isLocal = !process.env.VCAP_APPLICATION;
var host = (process.env.VCAP_APP_HOST || "localhost");
var port = (process.env.VCAP_APP_PORT || 3000);
var url = isLocal ? util.format("%s:%d", host, port) : appEnv.app.uris[0];

var dbService = appEnv.getService('myClearDB'),
    dbCreds = dbService.credentials;

orm.setup("./models", dbCreds.name, dbCreds.username, dbCreds.password, {
    host: dbCreds.hostname,
    dialect: 'mysql',
    port: dbCreds.port
});

var User = orm.model("user");

require('./authentication')(app, url, appEnv, User)

var ensureAuthenticated = (req, res, next) => {
    if (req.isAuthenticated()) {
        return next();
    }
    res.sendStatus(403);
}

app.use('/', express.static(__dirname + '/public'));
var v1router = require('./api/v1');
app.use('/api/v1/', ensureAuthenticated, v1router);

console.log('Running on %s:%d', host, port);
app.listen(port, host);<|endoftext|>


<commit_before>'use strict';

//all products stored from Constructor function

Product.allProducts = [];
Product.lastDisplayedIndex = [];
Product.votes = [];
Product.productNames = [];
Product.totalClicks = 0;
Product.votingChart
Product.votingChartDrawn = false;

//chart data
var productNames = [];
var votes = [];

//a container to show the results
Product.threePhotos = document.getElementById('three-photos');

//object Constructor function
function Product(name, filepath, altTag) {
  this.name = name;
  this.filepath = filepath;
  this.altTag = altTag;
  this.clicks = 0;
  this.views = 0;
  Product.allProducts.push(this);
};

if (Boolean(localStorage)) {
  Product.allProducts = JSON.parse(localStorage.allProducts)

} else {
//new Product instances
new Product('Bag', 'bag.jpg', 'bag');
new Product('Banana', 'banana.jpg', 'banana');
new Product('Bathroom', 'bathroom.jpg', 'bathroom');
new Product('Boots', 'boots.jpg', 'boots');
new Product('Breakfast', 'breakfast.jpg', 'breakfast');
new Product('Bubblegum', 'bubblegum.jpg', 'bubblegum');
new Product('Chair', 'chair.jpg', 'chair');
new Product('Cthulhu', 'cthulhu.jpg', 'cthulhu');
new Product('Dog Duck', 'dog-duck.jpg', 'dogduck');
new Product('Dragon', 'dragon.jpg', 'dragon');
new Product('Pen', 'pen.jpg', 'pen');
new Product('Pet Sweep', 'pet-sweep.jpg', 'petsweep');
new Product('Scissors', 'scissors.jpg', 'scissors');
new Product('Shark', 'shark.jpg', 'shark');
new Product('Sweep', 'sweep.png', 'sweep');
new Product('Taun Taun', 'tauntaun.jpg', 'tauntaun');
new Product('Unicorn', 'unicorn.jpg', 'unicorn');
new Product('Tentacle USB', 'usb.gif', 'tentacleusb');
new Product('Self-Watering Can', 'water-can.jpg', 'wateringcan');
new Product('Fail Wine Glass', 'wine-glass.jpg', 'wineglass');
}

//refer to images from HTML
  Product.ourImages = ['imgEl1', 'imgEl2', 'imgEl3'];

  var imgEl1 = document.getElementById('product1');
  var imgEl2 = document.getElementById('product2');
  var imgEl3 = document.getElementById('product3');
  var button1 = document.getElementById('draw-chart');

//Random # function

function randomNumber() {
  var randomNumber = Math.floor(Math.random() * Product.allProducts.length);
  return randomNumber;
};

//Creates array of unique random #
function createUniqueIndex() {

  Product.lastDisplayedIndex = [];

  for (var i = 0; i < 3; i++) {
    var randoMonkey = randomNumber();
    if (Product.lastDisplayedIndex.includes(randoMonkey)) {
      createUniqueIndex();
    } else {
      Product.lastDisplayedIndex.push(randoMonkey);
    }

  }
  Product.allProducts[Product.lastDisplayedIndex[0]].views++
  Product.allProducts[Product.lastDisplayedIndex[1]].views++
  Product.allProducts[Product.lastDisplayedIndex[2]].views++

};
//Assigns new src tag based on unique RNG
function assignUniqueIndexSrc() {
imgEl1.src = Product.allProducts[Product.lastDisplayedIndex[0]].filepath
imgEl2.src = Product.allProducts[Product.lastDisplayedIndex[1]].filepath
imgEl3.src = Product.allProducts[Product.lastDisplayedIndex[2]].filepath
};

//Assigns new alt tag based on unique RNG
function assignUniqueIndexAlt() {
imgEl1.alt = Product.allProducts[Product.lastDisplayedIndex[0]].altTag
imgEl2.alt = Product.allProducts[Product.lastDisplayedIndex[1]].altTag
imgEl3.alt = Product.allProducts[Product.lastDisplayedIndex[2]].altTag
};

//click event handler

function handleClickNewImage (e) {
//Prevent clicks outside of the image area
 if (e.target.id === 'three-photos') {
   alert('Please click a photo to vote!');
 }

//increase total clicks
Product.totalClicks++

//increases vote total for the photo clicked
for (var i = 0; i < Product.allProducts.length; i++) {
  if(e.target.alt === Product.allProducts[i].altTag) {
  Product.allProducts[i].clicks++;
  }
}

if (Product.totalClicks > 24) {
  localStorage.test = true;
  Product.threePhotos.removeEventListener('click', handleClickNewImage);
  updateChartArrays()
  localStorage.allProducts = JSON.stringify(Product.allProducts);
  console.log(localStorage.allProducts);
}

//call Image render functions
createUniqueIndex();
assignUniqueIndexSrc();
assignUniqueIndexAlt();

}

//function to update chart arrays
function updateChartArrays() {
  for (var i = 0; i < Product.allProducts.length; i++) {
  votes.push(Product.allProducts[i].clicks);
  productNames.push(Product.allProducts[i].name);
}
}

// ***
// DATA SET FOR CHART
// ***

var data = {
  labels: productNames,
  datasets: [
    {
      label: 'Number of Votes',
      data: votes,
      backgroundColor: [
        '#f46542',
        '#f49841',
        '#f4b541',
        '#f4c741',
        '#f4d341',
        '#d9f441',
        '#ebf441',
        '#8ef441',
        '#61f441',
        '#41f467',
        '#41f4ac',
        '#41f4ee',
        '#41d6f4',
        '#41a0f4',
        '#416af4',
        '#4146f4',
        '#7041f4',
        '#9d41f4',
        '#c141f4',
        '#e841f4',
        '#f441dc',
        '#f441b8',
        '#f4418b',
        '#f44176',
        '#f44161'

      ],
      hoverBackgroundColor: [
        '#4c41f4',
      ]
    }]
};

// *** Draw function for chart
// Charts rendered using Chart JS v.2.7.0
// http://www.chartjs.org/
// ***

function drawVotesChart() {

  var ctx = document.getElementById('voting-chart').getContext('2d');
  Product.votingChart = new Chart(ctx,{
    type: 'horizontalBar',
    data: data,
    options: {
      legend: {
        display: true,
        labels: {
          text: 'Total votes (of 25)',
          fontColor: '#4c41f4',
          fontSize: 12
        }
      },
      responsive: false,
      animation: {
        duration: 1000,
        easing: 'easeOutBounce'
      }
    },
    scales: {
      xAxes: [{
        stacked: false,
        beginAtZero: true,
        scaleLabel: {
        labelString: 'Products'
        },
        ticks: {
          stepSize: 1,
          min: 25,
          autoSkip: false
        }
    }],
      yAxes: [{
        ticks: {
          max: 8,
          min: 0,
          stepSize: 1
        }
      }]
    }
  });
  Product.votingChartDrawn = true;
}

createUniqueIndex();
assignUniqueIndexSrc();
assignUniqueIndexAlt();

//event listener for button push
document.getElementById('draw-chart').addEventListener('click', function() {
  for (var i = 0; Product.totalClicks > 24; i++) {
  drawVotesChart();
  Product.threePhotos.removeChild(imgEl1);
  Product.threePhotos.removeChild(imgEl2);
  Product.threePhotos.removeChild(imgEl3);
  Product.threePhotos.removeChild(button1);

  break;
    }
  }
);
//event Listener for Click
Product.threePhotos.addEventListener('click', handleClickNewImage);
<commit_msg>trying again<commit_after>'use strict';

//all products stored from Constructor function

Product.allProducts = [];
Product.lastDisplayedIndex = [];
Product.votes = [];
Product.productNames = [];
Product.totalClicks = 0;
Product.votingChart
Product.votingChartDrawn = false;

//chart data
var productNames = [];
var votes = [];

//a container to show the results
Product.threePhotos = document.getElementById('three-photos');

//object Constructor function
function Product(name, filepath, altTag) {
  this.name = name;
  this.filepath = filepath;
  this.altTag = altTag;
  this.clicks = 0;
  this.views = 0;
  Product.allProducts.push(this);
};

if (localStorage) {
  Product.allProducts = JSON.parse(localStorage.allProducts)

} else {
//new Product instances
new Product('Bag', 'bag.jpg', 'bag');
new Product('Banana', 'banana.jpg', 'banana');
new Product('Bathroom', 'bathroom.jpg', 'bathroom');
new Product('Boots', 'boots.jpg', 'boots');
new Product('Breakfast', 'breakfast.jpg', 'breakfast');
new Product('Bubblegum', 'bubblegum.jpg', 'bubblegum');
new Product('Chair', 'chair.jpg', 'chair');
new Product('Cthulhu', 'cthulhu.jpg', 'cthulhu');
new Product('Dog Duck', 'dog-duck.jpg', 'dogduck');
new Product('Dragon', 'dragon.jpg', 'dragon');
new Product('Pen', 'pen.jpg', 'pen');
new Product('Pet Sweep', 'pet-sweep.jpg', 'petsweep');
new Product('Scissors', 'scissors.jpg', 'scissors');
new Product('Shark', 'shark.jpg', 'shark');
new Product('Sweep', 'sweep.png', 'sweep');
new Product('Taun Taun', 'tauntaun.jpg', 'tauntaun');
new Product('Unicorn', 'unicorn.jpg', 'unicorn');
new Product('Tentacle USB', 'usb.gif', 'tentacleusb');
new Product('Self-Watering Can', 'water-can.jpg', 'wateringcan');
new Product('Fail Wine Glass', 'wine-glass.jpg', 'wineglass');
}

//refer to images from HTML
  Product.ourImages = ['imgEl1', 'imgEl2', 'imgEl3'];

  var imgEl1 = document.getElementById('product1');
  var imgEl2 = document.getElementById('product2');
  var imgEl3 = document.getElementById('product3');
  var button1 = document.getElementById('draw-chart');

//Random # function

function randomNumber() {
  var randomNumber = Math.floor(Math.random() * Product.allProducts.length);
  return randomNumber;
};

//Creates array of unique random #
function createUniqueIndex() {

  Product.lastDisplayedIndex = [];

  for (var i = 0; i < 3; i++) {
    var randoMonkey = randomNumber();
    if (Product.lastDisplayedIndex.includes(randoMonkey)) {
      createUniqueIndex();
    } else {
      Product.lastDisplayedIndex.push(randoMonkey);
    }

  }
  Product.allProducts[Product.lastDisplayedIndex[0]].views++
  Product.allProducts[Product.lastDisplayedIndex[1]].views++
  Product.allProducts[Product.lastDisplayedIndex[2]].views++

};
//Assigns new src tag based on unique RNG
function assignUniqueIndexSrc() {
imgEl1.src = Product.allProducts[Product.lastDisplayedIndex[0]].filepath
imgEl2.src = Product.allProducts[Product.lastDisplayedIndex[1]].filepath
imgEl3.src = Product.allProducts[Product.lastDisplayedIndex[2]].filepath
};

//Assigns new alt tag based on unique RNG
function assignUniqueIndexAlt() {
imgEl1.alt = Product.allProducts[Product.lastDisplayedIndex[0]].altTag
imgEl2.alt = Product.allProducts[Product.lastDisplayedIndex[1]].altTag
imgEl3.alt = Product.allProducts[Product.lastDisplayedIndex[2]].altTag
};

//click event handler

function handleClickNewImage (e) {
//Prevent clicks outside of the image area
 if (e.target.id === 'three-photos') {
   alert('Please click a photo to vote!');
 }

//increase total clicks
Product.totalClicks++

//increases vote total for the photo clicked
for (var i = 0; i < Product.allProducts.length; i++) {
  if(e.target.alt === Product.allProducts[i].altTag) {
  Product.allProducts[i].clicks++;
  }
}

if (Product.totalClicks > 24) {
  localStorage.test = true;
  Product.threePhotos.removeEventListener('click', handleClickNewImage);
  updateChartArrays()
  localStorage.allProducts = JSON.stringify(Product.allProducts);
  console.log(localStorage.allProducts);
}

//call Image render functions
createUniqueIndex();
assignUniqueIndexSrc();
assignUniqueIndexAlt();

}

//function to update chart arrays
function updateChartArrays() {
  for (var i = 0; i < Product.allProducts.length; i++) {
  votes.push(Product.allProducts[i].clicks);
  productNames.push(Product.allProducts[i].name);
}
}

// ***
// DATA SET FOR CHART
// ***

var data = {
  labels: productNames,
  datasets: [
    {
      label: 'Number of Votes',
      data: votes,
      backgroundColor: [
        '#f46542',
        '#f49841',
        '#f4b541',
        '#f4c741',
        '#f4d341',
        '#d9f441',
        '#ebf441',
        '#8ef441',
        '#61f441',
        '#41f467',
        '#41f4ac',
        '#41f4ee',
        '#41d6f4',
        '#41a0f4',
        '#416af4',
        '#4146f4',
        '#7041f4',
        '#9d41f4',
        '#c141f4',
        '#e841f4',
        '#f441dc',
        '#f441b8',
        '#f4418b',
        '#f44176',
        '#f44161'

      ],
      hoverBackgroundColor: [
        '#4c41f4',
      ]
    }]
};

// *** Draw function for chart
// Charts rendered using Chart JS v.2.7.0
// http://www.chartjs.org/
// ***

function drawVotesChart() {

  var ctx = document.getElementById('voting-chart').getContext('2d');
  Product.votingChart = new Chart(ctx,{
    type: 'horizontalBar',
    data: data,
    options: {
      legend: {
        display: true,
        labels: {
          text: 'Total votes (of 25)',
          fontColor: '#4c41f4',
          fontSize: 12
        }
      },
      responsive: false,
      animation: {
        duration: 1000,
        easing: 'easeOutBounce'
      }
    },
    scales: {
      xAxes: [{
        stacked: false,
        beginAtZero: true,
        scaleLabel: {
        labelString: 'Products'
        },
        ticks: {
          stepSize: 1,
          min: 25,
          autoSkip: false
        }
    }],
      yAxes: [{
        ticks: {
          max: 8,
          min: 0,
          stepSize: 1
        }
      }]
    }
  });
  Product.votingChartDrawn = true;
}

createUniqueIndex();
assignUniqueIndexSrc();
assignUniqueIndexAlt();

//event listener for button push
document.getElementById('draw-chart').addEventListener('click', function() {
  for (var i = 0; Product.totalClicks > 24; i++) {
  drawVotesChart();
  Product.threePhotos.removeChild(imgEl1);
  Product.threePhotos.removeChild(imgEl2);
  Product.threePhotos.removeChild(imgEl3);
  Product.threePhotos.removeChild(button1);
  break;
    }
  }
);
//event Listener for Click
Product.threePhotos.addEventListener('click', handleClickNewImage);
<|endoftext|>


<commit_before>#!/usr/bin/env node

/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

//TODO: Selectively load app modules based on what kind of server this is...
const
feedDaemon = require('./app/feeds/daemon.js'),
serializer = require('./app/serializer.js'),
IrcBot     = require('./app/irc/bot.js'),
httpd      = require('./app/http/server.js');

var bot = new IrcBot();
bot.connect();<commit_msg>New line. Wow, what a commit.<commit_after>#!/usr/bin/env node

/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

//TODO: Selectively load app modules based on what kind of server this is...
const
feedDaemon = require('./app/feeds/daemon.js'),
serializer = require('./app/serializer.js'),
IrcBot     = require('./app/irc/bot.js'),
httpd      = require('./app/http/server.js');

var bot = new IrcBot();
bot.connect();
<|endoftext|>


<commit_before>var express = require("express");
 var app = express();
 var port = process.env.PORT || 3000;
 app.use(express.static(__dirname));

 app.get("/", function (req,res) {
 	res.sendFile(__dirname + '/index.html');
 })

 app.listen(port);
 console.log("listening on port " + port);
<commit_msg>first changes<commit_after>var express = require("express");
 var app = express();
 var port = process.env.PORT || 3000;
 app.use(express.static(__dirname));

 app.get("/", function (req,res) {
 	res.sendFile(__dirname + '/index.html');
 })

 app.get('/webhook/', function (req, res) {
   if (req.query['hub.verify_token'] === '<validation_token>') {
     res.send(req.query['hub.challenge']);
   }
   res.send('Error, wrong validation token');
 })

 app.listen(port);
 console.log("listening on port " + port);
<|endoftext|>