<commit_before>var gzip = require('zlib').gzip;
var util = require('../../../lib/util');
var config = require('../../../lib/config');
var properties = require('../../../lib/rules/util').properties;

var PID = process.pid;
var MAX_OBJECT_SIZE = 1024 * 1024 * 6;
var index = 0;

exports.getClientId = function() {
  if (index > 9999) {
    index = 0;
  }
  return Date.now() + '-' + index++;
};

exports.getServerInfo = function(req) {
  var info = {
    pid: PID,
    version: config.version,
    networkMode: config.networkMode,
    pluginsMode: config.pluginsMode,
    rulesMode: config.rulesMode,
    strictMode: config.strict,
    multiEnv: config.multiEnv,
    baseDir: config.baseDirHash,
    username: config.username,
    nodeVersion: process.version,
    latestVersion: properties.get('latestVersion'),
    host: util.hostname(),
    isWin: util.isWin,
    port: config.port,
    realPort: config.realPort,
    socksPort: config.socksPort,
    httpPort: config.httpPort,
    httpsPort: config.httpsPort,
    ipv4: [],
    ipv6: [],
    mac: req.ip + (config.storage ? '\n' + config.storage : '')
  };
  var ifaces = util.networkInterfaces();
  Object.keys(ifaces).forEach(function(ifname) {
    ifaces[ifname].forEach(function (iface) {
      if (iface.internal) {
        return;
      }
      info[iface.family == 'IPv4' ? 'ipv4' : 'ipv6'].push(iface.address);
    });
  });

  return info;
};

var DATA_RE = /[\r\n]\s*(\{[\s\S]*\})[\r\n]/;
var REPLACE_RE = /[\r\n]1[\r\n]/;
exports.getReqData = function(req, callback) {
  var result = '';
  req.on('data', function(chunk) {
    result = result ? Buffer.concat([result, chunk]) : chunk;
    if (result.length > MAX_OBJECT_SIZE) {
      req.removeAllListeners('data');
      callback(new Error('The file size can not exceed 6m.'));
    }
  });
  req.on('error', callback);
  req.on('end', function() {
    result += '';
    var data;
    result = result.replace(DATA_RE, function(all, match) {
      data = match;
      return '';
    });
    if (!data) {
      return callback(new Error('The file content is not a JSON object'));
    }
    try {
      data = JSON.parse(data);
    } catch(err) {
      return callback(err);
    }
    callback(null, {
      data: data,
      replace: REPLACE_RE.test(result)
    });
  });
};

function padding(num) {
  return num < 10 ? '0' + num : num;
}

function paddingMS(ms) {
  if (ms > 99) {
    return ms;
  }
  if (ms > 9) {
    return '0' + ms;
  }
  return '00' + ms;
}

function formatDate() {
  var date = new Date();
  var result = [];
  result.push(date.getFullYear());
  result.push(padding(date.getMonth() + 1));
  result.push(padding(date.getDate()));
  result.push(padding(date.getHours()));
  result.push(padding(date.getMinutes()));
  result.push(padding(date.getSeconds()));
  result.push(paddingMS(date.getMilliseconds()));
  return result.join('');
}

exports.formatDate = formatDate;

exports.getClientIp = util.getClientIp;

exports.sendGzip = function(req, res, data) {
  if (!util.canGzip(req)) {
    return res.json(data);
  }
  gzip(JSON.stringify(data), function(err, result) {
    if (err) {
      try {
        res.json(data);
      } catch (e) {
        res.status(500).send(config.debugMode ?
          '
' + util.getErrorStack(err) + '
' : 'Internal Server Error');
      }
      return;
    }
    res.writeHead(200, {
      'Content-Type': 'application/json; charset=utf-8',
      'Content-Encoding': 'gzip',
      'Content-Length': result.length
    });
    res.end(result);
  });
};
<commit_msg>refactor: do not gzip local requests<commit_after>var gzip = require('zlib').gzip;
var util = require('../../../lib/util');
var config = require('../../../lib/config');
var properties = require('../../../lib/rules/util').properties;

var PID = process.pid;
var MAX_OBJECT_SIZE = 1024 * 1024 * 6;
var index = 0;

exports.getClientId = function() {
  if (index > 9999) {
    index = 0;
  }
  return Date.now() + '-' + index++;
};

exports.getServerInfo = function(req) {
  var info = {
    pid: PID,
    version: config.version,
    networkMode: config.networkMode,
    pluginsMode: config.pluginsMode,
    rulesMode: config.rulesMode,
    strictMode: config.strict,
    multiEnv: config.multiEnv,
    baseDir: config.baseDirHash,
    username: config.username,
    nodeVersion: process.version,
    latestVersion: properties.get('latestVersion'),
    host: util.hostname(),
    isWin: util.isWin,
    port: config.port,
    realPort: config.realPort,
    socksPort: config.socksPort,
    httpPort: config.httpPort,
    httpsPort: config.httpsPort,
    ipv4: [],
    ipv6: [],
    mac: req.ip + (config.storage ? '\n' + config.storage : '')
  };
  var ifaces = util.networkInterfaces();
  Object.keys(ifaces).forEach(function(ifname) {
    ifaces[ifname].forEach(function (iface) {
      if (iface.internal) {
        return;
      }
      info[iface.family == 'IPv4' ? 'ipv4' : 'ipv6'].push(iface.address);
    });
  });

  return info;
};

var DATA_RE = /[\r\n]\s*(\{[\s\S]*\})[\r\n]/;
var REPLACE_RE = /[\r\n]1[\r\n]/;
exports.getReqData = function(req, callback) {
  var result = '';
  req.on('data', function(chunk) {
    result = result ? Buffer.concat([result, chunk]) : chunk;
    if (result.length > MAX_OBJECT_SIZE) {
      req.removeAllListeners('data');
      callback(new Error('The file size can not exceed 6m.'));
    }
  });
  req.on('error', callback);
  req.on('end', function() {
    result += '';
    var data;
    result = result.replace(DATA_RE, function(all, match) {
      data = match;
      return '';
    });
    if (!data) {
      return callback(new Error('The file content is not a JSON object'));
    }
    try {
      data = JSON.parse(data);
    } catch(err) {
      return callback(err);
    }
    callback(null, {
      data: data,
      replace: REPLACE_RE.test(result)
    });
  });
};

function padding(num) {
  return num < 10 ? '0' + num : num;
}

function paddingMS(ms) {
  if (ms > 99) {
    return ms;
  }
  if (ms > 9) {
    return '0' + ms;
  }
  return '00' + ms;
}

function formatDate() {
  var date = new Date();
  var result = [];
  result.push(date.getFullYear());
  result.push(padding(date.getMonth() + 1));
  result.push(padding(date.getDate()));
  result.push(padding(date.getHours()));
  result.push(padding(date.getMinutes()));
  result.push(padding(date.getSeconds()));
  result.push(paddingMS(date.getMilliseconds()));
  return result.join('');
}

exports.formatDate = formatDate;

exports.getClientIp = util.getClientIp;

exports.sendGzip = function(req, res, data) {
  if (req.clientIp === '127.0.0.1' || !util.canGzip(req)) {
    return res.json(data);
  }
  gzip(JSON.stringify(data), function(err, result) {
    if (err) {
      try {
        res.json(data);
      } catch (e) {
        res.status(500).send(config.debugMode ?
          '
' + util.getErrorStack(err) + '
' : 'Internal Server Error');
      }
      return;
    }
    res.writeHead(200, {
      'Content-Type': 'application/json; charset=utf-8',
      'Content-Encoding': 'gzip',
      'Content-Length': result.length
    });
    res.end(result);
  });
};
<|endoftext|>


<commit_before>'use strict';

// Declare app level module which depends on views, and components
angular.module('myApp', [
  'ngRoute',
  'myApp.colors',
  'myApp.about'
  // 'myApp.colors'
]).
config(['$routeProvider', function($routeProvider) {
  $routeProvider.otherwise({redirectTo: '/colors'});
}])
// .directive('resize', function ($window) {
//     return function (scope, element) {
//         var w = angular.element($window);
//         scope.getWindowDimensions = function () {
//         	console.log("New Window Dimention:",w.innerHeight,w.innerWidth);
//             return {
//                 'h': w.innerHeight,
//                 'w': w.innerWidth
//             };
//         };
//         scope.$watch(scope.getWindowDimensions, function (newValue, oldValue) {
//             scope.windowHeight = newValue.h;
//             scope.windowWidth = newValue.w;

//             scope.style = function () {
//                 return {
//                     'height': (newValue.h - 100) + 'px',
//                         'width': (newValue.w - 100) + 'px'
//                 };
//             };

//         }, true);

//         w.bind('resize', function () {
//             scope.$apply();
//             alert("window resized");
//         });
//     }
// })
;<commit_msg>cleanup<commit_after>'use strict';

// Declare app level module which depends on views, and components
angular.module('myApp', [
  'ngRoute',
  'myApp.colors',
  'myApp.about'
  // 'myApp.colors'
]).
config(['$routeProvider', function($routeProvider) {
  $routeProvider.otherwise({redirectTo: '/colors'});
}]);
// .directive('resize', function ($window) {
//     return function (scope, element) {
//         var w = angular.element($window);
//         scope.getWindowDimensions = function () {
//         	console.log("New Window Dimention:",w.innerHeight,w.innerWidth);
//             return {
//                 'h': w.innerHeight,
//                 'w': w.innerWidth
//             };
//         };
//         scope.$watch(scope.getWindowDimensions, function (newValue, oldValue) {
//             scope.windowHeight = newValue.h;
//             scope.windowWidth = newValue.w;

//             scope.style = function () {
//                 return {
//                     'height': (newValue.h - 100) + 'px',
//                         'width': (newValue.w - 100) + 'px'
//                 };
//             };

//         }, true);

//         w.bind('resize', function () {
//             scope.$apply();
//             alert("window resized");
//         });
//     }
// })
;<|endoftext|>


<commit_before>
// Module dependencies
var express = require('express');
var strftime = require('strftime');
var _ = require('underscore');

var path = require('path');
var http = require('http');
var util = require('util');

// Internal modules
var routes = require('./routes');
var api = require('./routes/api');
var mid = require('./middlewares.js');
var store = require('./lib/store.js');
var tcpsrv = require('./lib/tcpsrv.js');

var ConnectStore = require('./lib/connect-store.js')(express);

// Initialisation of express
var app = express();

// Configuration
var public_path = path.join(__dirname, './public');
var config = require('../config.json');
var brush = require('../brush.json');

app.configure(function () {
  // Setup view tempates
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.locals.pretty = true;

  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());

  app.use(express.cookieParser());
  app.use(express.session({
    store: new ConnectStore,
    secret: config.session.secret,
    cookie: { maxAge: config.session.maxAge }
  }));

  app.use(express.static(public_path));
  // compile the less stylesheet to a css
  app.use(require('less-middleware')({ src: public_path }));

  // show awesome error messages
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));

  // setup locals / view/request helpers
  app.use(function (req, res, next) {
    res.locals.domain = req.headers.host;
    res.locals.url = function (args, hash) {
      var url = req.protocol + '://' + req.headers.host + '/' + args.join('/');
      if (typeof hash != 'undefined' && hash != null && hash != '') {
        url += '#' + hash;
      }
      if (url.charAt(0) != '/' && url.indexOf('http') !== 0)
        url = '/' + url;
      return url;
    };

    res.locals.config = config;
    res.locals.brush = brush;
    res.locals.strftime = strftime;
    res.locals.session = req.session;

    // set session default values:
    _.defaults(req.session, config.session.defaults);

    next();
  });
});

