<commit_before>/**
 * Created by Robert on 02/05/2014.
 */

var ProgressBar = require('progress');
var albumProgressBar;
var cheerio = require('cheerio');
var async = require('async');
var request;
var config;
var html;
var fs = require('fs');

module.exports = {
  login : function login(configIn, callback) {
    config = configIn;
    request = require('request');
    var cookie = 'pbx_www_photobox_ie="' + config.cookieValue + '";path=/;expires=' +
      new Date("6/1/2014	21:08:38") + ';';
    var j = request.jar();
    j.setCookie(cookie, 'http://' + config.baseDomain);

    request = request.defaults({jar : j});
    request('http://' + config.baseDomain + '/my/albums', function (err, response, body) {
//    request('http://localhost/photobox-downloader/mock/albumsList.html', function (error, response, body) {
      if (!err && response.statusCode == 200) {
        var $ = cheerio.load(body);
        if ($('#pbx_signout').length !== 0) {
          html = body;
          callback(null, true);
        } else {
          callback('Was unable to login with given cookie value!');
        }
      } else {
        callback(err);
      }
    });

  },

  setHtml : function setHtml(htmlIn) {
    html = htmlIn;
  },

  getAlbumList : function getAlbumList() {
    var $ = cheerio.load(html);
    var albumObjects = [];

    var albums = $('.pbx_myphotobox_thumbnail');
    //console.log(albums);
    albums.each(function () {

      albumObjects.push({
        name  : $(this).find('.pbx_object_name').text(),
        link  : $(this).find('.pbx_object_title').attr('href'),
        count : parseInt($($(this).find('span')[1]).text().replace(/\D/g, ""), 10)
      });
    });

    return albumObjects;
  },

  getPhotos : function getPhotos(html) {

    var $ = cheerio.load(html);
    var photos = [];

    $('.pbx_thumb_container').each(function () {
      photos.push({
        link : $(this).find('img').attr('onclick').split("'")[1],
        id   : $(this).find('img').attr('onclick').split("'")[1].split('photo_id=')[1]
      });
    });

    return photos;

  },

  downloadPhoto : function downloadPhotos(options, callback) {

    request('http://' + config.baseDomain + '/my/photo/full?photo_id=' + options.id,
      function (err, response, body) {
        if (!err && response.statusCode == 200) {
          var $ = cheerio.load(body);
          var name = $('img').attr('alt');
          if (name.match(/\./) === null) {
            name = name + '.jpg';
          }

          request($('img').attr('src'), callback).pipe(fs.createWriteStream(options.outputDir + '/' + name));

        } else {
          callback(err);
        }
      }
    );
  },

  downloadPagePhotos : function (options, callback) {
    var self = this;
    var photos = this.getPhotos(options.body);
    var outputDir = options.outputDir + '/' + options.album.name;

    if (!fs.existsSync(outputDir)) {
      fs.mkdirSync(outputDir);
    }

    async.each(photos, function (photo, callbackFn) {

      self.downloadPhoto({id : photo.id, outputDir : outputDir }, function (err) {
        if (err) {
          callback(err);
        } else {
          if (options.showProgress) {
            albumProgressBar.tick();
          }
          callbackFn(null, true);
        }
      });

    }, function (err) {

      if (err) {
        // One of the iterations produced an error.
        // All processing will now stop.
        console.log('A file failed to process');
      } else {
        callback(null, true)
      }

    });
  },

  getAlbumPages : function (album, callback) {

    var pageRequests = [];
    request('http://' + config.baseDomain + album.link, function (err, response, body) {
      if (!err && response.statusCode == 200) {

        pageRequests.push(body);
        var $ = cheerio.load(body);
        var pageLinks = $('.pbx_paginator_count a');

        if (pageLinks.length !== 0) {
          pageLinks = pageLinks.slice(0, pageLinks.length / 2);
          async.each(
            pageLinks,
            function (link, callbackFn) {
              request('http://' + config.baseDomain + '/my/album' + $(link).attr('href'), function (err, response, body) {
                if (!err && response.statusCode == 200) {
                  pageRequests.push(body);
                  callbackFn(null)
                } else {
                  callback(err);
                }
              });
            },
            function (err) {
              callback(null, pageRequests);
            }
          );
        } else {
          callback(null, pageRequests);
        }
      }
    });
  },

  downloadAlbum : function downloadAlbum(options, callback) {

    var self = this;
    if (options.showProgress) {
      console.log('Processing album:', options.album.name);
      albumProgressBar = new ProgressBar('  [:bar] Downloading :current of :total (:percent)', {
        total      : options.album.count,
        complete   : '*',
        incomplete : ' ',
        width      : 40
      });
    }

    // To download album, first get the content of every page in the album,
    // Then download the photos from each page
    this.getAlbumPages(options.album, function (err, getAlbumPages) {
      if (err) {
        callback(err);
      } else {
        async.each(
          getAlbumPages,
          function (body, callbackFn) {
            options.body = body;
            self.downloadPagePhotos(
              options,
              function (err) {
              if (err) {
                callback(err);
              } else {
                callbackFn();
              }
            });
          },
          function (err) {
            if (err) {
              callback(err);
            } else {
              callback(null, true, options.album)
            }
          });
      }
    });

  }
};<commit_msg>Adding downloadAll functionality<commit_after>/**
 * Created by Robert on 02/05/2014.
 */

var ProgressBar = require('progress');
var albumProgressBar;
var cheerio = require('cheerio');
var async = require('async');
var request;
var config;
var html;
var fs = require('fs');

module.exports = {
  login : function login(configIn, callback) {
    config = configIn;
    request = require('request');
    var cookie = 'pbx_www_photobox_ie="' + config.authCookieValue + '";path=/;expires=' +
      new Date("6/1/2014	21:08:38") + ';';
    var j = request.jar();
    j.setCookie(cookie, 'http://' + config.baseDomain);

    request = request.defaults({jar : j});
    request('http://' + config.baseDomain + '/my/albums', function (err, response, body) {
//    request('http://localhost/photobox-downloader/mock/albumsList.html', function (error, response, body) {
      if (!err && response.statusCode == 200) {
        var $ = cheerio.load(body);
        if ($('#pbx_signout').length !== 0) {
          html = body;
          callback(null, true);
        } else {
          callback('Was unable to login with given cookie value!');
        }
      } else {
        callback(err);
      }
    });

  },

  setHtml : function setHtml(htmlIn) {
    html = htmlIn;
  },

  getAlbumList : function getAlbumList() {
    var $ = cheerio.load(html);
    var albumObjects = [];

    var albums = $('.pbx_myphotobox_thumbnail');
    //console.log(albums);
    albums.each(function () {

      albumObjects.push({
        name  : $(this).find('.pbx_object_name').text(),
        link  : $(this).find('.pbx_object_title').attr('href'),
        count : parseInt($($(this).find('span')[1]).text().replace(/\D/g, ""), 10)
      });
    });

    return albumObjects;
  },

  getPhotos : function getPhotos(html) {

    var $ = cheerio.load(html);
    var photos = [];

    $('.pbx_thumb_container').each(function () {
      photos.push({
        link : $(this).find('img').attr('onclick').split("'")[1],
        id   : $(this).find('img').attr('onclick').split("'")[1].split('photo_id=')[1]
      });
    });

    return photos;

  },

  downloadPhoto : function downloadPhotos(options, callback) {

    request('http://' + config.baseDomain + '/my/photo/full?photo_id=' + options.id,
      function (err, response, body) {
        if (!err && response.statusCode == 200) {
          var $ = cheerio.load(body);
          var name = $('img').attr('alt');
          if (name.match(/\./) === null) {
            name = name + '.jpg';
          }

          request($('img').attr('src'), callback).pipe(fs.createWriteStream(options.outputDir + '/' + name));

        } else {
          callback(err);
        }
      }
    );
  },

  downloadPagePhotos : function (options, callback) {
    var self = this;
    var photos = this.getPhotos(options.body);
    var outputDir = options.outputDir + '/' + options.album.name;

    if (!fs.existsSync(outputDir)) {
      fs.mkdirSync(outputDir);
    }

    async.each(photos, function (photo, callbackFn) {

      self.downloadPhoto({id : photo.id, outputDir : outputDir }, function (err) {
        if (err) {
          callback(err);
        } else {
          if (options.showProgress) {
            albumProgressBar.tick();
          }
          callbackFn(null, true);
        }
      });

    }, function (err) {

      if (err) {
        // One of the iterations produced an error.
        // All processing will now stop.
        console.log('A file failed to process');
      } else {
        callback(null, true)
      }

    });
  },

  getAlbumPages : function (album, callback) {

    var pageRequests = [];
    request('http://' + config.baseDomain + album.link, function (err, response, body) {
      if (!err && response.statusCode == 200) {

        pageRequests.push(body);
        var $ = cheerio.load(body);
        var pageLinks = $('.pbx_paginator_count a');

        if (pageLinks.length !== 0) {
          pageLinks = pageLinks.slice(0, pageLinks.length / 2);
          async.each(
            pageLinks,
            function (link, callbackFn) {
              request('http://' + config.baseDomain + '/my/album' + $(link).attr('href'), function (err, response, body) {
                if (!err && response.statusCode == 200) {
                  pageRequests.push(body);
                  callbackFn(null)
                } else {
                  callback(err);
                }
              });
            },
            function (err) {
              callback(null, pageRequests);
            }
          );
        } else {
          callback(null, pageRequests);
        }
      }
    });
  },

  downloadAlbum : function downloadAlbum(options, callback) {

    var self = this;
    if (options.showProgress) {
      console.log('Processing album:', options.album.name);

      if (options.album.count === 0) {
        console.log('  [Album empty]');
        return callback(null);
      } else {
        albumProgressBar = new ProgressBar('  [:bar] Downloading :current of :total (:percent)', {
          total      : options.album.count,
          complete   : '*',
          incomplete : ' ',
          width      : 40
        });
      }
    }

    // To download album, first get the content of every page in the album,
    // Then download the photos from each page
    this.getAlbumPages(options.album, function (err, getAlbumPages) {
      if (err) {
        callback(err);
      } else {
        async.each(
          getAlbumPages,
          function (body, callbackFn) {
            options.body = body;
            self.downloadPagePhotos(
              options,
              function (err) {
                if (err) {
                  callback(err);
                } else {
                  callbackFn();
                }
              });
          },
          function (err) {
            if (err) {
              callback(err);
            } else {
              callback(null, true, options.album)
            }
          }
        );
      }
    });
  },

  downloadAll : function downloadAll(options, callback) {

    var self = this;
    var albums = this.getAlbumList();

    async.eachSeries(
      albums,
      function iterator(album, callbackFn) {
        options.album = album;
        self.downloadAlbum({
          album        : album,
          showProgress : options.showProgress,
          outputDir    : options.outputDir
        }, function (err) {
          if (err) {
            callback(err);
          } else {
            callbackFn(null, true, options.album);
          }
        })
      },
      function finalCallback(err) {
        if (err) {
          callback(err);
        } else {
          callback(null, true, options.album)
        }
      }
    );
  }
};<|endoftext|>


<commit_before>currentSearch = new Mongo.Collection("currentsearch");

Meteor.subscribe('movies');
Meteor.subscribe('tv');
Meteor.subscribe('cpapi');