// sets a timer to delete expired pastes every 5 minutes
setInterval(function () {
  console.log('delete expired pastes');
  Paste.deleteExpired(function (err) {
    if (err != null) console.error(err);
  });
}, 15 * 60 * 1000);

// setup routes
app.get ('/'                   , routes.index);
app.get ('/list'               , routes.list);
app.get ('/create'             , routes.createPasteForm);
app.post('/create'             , routes.createPaste);
app.get ('/:id.:format?/:file?', routes.readPaste);
app.get ('/update/:id/:secret' , routes.updatePasteForm);
app.post('/update'             , routes.updatePaste);
app.get ('/delete/:id/:secret' , routes.deletePasteForm);
app.post('/delete'             , routes.deletePaste);
app.post('/settings'           , routes.settings);
app.get ('/about'              , routes.about);

// setup REST API routes
app.get ('/api/1/paste'        , api.list);
app.get ('/api/1/paste/:id'    , api.readPaste);
app.post('/api/1/paste'        , api.createPaste);
app.put ('/api/1/paste/:id'    , api.updatePaste);
app.delete('/api/1/paste/:id'  , api.deletePaste);

app.get ('*'                   , routes.notFound);

// Error messages all redirect to create
app.use(function (err, req, res, next) {
  console.log('\n');
  console.log('AN ERROR OCCURED :: ' + req.ip + ' :: ' + req.originalUrl);
  console.log(' ========================================================= ');
  console.log(err.stack);
  console.log('\n');
  res.render('create', {notice: err});
});

// start the express server
http.createServer(app).listen(config.server.port, config.server.bind, function() {
  console.log('Express server listening on port ' + config.server.port);
});

// start the TCP server, for netcat/telnet posting;)
tcpsrv.create();

<commit_msg>fix bug in expire delete job<commit_after>
// Module dependencies
var express = require('express');
var strftime = require('strftime');
var _ = require('underscore');

var path = require('path');
var http = require('http');
var util = require('util');

// Internal modules
var routes = require('./routes');
var api = require('./routes/api');
var mid = require('./middlewares.js');
var store = require('./lib/store.js');
var tcpsrv = require('./lib/tcpsrv.js');

var ConnectStore = require('./lib/connect-store.js')(express);

var Paste = require('./models/paste.js').Paste;

// Initialisation of express
var app = express();

// Configuration
var public_path = path.join(__dirname, './public');
var config = require('../config.json');
var brush = require('../brush.json');

app.configure(function () {
  // Setup view tempates
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.locals.pretty = true;

  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());

  app.use(express.cookieParser());
  app.use(express.session({
    store: new ConnectStore,
    secret: config.session.secret,
    cookie: { maxAge: config.session.maxAge }
  }));

  app.use(express.static(public_path));
  // compile the less stylesheet to a css
  app.use(require('less-middleware')({ src: public_path }));

  // show awesome error messages
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));

  // setup locals / view/request helpers
  app.use(function (req, res, next) {
    res.locals.domain = req.headers.host;
    res.locals.url = function (args, hash) {
      var url = req.protocol + '://' + req.headers.host + '/' + args.join('/');
      if (typeof hash != 'undefined' && hash != null && hash != '') {
        url += '#' + hash;
      }
      if (url.charAt(0) != '/' && url.indexOf('http') !== 0)
        url = '/' + url;
      return url;
    };

    res.locals.config = config;
    res.locals.brush = brush;
    res.locals.strftime = strftime;
    res.locals.session = req.session;

    // set session default values:
    _.defaults(req.session, config.session.defaults);

    next();
  });
});

// sets a timer to delete expired pastes every 5 minutes
setInterval(function () {
  console.log('delete expired pastes');
  Paste.deleteExpired(function (err) {
    if (err != null) console.error(err);
  });
}, 15 * 60 * 1000);

// setup routes
app.get ('/'                   , routes.index);
app.get ('/list'               , routes.list);
app.get ('/create'             , routes.createPasteForm);
app.post('/create'             , routes.createPaste);
app.get ('/:id.:format?/:file?', routes.readPaste);
app.get ('/update/:id/:secret' , routes.updatePasteForm);
app.post('/update'             , routes.updatePaste);
app.get ('/delete/:id/:secret' , routes.deletePasteForm);
app.post('/delete'             , routes.deletePaste);
app.post('/settings'           , routes.settings);
app.get ('/about'              , routes.about);

// setup REST API routes
app.get ('/api/1/paste'        , api.list);
app.get ('/api/1/paste/:id'    , api.readPaste);
app.post('/api/1/paste'        , api.createPaste);
app.put ('/api/1/paste/:id'    , api.updatePaste);
app.delete('/api/1/paste/:id'  , api.deletePaste);

app.get ('*'                   , routes.notFound);

// Error messages all redirect to create
app.use(function (err, req, res, next) {
  console.log('\n');
  console.log('AN ERROR OCCURED :: ' + req.ip + ' :: ' + req.originalUrl);
  console.log(' ========================================================= ');
  console.log(err.stack);
  console.log('\n');
  res.render('create', {notice: err});
});

// start the express server
http.createServer(app).listen(config.server.port, config.server.bind, function() {
  console.log('Express server listening on port ' + config.server.port);
});

// start the TCP server, for netcat/telnet posting;)
tcpsrv.create();

<|endoftext|>


<commit_before>// Load App dependencies (packages)
var express    = require('express');
var path       = require('path');
var logger     = require('morgan');
var bodyParser = require('body-parser');

// Load App dependencies (local modules)
var dbManager     = require('./Core/Services/DatabaseManager');
var moduleManager = require('./Core/Services/ModuleManager');

// Load configuration file
var config = require('./config');

// Initialize the App
var app = express();

// Configuration
app.use(logger('dev'));
app.use(bodyParser.json());

// Allow cross-origin request to make the API available even when you are not on same network
app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});

// Start DB
var db = new dbManager();
db.connect();

// Register modules
if (config && config.modules) {
    var mod = new moduleManager();

    var registeredModules = Object.keys(config.modules);
    for (var i = 0; i < registeredModules.length; i++) {
        var registeredModule = registeredModules[i];
        var registeredConfig = config.modules[registeredModule];

        // Register module
        mod.register(registeredModule, registeredConfig);

        // Check if current module provides route
        if (registeredConfig.route) {
            var routeFilePath = './' + registeredModule + '/routes';

            try {
                // Try to load the routes
                var routes = require(routeFilePath);

                // Register routes into the app
                app.use(registeredConfig.route, routes);
            } catch (e) {
                console.log('Load modules : Module "' + registeredModule + '". (' + e + ')');
            }
        }
    }
}

// Declare default routes
var defaultRoutes = require('./routes');
app.use('/', defaultRoutes);

module.exports = app;<commit_msg>force first travis build<commit_after>// Load App dependencies (packages)
var express    = require('express');
var path       = require('path');
var logger     = require('morgan');
var bodyParser = require('body-parser');

// Load App dependencies (local modules)
var dbManager     = require('./Core/Services/DatabaseManager');
var moduleManager = require('./Core/Services/ModuleManager');

// Load configuration file
var config = require('./config');

// Initialize the App
var app = express();

// Configuration
app.use(logger('dev'));
app.use(bodyParser.json());

// Allow cross-origin request to make the API available even when you are not on same network
app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});

// Start DB
var db = new dbManager();
db.connect();

// Register modules
if (config && config.modules) {
    var mod = new moduleManager();

    var registeredModules = Object.keys(config.modules);
    for (var i = 0; i < registeredModules.length; i++) {
        var registeredModule = registeredModules[i];
        var registeredConfig = config.modules[registeredModule];

        // Register module
        mod.register(registeredModule, registeredConfig);

        // Check if current module provides route
        if (registeredConfig.route) {
            var routeFilePath = './' + registeredModule + '/routes';

            try {
                // Try to load the routes
                var routes = require(routeFilePath);

                // Register routes into the app
                app.use(registeredConfig.route, routes);
            } catch (e) {
                console.log('Load modules : Module "' + registeredModule + '". (' + e + ')');
            }
        }
    }
}

// Declare default routes
var defaultRoutes = require('./routes');
app.use('/', defaultRoutes);