Session.set('searchType', '');

Router.configure({
    notFoundTemplate: "NotFound"
});

Router.route('/', function () {
    this.render('home');
});

Router.route('/couchpotato', function () {
    this.render('couchpotato');
});

Router.route('/plex', function () {
    this.render('plex');
});

Router.route('/sickrage', function () {
    this.render('sickrage');
});

Template.body.helpers({
    url: function () {
    return Meteor.absoluteUrl();
    }
});

Houston.menu({
    'type': 'link',
    'use': '/plex',
    'title': 'Plex Auth Setup',
});

Houston.menu({
    'type': 'link',
    'use': '/couchpotato',
    'title': 'CouchPotato Status',
});

Houston.menu({
    'type': 'link',
    'use': '/sickrage',
    'title': 'SickRage Status',
});

Houston.menu({
    'type': 'link',
    'use': 'http://plexrequests.8bits.ca',
    'title': 'Project Site',
    'target': '_blank'
});<commit_msg>Added sonarr route and link to sonarr via houston<commit_after>currentSearch = new Mongo.Collection("currentsearch");

Meteor.subscribe('movies');
Meteor.subscribe('tv');
Meteor.subscribe('cpapi');

Session.set('searchType', '');

Router.configure({
    notFoundTemplate: "NotFound"
});

Router.route('/', function () {
    this.render('home');
});

Router.route('/couchpotato', function () {
    this.render('couchpotato');
});

Router.route('/plex', function () {
    this.render('plex');
});

Router.route('/sickrage', function () {
    this.render('sickrage');
});

Router.route('/sonarr', {
    name: 'sonarr'
});

Template.body.helpers({
    url: function () {
    return Meteor.absoluteUrl();
    }
});

Houston.menu({
    'type': 'link',
    'use': '/plex',
    'title': 'Plex Auth Setup',
});

Houston.menu({
    'type': 'link',
    'use': '/couchpotato',
    'title': 'CouchPotato Status',
});

Houston.menu({
    'type': 'link',
    'use': '/sickrage',
    'title': 'SickRage Status',
});

Houston.menu({
    'type': 'link',
    'use': '/sonarr',
    'title': 'Sonarr Status',
});

Houston.menu({
    'type': 'link',
    'use': 'http://plexrequests.8bits.ca',
    'title': 'Project Site',
    'target': '_blank'
});<|endoftext|>


<commit_before>// Substitutes

var chars = {
	'o': ['0'],
	'e': ['3'],
	'i': ['1']
}

// this is matched using regex (case-insensitive)
// the following match anywhere in the text
var words = {
	'tha': 'da',
	'wha': 'wa',
	'this': 'dis'
}
// the follwing should match at word end (or they should be complete words)
var endWords = {
	'ith': 'id',
	'([er])s': '$1zz'
}
// the following should match whole words
var completeWords = {
	'is': 'izz',
	'my': 'mah',
	'you': 'u',
	'are': 'r',
	'the': 'da'
}

// join to words
for (var key in endWords){
	words[key + '(?=[^a-z])'] = endWords[key]
}
for (var key in completeWords){
	words['([^a-z]|^)' + key + '(?=[^a-z])'] = '$1' + completeWords[key]
}

function convertChars(text){
	var text = String(text)
	var probab = 0.6

	for (var key in words) {
		reg = new RegExp(key, "gi")
		var bracketCount = (key.match(/\(/g) || []).length

		if (reg.test(text)){
			// replace
			text = text.replace(reg, (match, p1, p2) => {
				chance = Math.random()
				if (chance <= probab){
					if (bracketCount < 2){
						return words[key]
					} else if (bracketCount == 2){  // ([ae])s: $1zz, complete words
						return words[key].replace("$1", p1)
					}
				} else {
					return match
				}
			})
			// end replace
		}
	}

	return text
}

function loadSubstitutes(orig, newCh){
	list = [newCh]
	orig = orig.toLowerCase()
	if (orig in chars) {
		Array.prototype.push.apply(list, chars[orig]);
	}
	return list
}

function convertSingleChar(text){
	var upProbab = 0.5
	var downProbab = 0.7
	len = text.length
	var newText = ""

	for (var i=0; i < len; i++){
		charCode = text[i].charCodeAt()
		chance = Math.random()

		if (charCode >= 65 && charCode <= 90 && chance <= downProbab){
			subs = loadSubstitutes(text[i], String.fromCharCode(charCode + 32))
			newText += subs[Math.floor(Math.random() * subs.length)]; // random from list
		} else if (charCode >= 97 && charCode <= 122 && chance <= upProbab){
			subs = loadSubstitutes(text[i], String.fromCharCode(charCode - 32))
			newText += subs[Math.floor(Math.random() * subs.length)];
		} else {
			newText += text[i]
		}
	}

	return newText
}

function inputChangeEvent(){
	val = $("#input").val()
	newVal = convertChars(val)
	console.log(newVal)
	newVal = convertSingleChar(newVal)
	console.log(newVal)
	$("#output").text(newVal)
}

$(document).ready(function(){
	$("#input").bind('input propertychange', inputChangeEvent)
})
<commit_msg>add ks$ -> kzz$ substitution<commit_after>// Substitutes

var chars = {
	'o': ['0'],
	'e': ['3'],
	'i': ['1']
}

// this is matched using regex (case-insensitive)
// the following match anywhere in the text
var words = {
	'tha': 'da',
	'wha': 'wa',
	'this': 'dis'
}
// the follwing should match at word end (or they should be complete words)
var endWords = {
	'ith': 'id',
	'([erk])s': '$1zz'
}
// the following should match whole words
var completeWords = {
	'is': 'izz',
	'my': 'mah',
	'you': 'u',
	'are': 'r',
	'the': 'da'
}

// join to words
for (var key in endWords){
	words[key + '(?=[^a-z])'] = endWords[key]
}
for (var key in completeWords){
	words['([^a-z]|^)' + key + '(?=[^a-z])'] = '$1' + completeWords[key]
}

function convertChars(text){
	var text = String(text)
	var probab = 0.6

	for (var key in words) {
		reg = new RegExp(key, "gi")
		var bracketCount = (key.match(/\(/g) || []).length

		if (reg.test(text)){
			// replace
			text = text.replace(reg, (match, p1, p2) => {
				chance = Math.random()
				if (chance <= probab){
					if (bracketCount < 2){
						return words[key]
					} else if (bracketCount == 2){  // ([ae])s: $1zz, complete words
						return words[key].replace("$1", p1)
					}
				} else {
					return match
				}
			})
			// end replace
		}
	}

	return text
}

function loadSubstitutes(orig, newCh){
	list = [newCh]
	orig = orig.toLowerCase()
	if (orig in chars) {
		Array.prototype.push.apply(list, chars[orig]);
	}
	return list
}

function convertSingleChar(text){
	var upProbab = 0.5
	var downProbab = 0.7
	len = text.length
	var newText = ""

	for (var i=0; i < len; i++){
		charCode = text[i].charCodeAt()
		chance = Math.random()

		if (charCode >= 65 && charCode <= 90 && chance <= downProbab){
			subs = loadSubstitutes(text[i], String.fromCharCode(charCode + 32))
			newText += subs[Math.floor(Math.random() * subs.length)]; // random from list
		} else if (charCode >= 97 && charCode <= 122 && chance <= upProbab){
			subs = loadSubstitutes(text[i], String.fromCharCode(charCode - 32))
			newText += subs[Math.floor(Math.random() * subs.length)];
		} else {
			newText += text[i]
		}
	}

	return newText
}

function inputChangeEvent(){
	val = $("#input").val()
	newVal = convertChars(val)
	console.log(newVal)
	newVal = convertSingleChar(newVal)
	console.log(newVal)
	$("#output").text(newVal)
}

$(document).ready(function(){
	$("#input").bind('input propertychange', inputChangeEvent)
})
<|endoftext|>


<commit_before>import React from 'react';
import { render } from 'react-dom';

class App extends React.Component {
  render() {
    return (

spurt...

    );
  }
};

console.log('-- -- MAIN -- --');
render(<App />, document.getElementById('root'));
<commit_msg>Client: skeleton flexbox layout.<commit_after>import React from 'react';
import { render } from 'react-dom';

const flexContainer = {
  width: '100%',
  height: '100%'
};

const rowParent = {
  display: 'flex',
  flexDirection: 'row',
  flexWrap: 'nowrap',
  justifyContent: 'flex-start',
  alignContent: 'stretch',
  alignItems: 'stretch'
};

const columnParent = {
  ...rowParent,
  flexDirection: 'column'
};

const flexChild = {
  flex: '1 0 0',
  alignSelf: 'auto'
};

const narrow = {
  flex: '0 0 auto',
  height: '2em'
};

class App extends React.Component {
  render() {
    return (

          HEADER

            WORD EDITOR

              MASTER

WORD LIST

asdfghjkl

bacon

                LFO OPACITY

                SEQUENCER

          FOOTER

    );
  }
};

console.log('-- -- MAIN -- --');
render(<App />, document.getElementById('app'));
console.log('-- -- MAIN -- --');
<|endoftext|>


<commit_before>'use strict';

/**
 * controller for (rickshaw) graph on entry page
 */
analyticsControllers.controller('RGraphController', ['$scope', '$attrs', 'EntrySvc',
    function($scope, $attrs, EntrySvc) {
		var self = this;
		var graphElement = null; 	// HTML element showing the graph
		var graph = null;			// graph JS object
		var series = null;			// data container

		this.init = function init (element) {
			graphElement = element;
			var d = new Date();
			var t = d.getTime()/1000;
			series = [{
					color : 'steelblue',
					data : [ {x:t, y:0} ],
					name : "Line 1"
				}];

			graph = createGraph(series, element);
		};

		var isRecordedEntry = function isRecordedEntry() {
			return !$scope.entry.isLive && $scope.entry.recordedEntryId && $scope.entry.recordedEntryId != '';
		};

		var graphClickHandler = function graphClickHandler(time) {
			if (isRecordedEntry()) {
				// click - only for recorded entries that are not currently live
				$scope.$emit('gotoTime', time);
			}
		};

		/**
		 * create graph and its parts
		 * @param series
		 * @param element
		 * @return rickshaw graph
		 */
		var createGraph = function createGraph(series, element) {
			var graph = new Rickshaw.Graph({
				element : element[0].children[0],
				width : element.width(),
				height : element.height() - 20,
				renderer : 'line',
				interpolation: 'linear',
				series : series
			});
			graph.render();

			var preview = new Rickshaw.Graph.RangeSlider({
				graph : graph,
				element : element[0].children[1]
			});

			var xAxis = new Rickshaw.Graph.Axis.Time({
				graph : graph,
				ticksTreatment : 'glow',
				timeFixture : new KTime_Local()
			});
			xAxis.render();

			var yAxis = new Rickshaw.Graph.Axis.Y({
				graph : graph,
				tickFormat : Rickshaw.Fixtures.Number.formatKMBT,
				ticksTreatment : 'glow'
			});
			yAxis.render();

			var hoverDetail = new KHoverDetail( {
			    graph: graph,
			    formatter: function(series, x, y, formattedXValue, formattedYValue, point) {
			    	return formattedXValue + '
' + y + ' views';
			    },
				onClick : graphClickHandler
			} );

			return graph;
		};

		/**
		 * @param str	info string
		 * @return Array [{x, y}, ..]
		 */
		var parseData = function parseData(str) {
			var os = str.split(';');
			var objects = new Array();
			os.forEach(function (sLine) {
				if (sLine) {
					var vals = sLine.split(',');
					objects.push({'x':parseInt(vals[0], 10), 'timestamp':parseInt(vals[0], 10), 'y':parseInt(vals[1], 10)});
				}
			});
			return objects;
		};

		/**
		 * add 0 points where no data received
		 * for live - all the way
		 * for dead - after first point, before last point
		 * @param data 		objects array with "holes"
		 * @param fromDate	timestamp, seconds
		 * @param toDate	timestamp, seconds
		 * @param fillAll	boolean, should data outside existing range be filled
		 * @return array without "holes"
		 */
		var balanceData = function balanceData(data, fromDate, toDate, fillAll) {
			var firstPoint = Math.floor(fromDate/10)*10;	// init like this for when no data
			var lastPoint = firstPoint;
			var curx, nextx, i = 1;
			if (data.length) {
				firstPoint = data[0].x;
				lastPoint = data[data.length-1].x;
			}

			// add points between lastPoint and firstPoint
			curx = firstPoint + 10;
			while (curx < lastPoint) {
				nextx = data[i].x;
				if (curx < nextx) {
					// need to add point here
					data.splice(i, 0, {'x':curx, 'timestamp':curx, 'y':0});
				}
				curx += 10;
				i++;
			}

			if (fillAll) {
				// add points between firstPoint and fromDate
				curx = firstPoint - 10;
				while (curx >= fromDate) {
					data.unshift({'x':curx, 'timestamp':curx, 'y':0});
					curx -= 10;
				}

				// add points after lastPoint
				curx = lastPoint + 10;
				while (curx <= toDate) {
					data.push({'x':curx, 'timestamp':curx, 'y':0});
					curx += 10;
				}
			}
			return data;
		};

		/**
		 * get graph data for the last 36 hrs
		 * @param end of 36 hrs term (timestamp sec)
		 */
		var getGraph36Hrs = function getGraph36Hrs(toDate) {
			toDate = toDate - 60;
			var fromDate = toDate - 12960; // 60 sec per minute * 60 minutes per hour * 36 hrs
			EntrySvc.getGraph($scope.entryId, -129660, -60).then(function(data) {
				if (data[0] && graph != null) {
					// parse string into objects
					var objects = parseData(data[0].data);
					// add 0 points where no data received
					objects = balanceData(objects, fromDate, toDate, $scope.entry.isLive);
					if (!$scope.entry.isLive) {
						var firstBroadcast = parseInt($scope.entry.firstBroadcast, 10);
						// trim data edges:
						if (!isNaN(firstBroadcast)) {	// non-kaltura don't have firstBroadcast
							for (var i = 0; i < objects.length; i++) {
								if (objects[i].timestamp >= firstBroadcast) {
									break;
								}
							}
						}
						for (var j = objects.length - 1; j>=0; j--) {
							if (objects[j].value != 0) {
								j++;
								break;
							}
						}
						objects = objects.slice(i, j);
						$scope.$emit('TimeBoundsSet', objects[0].timestamp, objects[objects.length - 1].timestamp);
					}
					resetGraphContent(objects);
				};
			});
		};

		/**
		 * get graph data for the last 30 secs
		 * @param endTime (timestamp sec) get graph data for 30 secs up to this time
		 */
		var getGraph30Secs = function getGraph30Secs(endTime) {
			var toDate = -60;	//endTime;
			var fromDate = -122;
			EntrySvc.getGraph($scope.entryId, fromDate, toDate).then(function(data) {
				var objects = parseData(data[0].data);
				objects = balanceData(objects, endTime-122, endTime-60, $scope.entry.isLive);
				if (graph != null) {
					updateGraphContent(objects);
				}
			});
		};

		/**
		 * remove all previous data and set new
		 * @param value
		 */
		var resetGraphContent = function resetGraphContent(value) {
			var ar = series[0].data;
			while (ar.length > 0) {
				ar.pop();
			}
			for ( var i = 0; i < value.length; i++) {
				ar.push(value[i]);
			}
			graph.update();
		};

		/**
		 * add new data and purge oldest so we keep only 36 hrs
		 * @param value points to add tot he graph
		 */
		var updateGraphContent = function updateGraphContent(value) {
			var graphData = series[0].data; // already in the graph
			var lastGraphDataX = graphData[graphData.length-1].x;
			// first see if any existing values need to be updated
			for (var i = 0; i<value.length; i++) {
				var valX = value[i].x;
				if (valX <= lastGraphDataX) {
					// this x value is already in the graph
					for (var j = graphData.length-1; j>=0; j--) {
						if (graphData[j].x == valX) {
							if ( value[i].y != 0) {
								graphData[j].y = value[i].y;
							}
							break;
						}
						else if (graphData[j].x < valX) {
							// j will only become smaller
							break;
						}
					}
				}
				else {
					// valX is out of graphData bounds, will be so for any larger i
					break;
				}
			}

			// then shift/push for new ones
			while(i < value.length) {
				graphData.shift();
				graphData.push(value[i]);
				i++;
			}

			graph.update();
		};

		/**
		 * event handler for main screen setup event
		 * @param event
		 * @param time (timestamp sec)
		 */
		var setupScreenHandler = function setupScreenHandler(event, time) {
			getGraph36Hrs(time);
		};

		/**
		 * event handler for main screen update interval
		 * @param event
		 * @param time (timestamp sec)
		 */
		var updateScreenHandler = function updateScreenHandler(event, time) {
			getGraph30Secs(time);
		};

		$scope.$on('setupScreen', setupScreenHandler);
		$scope.$on('updateScreen', updateScreenHandler);
}]);<commit_msg>PLAT-2411 emit event also if no recording<commit_after>'use strict';

/**
 * controller for (rickshaw) graph on entry page
 */
analyticsControllers.controller('RGraphController', ['$scope', '$attrs', 'EntrySvc',
    function($scope, $attrs, EntrySvc) {
		var self = this;
		var graphElement = null; 	// HTML element showing the graph
		var graph = null;			// graph JS object
		var series = null;			// data container

		this.init = function init (element) {
			graphElement = element;
			var d = new Date();
			var t = d.getTime()/1000;
			series = [{
					color : 'steelblue',
					data : [ {x:t, y:0} ],
					name : "Line 1"
				}];

			graph = createGraph(series, element);
		};

		var graphClickHandler = function graphClickHandler(time) {
			if (!$scope.entry.isLive) {
				// click - only for recorded entries that are not currently live
				$scope.$emit('gotoTime', time);
			}
		};

		/**
		 * create graph and its parts
		 * @param series
		 * @param element
		 * @return rickshaw graph
		 */
		var createGraph = function createGraph(series, element) {
			var graph = new Rickshaw.Graph({
				element : element[0].children[0],
				width : element.width(),
				height : element.height() - 20,
				renderer : 'line',
				interpolation: 'linear',
				series : series
			});
			graph.render();

			var preview = new Rickshaw.Graph.RangeSlider({
				graph : graph,
				element : element[0].children[1]
			});

			var xAxis = new Rickshaw.Graph.Axis.Time({
				graph : graph,
				ticksTreatment : 'glow',
				timeFixture : new KTime_Local()
			});
			xAxis.render();

			var yAxis = new Rickshaw.Graph.Axis.Y({
				graph : graph,
				tickFormat : Rickshaw.Fixtures.Number.formatKMBT,
				ticksTreatment : 'glow'
			});
			yAxis.render();

			var hoverDetail = new KHoverDetail( {
			    graph: graph,
			    formatter: function(series, x, y, formattedXValue, formattedYValue, point) {
			    	return formattedXValue + '
' + y + ' views';
			    },
				onClick : graphClickHandler
			} );

			return graph;
		};

		/**
		 * @param str	info string
		 * @return Array [{x, y}, ..]
		 */
		var parseData = function parseData(str) {
			var os = str.split(';');
			var objects = new Array();
			os.forEach(function (sLine) {
				if (sLine) {
					var vals = sLine.split(',');
					objects.push({'x':parseInt(vals[0], 10), 'timestamp':parseInt(vals[0], 10), 'y':parseInt(vals[1], 10)});
				}
			});
			return objects;
		};

		/**
		 * add 0 points where no data received
		 * for live - all the way
		 * for dead - after first point, before last point
		 * @param data 		objects array with "holes"
		 * @param fromDate	timestamp, seconds
		 * @param toDate	timestamp, seconds
		 * @param fillAll	boolean, should data outside existing range be filled
		 * @return array without "holes"
		 */
		var balanceData = function balanceData(data, fromDate, toDate, fillAll) {
			var firstPoint = Math.floor(fromDate/10)*10;	// init like this for when no data
			var lastPoint = firstPoint;
			var curx, nextx, i = 1;
			if (data.length) {
				firstPoint = data[0].x;
				lastPoint = data[data.length-1].x;
			}

			// add points between lastPoint and firstPoint
			curx = firstPoint + 10;
			while (curx < lastPoint) {
				nextx = data[i].x;
				if (curx < nextx) {
					// need to add point here
					data.splice(i, 0, {'x':curx, 'timestamp':curx, 'y':0});
				}
				curx += 10;
				i++;
			}

			if (fillAll) {
				// add points between firstPoint and fromDate
				curx = firstPoint - 10;
				while (curx >= fromDate) {
					data.unshift({'x':curx, 'timestamp':curx, 'y':0});
					curx -= 10;
				}

				// add points after lastPoint
				curx = lastPoint + 10;
				while (curx <= toDate) {
					data.push({'x':curx, 'timestamp':curx, 'y':0});
					curx += 10;
				}
			}
			return data;
		};

		/**
		 * get graph data for the last 36 hrs
		 * @param end of 36 hrs term (timestamp sec)
		 */
		var getGraph36Hrs = function getGraph36Hrs(toDate) {
			toDate = toDate - 60;
			var fromDate = toDate - 12960; // 60 sec per minute * 60 minutes per hour * 36 hrs
			EntrySvc.getGraph($scope.entryId, -129660, -60).then(function(data) {
				if (data[0] && graph != null) {
					// parse string into objects
					var objects = parseData(data[0].data);
					// add 0 points where no data received
					objects = balanceData(objects, fromDate, toDate, $scope.entry.isLive);
					if (!$scope.entry.isLive) {
						var firstBroadcast = parseInt($scope.entry.firstBroadcast, 10);
						// trim data edges:
						if (!isNaN(firstBroadcast)) {	// non-kaltura don't have firstBroadcast
							for (var i = 0; i < objects.length; i++) {
								if (objects[i].timestamp >= firstBroadcast) {
									break;
								}
							}
						}
						for (var j = objects.length - 1; j>=0; j--) {
							if (objects[j].value != 0) {
								j++;
								break;
							}
						}
						objects = objects.slice(i, j);
						$scope.$emit('TimeBoundsSet', objects[0].timestamp, objects[objects.length - 1].timestamp);
					}
					resetGraphContent(objects);
				};
			});
		};

		/**
		 * get graph data for the last 30 secs
		 * @param endTime (timestamp sec) get graph data for 30 secs up to this time
		 */
		var getGraph30Secs = function getGraph30Secs(endTime) {
			var toDate = -60;	//endTime;
			var fromDate = -122;
			EntrySvc.getGraph($scope.entryId, fromDate, toDate).then(function(data) {
				var objects = parseData(data[0].data);
				objects = balanceData(objects, endTime-122, endTime-60, $scope.entry.isLive);
				if (graph != null) {
					updateGraphContent(objects);
				}
			});
		};

		/**
		 * remove all previous data and set new
		 * @param value
		 */
		var resetGraphContent = function resetGraphContent(value) {
			var ar = series[0].data;
			while (ar.length > 0) {
				ar.pop();
			}
			for ( var i = 0; i < value.length; i++) {
				ar.push(value[i]);
			}
			graph.update();
		};

		/**
		 * add new data and purge oldest so we keep only 36 hrs
		 * @param value points to add tot he graph
		 */
		var updateGraphContent = function updateGraphContent(value) {
			var graphData = series[0].data; // already in the graph
			var lastGraphDataX = graphData[graphData.length-1].x;
			// first see if any existing values need to be updated
			for (var i = 0; i<value.length; i++) {
				var valX = value[i].x;
				if (valX <= lastGraphDataX) {
					// this x value is already in the graph
					for (var j = graphData.length-1; j>=0; j--) {
						if (graphData[j].x == valX) {
							if ( value[i].y != 0) {
								graphData[j].y = value[i].y;
							}
							break;
						}
						else if (graphData[j].x < valX) {
							// j will only become smaller
							break;
						}
					}
				}
				else {
					// valX is out of graphData bounds, will be so for any larger i
					break;
				}
			}

			// then shift/push for new ones
			while(i < value.length) {
				graphData.shift();
				graphData.push(value[i]);
				i++;
			}

			graph.update();
		};

		/**
		 * event handler for main screen setup event
		 * @param event
		 * @param time (timestamp sec)
		 */
		var setupScreenHandler = function setupScreenHandler(event, time) {
			getGraph36Hrs(time);
		};

		/**
		 * event handler for main screen update interval
		 * @param event
		 * @param time (timestamp sec)
		 */
		var updateScreenHandler = function updateScreenHandler(event, time) {
			getGraph30Secs(time);
		};

		$scope.$on('setupScreen', setupScreenHandler);
		$scope.$on('updateScreen', updateScreenHandler);
}]);<|endoftext|>


<commit_before>
define([
  'jquery',
  'underscore',
  'backbone',
  'helpers/app'
], function ($, _, Backbone, AppHelper) {

  var OlayList = Backbone.Collection.extend ({

    url: AppHelper.urlPrefix + 'basliklar/olay',

    parse: function (resp) {
      var entries = [];
      var htmlDoc = $.parseHTML (resp);
      $(htmlDoc).find ('#content ul.topic-list li a').each (function () {

        if ($(this).attr ('class') == 'empty-index-item')
          return;

        var entry_url = $(this).attr ('href').replace (/\?.*/, '');
        var entry_snapshot = $(this).attr ('href').replace (/.*snapshot=/, '');
        // TODO: remove entry count from title
        var entry_title = $(this).text ();
        var entry_count = parseInt ($(this).find ('small').text ());

        if (entry_count) {
          var re = new RegExp(entry_count + '$');
          entry_title = entry_title.replace(re, '(' + entry_count + ')');

          entries.push ({ url: entry_url,
                          title: entry_title,
                          count: entry_count ? entry_count : 0,
                          snapshot: entry_snapshot });
        }
      });

      return entries;
    },

    fetch: function (options) {
      options = options || {};
      options.dataType = 'html';
      return Backbone.Collection.prototype.fetch.call (this, options);
    }

  });

  return OlayList;

});
<commit_msg>Show all topic that have at least 1 unread entry<commit_after>
define([
  'jquery',
  'underscore',
  'backbone',
  'helpers/app'
], function ($, _, Backbone, AppHelper) {

  var OlayList = Backbone.Collection.extend ({

    url: AppHelper.urlPrefix + 'basliklar/olay',

    parse: function (resp) {
      var entries = [];
      var htmlDoc = $.parseHTML (resp);
      $(htmlDoc).find ('#content ul.topic-list li a').each (function () {

        if ($(this).attr ('class') == 'empty-index-item')
          return;

        var entry_url = $(this).attr ('href').replace (/\?.*/, '');
        var entry_snapshot = $(this).attr ('href').replace (/.*snapshot=/, '');
        // TODO: remove entry count from title
        var entry_title = $(this).text ();
        var entry_count = parseInt ($(this).find ('small').text ());

        var re = new RegExp(entry_count + '$');
        entry_title = entry_title.replace(re, '(' + entry_count + ')');

        entries.push ({ url: entry_url,
                        title: entry_title,
                        count: entry_count ? entry_count : 1,
                        snapshot: entry_snapshot });
      });

      return entries;
    },

    fetch: function (options) {
      options = options || {};
      options.dataType = 'html';
      return Backbone.Collection.prototype.fetch.call (this, options);
    }

  });

  return OlayList;

});
<|endoftext|>


<commit_before>import {
  REMEMBER_ARTICLE_SUCCESS,
  UPDATE_ARTICLE_SUCCESS,
  LOAD_ARTICLE_SUCCESS,
  REMOVE_ARTICLE_SUCCESS,
} from './../../actions/article';

export default (state, action) => {
  switch (action.type) {
    case LOAD_ARTICLE_SUCCESS: {
      const articles = action.payload.getIn(['entities', 'article']);

      if (!articles) {
        return state;
      }

      return state.setIn(['article', action.meta.articleUrl], articles.first());
    }
    case REMEMBER_ARTICLE_SUCCESS: {
      const article = action.payload.getIn(['entities', 'article']).first();

      return state.setIn(['article', action.meta.articleUrl], article);
    }
    case UPDATE_ARTICLE_SUCCESS: {
      const article = action.payload.getIn(['entities', 'article']).first();
      const articleUrl = state.getIn(['article']).findKey((el) => el.get('id') === action.meta.articleId);

      return state.setIn(['article', articleUrl], article);
    }
    case REMOVE_ARTICLE_SUCCESS: {
      const articleUrl = state.getIn(['article']).findKey((el) => el.get('id') === action.meta.articleId);

      return state.deleteIn(['article', articleUrl]);
    }
    default: {
      return state;
    }
  }
};
<commit_msg>Fix popup updates when url changes<commit_after>import {
  REMEMBER_ARTICLE_SUCCESS,
  UPDATE_ARTICLE_SUCCESS,
  LOAD_ARTICLE_SUCCESS,
  REMOVE_ARTICLE_SUCCESS,
} from './../../actions/article';

export default (state, action) => {
  switch (action.type) {
    case LOAD_ARTICLE_SUCCESS: {
      const articles = action.payload.getIn(['entities', 'article']);

      if (!articles) {
        return state;
      }

      return state.setIn(['article', action.meta.articleUrl], articles.first());
    }
    case REMEMBER_ARTICLE_SUCCESS: {
      const article = action.payload.getIn(['entities', 'article']).first();

      return state.setIn(['article', action.meta.articleUrl], article);
    }
    case UPDATE_ARTICLE_SUCCESS: {
      const article = action.payload.getIn(['entities', 'article']).first();

      return state.update('article', (articles) =>
                          articles.map((v) =>
                                       (v.get('id') === action.meta.articleId ? article : v)));
    }
    case REMOVE_ARTICLE_SUCCESS: {
      return state.update('article', (articles) =>
                          articles.filter((v) => v.get('id') !== action.meta.articleId));
    }
    default: {
      return state;
    }
  }
};
<|endoftext|>


<commit_before>var game = new Phaser.Game(800, 600, Phaser.CANVAS, '', { preload: preload, create: create, update: update });
var cursors;

function preload() {
	game.load.image('food', 'asset/pizza.png');
	game.load.image('snake', 'asset/circle.png');
}

function create() {
	game.physics.startSystem(Phaser.Physics.ARCADE);
	initFood();
	initSnake();
	cursors = game.input.keyboard.createCursorKeys();
}

function update() {
	player.sprite.movimiento(player.sprite);
	game.physics.arcade.overlap(player.sprite, food.sprite, eatFood, null, this);
}

function initFood() {
	var rx = Math.floor((Math.random() * 800) + 1);
	var ry = Math.floor((Math.random() * 600) + 1);
	food = new Food(game, rx, ry);
	return food;

}

function initSnake() {
	var rx = Math.floor((Math.random() * 800) + 1);
	var ry = Math.floor((Math.random() * 600) + 1);
	player = new Snake(game, rx, ry);
	return player;
}

function eatFood(player,food) {
	food.kill();
	initFood();
}<commit_msg>Delete script.js<commit_after><|endoftext|>


<commit_before>// Margin amounts
var margin = {
  top: 20,
  right: 80,
  bottom: 40,
  left: 50
};

// Canvas size
var canvasWidth = 600;
var canvasHeight = 500;

// Tooltip
var tooltip = d3.select('body')
  .append('div')
  .attr('class', 'tooltip');

/**
 * Loads the data file.
 */
function loadTSV() {
  d3.tsv('data.tsv', function(d) {
    var mileage = +d['Mileage'];
    var gallonsFilled = +d['Gallons Filled'];
    var pricePerGallon = +d['Price Per Gallon'];
    var milesRemaining = +d['Miles Remaining'];

    var pricePerMile = (gallonsFilled * pricePerGallon) / mileage;
    var gasUtilization = mileage / (mileage + milesRemaining);

    return {
      date: d['Date'],
      mileage: mileage,
      milesRemaining: milesRemaining,
      gallonsFilled: gallonsFilled,
      pricePerGallon: pricePerGallon,
      mpg: +d['MPG'],
      pricePerMile: pricePerMile,
      gasUtilization: gasUtilization
    };
  }, function(error, data) {
    if (error) {
      console.log('Read error');
      return;
    }

    /**
     * Loads the mileage and miles remaining line chart.
     *
     * @param data The data for the chart.
     */
    function loadMileageLineChart(data) {
      var svg = d3.select('#mileage-canvas')
        .attr('width', canvasWidth)
        .attr('height', canvasHeight);

      var milesColorIndex = 0;
      var remainingMilesColorIndex = 1;

      // Scales
      var timeScale = d3.scaleTime()
        .domain([d3.timeDay.offset(new Date(data[0].date), -3), d3.timeDay.offset(new Date(data[data.length - 1].date), 1)])
        .rangeRound([margin.left, canvasWidth - margin.right]);

      var milesScale = d3.scaleLinear()
        .domain([0, Math.floor((d3.max(data.map(function(d) {
          return d.mileage + d.milesRemaining;
        })) / 10) + 1) * 10 + 100])
        .range([canvasHeight - margin.bottom, margin.top]);
      console.log(milesScale.domain())

      var colorScale = d3.scaleOrdinal(d3.schemeCategory10);

      // Mileage line
      var mileageLine = d3.line()
        .x(function(d) {
          return timeScale(new Date(d.date));
        })
        .y(function(d) {
          return milesScale(d.mileage);
        });

      // Remaining miles line
      var remainingMilesLine = d3.line()
        .x(function(d) {
          return timeScale(new Date(d.date));
        })
        .y(function(d) {
          return milesScale(d.milesRemaining + d.mileage);
        });

      // Axes
      var xAxis = d3.axisBottom()
        .scale(timeScale)
        .tickFormat(d3.timeFormat('%Y/%m'));

      var yAxis = d3.axisLeft()
        .scale(milesScale);

      // Data line groups
      var mileageLineGroup = svg.append('g')
        .classed('miles-line', true)

      mileageLineGroup.append('path')
        .attr('class', 'line')
        .attr('stroke', function(d) {
          return colorScale(milesColorIndex);
        })
        .attr('fill', 'none');

      var remainingMilesLineGroup = svg.append('g')
        .classed('remain-line', true)

      remainingMilesLineGroup.append('path')
        .attr('class', 'line')
        .attr('stroke', function(d) {
          return colorScale(remainingMilesColorIndex);
        })
        .attr('fill', 'none');

      // Data lines
      mileageLineGroup.select('.line')
        .datum(data)
        .attr('d', mileageLine);

      remainingMilesLineGroup.select('.line')
        .datum(data)
        .attr('d', remainingMilesLine);

      // SVG groups
      svg.append('g')
        .attr('class', 'x-axis')
        .attr('transform', 'translate(0,' + (canvasHeight - margin.bottom) + ')');

      svg.append('g')
        .attr('class', 'y-axis')
        .attr('transform', 'translate(' + margin.left + ',0)');

      svg
        .append('text')
        .classed('label', true)
        .attr('x', canvasWidth / 2)
        .attr('y', canvasHeight - margin.top / 2)
        .attr('text-anchor', 'middle')
        .text('Date');

      svg.append('text')
        .classed('label', true)
        .attr('x', -canvasHeight / 2)
        .attr('y', 15)
        .attr('text-anchor', 'middle')
        .attr('transform', 'rotate(-90, 0, 0)')
        .text('Miles Driven');

      svg.append('g')
        .classed('dots', true);

      svg.select('.x-axis')
        .call(xAxis);

      svg.select('.y-axis')
        .call(yAxis);

      svg
        .append('text')
        .classed('chart-title', true)
        .attr('x', canvasWidth / 2)
        .attr('y', margin.bottom)
        .attr('text-anchor', 'middle')
        .text('Miles Before Fillup vs. Potential Drivable Miles');

      // Add dots
      var dataDots = svg.select('.dots')
        .selectAll('.dot')
        .data(data)
        .enter()
        .append('g')
        .classed('dot', true);

      dataDots.append('circle')
        .attr('r', 4)
        .attr('cx', function(d) {
          return timeScale(new Date(d.date));
        })
        .attr('cy', function(d) {
          return milesScale(d.mileage);
        })
        .attr('opacity', 1)
        .attr('fill', function(d) {
          return colorScale(milesColorIndex);
        })
        .on('mouseover', function(d) {
          tooltipMileageLineMouseOver(d);
        })
        .on('mousemove', function(d) {
          tooltipMileageLineMouseMove(d);
        })
        .on('mouseout', function(d) {
          tooltipMouseOut(d);
        });

      dataDots.append('circle')
        .attr('r', 4)
        .attr('cx', function(d) {
          return timeScale(new Date(d.date));
        })
        .attr('cy', function(d) {
          return milesScale(d.milesRemaining + d.mileage);
        })
        .attr('opacity', 1)
        .attr('fill', function(d) {
          return colorScale(remainingMilesColorIndex);
        })
        .on('mouseover', function(d) {
          tooltipRemainingMilesLineMouseOver(d);
        })
        .on('mousemove', function(d) {
          tooltipRemainingMilesLineMouseMove(d);
        })
        .on('mouseout', function(d) {
          tooltipMouseOut(d);
        });

      svg.append('text')
        .classed('legend-item', true)
        .datum(data[data.length - 1])
        .attr('transform', function(d) {
          return 'translate(' + timeScale(new Date(d.date)) + ',' + milesScale(d.mileage) + ')';
        })
        .attr('x', -10)
        .attr('y', -10)
        .attr('alignment-baseline', 'middle')
        .text('Mileage');

      svg.append('text')
        .classed('legend-item', true)
        .datum(data[data.length - 1])
        .attr('transform', function(d) {
          return 'translate(' + timeScale(new Date(d.date)) + ',' + milesScale(d.milesRemaining + d.mileage) + ')';
        })
        .attr('x', -18)
        .attr('y', -10)
        .attr('alignment-baseline', 'middle')
        .text('Potential Miles');
    }

    function loadAverageMPGChart(data) {
      var svg = d3.select('#avg-canvas')
        .attr('width', canvasWidth)
        .attr('height', canvasHeight);

      var barWidth = 10;
      var colorScale = d3.scaleOrdinal(d3.schemeCategory20);

      var timeScale = d3.scaleTime()
        .domain([d3.timeDay.offset(new Date(data[0].date), -5), d3.timeDay.offset(new Date(data[data.length - 1].date), 5)])
        .rangeRound([margin.left, canvasWidth - margin.right]);

      var avgMPGScale = d3.scaleLinear()
        .domain([(Math.floor(d3.min(data.map(function(d) {
          return d.mpg;
        })))), (Math.floor(d3.max(data.map(function(d) {
          return d.mpg;
        })))) + 3])
        .range([canvasHeight - margin.bottom, margin.top]);

      var xAxis = d3.axisBottom()
        .scale(timeScale)
        .tickFormat(d3.timeFormat('%Y/%m'));

      var yAxis = d3.axisLeft()
        .scale(avgMPGScale);

      svg.append('g')
        .attr('class', 'x-axis')
        .attr('transform', 'translate(0,' + (canvasHeight - margin.bottom) + ')');

      svg.append('g')
        .attr('class', 'y-axis')
        .attr('transform', 'translate(' + margin.left + ',0)');

      svg.select('.x-axis')
        .call(xAxis);

      svg.select('.y-axis')
        .call(yAxis);

      svg
        .append('text')
        .classed('label', true)
        .attr('x', canvasWidth / 2)
        .attr('y', canvasHeight - margin.top / 2)
        .attr('text-anchor', 'middle')
        .text('Date');

      svg.append('text')
        .classed('label', true)
        .attr('x', -canvasHeight / 2)
        .attr('y', 10)
        .attr('text-anchor', 'middle')
        .attr('transform', 'rotate(-90, 0, 0)')
        .text('Miles Per Gallon');

      svg
        .append('text')
        .classed('chart-title', true)
        .attr('x', canvasWidth / 2)
        .attr('y', margin.bottom)
        .attr('text-anchor', 'middle')
        .text('Average Mileage Between Fillups');

      var barGroup = svg
        .append('g')
        .classed('bars', true);

      var bars = barGroup.selectAll('.bar')
        .data(data)
        .enter()
        .append('g')
        .classed('bar', true);

      bars.append('rect')
        .attr('x', function(d) {
          return timeScale(new Date(d.date)) - (barWidth / 2);
        })
        .attr('y', function(d) {
          return avgMPGScale(d.mpg);
        })
        .attr('height', function(d) {
          return canvasHeight - avgMPGScale(d.mpg) - margin.bottom;
        })
        .attr('width', function(d) {
          return barWidth;
        })
        .attr('fill', function(d, i) {
          return colorScale(i % 20);
        })
        .on('mouseover', function(d) {
          tooltipAvgMPGMouseOver(d);
        })
        .on('mousemove', function(d) {
          tooltipAvgMPGMouseMove(d);
        })
        .on('mouseout', function(d) {
          tooltipMouseOut(d);
        });
    }

    function tooltipMileageLineMouseOver(d) {
      tooltipMouseOver(d, d.mileage);
    }

    function tooltipRemainingMilesLineMouseOver(d) {
      tooltipMouseOver(d, d.mileage + ' + ' + d.milesRemaining + ' = ' + (d.milesRemaining + d.mileage));
    }

    function tooltipMileageLineMouseMove(d) {
      tooltipMouseMove(d, d.mileage);
    }

    function tooltipRemainingMilesLineMouseMove(d) {
      tooltipMouseMove(d, d.mileage + ' + ' + d.milesRemaining + ' = ' + (d.milesRemaining + d.mileage));
    }

    function tooltipAvgMPGMouseOver(d) {
      tooltipMouseOver(d, d.mpg + ' mpg');
    }

    function tooltipAvgMPGMouseMove(d) {
      tooltipMouseMove(d, d.mpg + ' mpg');
    }

    function tooltipMouseOver(d, text) {
      tooltip
        .style('top', (d3.event.pageY - 20) + "px")
        .style('left', (d3.event.pageX) + "px")
        .text(text);

      tooltip.transition()
        .duration(200)
        .style('opacity', 1)
    }

    function tooltipMouseMove(d, text) {
      tooltip
        .style('top', (d3.event.pageY - 20) + "px")
        .style('left', (d3.event.pageX) + "px")
        .text(text);
    }

    function tooltipMouseOut(d) {
      tooltip
        .transition()
        .duration(200)
        .style('opacity', 0)
    }

    loadMileageLineChart(data);
    loadAverageMPGChart(data);
  });
}

loadTSV();<commit_msg>Rotated axis labels so they don't overlap.<commit_after>// Margin amounts
var margin = {
  top: 20,
  right: 80,
  bottom: 60,
  left: 50
};

// Canvas size
var canvasWidth = 600;
var canvasHeight = 500;

// Tooltip
var tooltip = d3.select('body')
  .append('div')
  .attr('class', 'tooltip');

/**
 * Loads the data file.
 */
function loadTSV() {
  d3.tsv('data.tsv', function(d) {
    var mileage = +d['Mileage'];
    var gallonsFilled = +d['Gallons Filled'];
    var pricePerGallon = +d['Price Per Gallon'];
    var milesRemaining = +d['Miles Remaining'];

    var pricePerMile = (gallonsFilled * pricePerGallon) / mileage;
    var gasUtilization = mileage / (mileage + milesRemaining);

    return {
      date: d['Date'],
      mileage: mileage,
      milesRemaining: milesRemaining,
      gallonsFilled: gallonsFilled,
      pricePerGallon: pricePerGallon,
      mpg: +d['MPG'],
      pricePerMile: pricePerMile,
      gasUtilization: gasUtilization
    };
  }, function(error, data) {
    if (error) {
      console.log('Read error');
      return;
    }

    /**
     * Loads the mileage and miles remaining line chart.
     *
     * @param data The data for the chart.
     */
    function loadMileageLineChart(data) {
      var svg = d3.select('#mileage-canvas')
        .attr('width', canvasWidth)
        .attr('height', canvasHeight);

      var milesColorIndex = 0;
      var remainingMilesColorIndex = 1;

      // Scales
      var timeScale = d3.scaleTime()
        .domain([d3.timeMonth.offset(new Date(data[0].date), -1), d3.timeMonth.offset(new Date(data[data.length - 1].date), 1)])
        .rangeRound([margin.left, canvasWidth - margin.right]);

      var milesScale = d3.scaleLinear()
        .domain([0, Math.floor((d3.max(data.map(function(d) {
          return d.mileage + d.milesRemaining;
        })) / 10) + 1) * 10 + 100])
        .range([canvasHeight - margin.bottom, margin.top]);
      console.log(milesScale.domain())

      var colorScale = d3.scaleOrdinal(d3.schemeCategory10);

      // Mileage line
      var mileageLine = d3.line()
        .x(function(d) {
          return timeScale(new Date(d.date));
        })
        .y(function(d) {
          return milesScale(d.mileage);
        });

      // Remaining miles line
      var remainingMilesLine = d3.line()
        .x(function(d) {
          return timeScale(new Date(d.date));
        })
        .y(function(d) {
          return milesScale(d.milesRemaining + d.mileage);
        });

      // Axes
      var xAxis = d3.axisBottom()
        .scale(timeScale)
        .tickFormat(d3.timeFormat('%Y/%m'));

      var yAxis = d3.axisLeft()
        .scale(milesScale);

      // Data line groups
      var mileageLineGroup = svg.append('g')
        .classed('miles-line', true)

      mileageLineGroup.append('path')
        .attr('class', 'line')
        .attr('stroke', function(d) {
          return colorScale(milesColorIndex);
        })
        .attr('fill', 'none');

      var remainingMilesLineGroup = svg.append('g')
        .classed('remain-line', true)

      remainingMilesLineGroup.append('path')
        .attr('class', 'line')
        .attr('stroke', function(d) {
          return colorScale(remainingMilesColorIndex);
        })
        .attr('fill', 'none');

      // Data lines
      mileageLineGroup.select('.line')
        .datum(data)
        .attr('d', mileageLine);

      remainingMilesLineGroup.select('.line')
        .datum(data)
        .attr('d', remainingMilesLine);

      // SVG groups
      svg.append('g')
        .attr('class', 'x-axis')
        .attr('transform', 'translate(0,' + (canvasHeight - margin.bottom) + ')');

      svg.append('g')
        .attr('class', 'y-axis')
        .attr('transform', 'translate(' + margin.left + ',0)');

      svg
        .append('text')
        .classed('label', true)
        .attr('x', canvasWidth / 2)
        .attr('y', canvasHeight - margin.top / 2 + 5)
        .attr('text-anchor', 'middle')
        .text('Date');

      svg.append('text')
        .classed('label', true)
        .attr('x', -canvasHeight / 2)
        .attr('y', 15)
        .attr('text-anchor', 'middle')
        .attr('transform', 'rotate(-90, 0, 0)')
        .text('Miles Driven');

      svg.append('g')
        .classed('dots', true);

      svg.select('.x-axis')
        .call(xAxis)
        .selectAll('text')
        .attr('x', -25)
        .attr('y', 5)
        .attr('transform', 'rotate(-45, 0, 0)');

      svg.select('.y-axis')
        .call(yAxis);

      svg
        .append('text')
        .classed('chart-title', true)
        .attr('x', canvasWidth / 2)
        .attr('y', margin.bottom)
        .attr('text-anchor', 'middle')
        .text('Miles Before Fillup vs. Potential Drivable Miles');

      // Add dots
      var dataDots = svg.select('.dots')
        .selectAll('.dot')
        .data(data)
        .enter()
        .append('g')
        .classed('dot', true);

      dataDots.append('circle')
        .attr('r', 4)
        .attr('cx', function(d) {
          return timeScale(new Date(d.date));
        })
        .attr('cy', function(d) {
          return milesScale(d.mileage);
        })
        .attr('opacity', 1)
        .attr('fill', function(d) {
          return colorScale(milesColorIndex);
        })
        .on('mouseover', function(d) {
          tooltipMileageLineMouseOver(d);
        })
        .on('mousemove', function(d) {
          tooltipMileageLineMouseMove(d);
        })
        .on('mouseout', function(d) {
          tooltipMouseOut(d);
        });

      dataDots.append('circle')
        .attr('r', 4)
        .attr('cx', function(d) {
          return timeScale(new Date(d.date));
        })
        .attr('cy', function(d) {
          return milesScale(d.milesRemaining + d.mileage);
        })
        .attr('opacity', 1)
        .attr('fill', function(d) {
          return colorScale(remainingMilesColorIndex);
        })
        .on('mouseover', function(d) {
          tooltipRemainingMilesLineMouseOver(d);
        })
        .on('mousemove', function(d) {
          tooltipRemainingMilesLineMouseMove(d);
        })
        .on('mouseout', function(d) {
          tooltipMouseOut(d);
        });

      svg.append('text')
        .classed('legend-item', true)
        .datum(data[data.length - 1])
        .attr('transform', function(d) {
          return 'translate(' + timeScale(new Date(d.date)) + ',' + milesScale(d.mileage) + ')';
        })
        .attr('x', -10)
        .attr('y', -10)
        .attr('alignment-baseline', 'middle')
        .text('Mileage');

      svg.append('text')
        .classed('legend-item', true)
        .datum(data[data.length - 1])
        .attr('transform', function(d) {
          return 'translate(' + timeScale(new Date(d.date)) + ',' + milesScale(d.milesRemaining + d.mileage) + ')';
        })
        .attr('x', -18)
        .attr('y', -10)
        .attr('alignment-baseline', 'middle')
        .text('Potential Miles');
    }

    function loadAverageMPGChart(data) {
      var svg = d3.select('#avg-canvas')
        .attr('width', canvasWidth)
        .attr('height', canvasHeight);

      var barWidth = 10;
      var colorScale = d3.scaleOrdinal(d3.schemeCategory20);

      var timeScale = d3.scaleTime()
        .domain([d3.timeMonth.offset(new Date(data[0].date), -1), d3.timeMonth.offset(new Date(data[data.length - 1].date), 1)])
        .rangeRound([margin.left, canvasWidth - margin.right]);

      var avgMPGScale = d3.scaleLinear()
        .domain([(Math.floor(d3.min(data.map(function(d) {
          return d.mpg;
        })))), (Math.floor(d3.max(data.map(function(d) {
          return d.mpg;
        })))) + 3])
        .range([canvasHeight - margin.bottom, margin.top]);

      var xAxis = d3.axisBottom()
        .scale(timeScale)
        .tickFormat(d3.timeFormat('%Y/%m'));

      var yAxis = d3.axisLeft()
        .scale(avgMPGScale);

      svg.append('g')
        .attr('class', 'x-axis')
        .attr('transform', 'translate(0,' + (canvasHeight - margin.bottom) + ')');

      svg.append('g')
        .attr('class', 'y-axis')
        .attr('transform', 'translate(' + margin.left + ',0)');

      svg.select('.x-axis')
        .call(xAxis)
        .selectAll('text')
        .attr('x', -25)
        .attr('y', 5)
        .attr('transform', 'rotate(-45, 0, 0)');

      svg.select('.y-axis')
        .call(yAxis);

      svg
        .append('text')
        .classed('label', true)
        .attr('x', canvasWidth / 2)
        .attr('y', canvasHeight - margin.top / 2 + 5)
        .attr('text-anchor', 'middle')
        .text('Date');

      svg.append('text')
        .classed('label', true)
        .attr('x', -canvasHeight / 2)
        .attr('y', 10)
        .attr('text-anchor', 'middle')
        .attr('transform', 'rotate(-90, 0, 0)')
        .text('Miles Per Gallon');

      svg
        .append('text')
        .classed('chart-title', true)
        .attr('x', canvasWidth / 2)
        .attr('y', margin.bottom)
        .attr('text-anchor', 'middle')
        .text('Average Mileage Between Fillups');

      var barGroup = svg
        .append('g')
        .classed('bars', true);

      var bars = barGroup.selectAll('.bar')
        .data(data)
        .enter()
        .append('g')
        .classed('bar', true);

      bars.append('rect')
        .attr('x', function(d) {
          return timeScale(new Date(d.date)) - (barWidth / 2);
        })
        .attr('y', function(d) {
          return avgMPGScale(d.mpg);
        })
        .attr('height', function(d) {
          return canvasHeight - avgMPGScale(d.mpg) - margin.bottom;
        })
        .attr('width', function(d) {
          return barWidth;
        })
        .attr('fill', function(d, i) {
          return colorScale(i % 20);
        })
        .on('mouseover', function(d) {
          tooltipAvgMPGMouseOver(d);
        })
        .on('mousemove', function(d) {
          tooltipAvgMPGMouseMove(d);
        })
        .on('mouseout', function(d) {
          tooltipMouseOut(d);
        });
    }

    function tooltipMileageLineMouseOver(d) {
      tooltipMouseOver(d, d.mileage);
    }

    function tooltipRemainingMilesLineMouseOver(d) {
      tooltipMouseOver(d, '[' + d.date + ']: ' + d.mileage + ' + ' + d.milesRemaining + ' = ' + (d.milesRemaining + d.mileage));
    }

    function tooltipMileageLineMouseMove(d) {
      tooltipMouseMove(d, '[' + d.date + ']: ' + d.mileage);
    }

    function tooltipRemainingMilesLineMouseMove(d) {
      tooltipMouseMove(d, '[' + d.date + ']: ' + d.mileage + ' + ' + d.milesRemaining + ' = ' + (d.milesRemaining + d.mileage));
    }

    function tooltipAvgMPGMouseOver(d) {
      tooltipMouseOver(d, '[' + d.date + ']: ' + d.mpg + ' mpg');
    }

    function tooltipAvgMPGMouseMove(d) {
      tooltipMouseMove(d, '[' + d.date + ']: ' + d.mpg + ' mpg');
    }

    function tooltipMouseOver(d, text) {
      tooltip
        .style('top', (d3.event.pageY - 20) + "px")
        .style('left', (d3.event.pageX) + "px")
        .text(text);

      tooltip.transition()
        .duration(200)
        .style('opacity', 1)
    }

    function tooltipMouseMove(d, text) {
      tooltip
        .style('top', (d3.event.pageY - 20) + "px")
        .style('left', (d3.event.pageX) + "px")
        .text(text);
    }

    function tooltipMouseOut(d) {
      tooltip
        .transition()
        .duration(200)
        .style('opacity', 0)
    }

    loadMileageLineChart(data);
    loadAverageMPGChart(data);
  });
}

loadTSV();<|endoftext|>


<commit_before>import React from 'react'
import BrowserRouter from 'react-router-dom/es/BrowserRouter'
import App from 'components/App/App'
import routes from './routes'
import RouteWithSubRoutes from './utils/RouteUtil'
import { environment } from 'utils/relay'
import { isAuthenticated } from 'modules/auth/utils'
//require('offline-plugin/runtime').install()

const Root = (props) =>
  <BrowserRouter history={history} >
    <App {...props}>
      <RouteWithSubRoutes
        {...props}
        routes={routes}
        relay={{ environment }}
      />
    </App>
  </BrowserRouter>

export default isAuthenticated(Root)
<commit_msg>Remove history<commit_after>import React from 'react'
import BrowserRouter from 'react-router-dom/es/BrowserRouter'
import App from 'components/App/App'
import routes from './routes'
import RouteWithSubRoutes from './utils/RouteUtil'
import { environment } from 'utils/relay'
import { isAuthenticated } from 'modules/auth/utils'
//require('offline-plugin/runtime').install()

const Root = (props) =>
  <BrowserRouter >
    <App {...props}>
      <RouteWithSubRoutes
        {...props}
        routes={routes}
        relay={{ environment }}
      />
    </App>
  </BrowserRouter>

export default isAuthenticated(Root)
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */

module.exports = function(app) {
	// Article Routes
	var users = require('../../app/controllers/users.server.controller'),
		localStore = require('../../app/controllers/localStore.server.controller');

	app.route('/api/localstore/')
		.get(localStore.getLocalStore);

	app.route('/api/localstore/:localStoreSlug')
		.get(localStore.readLocalStoreSlug);

	// Finish by binding the article middleware
	app.param('localStoreSlug', localStore.localStoreBySlug);
};<commit_msg>fixing typo in route from localstore<commit_after>'use strict';

/**
 * Module dependencies.
 */

module.exports = function(app) {
	// Article Routes
	var users = require('../../app/controllers/users.server.controller'),
		localStore = require('../../app/controllers/localstore.server.controller');

	app.route('/api/localstore/')
		.get(localStore.getLocalStore);

	app.route('/api/localstore/:localStoreSlug')
		.get(localStore.readLocalStoreSlug);

	// Finish by binding the article middleware
	app.param('localStoreSlug', localStore.localStoreBySlug);
};<|endoftext|>


<commit_before>'use strict';

angular.module('backAnd.controllers')
    .controller('menuController', ['$scope', 'Global', 'menuService', '$timeout', '$rootScope', '$http', '$location', '$route',
        function($scope, Global, menuService, $timeout, $rootScope, $http, $location, $route) {

            $scope.global = Global;
            /*set contentType*/
//$scope.global.url = "dashboard/my-website"
            $scope.templateUrl = function() {
                return "views/" + $scope.global.url + ".html";
            }
            /**/
            $scope.init = function() {
                console.log("fff")
                if (!localStorage.getItem('Authorization')) {
                    $location.path('/login');
                } else {
                    $location.path('/');
                    $http.defaults.headers.common['Authorization'] = localStorage.getItem('Authorization');
                    menuService.queryjsonp({},
                        function success(data) {
                            $scope.pages = data.workspace.pages;

                            $timeout(function() {
                                adminLteInit();
                            });
                        },
                        function err(error) {
                            if (error.status == 401) {
                                localStorage.removeItem("Authorization");
                                window.location.reload();
                            }
                        });
                }
            }
            $scope.setCurrentTable = function(table, index, partType) {
                console.log(partType)
                if (partType == "table")
                    $scope.global.url = "tables"
                if (partType == "dashboard")
                    $scope.global.url = "dashboard/my-website"

                $scope.curTable = index;
                $scope.global.currentTable = table;
                //$rootScope.$broadcast('loadData');
            }
            $scope.$on('load', function() {
                $scope.init();
            });

        }
    ])
<commit_msg>dashboard chrts example fix<commit_after>'use strict';

angular.module('backAnd.controllers')
    .controller('menuController', ['$scope', 'Global', 'menuService', '$timeout', '$rootScope', '$http', '$location', '$route',
        function($scope, Global, menuService, $timeout, $rootScope, $http, $location, $route) {

            $scope.global = Global;

            $scope.templateUrl = function() {
                if ($scope.global.url)
                    return "views/" + $scope.global.url + ".html";
            }

            $scope.init = function() {

                if (!localStorage.getItem('Authorization')) {
                    $location.path('/login');
                } else {
                    $location.path('/');
                    $http.defaults.headers.common['Authorization'] = localStorage.getItem('Authorization');
                    menuService.queryjsonp({},
                        function success(data) {
                            $scope.pages = data.workspace.pages;

                            $timeout(function() {
                                adminLteInit();
                            });
                        },
                        function err(error) {
                            if (error.status == 401) {
                                localStorage.removeItem("Authorization");
                                window.location.reload();
                            }
                        });
                }
            }
            $scope.setCurrentTable = function(table, index, partType) {

                if (partType == "table")
                    $scope.global.url = "tables"
                if (partType == "dashboard")
                    $scope.global.url = "dashboard/my-website"

                $scope.curTable = index;
                $scope.global.currentTable = table;
                //$rootScope.$broadcast('loadData');
            }

            $scope.$on('load', function() {
                $scope.init();
            });

        }
    ])
<|endoftext|>


<commit_before>const utils = require('./utils');

var LOCK_URL = 'http://192.168.0.3:8080/';
var SECONDS_TO_LEAVE = 300;

var URL_WHITELIST = new Set([
    'https://straylight.jp/one/00001',
    'https://straylight.jp/one/00002',
    'https://straylight.jp/one/vk2g7',
    'https://straylight.jp/one/b4cz6',
    'https://straylight.jp/one/6ej7n',
    'https://straylight.jp/one/u36bx',
    'https://straylight.jp/one/9y2tk',
    'https://straylight.jp/one/33fxm',
    'https://straylight.jp/one/ujv3w',
    'https://straylight.jp/one/zz6n7',
]);
var MAC_ADDRESS_WHITELIST = new Map([
    //['F0:2A:63:5C:E3:E5', ['SLBeacon99998', '']],
    //['EB:B4:73:21:AC:3C', ['SLBeacon99997', '']],
    //['D7:AF:DA:DF:43:85', ['SLBeacon99999', '']],
    ['E6:64:E0:C6:40:F1', ['SLBeacon00001', 'Alisaun']],
    ['CA:5F:63:5B:17:D5', ['SLBeacon00002', 'Lauren']],
    ['D6:60:A7:9F:E5:DF', ['SLBeacon00003', 'Daniel']],
    ['C7:D7:61:92:28:85', ['SLBeacon00004', 'Roy']],
    ['EF:EA:6A:BD:C7:29', ['SLBeacon00005', 'Jake']],
    ['D5:DB:E9:EE:D8:BB', ['SLBeacon00006', 'Keigo']],
    ['E7:A1:7A:F0:41:A6', ['SLBeacon00007', 'Ikue']],
    ['D8:3E:FB:33:28:FC', ['SLBeacon00008', 'Taj']],
    ['C2:12:FB:37:74:C6', ['SLBeacon00009', 'Ryo']],
    // ['C2:12:FB:37:74:C6', ['SLBeacon00010', '']],
    // ['E3:DA:76:79:72:A2', ['SLBeacon00011', '']],
    // ['CD:E9:12:5F:27:42', ['SLBeacon00012', '']],
]);

var lastSeenMap = new Map();
var presentMacAddressSet = new Set();
var leavingMacAddressSet = new Set();
var leftoverMacAddressSet = new Set();
var leavingMacAddressClearTimer;
var latestJpegData;

var sendUnlockAction = utils.throttle(5000, function() {
  utils.get(LOCK_URL + 'unlock');
});

function pulseLEDs() {
  utils.get('http://192.168.0.6:8080/pulse(200,200,200,1,1)');
}

function clearAfterUnlock() {
  leavingMacAddressSet.clear();
  leftoverMacAddressSet.clear();
  clearTimeout(leavingMacAddressClearTimer);
}

function unlock() {
  sendUnlockAction();
  clearAfterUnlock();
  pulseLEDs();
}

function getOwner(macAddress) {
  var ownerData = MAC_ADDRESS_WHITELIST.get(macAddress);
  if (!ownerData) {
    return 'Unknown Owner';
  }
  return ownerData[1];
}

function processNfc(url) {
  console.info('processNfc: ' + url);
  if (URL_WHITELIST.has(url)) {
    console.info('UNLOCKING with NFC: ' + url);
    unlock();
  }
}

function processBle(macAddress, rssi) {
  console.info('processBle: ' + macAddress + ' RSSI=' + rssi);
  lastSeenMap.set(macAddress, new Date().getTime());
  if (MAC_ADDRESS_WHITELIST.has(macAddress) &&
      !leavingMacAddressSet.has(macAddress) &&
      !leftoverMacAddressSet.has(macAddress) &&
      !presentMacAddressSet.has(macAddress)) {
    console.info('UNLOCKING with BLE: ' + macAddress);
    presentMacAddressSet.add(macAddress);
    console.info('Found ' + macAddress + ' ' + getOwner(macAddress));
    logPresentMembers();
    unlock();
  }
}

setInterval(function() {
  var now = new Date().getTime();
  for (var [macAddress, lastSeen] of lastSeenMap) {
    if (lastSeen !== undefined && now - lastSeen >= 300 * 1000) {
      presentMacAddressSet.delete(macAddress);
      console.info('Lost ' + macAddress + ' ' + getOwner(macAddress));
      logPresentMembers();
      lastSeenMap.delete(macAddress);
    }
  }
}, 60 * 1000);

function logPresentMembers() {
  var presentNames = [];
  presentMacAddressSet.forEach(function(macAddress) {
    var name = MAC_ADDRESS_WHITELIST.get(macAddress)[1];
    presentNames.push(name);
  });
  console.info('Present members: ' + presentNames);
}

function processLockStateChange(state) {
  console.info('processLockStateChange: ' + state);
  if (state == 'locked') {
    console.info('LOCKED');

    leavingMacAddressSet = new Set(presentMacAddressSet);
    console.info('Leaving IDs: ' + [...leavingMacAddressSet]);

    clearTimeout(leavingMacAddressClearTimer);
    leavingMacAddressClearTimer = setTimeout(function() {
      leavingMacAddressSet.clear();

      leftoverMacAddressSet = new Set(presentMacAddressSet);
      console.info('Leftover IDs: ' + [...leftoverMacAddressSet]);
    }, SECONDS_TO_LEAVE * 1000);
  } else if (state == 'unlocked') {
    console.info('UNLOCKED');
    clearAfterUnlock();
  } else if (state == 'unreachable') {
    console.info('UNREACHABLE');
  } else {
    console.error('Unknown lock state: ' + state);
  }
}

function processImage(data) {
  latestJpegData = Buffer.from(data, 'base64');
}

function process(data) {
  if (data.type == 'nfc') {
    processNfc(data.url);
  } else if (data.type == 'ble') {
    processBle(data.macAddress, data.rssi);
  } else if (data.type == 'lockStateChange') {
    processLockStateChange(data.state);
  } else if (data.type == 'image') {
    processImage(data.data);
  } else {
    console.error('Unknown message type: ' + data.type);
  }
}

exports.post = function(req, res) {
  process(req.body);
  res.send('OK');
}

exports.socket = function(message) {
  var data = JSON.parse(message);
  process(data);
}

exports.getLatestImage = function(req, res) {
  if (!latestJpegData) {
    return res.status(404).send('Not found');
  }
  res.writeHead(200, {'Content-Type': 'image/jpeg'});
  res.end(latestJpegData);
}

<commit_msg>Fix mac address of 00009 beacon<commit_after>const utils = require('./utils');

var LOCK_URL = 'http://192.168.0.3:8080/';
var SECONDS_TO_LEAVE = 300;

var URL_WHITELIST = new Set([
    'https://straylight.jp/one/00001',
    'https://straylight.jp/one/00002',
    'https://straylight.jp/one/vk2g7',
    'https://straylight.jp/one/b4cz6',
    'https://straylight.jp/one/6ej7n',
    'https://straylight.jp/one/u36bx',
    'https://straylight.jp/one/9y2tk',
    'https://straylight.jp/one/33fxm',
    'https://straylight.jp/one/ujv3w',
    'https://straylight.jp/one/zz6n7',
]);
var MAC_ADDRESS_WHITELIST = new Map([
    //['F0:2A:63:5C:E3:E5', ['SLBeacon99998', '']],
    //['EB:B4:73:21:AC:3C', ['SLBeacon99997', '']],
    //['D7:AF:DA:DF:43:85', ['SLBeacon99999', '']],
    ['E6:64:E0:C6:40:F1', ['SLBeacon00001', 'Alisaun']],
    ['CA:5F:63:5B:17:D5', ['SLBeacon00002', 'Lauren']],
    ['D6:60:A7:9F:E5:DF', ['SLBeacon00003', 'Daniel']],
    ['C7:D7:61:92:28:85', ['SLBeacon00004', 'Roy']],
    ['EF:EA:6A:BD:C7:29', ['SLBeacon00005', 'Jake']],
    ['D5:DB:E9:EE:D8:BB', ['SLBeacon00006', 'Keigo']],
    ['E7:A1:7A:F0:41:A6', ['SLBeacon00007', 'Ikue']],
    ['D8:3E:FB:33:28:FC', ['SLBeacon00008', 'Taj']],
    ['CA:DC:C0:96:C1:A4', ['SLBeacon00009', 'Ryo']],
    // ['C2:12:FB:37:74:C6', ['SLBeacon00010', '']],
    // ['E3:DA:76:79:72:A2', ['SLBeacon00011', '']],
    // ['CD:E9:12:5F:27:42', ['SLBeacon00012', '']],
]);

var lastSeenMap = new Map();
var presentMacAddressSet = new Set();
var leavingMacAddressSet = new Set();
var leftoverMacAddressSet = new Set();
var leavingMacAddressClearTimer;
var latestJpegData;

var sendUnlockAction = utils.throttle(5000, function() {
  utils.get(LOCK_URL + 'unlock');
});

function pulseLEDs() {
  utils.get('http://192.168.0.6:8080/pulse(200,200,200,1,1)');
}

function clearAfterUnlock() {
  leavingMacAddressSet.clear();
  leftoverMacAddressSet.clear();
  clearTimeout(leavingMacAddressClearTimer);
}

function unlock() {
  sendUnlockAction();
  clearAfterUnlock();
  pulseLEDs();
}

function formatBeacon(macAddress) {
  var ownerData = MAC_ADDRESS_WHITELIST.get(macAddress);
  if (!ownerData) {
    return macAddress;
  }
  return ([macAddress].concat(ownerData)).join(' ');
}

function processNfc(url) {
  console.info('processNfc: ' + url);
  if (URL_WHITELIST.has(url)) {
    console.info('UNLOCKING with NFC: ' + url);
    unlock();
  }
}

function processBle(macAddress, rssi) {
  console.info('processBle: ' + macAddress + ' RSSI=' + rssi);
  lastSeenMap.set(macAddress, new Date().getTime());
  if (MAC_ADDRESS_WHITELIST.has(macAddress) &&
      !leavingMacAddressSet.has(macAddress) &&
      !leftoverMacAddressSet.has(macAddress) &&
      !presentMacAddressSet.has(macAddress)) {
    console.info('UNLOCKING with BLE: ' + macAddress);
    presentMacAddressSet.add(macAddress);
    console.info('Found ' + formatBeacon(macAddress));
    logPresentMembers();
    unlock();
  }
}

setInterval(function() {
  var now = new Date().getTime();
  for (var [macAddress, lastSeen] of lastSeenMap) {
    if (lastSeen !== undefined && now - lastSeen >= 300 * 1000) {
      presentMacAddressSet.delete(macAddress);
      console.info('Lost ' + formatBeacon(macAddress));
      logPresentMembers();
      lastSeenMap.delete(macAddress);
    }
  }
}, 60 * 1000);

function logPresentMembers() {
  var presentNames = [];
  presentMacAddressSet.forEach(function(macAddress) {
    var name = MAC_ADDRESS_WHITELIST.get(macAddress)[1];
    presentNames.push(name);
  });
  console.info('Present members: ' + presentNames);
}

function processLockStateChange(state) {
  console.info('processLockStateChange: ' + state);
  if (state == 'locked') {
    console.info('LOCKED');

    leavingMacAddressSet = new Set(presentMacAddressSet);
    console.info('Leaving IDs: ' + [...leavingMacAddressSet]);

    clearTimeout(leavingMacAddressClearTimer);
    leavingMacAddressClearTimer = setTimeout(function() {
      leavingMacAddressSet.clear();

      leftoverMacAddressSet = new Set(presentMacAddressSet);
      console.info('Leftover IDs: ' + [...leftoverMacAddressSet]);
    }, SECONDS_TO_LEAVE * 1000);
  } else if (state == 'unlocked') {
    console.info('UNLOCKED');
    clearAfterUnlock();
  } else if (state == 'unreachable') {
    console.info('UNREACHABLE');
  } else {
    console.error('Unknown lock state: ' + state);
  }
}

function processImage(data) {
  latestJpegData = Buffer.from(data, 'base64');
}

function process(data) {
  if (data.type == 'nfc') {
    processNfc(data.url);
  } else if (data.type == 'ble') {
    processBle(data.macAddress, data.rssi);
  } else if (data.type == 'lockStateChange') {
    processLockStateChange(data.state);
  } else if (data.type == 'image') {
    processImage(data.data);
  } else {
    console.error('Unknown message type: ' + data.type);
  }
}

exports.post = function(req, res) {
  process(req.body);
  res.send('OK');
}

exports.socket = function(message) {
  var data = JSON.parse(message);
  process(data);
}

exports.getLatestImage = function(req, res) {
  if (!latestJpegData) {
    return res.status(404).send('Not found');
  }
  res.writeHead(200, {'Content-Type': 'image/jpeg'});
  res.end(latestJpegData);
}

<|endoftext|>


<commit_before>//load a sprite -- mave it default to sinking -- on keypress have it thrust up

//make blocks come at player -- if collision, player explodes -- player starts over

var game = new Phaser.Game(1000, 300, Phaser.AUTO, '', { preload: preload, create: create, update: update });

function preload() {

    game.load.spritesheet('ship', 'assets/gfx/ship.png', 32, 32);
    game.load.spritesheet('block', 'assets/gfx/block.png');
    game.load.spritesheet('explosion', '/assets/gfx/explosion.png', 128, 128);

}

function create() {
 //player
  player = game.add.sprite(32,32, 'ship');
  player.animations.add('up', [1]);
  player.animations.add('down', [0]);

  game.physics.startSystem(Phaser.Physics.ARCADE);
  game.physics.arcade.enable(player);
  player.body.gravity.y = 300;
  player.body.collideWorldBounds = true;

  player.body.bounce.setTo(0.25, 0.25);

}

function update() {
  cursors = game.input.keyboard.createCursorKeys();

      if (cursors.up.isDown){
        player.body.velocity.y = -170;
        player.animations.play('up');
      }
      else {
        player.animations.play('down');
      }

}

<commit_msg>added moving block<commit_after>//load a sprite -- mave it default to sinking -- on keypress have it thrust up XXXXXXXX

//make blocks come at player -- XXXXXXXX

//make loop that makes block segments

//if collision, player explodes -- player starts over

var game = new Phaser.Game(1000, 300, Phaser.AUTO, '', { preload: preload, create: create, update: update });

function preload() {

    game.load.spritesheet('ship', 'assets/gfx/ship.png', 32, 32);
    game.load.image('block', 'assets/gfx/block.png');
    game.load.spritesheet('explosion', '/assets/gfx/explosion.png', 128, 128);

}

function create() {

  game.physics.startSystem(Phaser.Physics.ARCADE);

 //player
  player = game.add.sprite(32,32, 'ship');
  player.animations.add('up', [1]);
  player.animations.add('down', [0]);

  game.physics.arcade.enable(player);
  player.body.gravity.y = 300;
  player.body.collideWorldBounds = true;
  player.body.bounce.setTo(0.25, 0.25);

 //block
  block = game.add.sprite(200,100, 'block');

  game.physics.arcade.enable(block);
  block.body.collideWorldBounds = false;
  block.body.velocity.x = -300;

}

function update() {
  cursors = game.input.keyboard.createCursorKeys();

      if (cursors.up.isDown){
        player.body.velocity.y = -170;
        player.animations.play('up');
      }
      else {
        player.animations.play('down');
      }

}

<|endoftext|>


<commit_before>
var CommentBox = React.createClass({
  loadCommentsFromServer: function() {
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      cache: false,
      success: function(data) {
        this.setState({data: data});
      }.bind(this),
      error: function(xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  },

  getInitialState: function() {
    return {data: []};
  },

  componentDidMount: function() {
    this.loadCommentsFromServer();
    setInterval(this.loadCommentsFromServer, this.props.pollInterval);
  },

  render: function() {
    return (

        <EventTable data={this.state.data}/>

    );
  }
});

var EventDeleteBtn = React.createClass({
  handleClick: function(e) {
    console.log("clicked " + this.props.event.venue);
  },
  render: function() {
    return (

<button onClick={this.handleClick}>Delete</button>

    );
  }
});

var EventRow = React.createClass({
  render: function() {
    return (

        {this.props.event.date}
        {this.props.event.time}
        {this.props.event.venue}
        {this.props.event.attendees}
        {this.props.event.rating}
        <EventDeleteBtn event={this.props.event}></EventDeleteBtn>

    );
  }
});

var EventTable = React.createClass({
  render: function() {
    var rows = [];
    this.props.data.forEach(function(event) {
      rows.push(<EventRow event={event} key={event._id}/>);
    });
    return (

            Date
            Time
            Venue
            Attendees
            Rating

{rows}

    );
  }
});

ReactDOM.render(
  <CommentBox url="/events" pollInterval={2000} />,
  document.getElementById('content')
);      <commit_msg>Pass url down to EventTable<commit_after>
var CommentBox = React.createClass({
  loadCommentsFromServer: function() {
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      cache: false,
      success: function(data) {
        this.setState({data: data});
      }.bind(this),
      error: function(xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  },

  getInitialState: function() {
    return {data: []};
  },

  componentDidMount: function() {
    this.loadCommentsFromServer();
    setInterval(this.loadCommentsFromServer, this.props.pollInterval);
  },

  render: function() {
    return (

        <EventTable data={this.state.data} url={this.props.url}/>

    );
  }
});

var EventDeleteBtn = React.createClass({
  handleClick: function(e) {
    console.log("clicked " + this.props.event.venue);
  },
  render: function() {
    return (

<button onClick={this.handleClick}>Delete</button>

    );
  }
});

var EventRow = React.createClass({
  render: function() {
    return (

        {this.props.event.date}
        {this.props.event.time}
        {this.props.event.venue}
        {this.props.event.attendees}
        {this.props.event.rating}
        <EventDeleteBtn event={this.props.event}></EventDeleteBtn>

    );
  }
});

var EventTable = React.createClass({
  render: function() {
    var rows = [];
    this.props.data.forEach(function(event) {
      rows.push(<EventRow event={event} key={event._id}/>);
    });
    return (

            Date
            Time
            Venue
            Attendees
            Rating

{rows}

    );
  }
});

ReactDOM.render(
  <CommentBox url="/events" pollInterval={2000} />,
  document.getElementById('content')
);      <|endoftext|>