module.exports = app;
<|endoftext|>


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

    angular
        .module('DeezerKids', [
            // Angular modules.
            'ngRoute',
            'ngCookies',
            'ngAnimate',
            'ngMaterial',
            'ngMessages'
        ])
        .config(config)
        .run(run);

    config.$inject = ['$routeProvider', '$locationProvider', '$mdDateLocaleProvider', '$mdThemingProvider'];

    function config($routeProvider, $locationProvider, $mdDateLocaleProvider, $mdThemingProvider) {
        $routeProvider.otherwise({
            redirectTo: '/startup'
        });

        $mdDateLocaleProvider.months = ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'];
        $mdDateLocaleProvider.shortMonths = ['Jan', 'Feb', 'Mrz', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez'];
        $mdDateLocaleProvider.days = ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'];
        $mdDateLocaleProvider.shortDays = ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa'];
        // Can change week display to start on Monday.
        $mdDateLocaleProvider.firstDayOfWeek = 1;
        // Example uses moment.js to parse and format dates.
        $mdDateLocaleProvider.parseDate = function (dateString) {
            var m = moment(dateString, 'DD.MM.YYYY', true);
            return m.isValid() ? m.toDate() : new Date(NaN);
        };
        $mdDateLocaleProvider.formatDate = function (date) {
            return moment(date).format('DD.MM.YYYY');
        };
        $mdDateLocaleProvider.monthHeaderFormatter = function (date) {
            return $mdDateLocaleProvider.shortMonths[date.getMonth()] + ' ' + date.getFullYear();
        };
        // In addition to date display, date components also need localized messages
        // for aria-labels for screen-reader users.
        $mdDateLocaleProvider.weekNumberFormatter = function (weekNumber) {
            return 'Woche ' + weekNumber;
        };
        $mdDateLocaleProvider.msgCalendar = 'Kalender';
        $mdDateLocaleProvider.msgOpenCalendar = 'Kalender öffnen';

        $mdThemingProvider
            .theme('default')
            .primaryPalette('green')
            .accentPalette('blue-grey');
    }

    run.$inject = ['$rootScope', '$location', '$cookieStore', '$http'];

    function run($rootScope, $location, $cookieStore, $http) {
        // keep user logged in after page refresh
        $rootScope.globals = $cookieStore.get('globals') || {};

        $rootScope.$on('$locationChangeStart', function (event, next, current) {
            // redirect to startup procedure if no mode is set
            var restrictedPage = $.inArray($location.path(), ['/startup']) === -1;
            //var mode = false;
            var mode = $rootScope.globals.mode;
            if (restrictedPage && !mode) {
                $location.path('/startup');
            }
        });
    }
})();
<commit_msg>Update app.js<commit_after>(function () {
    'use strict';

    angular
        .module('DeezerKids', [
            // Angular modules.
            'ngRoute',
            'ngCookies',
            'ngAnimate',
            'ngMaterial',
            'ngMessages'
        ])
        .config(config)
        .run(run);

    config.$inject = ['$routeProvider', '$locationProvider', '$mdDateLocaleProvider', '$mdThemingProvider', '$rootScope'];

    function config($routeProvider, $locationProvider, $mdDateLocaleProvider, $mdThemingProvider, $rootScope) {
        $routeProvider.otherwise({
            redirectTo: '/startup'
        });

        $mdDateLocaleProvider.months = ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'];
        $mdDateLocaleProvider.shortMonths = ['Jan', 'Feb', 'Mrz', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez'];
        $mdDateLocaleProvider.days = ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'];
        $mdDateLocaleProvider.shortDays = ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa'];
        // Can change week display to start on Monday.
        $mdDateLocaleProvider.firstDayOfWeek = 1;
        // Example uses moment.js to parse and format dates.
        $mdDateLocaleProvider.parseDate = function (dateString) {
            var m = moment(dateString, 'DD.MM.YYYY', true);
            return m.isValid() ? m.toDate() : new Date(NaN);
        };
        $mdDateLocaleProvider.formatDate = function (date) {
            return moment(date).format('DD.MM.YYYY');
        };
        $mdDateLocaleProvider.monthHeaderFormatter = function (date) {
            return $mdDateLocaleProvider.shortMonths[date.getMonth()] + ' ' + date.getFullYear();
        };
        // In addition to date display, date components also need localized messages
        // for aria-labels for screen-reader users.
        $mdDateLocaleProvider.weekNumberFormatter = function (weekNumber) {
            return 'Woche ' + weekNumber;
        };
        $mdDateLocaleProvider.msgCalendar = 'Kalender';
        $mdDateLocaleProvider.msgOpenCalendar = 'Kalender öffnen';

        $mdThemingProvider
            .theme('default')
            .primaryPalette('green')
            .accentPalette('blue-grey');

        $rootScope.mode = null;
    }

    run.$inject = ['$rootScope', '$location', '$cookieStore', '$http'];

    function run($rootScope, $location, $cookieStore, $http) {
        // keep user logged in after page refresh
        //$rootScope.globals = $cookieStore.get('globals') || {};

        $rootScope.$on('$locationChangeStart', function (event, next, current) {
            // redirect to startup procedure if no mode is set
            var restrictedPage = $.inArray($location.path(), ['/startup']) === -1;
            var mode = $rootScope.mode;
            if (restrictedPage && mode == null) {
                $location.path('/startup');
            }
        });
    }
})();
<|endoftext|>


<commit_before>// for debug only
var __kb;
var __scope;

/**
* The main app
*/
var App = angular.module('Timeline', [
  'ngAudio',
  'lumx',
  'angularMoment'
]);

App.config(function($locationProvider) {
  $locationProvider
  .html5Mode({ enabled: true, requireBase: false });
});

App.controller('Main', function($scope, $http, $location, $timeout, ngAudio, LxNotificationService, LxProgressService, LxDialogService) {
  // Namespaces
  var CHAT  = $rdf.Namespace("https://ns.rww.io/chat#");
  var CURR  = $rdf.Namespace("https://w3id.org/cc#");
  var DCT   = $rdf.Namespace("http://purl.org/dc/terms/");
  var FACE  = $rdf.Namespace("https://graph.facebook.com/schema/~/");
  var FOAF  = $rdf.Namespace("http://xmlns.com/foaf/0.1/");
  var LIKE  = $rdf.Namespace("http://ontologi.es/like#");
  var LDP   = $rdf.Namespace("http://www.w3.org/ns/ldp#");
  var MBLOG = $rdf.Namespace("http://www.w3.org/ns/mblog#");
  var OWL   = $rdf.Namespace("http://www.w3.org/2002/07/owl#");
  var PIM   = $rdf.Namespace("http://www.w3.org/ns/pim/space#");
  var RDF   = $rdf.Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#");
  var RDFS  = $rdf.Namespace("http://www.w3.org/2000/01/rdf-schema#");
  var SIOC  = $rdf.Namespace("http://rdfs.org/sioc/ns#");
  var SOLID = $rdf.Namespace("http://www.w3.org/ns/solid/app#");
  var TMP   = $rdf.Namespace("urn:tmp:");

  var f,g;

  var defaultStorageURI = 'https://melvin.databox.me/Public/timeline/stats.ttl';
  var defaultTimelineURI = 'https://melvin.databox.me/Public/timeline/';

  // INIT
  /**
  * Init app
  */
  $scope.initApp = function() {
    $scope.init();
  };

  /**
  * Set Initial variables
  */
  $scope.init = function() {

    $scope.initRDF();
    $scope.initUI();
    $scope.initLocalStorage();

    __kb = g;
    __scope = $scope;
  };

  /**
   * Init UI
   */
  $scope.initUI = function() {
    $scope.initialized = true;
    $scope.loggedIn = false;
    $scope.loginTLSButtonText = "Login";
    $scope.audio = ngAudio.load('audio/button-3.mp3');
    $scope.ponts = [];
  };

  /**
  * Get values from localStorage
  */
  $scope.initLocalStorage = function() {
    if (localStorage.getItem('user')) {
      var user = JSON.parse(localStorage.getItem('user'));
      $scope.loginSuccess(user);
    }
  };

  /**
  * init RDF knowledge base
  */
  $scope.initRDF = function() {
    var PROXY = "https://rww.io/proxy.php?uri={uri}";
    var AUTH_PROXY = "https://rww.io/auth-proxy?uri=";
    var TIMEOUT = 90000;
    $rdf.Fetcher.crossSiteProxyTemplate=PROXY;

    g = $rdf.graph();
    f = $rdf.fetcher(g, TIMEOUT);
  };

  /**
  * init from query string
  */
  $scope.initQueryString = function() {
    $scope.storageURI = defaultStorageURI;
    if ($location.search().storageURI) {
      $scope.storageURI = $location.search().storageURI;
    }
    $scope.setStorageURI($scope.storageURI);
  };

  /**
  * setStorageURI set the storage URI for words
  * @param  {String} the storage URI for words
  */
  $scope.setStorageURI = function(storageURI) {
    $scope.storageURI = storageURI;
    $location.search('storageURI', $scope.storageURI);
  };

  // AUTH
  /**
  * TLS Login with WebID
  */
  $scope.TLSlogin = function() {
    var AUTHENDPOINT = "https://databox.me/";
    $scope.loginTLSButtonText = 'Logging in...';
    $http({
      method: 'HEAD',
      url: AUTHENDPOINT,
      withCredentials: true
    }).success(function(data, status, headers) {
      var header = 'User';
      var scheme = 'http';
      var user = headers(header);
      if (user && user.length > 0 && user.slice(0,scheme.length) === scheme) {
        $scope.loginSuccess(user);
      } else {
        $scope.notify('WebID-TLS authentication failed.', 'error');
      }
      $scope.loginTLSButtonText = 'Login';
    }).error(function(data, status, headers) {
      $scope.notify('Could not connect to auth server: HTTP '+status);
      $scope.loginTLSButtonText = 'Login';
    });
  };

  /**
  * loginSuccess called after successful login
  * @param  {String} user the logged in user
  */
  $scope.loginSuccess = function(user) {
    //$scope.notify('Login Successful!');
    console.log(user);
    $scope.loggedIn = true;
    $scope.user = user;
    $scope.fetchAll();
    localStorage.setItem('user', JSON.stringify(user));
  };

  /**
  * Logout
  */
  $scope.logout = function() {
    $scope.init();
    $scope.notify('Logout Successful!');
    localStorage.removeItem('user');
  };

  // FETCH functions
  //
  //
  $scope.fetchAll = function() {
    $scope.fetchStats();
    $scope.fetchTimeline();
    $scope.fetchWebid();
  };

  /**
   * Fetch the stats
   * @param  {String} position The URI for the position
   */
  $scope.fetchStats = function (position) {
    var storageURI = defaultStorageURI;
    if ($location.search().storageURI) {
      storageURI = $location.search().storageURI;
    }
    $scope.storageURI = storageURI;
    connectToSocket($scope.storageURI);

    f.requestURI(storageURI, undefined, true, function(ok, body) {
      var p = g.statementsMatching(undefined, TMP('stats'));
      if (p.length) {
        $scope.stats = p[0].object.value;
        $scope.render();
      }
    });
  };

  /**
   * Fetch the webid
   * @param  {String} position The URI for the position
   */
  $scope.fetchWebid = function (webid) {
    var uri = webid || $scope.user;

    if (!uri) return;
    console.log(uri);

    f.requestURI(uri.split('#')[0], undefined, true, function(ok, body) {
      var name = g.statementsMatching($rdf.sym(uri), FOAF('name'));
      if (name.length) {
        $scope.name = name[0].object.value;
        $scope.render();
      }
      var friends = g.statementsMatching(undefined, FOAF('knows'));
      $scope.friends = friends.length;
    });
  };

  /**
   * Invalidate a cached URI
   * @param  {String} uri The URI to invalidate
   */
  $scope.invalidate = function(uri) {
    console.log('invalidate : ' + uri);
    f.unload(uri);
    f.refresh($rdf.sym(uri));
  };

  /**
  * fetchSeeAlso fetches the see also
  */
  $scope.fetchSeeAlso = function() {
    var seeAlso = 'https://melvincarvalho.github.io/chess/data/seeAlso.ttl';
    if ($location.search().seeAlso) {
      seeAlso = $location.search().seeAlso;
    }
    f.nowOrWhenFetched(seeAlso, undefined, function(ok, body) {
      console.log('seeAlso fetched from : ' + seeAlso);
    });

  };

  /**
  * fetchTimeline fetches the see also
  */
  $scope.fetchTimeline = function() {
    var timeline = defaultTimelineURI;
    if ($location.search().timeline) {
      timeline = $location.search().timeline;
    }
    $scope.timeline = timeline;
    $location.search('timeline', $scope.timeline);

    var today = new Date().toISOString().substr(0,10);
    var uri = timeline + today + '/*';
    f.nowOrWhenFetched(uri, undefined, function(ok, body) {
      console.log('timeline fetched from : ' + uri);
      $scope.render();
    });

  };

  /**
   * Save the position
   */
  $scope.save = function() {
    var position = $scope.position;
    if (!position) {
      LxNotificationService.error('position is empty');
      return;
    }
    console.log(position);

    $http({
      method: 'PUT',
      url: $scope.storageURI,
      withCredentials: true,
      headers: {
        "Content-Type": "text/turtle"
      },
      data: '<#this> '+ TMP('fen') +' """' + position + '""" .',
    }).
    success(function(data, status, headers) {
      LxNotificationService.success('Position saved');
      $location.search('storageURI', $scope.storageURI);
      $scope.renderBoard(position);
    }).
    error(function(data, status, headers) {
      LxNotificationService.error('could not save position');
    });

  };

  // HELPER
  /**
  * Notify
  * @param  {String} message the message to display
  * @param  {String} type the type of notification, error or success
  */
  $scope.notify = function(message, type) {
    console.log(message);
    if (type === 'error') {
      LxNotificationService.error(message);
    } else {
      LxNotificationService.success(message);
    }
  };

  // RENDER
  /**
  * Render screen
  */
  $scope.render = function() {
    $scope.renderStats();
    $scope.renderTimeline();
  };

  /**
   * Render the stats
   */
  $scope.renderStats = function () {
    if ($scope.stats) {
      $scope.points = $scope.stats.split('-');
    }
  };

  /**
   * Render the timeline
   */
  $scope.renderTimeline = function () {
    var p = g.statementsMatching(null, null, SIOC('Post'));
    $scope.posts = [];
    for (var i=0; i<p.length;i++) {
      var subject = p[i].subject;
      var created = g.any(subject, DCT('created'));
      var creator = g.any(subject, DCT('creator'));
      var content = g.any(subject, SIOC('content'));
      var author  = g.any(subject, MBLOG('author'));
      var img  = g.any(subject, FOAF('img'));

      if (img) {
        img = img.uri;
      }

      $scope.posts.push([created.value, creator.uri, content.value, subject.uri, img]);

    }

    $scope.posts = $scope.posts.sort(function(a, b) {
      createda = a[0];
      createdb = b[0];
      //if ( !createda || !createdb ) return;
      a = new Date(createda);
      b = new Date(createdb);
      return a>b ? -1 : a<b ? 1 : 0;
    });

  };

  /**
   * Refresh the board
   */
  $scope.refresh = function() {
    $scope.fetchBoard();
    $scope.render();
  };

  /**
  * openDialog opens a dialog box
  * @param  {String} elem  The element to display
  */
  $scope.openDialog = function(elem) {
    LxDialogService.open(elem);
    $(document).keyup(function(e) {
      if (e.keyCode===27) {
        LxDialogService.close(elem);
      }
    });
  };

  // SOCKETS
  //
  //
  /**
   * Get wss from URI
   * @param  {String} uri The URI to use
   */
  function getWss(uri) {
    return 'wss://' + uri.split('/')[2];
  }

  /**
   * Connect to a web socket
   * @param  {String}  sub Where to subscribe to
   * @param  {boolean} quiet dont ping server
   */
  function connectToSocket(sub, quiet) {
    // Some servers time out after 5 minutes inactive
    var INTERVAL  = 240 * 1000;
    var RECONNECT = 60 * 1000;

    if ($scope.socket) return;

    var socket;

    var wss = getWss(sub);
    console.log('connecting to : ' + wss);

    socket = new WebSocket(wss);

    socket.onopen = function(){
      console.log(sub);
      $scope.socket = socket;
      socket.send('sub ' + sub, socket);

      if (!quiet) {
        setInterval(function() { socket.send('ping'); }, INTERVAL);
      }

    };

    socket.onerror = function(){
      console.log('socket error');
      setTimeout(connect, RECONNECT);
    };

    socket.onclose = function(){
      console.log('socket closed');
      setTimeout(connect, RECONNECT);
    };

    socket.onmessage = function(msg) {
      var a = msg.data.split(' ');
      if (a[0] !== 'pub') return;
      processSocket(a[1]);
    };

  }

  /**
   * Process message from socket
   * @param  {String} uri uri that has changed
   */
  function processSocket(uri) {
    console.log(uri);

    $scope.invalidate(uri);
    $scope.fetchAll();
    $scope.audio.play();

    Notification.requestPermission(function (permission) {
      // If the user is okay, let's create a notification
      if (permission === "granted") {
        notify = true;
      }
    });
  }

  $scope.initApp();

});

/**
 * Escape URIs filter
 */
App.filter('escape', function() {
  return window.encodeURIComponent;
});
<commit_msg>Fix profiles<commit_after>// for debug only
var __kb;
var __scope;

/**
* The main app
*/
var App = angular.module('Timeline', [
  'ngAudio',
  'lumx',
  'angularMoment'
]);

App.config(function($locationProvider) {
  $locationProvider
  .html5Mode({ enabled: true, requireBase: false });
});

App.controller('Main', function($scope, $http, $location, $timeout, ngAudio, LxNotificationService, LxProgressService, LxDialogService) {
  // Namespaces
  var CHAT  = $rdf.Namespace("https://ns.rww.io/chat#");
  var CURR  = $rdf.Namespace("https://w3id.org/cc#");
  var DCT   = $rdf.Namespace("http://purl.org/dc/terms/");
  var FACE  = $rdf.Namespace("https://graph.facebook.com/schema/~/");
  var FOAF  = $rdf.Namespace("http://xmlns.com/foaf/0.1/");
  var LIKE  = $rdf.Namespace("http://ontologi.es/like#");
  var LDP   = $rdf.Namespace("http://www.w3.org/ns/ldp#");
  var MBLOG = $rdf.Namespace("http://www.w3.org/ns/mblog#");
  var OWL   = $rdf.Namespace("http://www.w3.org/2002/07/owl#");
  var PIM   = $rdf.Namespace("http://www.w3.org/ns/pim/space#");
  var RDF   = $rdf.Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#");
  var RDFS  = $rdf.Namespace("http://www.w3.org/2000/01/rdf-schema#");
  var SIOC  = $rdf.Namespace("http://rdfs.org/sioc/ns#");
  var SOLID = $rdf.Namespace("http://www.w3.org/ns/solid/app#");
  var ST    = $rdf.Namespace("http://www.w3.org/ns/solid/terms#");
  var TMP   = $rdf.Namespace("urn:tmp:");

  var f,g;

  // INIT
  /**
  * Init app
  */
  $scope.initApp = function() {
    $scope.init();
  };

  /**
  * Set Initial variables
  */
  $scope.init = function() {

    $scope.initRDF();
    $scope.initUI();
    $scope.initQueryString();
    $scope.initLocalStorage();

    $scope.fetchAll();

    __kb = g;
    __scope = $scope;
  };

  /**
   * Init UI
   */
  $scope.initUI = function() {
    $scope.initialized = true;
    $scope.loggedIn = false;
    $scope.loginTLSButtonText = "Login";
    $scope.audio = ngAudio.load('audio/button-3.mp3');
    $scope.ponts = [];
  };

  /**
  * Get values from localStorage
  */
  $scope.initLocalStorage = function() {
    if (localStorage.getItem('user')) {
      var user = JSON.parse(localStorage.getItem('user'));
      $scope.loginSuccess(user);
    }
  };

  /**
  * init RDF knowledge base
  */
  $scope.initRDF = function() {
    var PROXY = "https://rww.io/proxy.php?uri={uri}";
    var AUTH_PROXY = "https://rww.io/auth-proxy?uri=";
    var TIMEOUT = 90000;
    $rdf.Fetcher.crossSiteProxyTemplate=PROXY;

    g = $rdf.graph();
    f = $rdf.fetcher(g, TIMEOUT);
  };

  /**
  * init from query string
  */
  $scope.initQueryString = function() {
    if ($location.search().profile) {
      $scope.profile = $location.search().profile;
      return;
    }
    if ($location.search().timeline) {
      $scope.timeline = $location.search().timeline;
    }
  };

  /**
  * setStorageURI set the storage URI for words
  * @param  {String} the storage URI for words
  */
  $scope.setStorageURI = function(storageURI) {
    $scope.storageURI = storageURI;
    $location.search('storageURI', $scope.storageURI);
  };

  // AUTH
  /**
  * TLS Login with WebID
  */
  $scope.TLSlogin = function() {
    var AUTHENDPOINT = "https://databox.me/";
    $scope.loginTLSButtonText = 'Logging in...';
    $http({
      method: 'HEAD',
      url: AUTHENDPOINT,
      withCredentials: true
    }).success(function(data, status, headers) {
      var header = 'User';
      var scheme = 'http';
      var user = headers(header);
      if (user && user.length > 0 && user.slice(0,scheme.length) === scheme) {
        $scope.loginSuccess(user);
      } else {
        $scope.notify('WebID-TLS authentication failed.', 'error');
      }
      $scope.loginTLSButtonText = 'Login';
    }).error(function(data, status, headers) {
      $scope.notify('Could not connect to auth server: HTTP '+status);
      $scope.loginTLSButtonText = 'Login';
    });
  };

  /**
  * loginSuccess called after successful login
  * @param  {String} user the logged in user
  */
  $scope.loginSuccess = function(user) {
    //$scope.notify('Login Successful!');
    console.log(user);
    $scope.loggedIn = true;
    $scope.user = user;
    $scope.profile = user;
    localStorage.setItem('user', JSON.stringify(user));
  };

  /**
  * Logout
  */
  $scope.logout = function() {
    $scope.init();
    $scope.notify('Logout Successful!');
    localStorage.removeItem('user');
  };

  // FETCH functions
  //
  //
  $scope.fetchAll = function() {
    $scope.fetchWebid($scope.profile);
  };

  /**
   * Fetch the webid
   * @param  {String} position The URI for the position
   */
  $scope.fetchWebid = function (webid) {
    var uri = webid || $scope.user;

    if (!uri) return;
    console.log(uri);

    f.requestURI(uri.split('#')[0], undefined, true, function(ok, body) {
      var name = g.statementsMatching($rdf.sym(uri), FOAF('name'));
      if (name.length) {
        $scope.name = name[0].object.value;
        $scope.render();
      }
      var friends = g.statementsMatching(undefined, FOAF('knows'));
      $scope.friends = friends.length;

      var timeline = g.any($rdf.sym(uri), ST('timeline'));

      if (timeline) {
        $scope.timeline = timeline.uri;
      }

      $scope.fetchTimeline();

    });
  };

  /**
   * Invalidate a cached URI
   * @param  {String} uri The URI to invalidate
   */
  $scope.invalidate = function(uri) {
    console.log('invalidate : ' + uri);
    f.unload(uri);
    f.refresh($rdf.sym(uri));
  };

  /**
  * fetchTimeline fetches the see also
  */
  $scope.fetchTimeline = function() {
    var timeline = $scope.timeline;
    if ($location.search().timeline) {
      timeline = $location.search().timeline;
    }
    $scope.timeline = timeline;
    if ($scope.profile) {
      $location.search('profile', $scope.profile);
    }

    var today = new Date().toISOString().substr(0,10);
    var uri = timeline + today + '/*';
    f.nowOrWhenFetched(uri, undefined, function(ok, body) {
      console.log('timeline fetched from : ' + uri);
      $scope.render();
    });

  };

  /**
   * Save the position
   */
  $scope.save = function() {
    var position = $scope.position;
    if (!position) {
      LxNotificationService.error('position is empty');
      return;
    }
    console.log(position);

    $http({
      method: 'PUT',
      url: $scope.storageURI,
      withCredentials: true,
      headers: {
        "Content-Type": "text/turtle"
      },
      data: '<#this> '+ TMP('fen') +' """' + position + '""" .',
    }).
    success(function(data, status, headers) {
      LxNotificationService.success('Position saved');
      $location.search('storageURI', $scope.storageURI);
      $scope.renderBoard(position);
    }).
    error(function(data, status, headers) {
      LxNotificationService.error('could not save position');
    });

  };

  // HELPER
  /**
  * Notify
  * @param  {String} message the message to display
  * @param  {String} type the type of notification, error or success
  */
  $scope.notify = function(message, type) {
    console.log(message);
    if (type === 'error') {
      LxNotificationService.error(message);
    } else {
      LxNotificationService.success(message);
    }
  };

  // RENDER
  /**
  * Render screen
  */
  $scope.render = function() {
    $scope.renderStats();
    $scope.renderTimeline();
  };

  /**
   * Render the stats
   */
  $scope.renderStats = function () {
    if ($scope.stats) {
      $scope.points = $scope.stats.split('-');
    }
  };

  /**
   * Render the timeline
   */
  $scope.renderTimeline = function () {
    var p = g.statementsMatching(null, null, SIOC('Post'));
    $scope.posts = [];
    for (var i=0; i<p.length;i++) {
      var subject = p[i].subject;
      var created = g.any(subject, DCT('created'));
      var creator = g.any(subject, DCT('creator'));
      var content = g.any(subject, SIOC('content'));
      var author  = g.any(subject, MBLOG('author'));
      var img  = g.any(subject, FOAF('img'));

      if (img) {
        img = img.uri;
      }

      $scope.posts.push([created.value, creator.uri, content.value, subject.uri, img]);

    }

    $scope.posts = $scope.posts.sort(function(a, b) {
      createda = a[0];
      createdb = b[0];
      //if ( !createda || !createdb ) return;
      a = new Date(createda);
      b = new Date(createdb);
      return a>b ? -1 : a<b ? 1 : 0;
    });

  };

  /**
   * Refresh the board
   */
  $scope.refresh = function() {
    $scope.fetchBoard();
    $scope.render();
  };

  /**
  * openDialog opens a dialog box
  * @param  {String} elem  The element to display
  */
  $scope.openDialog = function(elem) {
    LxDialogService.open(elem);
    $(document).keyup(function(e) {
      if (e.keyCode===27) {
        LxDialogService.close(elem);
      }
    });
  };

  // SOCKETS
  //
  //
  /**
   * Get wss from URI
   * @param  {String} uri The URI to use
   */
  function getWss(uri) {
    return 'wss://' + uri.split('/')[2];
  }

  /**
   * Connect to a web socket
   * @param  {String}  sub Where to subscribe to
   * @param  {boolean} quiet dont ping server
   */
  function connectToSocket(sub, quiet) {
    // Some servers time out after 5 minutes inactive
    var INTERVAL  = 240 * 1000;
    var RECONNECT = 60 * 1000;

    if ($scope.socket) return;

    var socket;

    var wss = getWss(sub);
    console.log('connecting to : ' + wss);

    socket = new WebSocket(wss);

    socket.onopen = function(){
      console.log(sub);
      $scope.socket = socket;
      socket.send('sub ' + sub, socket);

      if (!quiet) {
        setInterval(function() { socket.send('ping'); }, INTERVAL);
      }

    };

    socket.onerror = function(){
      console.log('socket error');
      setTimeout(connect, RECONNECT);
    };

    socket.onclose = function(){
      console.log('socket closed');
      setTimeout(connect, RECONNECT);
    };

    socket.onmessage = function(msg) {
      var a = msg.data.split(' ');
      if (a[0] !== 'pub') return;
      processSocket(a[1]);
    };

  }

  /**
   * Process message from socket
   * @param  {String} uri uri that has changed
   */
  function processSocket(uri) {
    console.log(uri);

    $scope.invalidate(uri);
    $scope.fetchAll();
    $scope.audio.play();

    Notification.requestPermission(function (permission) {
      // If the user is okay, let's create a notification
      if (permission === "granted") {
        notify = true;
      }
    });
  }

  $scope.initApp();

});

/**
 * Escape URIs filter
 */
App.filter('escape', function() {
  return window.encodeURIComponent;
});
<|endoftext|>


<commit_before>'use strict';

var errorSound = "http://www.soundjay.com/button/sounds/button-10.mp3";
var startSound = "http://www.soundjay.com/misc/bell-ringing-05.mp3";
var victoryCount = 3;
var victorySeq = [3, 1, 0, 2, 3, 1, 0, 2];

// n: number, z: 0
function pad(n, width, z) {
    z = z || '0';
    n = n + '';
    return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}

function isPrefix(a, b) {
    var p = b.slice(0, a.length);
    var isSame = (a.length == p.length) && a.every(function(element, index) {
        return element === p[index];
    });
    return isSame;
}

function genSeq(len, min, max) {
    var seq = [];
    for (var i = 0; i < len; i++) {
        seq.push(Math.floor(Math.random() * max));
    }
    return seq;
}

function sleepPromise(ms) {
    return new Promise(function(resolve) {
        setTimeout(resolve, ms);
    });
}

function playSoundPromise(url) {
    return new Promise(function(resolve, reject) {
        var audio = new Audio();
        audio.preload = "auto";
        audio.autoplay = true;
        audio.onerror = reject;
        audio.onended = resolve;

        audio.src = url
    });
}

var quad = Vue.extend({
    template: '#quad-template',
    props: ['qid', 'soundUrl'],
    data: function() {
        return {
            lightened: false,
        }
    },
    methods: {
        play: function() {
            this.lighten().then(this.darken);
            this.$dispatch('quad-played', this.qid);
        },
        lighten: function() {
            this.lightened = true
            this.$parent.countDisplay = pad(this.$parent.count, 2);
            return playSoundPromise(this.soundUrl);
        },
        darken: function() {
            this.lightened = false
        }
    }
});

var main = new Vue({
    el: '#main',
    data: {
        'isStrict': false,
        'isOn': false,
        'count': 0,
        'latency': 500,
        'countDisplay': '--',
        'blink': false,
        'showedSeq': [],
        'playedSeq': [],
        'generatedSeq': [],
        'quads': []
    },
    components: {
        'quad': quad
    },
    methods: {
        showSeq: function() {
            console.log("showSeq");
            var sequence = Promise.resolve();
            for (var i = 0; i < this.generatedSeq.length; i++) {
                var child = this.quads[this.generatedSeq[i]];
                sequence = sequence.then(sleepPromise.bind(null, this.latency))
                .then(child.lighten)
                .then(child.darken)
                .then(function(showedSeq, qid) {
                    showedSeq.push(qid);
                }.bind(null, this.showedSeq, child.qid));
            }
            return sequence;
        },
        nextSeq: function() {
            console.log("nextSeq");
            if (this.isOn) {
                this.count ++;
                this.countDisplay = pad(this.count, 2);
                this.showedSeq = [];
                this.playedSeq = [];
                this.generatedSeq = genSeq(this.count, 0, this.quads.length);
                return this.showSeq();
            }
        },
        toggleStrict: function() {
            if (this.isOn) {
                this.isStrict = !this.isStrict;
            }
        },
        reset: function() {
            this.count = 0;
            this.countDisplay = '--';
            this.showedSeq = [];
            this.playedSeq = [];
            this.generatedSeq = [];
            this.blink = false;
            this.latency = 500;
            this.quads = this.$children.sort(function(a, b){
                return a.qid - b.qid;
            })
        },
        start: function() {
            if (this.isOn) {
                this.reset();
                playSoundPromise(startSound).then(this.nextSeq);
            }
        },
        toggleOn: function() {
            this.reset();
            this.isStrict = false;
            this.isOn = !this.isOn;
        },
        quadPlayed: function(qid) {
            if (this.isOn) {
                this.playedSeq.push(qid);
                // check array contains
                console.log(this.playedSeq);
                if (isPrefix(this.playedSeq, this.showedSeq)) {
                    if (this.playedSeq.length === this.showedSeq.length) {
                        if (this.count === victoryCount) {
                            this.generatedSeq = victorySeq;
                            this.blink = true;
                            this.latency = 0;
                            sleepPromise(500)
                                .then(this.showSeq)
                                .then(sleepPromise.bind(null, 3000))
                                .then(this.start);
                        } else {
                            sleepPromise(2000).then(this.nextSeq);
                        }
                    }
                } else {
                    console.log("Error!");
                    var that = this;
                    this.blink = true;
                    this.playedSeq = [];
                    this.showedSeq = [];
                    this.countDisplay = '!!';
                    sleepPromise(300)
                        .then(playSoundPromise.bind(null, errorSound))
                        .then(sleepPromise.bind(null, 2000))
                        .then(function(){
                            that.blink = false;
                            if (that.isStrict) {
                                that.start();
                            } else {
                                that.showSeq();
                            }
                        });
                }
            }
        }
    }
});
<commit_msg>Use broadcast for parent-children communication<commit_after>'use strict';

var errorSound = "http://www.soundjay.com/button/sounds/button-10.mp3";
var startSound = "http://www.soundjay.com/misc/bell-ringing-05.mp3";
var victoryCount = 3;
var victorySeq = [3, 1, 0, 2, 3, 1, 0, 2];

// n: number, z: 0
function pad(n, width, z) {
    z = z || '0';
    n = n + '';
    return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}

function isPrefix(a, b) {
    var p = b.slice(0, a.length);
    var isSame = (a.length == p.length) && a.every(function(element, index) {
        return element === p[index];
    });
    return isSame;
}

function genSeq(len, min, max) {
    var seq = [];
    for (var i = 0; i < len; i++) {
        seq.push(Math.floor(Math.random() * max));
    }
    return seq;
}

function sleepPromise(ms) {
    return new Promise(function(resolve) {
        setTimeout(resolve, ms);
    });
}

function playSoundPromise(url) {
    return new Promise(function(resolve, reject) {
        var audio = new Audio();
        audio.preload = "auto";
        audio.autoplay = true;
        audio.onerror = reject;
        audio.onended = resolve;

        audio.src = url
    });
}

var quad = Vue.extend({
    template: '#quad-template',
    props: ['qid', 'soundUrl'],
    data: function() {
        return {
            lightened: false,
            enabled: true,
        }
    },
    methods: {
        play: function() {
            if (this.enabled) {
                this.lighten().then(this.darken);
                this.$dispatch('quad-played', this.qid);
            }
        },
        lighten: function() {
            this.lightened = true
            this.$parent.countDisplay = pad(this.$parent.count, 2);
            return playSoundPromise(this.soundUrl);
        },
        darken: function() {
            this.lightened = false
        }
    },
    events: {
        'disable-quad': function() {
            this.enabled = false;
        },
        'enable-quad': function() {
            this.enabled = true;
        }
    }
});

var main = new Vue({
    el: '#main',
    data: {
        'isStrict': false,
        'isOn': false,
        'count': 0,
        'latency': 500,
        'countDisplay': '--',
        'blink': false,
        'showedSeq': [],
        'playedSeq': [],
        'generatedSeq': [],
        'quads': []
    },
    components: {
        'quad': quad
    },
    methods: {
        showSeq: function() {
            console.log("showSeq");
            this.$broadcast('disable-quad');
            var sequence = Promise.resolve();
            for (var i = 0; i < this.generatedSeq.length; i++) {
                var child = this.quads[this.generatedSeq[i]];
                sequence = sequence.then(sleepPromise.bind(null, this.latency))
                .then(child.lighten)
                .then(child.darken)
                .then(function(showedSeq, qid) {
                    showedSeq.push(qid);
                }.bind(null, this.showedSeq, child.qid));
            }
            return sequence.then(this.$broadcast.bind(this, 'enable-quad'));
        },
        nextSeq: function() {
            console.log("nextSeq");
            if (this.isOn) {
                this.count ++;
                this.countDisplay = pad(this.count, 2);
                this.showedSeq = [];
                this.playedSeq = [];
                this.generatedSeq = genSeq(this.count, 0, this.quads.length);
                return this.showSeq();
            }
        },
        toggleStrict: function() {
            if (this.isOn) {
                this.isStrict = !this.isStrict;
            }
        },
        reset: function() {
            this.count = 0;
            this.countDisplay = '--';
            this.showedSeq = [];
            this.playedSeq = [];
            this.generatedSeq = [];
            this.blink = false;
            this.latency = 500;
            this.quads = this.$children.sort(function(a, b){
                return a.qid - b.qid;
            })
        },
        start: function() {
            if (this.isOn) {
                this.reset();
                playSoundPromise(startSound).then(this.nextSeq);
            }
        },
        toggleOn: function() {
            this.reset();
            this.isStrict = false;
            this.isOn = !this.isOn;
        },
        quadPlayed: function(qid) {
            if (this.isOn) {
                this.playedSeq.push(qid);
                // check array contains
                console.log(this.playedSeq);
                if (isPrefix(this.playedSeq, this.showedSeq)) {
                    if (this.playedSeq.length === this.showedSeq.length) {
                        if (this.count === victoryCount) {
                            this.generatedSeq = victorySeq;
                            this.blink = true;
                            this.latency = 0;
                            sleepPromise(500)
                                .then(this.showSeq)
                                .then(sleepPromise.bind(null, 3000))
                                .then(this.start);
                        } else {
                            sleepPromise(2000).then(this.nextSeq);
                        }
                    }
                } else {
                    console.log("Error!");
                    var that = this;
                    this.blink = true;
                    this.playedSeq = [];
                    this.showedSeq = [];
                    this.countDisplay = '!!';
                    sleepPromise(300)
                        .then(playSoundPromise.bind(null, errorSound))
                        .then(sleepPromise.bind(null, 2000))
                        .then(function(){
                            that.blink = false;
                            if (that.isStrict) {
                                that.start();
                            } else {
                                that.showSeq();
                            }
                        });
                }
            }
        }
    }
});
<|endoftext|>


<commit_before>// Module dependencies
var fs = require('fs'),
    path = require('path'),
    express = require('express'),
    engines = require('consolidate'),
    logger = require('./lib/logger'),
    settings = require('./config/settings');

module.exports = function() {
    // Main app
    var app = express();

    var env = process.env.NODE_ENV || 'development';
    if ('production' === env) {
        app.use(express.errorHandler());
        // a custom "verbose errors" setting which can be used in the templates via settings['verbose errors']
        app.disable('verbose errors'); // disable verbose errors in production
    }
    if ('development' === env) {
        app.use(express.errorHandler({
            dumpExceptions: true,
            showStack: true
        }));

        // a custom "verbose errors" setting which can be used in the templates via settings['verbose errors']
        app.enable('verbose errors'); // enable verbose errors in development
    }

    logger.init(settings.winston);

    var log = logger();

    // Register app.locals (app.helper):
    logger.registerAppHelper(app);

    // Define view engine with its options
    for (var i = 0; i < settings.view.engines.length; ++i) {
        var extension = settings.view.engines[i].extension;
        var template = settings.view.engines[i].template;
        app.engine(extension, engines[template]);
    }
    app.set('view engine', settings.view.defaultExtension);
    app.set('views', path.join(__dirname, 'views'));

    // Enables reverse proxy support
    app.enable('trust proxy');
    app.enable('jsonp callback');

    /**
     * Auto-load bundled middleware
     */
    var middleware = {};

    fs.readdirSync(__dirname + '/lib/middleware').forEach(function(filename) {
        if ( ! /\.js$/.test(filename)) {
            return;
        }
        var name = path.basename(filename, '.js');
        middleware[name] = require('./lib/middleware/' + name);
    });

    /**
     * Multihost
     */
    for (var i = 0; i < settings.multihost.index.length; ++i) {
        var options = settings.multihost.index[i];

        /**
         * Modules are cached after the first time they are loaded.
         * The cached module must be invalidated to ensure data-independence
         * in a multi-host environment.
         */
        var server_path = path.join(settings.multihost.path, options.server);
        if (require.cache[server_path]) {
            delete require.cache[server_path];
        }
        var server = require(server_path);
        if ( ! server) {
            log.error('The multi-host server does not exist: %s', server_path);
            return;
        }

        app.use(middleware.multihost({
            hosts: options.hosts,
            route: options.route,
            server: server(options.hosts, options.route)
        }));

        log.info('Attached a multi-host server: %j', options);
    }

    // Log errors
    app.use(function(err, req, res, next) {
        console.log(err.stack);
        next(err);
    });

    // Client errors
    app.use(function(err, req, res, next) {
        if (req.xhr) {
            res.send(500, {
                error: 'Something blew up!'
            });
        } else {
            next(err);
        }
    });

    // 404 status
    app.use(function(req, res, next) {
        res.status(404);

        // respond with html page
        if (req.accepts('html')) {
            res.render('404.hogan', { url: req.url });
            return;
        }

        // respond with json
        if (req.accepts('json')) {
            res.send({ error: 'Not found' });
            return;
        }

        // default to plain-text. send()
        res.type('txt').send('Not found');
    });

    // error-handling middleware, take the same form
    // as regular middleware, however they require an
    // arity of 4, aka the signature (err, req, res, next).
    // when connect has an error, it will invoke ONLY error-handling
    // middleware.

    // If we were to next() here any remaining non-error-handling
    // middleware would then be executed, or if we next(err) to
    // continue passing the error, only error-handling middleware
    // would remain being executed, however here
    // we simply respond with an error page.
    app.use(function(err, req, res, next) {
        // we may use properties of the error object
        // here and next(err) appropriately, or if
        // we possibly recovered from the error, simply next().
        res.status(err.status || 500);
        res.render('500.jade', { error: err });
    });

    return app;
};
<commit_msg>Make code snippets easier to read<commit_after>// Module dependencies
var fs = require('fs'),
    path = require('path'),
    express = require('express'),
    engines = require('consolidate'),
    logger = require('./lib/logger'),
    settings = require('./config/settings');

/**
 * Auto-load bundled middleware
 */
var middleware = {};

fs.readdirSync(__dirname + '/lib/middleware').forEach(function(filename) {
    if ( ! /\.js$/.test(filename)) {
        return;
    }
    var name = path.basename(filename, '.js');
    middleware[name] = require('./lib/middleware/' + name);
});

module.exports = function() {
    // Main app
    var app = express();

    /**
     * Logger
     */
    logger.init(settings.winston);
    logger.registerAppHelper(app); // Register app.locals (app.helper)

    var log = logger();

    /**
     * Settings
     */
    (function(app) {
        var env = process.env.NODE_ENV || 'development';
        if ('production' === env) {
            app.use(express.errorHandler());
            // a custom "verbose errors" setting which can be used in the templates via settings['verbose errors']
            app.disable('verbose errors'); // disable verbose errors in production
            app.enable('view cache'); // Enables view template compilation caching in production
        }
        if ('development' === env) {
            app.use(express.errorHandler({
                dumpExceptions: true,
                showStack: true
            }));
            // a custom "verbose errors" setting which can be used in the templates via settings['verbose errors']
            app.enable('verbose errors'); // enable verbose errors in development
            app.disable('view cache'); // Disables view template compilation caching in development
        }

        app.enable('trust proxy'); // Enables reverse proxy support, disabled by default
        app.enable('case sensitive routing'); // Enable case sensitivity, disabled by default, treating "/Foo" and "/foo"as the same
        app.enable('strict routing'); // Enable strict routing, by default "/foo" and "/foo/" are treated the same by the router

        for (var i = 0; i < settings.view.engines.length; ++i) {
            var extension = settings.view.engines[i].extension;
            var template = settings.view.engines[i].template;
            app.engine(extension, engines[template]);
        }
        app.set('view engine', settings.view.defaultExtension); // The default engine extension to use when omitted
        app.set('views', path.join(__dirname, 'views')); // The view directory path

        log.debug('app.settings: %j', app.settings);
    }(app));

    /**
     * Multi-host
     */
    (function(app) {
        for (var i = 0; i < settings.multihost.index.length; ++i) {
            var options = settings.multihost.index[i];

            /**
             * Modules are cached after the first time they are loaded.
             * The cached module must be invalidated to ensure data-independence
             * in a multi-host environment.
             */
            var server_path = path.join(settings.multihost.path, options.server);
            if (require.cache[server_path]) {
                delete require.cache[server_path];
            }
            var server = require(server_path);
            if ( ! server) {
                log.error('The multi-host server does not exist: %s', server_path);
                return;
            }

            app.use(middleware.multihost({
                hosts: options.hosts,
                route: options.route,
                server: server(options.hosts, options.route)
            }));

            log.info('Attached a multi-host server: %j', options);
        }
    }(app));

    // Log errors
    app.use(function(err, req, res, next) {
        console.log(err.stack);
        next(err);
    });

    // Client errors
    app.use(function(err, req, res, next) {
        if (req.xhr) {
            res.send(500, {
                error: 'Something blew up!'
            });
        } else {
            next(err);
        }
    });

    // 404 status
    app.use(function(req, res, next) {
        res.status(404);

        // respond with html page
        if (req.accepts('html')) {
            res.render('404.hogan', { url: req.url });
            return;
        }

        // respond with json
        if (req.accepts('json')) {
            res.send({ error: 'Not found' });
            return;
        }

        // default to plain-text. send()
        res.type('txt').send('Not found');
    });

    // error-handling middleware, take the same form
    // as regular middleware, however they require an
    // arity of 4, aka the signature (err, req, res, next).
    // when connect has an error, it will invoke ONLY error-handling
    // middleware.

    // If we were to next() here any remaining non-error-handling
    // middleware would then be executed, or if we next(err) to
    // continue passing the error, only error-handling middleware
    // would remain being executed, however here
    // we simply respond with an error page.
    app.use(function(err, req, res, next) {
        // we may use properties of the error object
        // here and next(err) appropriately, or if
        // we possibly recovered from the error, simply next().
        res.status(err.status || 500);
        res.render('500.jade', { error: err });
    });

    return app;
};
<|endoftext|>


<commit_before>/**
 * React Starter Kit (https://www.reactstarterkit.com/)
 *
 * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.txt file in the root directory of this source tree.
 */

import React, { Component } from 'react';
import s from './SearchArea.scss';
import withStyles from '../../decorators/withStyles';
import axios from 'axios';
import Result from '../Result';

@withStyles(s)
class SearchArea extends Component {

  constructor(props) {
    super(props);
    this._handleKeyPress = this._handleKeyPress.bind(this);
    this.state = {
      results: [],
    };
  }

  _handleKeyPress(e) {
    if (e.key === 'Enter') {
      axios.get('http://localhost:9200/seinfeld/_search?q=text:' + e.target.value)
        .then(function processResponse(response) {
          const results = response.data.hits.hits.map(function getResultObject(hit) {
            return hit._source;
          });
          this.setState({
            results,
          });
        }.bind(this))
        .catch(function error(response) {
          console.log(response);
        });
    }
  }

  render() {
    return (

        <input type="text" placeholder="Search..." onKeyPress={this._handleKeyPress}/>

          {this.state.results.map(function getResult(result) {
            return <Result key={result.id} result={result}/>;
          })
          }

    );
  }

}

export default SearchArea;
<commit_msg>Changed key used in Result to be unique<commit_after>/**
 * React Starter Kit (https://www.reactstarterkit.com/)
 *
 * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.txt file in the root directory of this source tree.
 */

import React, { Component } from 'react';
import s from './SearchArea.scss';
import withStyles from '../../decorators/withStyles';
import axios from 'axios';
import Result from '../Result';

@withStyles(s)
class SearchArea extends Component {

  constructor(props) {
    super(props);
    this._handleKeyPress = this._handleKeyPress.bind(this);
    this.state = {
      results: [],
    };
  }

  _handleKeyPress(e) {
    if (e.key === 'Enter') {
      axios.get('http://localhost:9200/seinfeld/_search?q=text:' + e.target.value)
        .then(function processResponse(response) {
          const results = response.data.hits.hits.map(function getResultObject(hit) {
            return hit._source;
          });
          this.setState({
            results,
          });
        }.bind(this))
        .catch(function error(response) {
          console.log(response);
        });
    }
  }

  render() {
    return (

        <input type="text" placeholder="Search..." onKeyPress={this._handleKeyPress}/>

          {this.state.results.map(function getResult(result) {
            return <Result key={[result.episode, result.id].join(':')} result={result}/>;
          })
          }

    );
  }

}

export default SearchArea;
<|endoftext|>


<commit_before>var editor = ace.edit("game-rb-editor");
editor.setTheme("ace/theme/monokai");
editor.getSession().setMode("ace/mode/ruby");
editor.getSession().setTabSize(2);
editor.getSession().setUseSoftTabs(true);

var toggleConnectionStatus = function(display) {
    var connStatus = document.getElementById('conn-status');
    connStatus.innerHTML = display;
};

var addToTerminal = function(value, type) {
    var classes = 'outputs outputs-' + type;
    value = value.replace(/&/g, '&')
                 .replace(/>/g, '>')
                 .replace(/</g, '<')
                 .replace(/"/g, '"')
                 .replace(/'/g, ''')
                 .replace(/\n/g, '
');
    terminalOutputs.innerHTML += '
' + value + '
';
    terminalInput.scrollIntoView();
};

var handleterminalInput = function(event) {
    var key = event.which || event.keyCode;
    if (key == 13) {
        event.preventDefault();
        socket.emit('terminalInput', { input: terminalInput.value });
        addToTerminal(terminalInput.value, 'input');
        terminalInput.value = '';
    }
};

var handleFileRun = function() {
    var currentFileContent = editor.getValue();
    socket.emit('fileInput', { input: currentFileContent });
    addToTerminal('Running game...', 'input');
};

var socket = io('http://localhost:8888/ruby'),
    terminal = document.getElementById('terminal'),
    terminalOutputs = document.getElementById('terminal-outputs'),
    terminalInput = document.getElementById('terminal-input'),
    sourceActionSave = document.getElementById('source-action-save'),
    sourceActionRun = document.getElementById('source-action-run');

terminal.addEventListener('click', function(e) { terminalInput.focus() }, false);
sourceActionSave.addEventListener('click', function(e) { alert('Files saved!') }, false );
sourceActionRun.addEventListener('click', handleFileRun, false);

socket.on('connect', function() {
    toggleConnectionStatus('Server Connected');
    terminalInput.addEventListener('keypress', handleterminalInput, false);
});

socket.on('disconnect', function() {
    toggleConnectionStatus('Server Disconnected');
    terminalInput.removeEventListener('keypress', handleterminalInput, false);
});

socket.on('ready', function(data) {
    window.console.log(data);
    addToTerminal(data.output, 'welcome');
    handleFileRun();
});

socket.on('terminalOutput', function(data) {
    window.console.log(data);
    addToTerminal(data.output, 'output');
});
<commit_msg>Edit config for editor<commit_after>var editor = ace.edit("game-rb-editor");
editor.setTheme("ace/theme/monokai");
editor.getSession().setFoldStyle('manual');
editor.getSession().setMode("ace/mode/ruby");
editor.getSession().setTabSize(2);
editor.getSession().setUseSoftTabs(true);
editor.setDisplayIndentGuides(true);
editor.setHighlightActiveLine(true);
editor.setShowPrintMargin(false);
editor.setShowInvisibles(true);

var toggleConnectionStatus = function(display) {
    var connStatus = document.getElementById('conn-status');
    connStatus.innerHTML = display;
};

var addToTerminal = function(value, type) {
    var classes = 'outputs outputs-' + type;
    value = value.replace(/&/g, '&')
                 .replace(/>/g, '>')
                 .replace(/</g, '<')
                 .replace(/"/g, '"')
                 .replace(/'/g, ''')
                 .replace(/\n/g, '
');
    terminalOutputs.innerHTML += '
' + value + '
';
    terminalInput.scrollIntoView();
};

var handleterminalInput = function(event) {
    var key = event.which || event.keyCode;
    if (key == 13) {
        event.preventDefault();
        socket.emit('terminalInput', { input: terminalInput.value });
        addToTerminal(terminalInput.value, 'input');
        terminalInput.value = '';
    }
};

var handleFileRun = function() {
    var currentFileContent = editor.getValue();
    socket.emit('fileInput', { input: currentFileContent });
    addToTerminal('Running game...', 'input');
};

var socket = io('http://localhost:8888/ruby'),
    terminal = document.getElementById('terminal'),
    terminalOutputs = document.getElementById('terminal-outputs'),
    terminalInput = document.getElementById('terminal-input'),
    sourceActionSave = document.getElementById('source-action-save'),
    sourceActionRun = document.getElementById('source-action-run');

terminal.addEventListener('click', function(e) { terminalInput.focus() }, false);
sourceActionSave.addEventListener('click', function(e) { alert('Files saved!') }, false );
sourceActionRun.addEventListener('click', handleFileRun, false);

socket.on('connect', function() {
    toggleConnectionStatus('Server Connected');
    terminalInput.addEventListener('keypress', handleterminalInput, false);
});

socket.on('disconnect', function() {
    toggleConnectionStatus('Server Disconnected');
    terminalInput.removeEventListener('keypress', handleterminalInput, false);
});

socket.on('ready', function(data) {
    window.console.log(data);
    addToTerminal(data.output, 'welcome');
    handleFileRun();
});

socket.on('terminalOutput', function(data) {
    window.console.log(data);
    addToTerminal(data.output, 'output');
});
<|endoftext|>


<commit_before>console.log('boom');

function ad () {
  return 12;
}

console.log('boom');<commit_msg>initial react-router setup<commit_after>var React = require('react');
var Router = require('react-router');

var App = require('./components/App.jsx');
var Navbar = require('./components/Navbar.jsx');
var CharacterList = require('./components/CharacterList.jsx');

var DefaultRoute = Router.DefaultRoute;
var Link = Router.Link;
var Route = Router.Route;
var RouteHandler = Router.RouteHandler;

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

<Link to="app">app</Link>

<Link to="nav">nav</Link>

<Link to="top">top</Link>

          Logged in as Jane

        {/* this is the important part */}
        <RouteHandler/>

    );
  }
});

var routes = (
  <Route name='app' path='/' handler={App}>
    <Route name='nav' handler={Navbar}/>
    <Route name='top' handler={CharacterList}/>
    <DefaultRoute handler={App}/>
  </Route>
);

Router.run(routes, Router.HistoryLocation, function(Handler) {
  React.render(<Handler/>, document.body);
});
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import AirbrakeClient from 'airbrake-js';

let airbrakeClient;

export function notify(err) {
  if (!airbrakeClient) {
    airbrakeClient = new AirbrakeClient({
      projectId: 1,
      projectKey: 'FIXME'
    });
  }
  airbrakeClient.notify(err);
}

export default class AirbrakeComponent extends Component {
  render() {
    try {
      return this.unsafeRender();
    } catch (err) {
      notify(err);
      return
{String(err)}
;
    }
  }

  unsafeRender() {
    throw new Error('Abstract method unsafeRender not implemented');
  }
}
<commit_msg>Improve react example<commit_after>import React, { Component } from 'react';
import AirbrakeClient from 'airbrake-js';

let airbrakeClient;

export function notify(err) {
  if (!airbrakeClient) {
    airbrakeClient = new AirbrakeClient({
      projectId: 1,
      projectKey: 'FIXME'
    });
  }
  airbrakeClient.notify(err).catch(function(err) {
    console.warn('notify failed:', err);
  });
}

export default class AirbrakeComponent extends Component {
  render() {
    try {
      return this.unsafeRender();
    } catch (err) {
      notify(err);
      return
{String(err)}
;
    }
  }

  unsafeRender() {
    throw new Error('Abstract method unsafeRender not implemented');
  }
}
<|endoftext|>


<commit_before>var _; //globals

/* This section uses a functional extension known as Underscore.js - http://documentcloud.github.com/underscore/
     "Underscore is a utility-belt library for JavaScript that provides a lot of the functional programming support
      that you would expect in Prototype.js (or Ruby), but without extending any of the built-in JavaScript objects.
      It's the tie to go along with jQuery's tux."
 */
describe("About Higher Order Functions", function () {

  it("should use filter to return array items that meet a criteria", function () {
    var numbers = [1,2,3];
    var odd = _(numbers).filter(function (x) { return x % 2 !== 0 });

    expect(odd).toEqual(FILL_ME_IN);
    expect(odd.length).toBe(FILL_ME_IN);
    expect(numbers.length).toBe(FILL_ME_IN);
  });

  it("should use 'map' to transform each element", function () {
    var numbers = [1, 2, 3];
    var numbersPlus1 = _(numbers).map(function(x) { return x + 1 });

    expect(numbersPlus1).toEqual(FILL_ME_IN);
    expect(numbers).toEqual(FILL_ME_IN);
  });

  it("should use 'reduce' to update the same result on each iteration", function () {
    var numbers = [1, 2, 3];
    var reduction = _(numbers).reduce(
      function(memo, x) {
        //note: memo is the result from last call, and x is the current number
        return memo + x;
      },
      /* initial */ 0
    );

    expect(reduction).toBe(FILL_ME_IN);
    expect(numbers).toEqual(FILL_ME_IN);
  });

  it("should use 'forEach' for simple iteration", function () {
    var numbers = [1,2,3];
    var msg = "";
    var isEven = function (item) {
      msg += (item % 2) === 0;
    };

    _(numbers).forEach(isEven);

    expect(msg).toEqual(FILL_ME_IN);
    expect(numbers).toEqual(FILL_ME_IN);
  });

  it("should use 'all' to test whether all items pass condition", function () {
    var onlyEven = [2,4,6];
    var mixedBag = [2,4,5,6];

    var isEven = function(x) { return x % 2 === 0 };

    expect(_(onlyEven).all(isEven)).toBe(FILL_ME_IN);
    expect(_(mixedBag).all(isEven)).toBe(FILL_ME_IN);
  });

  it("should use 'any' to test if any items passes condition" , function () {
    var onlyEven = [2,4,6];
    var mixedBag = [2,4,5,6];

    var isEven = function(x) { return x % 2 === 0 };

    expect(_(onlyEven).any(isEven)).toBe(FILL_ME_IN);
    expect(_(mixedBag).any(isEven)).toBe(FILL_ME_IN);
  });

  it("should use range to generate an array", function() {
    expect(_.range(3)).toEqual(FILL_ME_IN);
    expect(_.range(1, 4)).toEqual(FILL_ME_IN);
    expect(_.range(0, -4, -1)).toEqual(FILL_ME_IN);
  });

  it("should use flatten to make nested arrays easy to work with", function() {
    expect(_([ [1, 2], [3, 4] ]).flatten()).toEqual(FILL_ME_IN);
  });

  it("should use chain() ... .value() to use multiple higher order functions", function() {
    var result = _([ [0, 1], 2 ]).chain()
                     .flatten()
                     .map(function(x) { return x+1 } )
                     .reduce(function (sum, x) { return sum + x })
                     .value();

    expect(result).toEqual(FILL_ME_IN);
  });

});

<commit_msg>finished AboutHigherOrderFunctions<commit_after>var _; //globals

/* This section uses a functional extension known as Underscore.js - http://documentcloud.github.com/underscore/
     "Underscore is a utility-belt library for JavaScript that provides a lot of the functional programming support
      that you would expect in Prototype.js (or Ruby), but without extending any of the built-in JavaScript objects.
      It's the tie to go along with jQuery's tux."
 */
describe("About Higher Order Functions", function () {

  it("should use filter to return array items that meet a criteria", function () {
    var numbers = [1,2,3];
    var odd = _(numbers).filter(function (x) { return x % 2 !== 0 });

    expect(odd).toEqual([1, 3]);
    expect(odd.length).toBe(2);
    expect(numbers.length).toBe(3);
  });

  it("should use 'map' to transform each element", function () {
    var numbers = [1, 2, 3];
    var numbersPlus1 = _(numbers).map(function(x) { return x + 1 });

    expect(numbersPlus1).toEqual([2, 3, 4]);
    expect(numbers).toEqual([1, 2, 3]);
  });

  it("should use 'reduce' to update the same result on each iteration", function () {
    var numbers = [1, 2, 3];
    var reduction = _(numbers).reduce(
      function(memo, x) {
        //note: memo is the result from last call, and x is the current number
        return memo + x;
      },
      /* initial */ 0
    );

    expect(reduction).toBe(6);
    expect(numbers).toEqual([1, 2, 3]);
  });

  it("should use 'forEach' for simple iteration", function () {
    var numbers = [1,2,3];
    var msg = "";
    var isEven = function (item) {
      msg += (item % 2) === 0;
    };

    _(numbers).forEach(isEven);

    expect(msg).toEqual("falsetruefalse");
    expect(numbers).toEqual([1, 2, 3]);
  });

  it("should use 'all' to test whether all items pass condition", function () {
    var onlyEven = [2,4,6];
    var mixedBag = [2,4,5,6];

    var isEven = function(x) { return x % 2 === 0 };

    expect(_(onlyEven).all(isEven)).toBe(true);
    expect(_(mixedBag).all(isEven)).toBe(false);
  });

  it("should use 'any' to test if any items passes condition" , function () {
    var onlyEven = [2,4,6];
    var mixedBag = [2,4,5,6];

    var isEven = function(x) { return x % 2 === 0 };

    expect(_(onlyEven).any(isEven)).toBe(true);
    expect(_(mixedBag).any(isEven)).toBe(true);
  });

  it("should use range to generate an array", function() {
    expect(_.range(3)).toEqual([0, 1, 2]);
    expect(_.range(1, 4)).toEqual([1, 2, 3]);
    expect(_.range(0, -4, -1)).toEqual([0, -1, -2, -3]);
  });

  it("should use flatten to make nested arrays easy to work with", function() {
    expect(_([ [1, 2], [3, 4] ]).flatten()).toEqual([1, 2, 3, 4]);
  });

  it("should use chain() ... .value() to use multiple higher order functions", function() {
    var result = _([ [0, 1], 2 ]).chain()
                     .flatten()
                     .map(function(x) { return x+1 } )
                     .reduce(function (sum, x) { return sum + x })
                     .value();

    expect(result).toEqual(6);
  });

});

<|endoftext|>


<commit_before>describe("About variables and If Statments", function() {
  it("should create a variable called myFirstVariable and set it equal to 1", function() {
    //code goes here.
    expect(myFirstVariable).toBe(1);
  });

  it("should understand if statements", function () {
    var message = 'my first if statement';
    var answer;

    if(message === 'my frist if statement'){
      answer = 'A';
    } else if (message === 'my first if statment'){
      answer = 'B';
    } else if(message === 'my first if statement'){
      answer = 'C';
    } else {
      answer = 'D';
    }

    expect(answer).toBe(FILL_ME_IN);
  });

  it("should understand equality operators", function () {
    var answer;
    var favoriteNumber = '33';

    if(favoriteNumber === 33){
      answer = 'A';
    } else if(favoriteNumber == 33){
      answer = 'B';
    } else if(favoriteNumber === '33'){
      answer = 'C';
    } else {
      answer = 'D';
    }

    expect(answer).toBe(FILL_ME_IN);

    //explain your answer here.
  });

  it("should understand equality operators, again", function () {
    var answer;
    var favoriteNumber = 50;

    if(favoriteNumber === '50'){
      answer = 'A';
    } else if(favoriteNumber === 40){
      answer = 'B';
    } else if(favoriteNumber = 12){
      answer = 'C';
    } else {
      answer = 'D';
    }

    expect(answer).toBe(FILL_ME_IN);

    //explain your answer here.
  });

  it('should understand adding strings', function(){
    var num = '3';
    expect(num + 8).toBe(FILL_ME_IN);

    //explain your answer here.
  });

  it('should understand adding strings, again', function(){
    var num = '3';
    expect(num + FILL_ME_IN).toBe(38);

    //explain your answer here.
  });
});

<commit_msg>Small change<commit_after>describe("About variables and If Statments", function() {
  it("should create a variable called myFirstVariable and set it equal to 1", function() {
    //code goes here.
    expect(myFirstVariable).toBe(1);
  });

  it("should understand if statements", function () {
    var message = 'my first if statement';
    var answer;

    if(message === 'my frist if statement'){
      answer = 'A';
    } else if (message === 'my first if statment'){
      answer = 'B';
    } else if(message === 'my first if statement'){
      answer = 'C';
    } else {
      answer = 'D';
    }

    expect(answer).toBe(FILL_ME_IN);
  });

  it("should understand equality operators", function () {
    var answer;
    var favoriteNumber = '33';

    if(favoriteNumber === 33){
      answer = 'A';
    } else if(favoriteNumber == 33){
      answer = 'B';
    } else if(favoriteNumber === '33'){
      answer = 'C';
    } else {
      answer = 'D';
    }

    expect(answer).toBe(FILL_ME_IN);

    //explain your answer here.
  });

  it("should understand equality operators, again", function () {
    var answer;
    var favoriteNumber = 50;

    if(favoriteNumber === '50'){
      answer = 'A';
    } else if(favoriteNumber === 40){
      answer = 'B';
    } else if(favoriteNumber = 12){
      answer = 'C';
    } else {
      answer = 'D';
    }

    expect(answer).toBe(FILL_ME_IN);

    //explain your answer here.
  });

  it('should understand adding strings', function(){
    var num = '3';
    expect(num + 8).toBe(FILL_ME_IN);

    //explain your answer here.
  });

  it('should understand adding strings, again', function(){
    var num = '3';
    expect(num + FILL_ME_IN).toBe('38');

    //explain your answer here.
  });
});

<|endoftext|>