<commit_before>(function() {
    /*
     * Polyfill
     */
    window.requestAnimationFrame =
        window.requestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        function(callback) {
            window.setTimeout(callback, 1000 / 60);
        };
    ;

    /*
     * Helpers
     */
    function rand(min, max) { return (Math.random() * (max - min) + min); }

    /*
     * Constantes
     */
    const STATE = {
        INIT: 0,
        PLAY: 1,
        PAUSE: 2,
        GAMEOVER: 3
    }

    const COLORS = {
        EMPTY: -1,
        GRAYLIGHT: "#adb5bd",
        GRAY: "#343a40",
        RED: "#e03131",
        PINK: "#c2255c",
        PURPLE: "#9c36b5",
        VIOLET: "#6741d9",
        INDIGO: "#3b5bdb",
        BLUE: "#1b6ec2",
        CYAN: "#0c8599",
        TEAL: "#099268",
        GREEN: "#2f9e44",
        LIME: "#66a80f",
        YELLOW: "#f08c00",
        ORANGE: "#e8590c"
    }

    const BACKGROUND_COLOR = COLORS.GRAYLIGHT; // Couleur de fond
    const TILES_X = 10; // Nombre de tiles horizontaux
    const TILES_Y = 16; // Nombre de tiles verticaux
    const TILE_SIZE = 8; // Largeur d'une tile
    // @TODO Rajouter une bordure autour de chaque tile

    const PIECES = {
        i: {
            color: COLORS.CYAN,
            blocks: [
                [0, 0, 0, 0],
                [0, 0, 0, 0],
                [1, 1, 1, 1],
                [0, 0, 0, 0]
            ]
        },
        j: {
            color: COLORS.BLUE,
            blocks: [
                [0, 0, 0],
                [1, 1, 1],
                [0, 0, 1]
            ]
        },
        l: {
            color: COLORS.ORANGE,
            blocks: [
                [0, 0, 0],
                [1, 1, 1],
                [0, 0, 1]
            ]
        },
        o: {
            color: COLORS.YELLOW,
            blocks: [
                [1, 1],
                [1, 1]
            ]
        },
        s: {
            color: COLORS.GREEN,
            blocks: [
                [0, 0, 0],
                [0, 1, 1],
                [1, 1, 0]
            ]
        },
        z: {
            color: COLORS.RED,
            blocks: [
                [0, 0, 0],
                [1, 1, 0],
                [0, 1, 1]
            ]
        },
        t: {
            color: COLORS.PURPLE,
            blocks: [
                [0, 0, 0],
                [1, 1, 1],
                [0, 1, 0]
            ]
        }
    };
    const BAG = [PIECES.i, PIECES.j, PIECES.l, PIECES.o, PIECES.s, PIECES.t, PIECES.z];

    /*
     * Global variables
     */
    var canvas = document.getElementById("canvas");
    var preview = document.getElementById("preview");

    var tet = canvas.getContext("2d"); // Canvas qui contient le plateau de jeu
    var pvw = preview.getContext("2d"); // Canvas qui contient la prochaine pice

    var _ = {
        tick: 0, // Tick game
        speed: 250, // Vitesse de dplacement des pices

        score: 0, // Score du joueur
        linesCleared: 0, // Nombre de ligne qui a t effac par le joueur

        loopRequestAnim: null,
        board: null, // Tableau 2d de la partie
        currentPiece: {
            type: null,
            offsetY: null,
            offsetY: null
        }
    };

    /*
     * Sac qui contient les 7 pices
     * Chaque fois que le game core a besoin d'une pice, on le retire du bag.
     * Quand le bag est rempli, on le rempli avec les 7 pices.
     */
    var bag = {
        currentBag: null,
        getRandomPiece: function() {

            // Si le bag est vide, on le remplit
            if (this.currentBag == null)
                this.currentBag = BAG;

            // On enlve une pice du bag et on le return
            return this.currentBag.splice(rand(0, this.currentBag.length-1), 1)[0];

        },
        rotatePiece: function(piece, direction) {

            // @TODO Algorythme pour tourner une pice

        }
    };

    /*
     * Game core
     */
    var game = {
        state: null,
        init: function() {

            this.state = STATE.INIT;

            // Changement de la taille des canvas
            canvas.width = TILES_X * TILE_SIZE;
            canvas.height = TILES_Y * TILE_SIZE;
            preview.width  = 32;
            preview.height = 32;

            // Gnration du terrain
            _.board = [];
            for (var i = 0; i < TILES_X; i++)
            {
                _.board[i] = [];
                for (var j = 0; j < TILES_Y; j++)
                {
                    _.board[i][j] = COLORS.EMPTY;
                }
            }

            this.state = STATE.PLAY;
            this.loop();

        },
        loop: function() {

            this.tick++;
            this.update();
            this.draw();

            _.loopRequestAnim = window.requestAnimationFrame(this.loop.bind(this));

        },
        update: function() {

            // @TODO Collisions
            // @TODO Effacer les lignes remplis
            // @TODO Changement de pice aprs une collision
            // @TODO Gravit sur les pices

        },
        draw: function() {

            this.drawBackground(); // @TODO Dessiner le background une seule fois. Ne pas le renouveler  chaque loop.
            this.drawPieces();
            this.drawPreview();

        },
        drawBackground: function() {

            tet.fillStyle = BACKGROUND_COLOR;
            tet.fillRect(0, 0, TILES_X*TILE_SIZE, TILES_Y*TILE_SIZE);

            pvw.fillStyle = BACKGROUND_COLOR;
            pvw.fillRect(0, 0, 32, 32);

        },
        drawPieces: function() {

            for (var i = 0; i < TILES_X; i++)
            {
                for (var j = 0; j < TILES_Y; j++)
                {
                    this.drawPiece(i, j, _.board[i][j]);
                }
            }

        },
        drawPiece: function(x, y, color) {

            if(color == COLORS.EMPTY) return;

            tet.fillStyle = color;
            tet.fillRect(x*TILE_SIZE, y*TILE_SIZE, x*TILE_SIZE+TILE_SIZE, y*TILE_SIZE+TILE_SIZE);

        },
        drawPreview: function() {

            // @TODO Dessiner la pice en cours dans le canvas preview

        },
        rotateCurrentPiece: function() {

            // @TODO Algorythme pour tourner la pice en cours
            // (grer les collisions et les kicks contre les bord du board)

        }
    };

    /*
     * Events listeners
     */
    window.addEventListener("keydown", function(event) {
        if (game.state !== STATE.PLAY) return;

        // @TODO Game controller
        switch (event.keyCode) {
            case 37: // gauche

                break;
            case 39: // droite

                break;
            case 38: // haut

                break;
            case 40: // bas

                break;
            case 32: // espace

                break;
            default:
                return;
        }
    });

    game.init();

})();<commit_msg>[Fix] Bag is automatically refilled when empty<commit_after>(function() {
    /*
     * Polyfill
     */
    window.requestAnimationFrame =
        window.requestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        function(callback) {
            window.setTimeout(callback, 1000 / 60);
        };
    ;

    /*
     * Helpers
     */
    function rand(min, max) { return (Math.random() * (max - min) + min); }

    Object.prototype.clone = function() {
        var newObj = (this instanceof Array) ? [] : {};
        for (i in this) {
            if (i == 'clone')
                continue;
            if (this[i] && typeof this[i] == "object") {
                newObj[i] = this[i].clone();
            }
            else
                newObj[i] = this[i]
        }
        return newObj;
    };

    /*
     * Constantes
     */
    const STATE = {
        INIT: 0,
        PLAY: 1,
        PAUSE: 2,
        GAMEOVER: 3
    }

    const COLORS = {
        EMPTY: -1,
        GRAYLIGHT: "#adb5bd",
        GRAY: "#343a40",
        RED: "#e03131",
        PINK: "#c2255c",
        PURPLE: "#9c36b5",
        VIOLET: "#6741d9",
        INDIGO: "#3b5bdb",
        BLUE: "#1b6ec2",
        CYAN: "#0c8599",
        TEAL: "#099268",
        GREEN: "#2f9e44",
        LIME: "#66a80f",
        YELLOW: "#f08c00",
        ORANGE: "#e8590c"
    }

    const BACKGROUND_COLOR = COLORS.GRAYLIGHT; // Couleur de fond
    const TILES_X = 10; // Nombre de tiles horizontaux
    const TILES_Y = 16; // Nombre de tiles verticaux
    const TILE_SIZE = 8; // Largeur d'une tile
    // @TODO Rajouter une bordure autour de chaque tile

    const PIECES = {
        i: {
            color: COLORS.CYAN,
            blocks: [
                [0, 0, 0, 0],
                [0, 0, 0, 0],
                [1, 1, 1, 1],
                [0, 0, 0, 0]
            ]
        },
        j: {
            color: COLORS.BLUE,
            blocks: [
                [0, 0, 0],
                [1, 1, 1],
                [0, 0, 1]
            ]
        },
        l: {
            color: COLORS.ORANGE,
            blocks: [
                [0, 0, 0],
                [1, 1, 1],
                [0, 0, 1]
            ]
        },
        o: {
            color: COLORS.YELLOW,
            blocks: [
                [1, 1],
                [1, 1]
            ]
        },
        s: {
            color: COLORS.GREEN,
            blocks: [
                [0, 0, 0],
                [0, 1, 1],
                [1, 1, 0]
            ]
        },
        z: {
            color: COLORS.RED,
            blocks: [
                [0, 0, 0],
                [1, 1, 0],
                [0, 1, 1]
            ]
        },
        t: {
            color: COLORS.PURPLE,
            blocks: [
                [0, 0, 0],
                [1, 1, 1],
                [0, 1, 0]
            ]
        }
    };
    const BAG = [PIECES.i, PIECES.j, PIECES.l, PIECES.o, PIECES.s, PIECES.t, PIECES.z];

    /*
     * Global variables
     */
    var canvas = document.getElementById("canvas");
    var preview = document.getElementById("preview");

    var tet = canvas.getContext("2d"); // Canvas qui contient le plateau de jeu
    var pvw = preview.getContext("2d"); // Canvas qui contient la prochaine pice

    var _ = {
        tick: 0, // Tick game
        speed: 250, // Vitesse de dplacement des pices

        score: 0, // Score du joueur
        linesCleared: 0, // Nombre de ligne qui a t effac par le joueur

        loopRequestAnim: null,
        board: null, // Tableau 2d de la partie
        currentPiece: {
            type: null,
            offsetY: null,
            offsetY: null
        }
    };

    /*
     * Sac qui contient les 7 pices
     * Chaque fois que le game core a besoin d'une pice, on le retire du bag.
     * Quand le bag est rempli, on le rempli avec les 7 pices.
     */
    var bag = {
        currentBag: [],
        getRandomPiece: function() {

            // Si le bag est vide, on le remplit
            if (this.currentBag.length == 0)
                this.currentBag = BAG.clone();

            // On enlve une pice du bag et on le return
            return this.currentBag.splice(rand(0, this.currentBag.length-1), 1)[0];

        },
        rotatePiece: function(piece, direction) {

            // @TODO Algorythme pour tourner une pice

        }
    };

    /*
     * Game core
     */
    var game = {
        state: null,
        init: function() {

            this.state = STATE.INIT;

            // Changement de la taille des canvas
            canvas.width = TILES_X * TILE_SIZE;
            canvas.height = TILES_Y * TILE_SIZE;
            preview.width  = 32;
            preview.height = 32;

            // Gnration du terrain
            _.board = [];
            for (var i = 0; i < TILES_X; i++)
            {
                _.board[i] = [];
                for (var j = 0; j < TILES_Y; j++)
                {
                    _.board[i][j] = COLORS.EMPTY;
                }
            }

            this.state = STATE.PLAY;
            this.loop();

        },
        loop: function() {

            this.tick++;
            this.update();
            this.draw();

            _.loopRequestAnim = window.requestAnimationFrame(this.loop.bind(this));

        },
        update: function() {

            // @TODO Collisions
            // @TODO Effacer les lignes remplis
            // @TODO Changement de pice aprs une collision
            // @TODO Gravit sur les pices

        },
        draw: function() {

            this.drawBackground(); // @TODO Dessiner le background une seule fois. Ne pas le renouveler  chaque loop.
            this.drawPieces();
            this.drawPreview();

        },
        drawBackground: function() {

            tet.fillStyle = BACKGROUND_COLOR;
            tet.fillRect(0, 0, TILES_X*TILE_SIZE, TILES_Y*TILE_SIZE);

            pvw.fillStyle = BACKGROUND_COLOR;
            pvw.fillRect(0, 0, 32, 32);

        },
        drawPieces: function() {

            for (var i = 0; i < TILES_X; i++)
            {
                for (var j = 0; j < TILES_Y; j++)
                {
                    this.drawPiece(i, j, _.board[i][j]);
                }
            }

        },
        drawPiece: function(x, y, color) {

            if(color == COLORS.EMPTY) return;

            tet.fillStyle = color;
            tet.fillRect(x*TILE_SIZE, y*TILE_SIZE, x*TILE_SIZE+TILE_SIZE, y*TILE_SIZE+TILE_SIZE);

        },
        drawPreview: function() {

            // @TODO Dessiner la pice en cours dans le canvas preview

        },
        rotateCurrentPiece: function() {

            // @TODO Algorythme pour tourner la pice en cours
            // (grer les collisions et les kicks contre les bord du board)

        }
    };

    /*
     * Events listeners
     */
    window.addEventListener("keydown", function(event) {
        if (game.state !== STATE.PLAY) return;

        // @TODO Game controller
        switch (event.keyCode) {
            case 37: // gauche

                break;
            case 39: // droite

                break;
            case 38: // haut

                break;
            case 40: // bas

                break;
            case 32: // espace

                break;
            default:
                return;
        }
    });

    game.init();

})();<|endoftext|>


<commit_before>var _ = require('underscore');
var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server, { pingInterval: 100000000 });
var port = 3030;

var LogReceiver = require('./log_receiver');
var LogSender = require('./log_sender');
var senders = LogSender.rooms;
var recievers = LogReceiver.rooms;

// HTTP Stuff
server.listen(port);
app.locals._ = require('underscore');
app.set('view engine', 'ejs');
app.set('views', './views');
app.use(express.static('public'));
app.get('/', function (req, res) {
  var roomIds = Object.keys(io.sockets.adapter.rooms);
  var rRoomIds = _.filter(roomIds, function(id) { return id.indexOf(LogReceiver.prefix) >= 0; });
  var rooms = _.map(rRoomIds, function(id) { return id.replace("room:r:", ""); }).concat("all");
  res.render('index', { rooms: _.uniq(rooms) || [] });
});

// Socket.IO Stuff
io.on("connection", function (socket, connCallback) {
  socket.on("create", function(data, ackCallback) {
    LogSender.create(socket, data.room);
    LogSender.create(socket, "all");
    ackCallback();
  });

  socket.on("join", function(data, ackCallback) {
    LogReceiver.create(socket, data.room);
    ackCallback(senders[data.room] ? senders[data.room].history : []);
  });

  socket.on("leave", function(data) {
    if(recievers[data.room]) {
      recievers[data.room].leave();
    }
  });
});

console.log("Server Started on http://localhost:" + port);
<commit_msg>clean up<commit_after>var _ = require('underscore');
var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server, { pingInterval: 100000000 });
var port = 3030;

var LogReceiver = require('./log_receiver');
var LogSender = require('./log_sender');
var senders = LogSender.rooms;
var recievers = LogReceiver.rooms;

// HTTP Stuff
server.listen(port);
app.locals._ = _;
app.set('view engine', 'ejs');
app.set('views', './views');
app.use(express.static('public'));
app.get('/', function (req, res) {
  var roomIds = Object.keys(io.sockets.adapter.rooms);
  var rooms =  _.chain(roomIds.concat(LogReceiver.prefix + "all"))
    .filter(function(id) { return id.indexOf(LogReceiver.prefix) >= 0; })
    .map(function(id) { return id.replace("room:r:", ""); })
    .uniq().value();
  res.render('index', { rooms: rooms });
});

// Socket.IO Stuff
io.on("connection", function (socket, connCallback) {
  socket.on("create", function(data, ackCallback) {
    LogSender.create(socket, data.room);
    LogSender.create(socket, "all");
    ackCallback();
  });

  socket.on("join", function(data, ackCallback) {
    LogReceiver.create(socket, data.room);
    ackCallback(senders[data.room] ? senders[data.room].history : []);
  });

  socket.on("leave", function(data) {
    if(recievers[data.room]) {
      recievers[data.room].leave();
    }
  });
});

console.log("Server Started on http://localhost:" + port);
<|endoftext|>


<commit_before>angular.module('ngLocalize')
    .service('locale', function ($injector, $http, $q, $log, $rootScope, $window, localeConf, localeEvents, localeSupported, localeFallbacks) {
        var TOKEN_REGEX = new RegExp('^[\\w\\.-]+\\.[\\w\\s\\.-]+\\w(:.*)?$'),

            currentLocale,
            deferrences,
            bundles,
            cookieStore;

        if (localeConf.persistSelection && $injector.has('$cookieStore')) {
            cookieStore = $injector.get('$cookieStore');
        }

        function isToken(str) {
            return (str && str.length && TOKEN_REGEX.test(str));
        }

        function getPath(tok) {
            var path = tok ? tok.split('.') : '',
                result = '';

            if (path.length > 1) {
                result = path.slice(0, -1).join('.');
            }

            return result;
        }

        function getKey(tok) {
            var path = tok ? tok.split('.') : [],
                result = '';

            if (path.length) {
                result = path[path.length - 1];
            }

            return result;
        }

        function getBundle(tok) {
            var result = null,
                path = tok ? tok.split('.') : [],
                i;

            if (path.length > 1) {
                result = bundles;

                for (i = 0; i < path.length - 1; i++) {
                    if (result[path[i]]) {
                        result = result[path[i]];
                    } else {
                        result = null;
                        break;
                    }
                }
            }

            return result;
        }

        function loadBundle(token) {
            var path = token ? token.split('.') : '',
                root = bundles,
                url = localeConf.basePath + '/' + currentLocale,
                i;

            if (path.length > 1) {
                for (i = 0; i < path.length - 1; i++) {
                    if (!root[path[i]]) {
                        root[path[i]] = {};
                    }
                    root = root[path[i]];
                    url += '/' + path[i];
                }

                if (!root._loading) {
                    root._loading = true;

                    url += localeConf.fileExtension;

                    $http.get(url)
                        .success(function (data) {
                            var key,
                                path = getPath(token);
                            // Merge the contents of the obtained data into the stored bundle.
                            for (key in data) {
                                if (data.hasOwnProperty(key)) {
                                    root[key] = data[key];
                                }
                            }

                            // Mark the bundle as having been "loaded".
                            delete root._loading;

                            // Notify anyone who cares to know about this event.
                            $rootScope.$broadcast(localeEvents.resourceUpdates);

                            // If we issued a Promise for this file, resolve it now.
                            if (deferrences[path]) {
                                deferrences[path].resolve(path);
                            }
                        })
                        .error(function () {
                            $log.error('[localizationService] Failed to load: ' + url);

                            // We can try it again later.
                            delete root._loading;
                        });
                }
            }
        }

        function bundleReady(path) {
            var bundle,
                token;

            path = path || localeConf.langFile;
            token = path + '._LOOKUP_';

            bundle = getBundle(token);

            if (!deferrences[path]) {
                deferrences[path] = $q.defer();
            }

            if (bundle && !bundle._loading) {
                deferrences[path].resolve(path);
            } else {
                if (!bundle) {
                    loadBundle(token);
                }
            }

            return deferrences[path].promise;
        }

        function ready(path) {
            var paths,
                deferred,
                outstanding;

            if (angular.isString(path)) {
                paths = path.split(',');
            } else if (angular.isArray(path)) {
                paths = path;
            } else {
                throw new Error('locale.ready requires either an Array or comma-separated list.');
            }

            if (paths.length > 1) {
                outstanding = [];
                paths.forEach(function (path) {
                    outstanding.push(bundleReady(path));
                });
                deferred = $q.all(outstanding);
            } else {
                deferred = bundleReady(path);
            }

            return deferred;
        }

        function applySubstitutions(text, subs) {
            var res = text,
                firstOfKind = 0;

            if (subs) {
                if (angular.isArray(subs)) {
                    angular.forEach(subs, function (sub, i) {
                        res = res.replace('%' + (i + 1), sub);
                        res = res.replace('{' + (i + 1) + '}', sub);
                    });
                } else {
                    angular.forEach(subs, function (v, k) {
                        ++firstOfKind;

                        res = res.replace('{' + k + '}', v);
                        res = res.replace('%' + k, v);
                        res = res.replace('%' + (firstOfKind), v);
                        res = res.replace('{' + (firstOfKind) + '}', v);
                    });
                }
            }
            res = res.replace(/\n/g, '
');

            return res;
        }

        function getLocalizedString(txt, subs) {
            var result = '',
                bundle,
                key,
                A,
                isValidToken = false;

            if (angular.isString(txt) && !subs && txt.indexOf(localeConf.delimiter) !== -1) {
                A = txt.split(localeConf.delimiter);
                txt = A[0];
                subs = angular.fromJson(A[1]);
            }

            isValidToken = isToken(txt);
            if (isValidToken) {
                if (!angular.isObject(subs)) {
                    subs = [subs];
                }

                bundle = getBundle(txt);
                if (bundle && !bundle._loading) {
                    key = getKey(txt);

                    if (bundle[key]) {
                        result = applySubstitutions(bundle[key], subs);
                    } else {
                        $log.info('[localizationService] Key not found: ' + txt);
                        result = '%%KEY_NOT_FOUND%%';
                    }
                } else {
                    if (!bundle) {
                        loadBundle(txt);
                    }
                }
            } else {
                result = txt;
            }

            return result;
        }

        function setLocale(value) {
            var lang;

            if (angular.isString(value)) {
                value = value.trim();
                if (localeSupported.indexOf(value) !== -1) {
                    lang = value;
                } else {
                    lang = localeFallbacks[value.split('-')[0]];
                    if (angular.isUndefined(lang)) {
                        lang = localeConf.defaultLocale;
                    }
                }
            } else {
                lang = localeConf.defaultLocale;
            }

            if (lang !== currentLocale) {
                bundles = {};
                deferrences = {};
                currentLocale = lang;

                $rootScope.$broadcast(localeEvents.localeChanges, currentLocale);
                $rootScope.$broadcast(localeEvents.resourceUpdates);

                if (cookieStore) {
                    cookieStore.put(localeConf.cookieName, lang);
                }
            }
        }

        function getLocale() {
            return currentLocale;
        }

        setLocale(cookieStore.get(localeConf.cookieName) ? cookieStore.get(localeConf.cookieName) : $window.navigator.userLanguage || $window.navigator.language);

        return {
            ready: ready,
            isToken: isToken,
            getPath: getPath,
            getKey: getKey,
            setLocale: setLocale,
            getLocale: getLocale,
            getString: getLocalizedString
        };
    });
<commit_msg>Ensure that cookieStore is defined.<commit_after>angular.module('ngLocalize')
    .service('locale', function ($injector, $http, $q, $log, $rootScope, $window, localeConf, localeEvents, localeSupported, localeFallbacks) {
        var TOKEN_REGEX = new RegExp('^[\\w\\.-]+\\.[\\w\\s\\.-]+\\w(:.*)?$'),

            currentLocale,
            deferrences,
            bundles,
            cookieStore;

        if (localeConf.persistSelection && $injector.has('$cookieStore')) {
            cookieStore = $injector.get('$cookieStore');
        }

        function isToken(str) {
            return (str && str.length && TOKEN_REGEX.test(str));
        }

        function getPath(tok) {
            var path = tok ? tok.split('.') : '',
                result = '';

            if (path.length > 1) {
                result = path.slice(0, -1).join('.');
            }

            return result;
        }

        function getKey(tok) {
            var path = tok ? tok.split('.') : [],
                result = '';

            if (path.length) {
                result = path[path.length - 1];
            }

            return result;
        }

        function getBundle(tok) {
            var result = null,
                path = tok ? tok.split('.') : [],
                i;

            if (path.length > 1) {
                result = bundles;

                for (i = 0; i < path.length - 1; i++) {
                    if (result[path[i]]) {
                        result = result[path[i]];
                    } else {
                        result = null;
                        break;
                    }
                }
            }

            return result;
        }

        function loadBundle(token) {
            var path = token ? token.split('.') : '',
                root = bundles,
                url = localeConf.basePath + '/' + currentLocale,
                i;

            if (path.length > 1) {
                for (i = 0; i < path.length - 1; i++) {
                    if (!root[path[i]]) {
                        root[path[i]] = {};
                    }
                    root = root[path[i]];
                    url += '/' + path[i];
                }

                if (!root._loading) {
                    root._loading = true;

                    url += localeConf.fileExtension;

                    $http.get(url)
                        .success(function (data) {
                            var key,
                                path = getPath(token);
                            // Merge the contents of the obtained data into the stored bundle.
                            for (key in data) {
                                if (data.hasOwnProperty(key)) {
                                    root[key] = data[key];
                                }
                            }

                            // Mark the bundle as having been "loaded".
                            delete root._loading;

                            // Notify anyone who cares to know about this event.
                            $rootScope.$broadcast(localeEvents.resourceUpdates);

                            // If we issued a Promise for this file, resolve it now.
                            if (deferrences[path]) {
                                deferrences[path].resolve(path);
                            }
                        })
                        .error(function () {
                            $log.error('[localizationService] Failed to load: ' + url);

                            // We can try it again later.
                            delete root._loading;
                        });
                }
            }
        }

        function bundleReady(path) {
            var bundle,
                token;

            path = path || localeConf.langFile;
            token = path + '._LOOKUP_';

            bundle = getBundle(token);

            if (!deferrences[path]) {
                deferrences[path] = $q.defer();
            }

            if (bundle && !bundle._loading) {
                deferrences[path].resolve(path);
            } else {
                if (!bundle) {
                    loadBundle(token);
                }
            }

            return deferrences[path].promise;
        }

        function ready(path) {
            var paths,
                deferred,
                outstanding;

            if (angular.isString(path)) {
                paths = path.split(',');
            } else if (angular.isArray(path)) {
                paths = path;
            } else {
                throw new Error('locale.ready requires either an Array or comma-separated list.');
            }

            if (paths.length > 1) {
                outstanding = [];
                paths.forEach(function (path) {
                    outstanding.push(bundleReady(path));
                });
                deferred = $q.all(outstanding);
            } else {
                deferred = bundleReady(path);
            }

            return deferred;
        }

        function applySubstitutions(text, subs) {
            var res = text,
                firstOfKind = 0;

            if (subs) {
                if (angular.isArray(subs)) {
                    angular.forEach(subs, function (sub, i) {
                        res = res.replace('%' + (i + 1), sub);
                        res = res.replace('{' + (i + 1) + '}', sub);
                    });
                } else {
                    angular.forEach(subs, function (v, k) {
                        ++firstOfKind;

                        res = res.replace('{' + k + '}', v);
                        res = res.replace('%' + k, v);
                        res = res.replace('%' + (firstOfKind), v);
                        res = res.replace('{' + (firstOfKind) + '}', v);
                    });
                }
            }
            res = res.replace(/\n/g, '
');

            return res;
        }

        function getLocalizedString(txt, subs) {
            var result = '',
                bundle,
                key,
                A,
                isValidToken = false;

            if (angular.isString(txt) && !subs && txt.indexOf(localeConf.delimiter) !== -1) {
                A = txt.split(localeConf.delimiter);
                txt = A[0];
                subs = angular.fromJson(A[1]);
            }

            isValidToken = isToken(txt);
            if (isValidToken) {
                if (!angular.isObject(subs)) {
                    subs = [subs];
                }

                bundle = getBundle(txt);
                if (bundle && !bundle._loading) {
                    key = getKey(txt);

                    if (bundle[key]) {
                        result = applySubstitutions(bundle[key], subs);
                    } else {
                        $log.info('[localizationService] Key not found: ' + txt);
                        result = '%%KEY_NOT_FOUND%%';
                    }
                } else {
                    if (!bundle) {
                        loadBundle(txt);
                    }
                }
            } else {
                result = txt;
            }

            return result;
        }

        function setLocale(value) {
            var lang;

            if (angular.isString(value)) {
                value = value.trim();
                if (localeSupported.indexOf(value) !== -1) {
                    lang = value;
                } else {
                    lang = localeFallbacks[value.split('-')[0]];
                    if (angular.isUndefined(lang)) {
                        lang = localeConf.defaultLocale;
                    }
                }
            } else {
                lang = localeConf.defaultLocale;
            }

            if (lang !== currentLocale) {
                bundles = {};
                deferrences = {};
                currentLocale = lang;

                $rootScope.$broadcast(localeEvents.localeChanges, currentLocale);
                $rootScope.$broadcast(localeEvents.resourceUpdates);

                if (cookieStore) {
                    cookieStore.put(localeConf.cookieName, lang);
                }
            }
        }

        function getLocale() {
            return currentLocale;
        }

        setLocale(cookieStore && cookieStore.get(localeConf.cookieName) ? cookieStore.get(localeConf.cookieName) : $window.navigator.userLanguage || $window.navigator.language);

        return {
            ready: ready,
            isToken: isToken,
            getPath: getPath,
            getKey: getKey,
            setLocale: setLocale,
            getLocale: getLocale,
            getString: getLocalizedString
        };
    });
<|endoftext|>


<commit_before>/*
 * VeraLink config file
 * Damian Alarcon
 * Dec 2015
 * damian@laerit.dk
 */

// Remember to edit the config.js file with your Vera information

var config          = require('./config.js');
var request         = require("sync-request");
var fs              = require('fs');
var path            = require('path');
var storage         = require('./').storage;
var uuid            = require('./').uuid;
var Bridge          = require('./').Bridge;
var Accessory       = require('./').Accessory;
var accessoryLoader = require('./').AccessoryLoader;
var Service         = require('./').Service;
var Characteristic  = require('./').Characteristic;
var hashing         = require("create-hash");
var debug           = require("debug")('VeraLink');

var HAPNode = {'request':request, 'storage':storage, 'uuid':uuid, 'Bridge':Bridge, 'Accessory':Accessory, 'accessoryLoader':accessoryLoader, 'hashing':hashing, 'Service':Service, 'Characteristic':Characteristic, 'debug':debug};

var functions       = require('./lib/functions.js')(HAPNode,config);

console.log("HAP-NodeJS starting...");

// Initialize our storage system
storage.initSync();

// Load Vera info from the data_request URL
var verainfo = functions.getVeraInfo(config.veraIP);

if(typeof verainfo === 'object')
{
    if(config.bridged === true)
    {
        functions.processrooms(verainfo);
    }
    else
    {
        functions.processall(verainfo);
    }
}<commit_msg>Readme change<commit_after>/*
 * VeraLink v0.1
 * Damian Alarcon
 * Dec 2015
 * damian@laerit.dk
 */

// Remember to edit the config.js file with your Vera information

var config          = require('./config.js');
var request         = require("sync-request");
var fs              = require('fs');
var path            = require('path');
var storage         = require('./').storage;
var uuid            = require('./').uuid;
var Bridge          = require('./').Bridge;
var Accessory       = require('./').Accessory;
var accessoryLoader = require('./').AccessoryLoader;
var Service         = require('./').Service;
var Characteristic  = require('./').Characteristic;
var hashing         = require("create-hash");
var debug           = require("debug")('VeraLink');

var HAPNode = {'request':request, 'storage':storage, 'uuid':uuid, 'Bridge':Bridge, 'Accessory':Accessory, 'accessoryLoader':accessoryLoader, 'hashing':hashing, 'Service':Service, 'Characteristic':Characteristic, 'debug':debug};

var functions       = require('./lib/functions.js')(HAPNode,config);

console.log("HAP-NodeJS starting...");

// Initialize our storage system
storage.initSync();

// Load Vera info from the data_request URL
var verainfo = functions.getVeraInfo(config.veraIP);

if(typeof verainfo === 'object')
{
    if(config.bridged === true)
    {
        functions.processrooms(verainfo);
    }
    else
    {
        functions.processall(verainfo);
    }
}<|endoftext|>


<commit_before>// Copyright 2016, Google, Inc.
// Licensed under the Apache License, Version 2.0 (the 'License');
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an 'AS IS' BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';

process.env.DEBUG = 'actions-on-google:*';
let Assistant = require('actions-on-google').ApiAiAssistant;
let express = require('express');
let bodyParser = require('body-parser');
let app = express();
app.use(bodyParser.json({type: 'application/json'}));

const CONFIRM_TYPE_CONTEXT = 'confirm_type';
const CLIENT_CODE_ACTION = 'get_client_code';
const CODE_TYPE_ACTION = 'ask_expenses_or_services';
const CODE_TYPE_ARGUMENT = 'codetype';
const CLIENT_NAME_ARGUMENT = 'clientname';

var data = {
  "BioTeSys" : {
    "ExpenseCode": "1 1",
    "ServiceCode": "2 2"
  }
};

app.post('/', function (req, res) {
  const assistant = new Assistant({request: req, response: res});
  console.log('Request headers: ' + JSON.stringify(req.headers));
  console.log('Request body: ' + JSON.stringify(req.body));

  function askExpensesOrServices(assistant){
    let name = assistant.getArgument(CLIENT_NAME_ARGUMENT);
    assistant.setContext(CONFIRM_TYPE_CONTEXT);
    assistant.data.clientName = name;
    assistant.ask('You asked about ' + name + '.  Do you need an expenses or services code?');
  }

  function getClientCode (assistant) {
	  let type = assistant.getArgument(CODE_TYPE_ARGUMENT);
    let name = assistant.data.clientName;
    var key = name;
    var clientNameKeyIndex = data[key];
    if (type === 'Expenses'){
        let code = clientNameKeyIndex.ExpenseCode;
    }
    else if (type === 'Services'){
        let code = clientNameKeyIndex.ServiceCode;
    }
    assistant.tell('The ' + type + ' code for ' + name + ' is X.');// + code + '.');
    //assistant.tell('I\'ll try to get the ' + assitant.data.clientName + ' ' + type + ' code.');
	  /*if (name === 'CRS'){
		  assistant.tell('The CRS services code is 1 2 5 0 0 0 2 3');
	  }
	  else{
	    assistant.ask ('Sorry, I dont know any ' + name + ' client codes.  Try again.');*/
	  }

  let actionMap = new Map();
  actionMap.set(CLIENT_CODE_ACTION, getClientCode);
  actionMap.set(CODE_TYPE_ACTION, askExpensesOrServices);
  assistant.handleRequest(actionMap);
});

if (module === require.main) {
  // [START server]
  // Start the server
  let server = app.listen(process.env.PORT || 8080, function () {
    let port = server.address().port;
    console.log('App listening on port %s', port);
  });
  // [END server]
}

module.exports = app;
<commit_msg>try if then client code type handling<commit_after>// Copyright 2016, Google, Inc.
// Licensed under the Apache License, Version 2.0 (the 'License');
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an 'AS IS' BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';

process.env.DEBUG = 'actions-on-google:*';
let Assistant = require('actions-on-google').ApiAiAssistant;
let express = require('express');
let bodyParser = require('body-parser');
let app = express();
app.use(bodyParser.json({type: 'application/json'}));

const CONFIRM_TYPE_CONTEXT = 'confirm_type';
const CLIENT_CODE_ACTION = 'get_client_code';
const CODE_TYPE_ACTION = 'ask_expenses_or_services';
const CODE_TYPE_ARGUMENT = 'codetype';
const CLIENT_NAME_ARGUMENT = 'clientname';

var data = {
  "BioTeSys" : {
    "ExpenseCode": "1 1",
    "ServiceCode": "2 2"
  }
};

app.post('/', function (req, res) {
  const assistant = new Assistant({request: req, response: res});
  console.log('Request headers: ' + JSON.stringify(req.headers));
  console.log('Request body: ' + JSON.stringify(req.body));

  function askExpensesOrServices(assistant){
    let name = assistant.getArgument(CLIENT_NAME_ARGUMENT);
    assistant.setContext(CONFIRM_TYPE_CONTEXT);
    assistant.data.clientName = name;
    assistant.ask('You asked about ' + name + '.  Do you need an expenses or services code?');
  }

  function getClientCode (assistant) {
	  let type = assistant.getArgument(CODE_TYPE_ARGUMENT);
    let name = assistant.data.clientName;
    var key = name;
    var clientNameKeyIndex = data[key];
    if (type === 'Expenses'){
        let code = clientNameKeyIndex.ExpenseCode;
    }
    else if (type === 'Services'){
        let code = clientNameKeyIndex.ServiceCode;
    }
    assistant.tell('The ' + type + ' code for ' + name + ' is ' + code + '.');
    //assistant.tell('I\'ll try to get the ' + assitant.data.clientName + ' ' + type + ' code.');
	  /*if (name === 'CRS'){
		  assistant.tell('The CRS services code is 1 2 5 0 0 0 2 3');
	  }
	  else{
	    assistant.ask ('Sorry, I dont know any ' + name + ' client codes.  Try again.');*/
	  }

  let actionMap = new Map();
  actionMap.set(CLIENT_CODE_ACTION, getClientCode);
  actionMap.set(CODE_TYPE_ACTION, askExpensesOrServices);
  assistant.handleRequest(actionMap);
});

if (module === require.main) {
  // [START server]
  // Start the server
  let server = app.listen(process.env.PORT || 8080, function () {
    let port = server.address().port;
    console.log('App listening on port %s', port);
  });
  // [END server]
}

module.exports = app;
<|endoftext|>


<commit_before>"use strict";

var express = require('express');
var path = require('path');
var kiwi = require('kiwi');
var publicDir = path.join(__dirname, 'public');

var decks = [{id: 1, name: 'English', slug: 'english', user_id: 1, description: 'Basic english words', stats: {new: 20, review: 15, again: 3, total: 2600}}, {id: 1, name: 'Heisigs Remember the Kanji (RTK)', slug: 'rtk1', user_id: 1, description: 'Classic book for learning kanji', stats: {new: 2, review: 1, again: 0, total: 2520}}];

var app = express();

app.configure(function(){
	app.set('views', path.join(__dirname, 'view'));
	app.set('port', process.env.PORT || 8080);
	app.set('view engine', 'kiwi');
	this.engine('kiwi', function(filename, options, callback) {
		kiwi.__express(filename, options, function(err, rendered) {
			if(!process.env.production && err){
				console.error(err);
			}
			callback(err, rendered.toString());
		});
	});

	app.use(express.compress());
	app.use(require('less-middleware')({ src: publicDir }));
	app.use(express.favicon());
	app.use(express.static(publicDir));
});
app.configure('development', function(){
	app.use(express.logger());
});

app.get('/', function(req, res){
	res.render('index', {title: 'miwi'});
});

app.get('/decks', function(req, res){
	res.render('decks', {title: 'My decks', decks: decks});
});

app.get('/:deck', function(req, res){
	var deck = null;
	for (var i = 0; i < decks.length; i++) {
		if(decks[i].slug == req.params.deck) {
			deck = decks[i];
		}
	};
	if(deck) {
		res.render('card', {title: deck.name, deck: deck});
	} else {
		res.send(404);
	}
});

app.listen(app.get('port'), function() {
	console.log('Started app on port %d', app.get('port'));
});<commit_msg>code style<commit_after>"use strict";

var express = require('express');
var path = require('path');
var kiwi = require('kiwi');
var publicDir = path.join(__dirname, 'public');

var decks = [{id: 1, name: 'English', slug: 'english', user_id: 1, description: 'Basic english words', stats: {new: 20, review: 15, again: 3, total: 2600}}, {id: 1, name: 'Heisigs Remember the Kanji (RTK)', slug: 'rtk1', user_id: 1, description: 'Classic book for learning kanji', stats: {new: 2, review: 1, again: 0, total: 2520}}];

var app = express();

app.configure(function(){
	app.set('views', path.join(__dirname, 'view'));
	app.set('port', process.env.PORT || 8080);
	app.set('view engine', 'kiwi');
	this.engine('kiwi', function(filename, options, callback) {
		kiwi.__express(filename, options, function(err, rendered) {
			if(!process.env.production && err){
				console.error(err);
			}
			callback(err, rendered.toString());
		});
	});

	app.use(express.compress());
	app.use(require('less-middleware')({src: publicDir}));
	app.use(express.favicon());
	app.use(express.static(publicDir));
});
app.configure('development', function(){
	app.use(express.logger());
});

app.get('/', function(req, res){
	res.render('index', {title: 'miwi'});
});

app.get('/decks', function(req, res){
	res.render('decks', {title: 'My decks', decks: decks});
});

app.get('/:deck', function(req, res){
	var deck = null;
	for(var i = 0; i < decks.length; i++) {
		if(decks[i].slug == req.params.deck) {
			deck = decks[i];
		}
	};
	if(deck) {
		res.render('card', {title: deck.name, deck: deck});
	} else {
		res.send(404);
	}
});

app.listen(app.get('port'), function() {
	console.log('Started app on port %d', app.get('port'));
});<|endoftext|>


<commit_before>var express = require('express');
var cheerio = require('cheerio');
var superagent = require('superagent');
var eventproxy = require('eventproxy');

var app = express();

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

var cnodeUrl = "https://www.cnodejs.org";
app.get('/', function (req, res, next) {
  superagent.get(cnodeUrl)
    .end(function (err, sres) {
      if (err) {
        return next(err);
      }

      var topicUrls = [];
      var $ = cheerio.load(sres.text);
      $('a.topic_title').each(function (i, element) {
        topicUrls.push(cnodeUrl + $(element).attr('href'));
      });

      var ep = new eventproxy();

      topicUrls.forEach(function (topicUrl) {
        superagent.get(topicUrl)
          .end(function (err, sres) {
            ep.emit('topic_html', [topicUrl, sres.text]);
          });
      });

      ep.after("topic_html", topicUrls.length, function (topics) {
        topics = topics.map(function (topicPair) {
          var topicUrl = topicPair[0];
          var topicHtml = topicPair[1];
          var $ = cheerio.load(topicHtml);
          return ({
            title : $('.topic_full_title').text().trim(),
            href : topicUrl,
            comment1: $('.reply_content').eq(0).text().trim(),
          });
        });
        res.send(topics);
      });
  });
});
module.exports = app;
<commit_msg>update app.js<commit_after>var express = require('express');
var cheerio = require('cheerio');
var superagent = require('superagent');
var eventproxy = require('eventproxy');

var app = express();

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

var cnodeUrl = "https://www.cnodejs.org";
app.get('/', function (req, res, next) {
  superagent.get(cnodeUrl)
    .end(function (err, sres) {
      if (err) {
        return next(err);
      }

      var topicUrls = [];
      var $ = cheerio.load(sres.text);
      $('a.topic_title').each(function (i, element) {
        topicUrls.push(cnodeUrl + $(element).attr('href'));
      });

      var ep = new eventproxy();

      topicUrls.forEach(function (topicUrl) {
        superagent.get(topicUrl)
          .end(function (err, sres) {
            ep.emit('topic_html', [topicUrl, sres.text]);
          });
      });

      ep.after("topic_html", topicUrls.length, function (topics) {
        topics = topics.map(function (topicPair) {
          var topicUrl = topicPair[0];
          var topicHtml = topicPair[1];
          var $ = cheerio.load(topicHtml);
          return ({
            title : $('.topic_full_title').text().trim(),
            href : topicUrl,
            comment1: $('.reply_content').eq(0).text().trim(),
          });
        });
        res.send(topics);
      });
  });
});
module.exports = app;
<|endoftext|>


<commit_before>/*jslint node: true */
'use strict';

var express = require('express');
var path = require('path');
var logger = require('morgan');
var bodyParser = require('body-parser');
var app = express();
var http = require('http');
var https = require('https');
var fs = require('fs');
var config = require('config');
var cookieParser = require('cookie-parser')(config.get('session.secret'));

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

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

// live reload
if (app.get('env') === 'development') {
  app.use(require('connect-livereload')({
    port: 4002
  }));
}

// static css/js/images
app.use(express.static(path.join(__dirname, 'public')));

// Create HTTP and IO servers
//var server = http.createServer(app);
var options = {
  pfx: fs.readFileSync('./certs/ss.pfx'),
  passphrase: "123456"
};
var server = https.createServer(options, app);

var SocketIOHelper = require('./libs/core/socketIoHelper.js');
SocketIOHelper.init(server);
var io = SocketIOHelper.io;
var db = require('./libs/core/database.js');
require('./libs/core/session.js')(app, db, io);

var multiRouterSocket = require('./libs/core/multiRouterSocket.js');
new multiRouterSocket(io, __dirname + '/routes-socket').populateRoutes();

// auto create and use routes
var multiRouter = require('./libs/core/multiRouter.js');
new multiRouter(app, __dirname + '/routes').populateRoutes();

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

// development error handler
// will print stack trace
if (app.get('env') === 'development') {
  app.use(function (err, req, res, next) {
    res.status(err.status || 500);

    if (req.path && req.path.indexOf('api') >= 0) {
      res.json(
        {
          message: err.message,
          errors: [err.stack]
        }
      );
    }
    else {
      res.render('admin-lte/error', {
        message: err.message,
        error: err
      });
    }
  });
}

// production error handler
// no stack traces leaked to user
app.use(function (err, req, res, next) {
  res.status(err.status || 500);
  if (req.path && req.path.indexOf('api') >= 0) {
    res.json(
      {
        message: err.message,
        error: {}
      }
    );
  }
  else
    res.render('error', {
      message: err.message,
      error: {}
    });
});

module.exports = server;
<commit_msg>back to http<commit_after>/*jslint node: true */
'use strict';

var express = require('express');
var path = require('path');
var logger = require('morgan');
var bodyParser = require('body-parser');
var app = express();
var http = require('http');
var https = require('https');
var fs = require('fs');
var config = require('config');
var cookieParser = require('cookie-parser')(config.get('session.secret'));

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

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

// live reload
if (app.get('env') === 'development') {
  app.use(require('connect-livereload')({
    port: 4002
  }));
}

// static css/js/images
app.use(express.static(path.join(__dirname, 'public')));

// Create HTTP and IO servers
var server = http.createServer(app);
//var options = {
//  pfx: fs.readFileSync('./certs/ss.pfx'),
//  passphrase: "123456"
//};
//var server = https.createServer(options, app);

var SocketIOHelper = require('./libs/core/socketIoHelper.js');
SocketIOHelper.init(server);
var io = SocketIOHelper.io;
var db = require('./libs/core/database.js');
require('./libs/core/session.js')(app, db, io);

var multiRouterSocket = require('./libs/core/multiRouterSocket.js');
new multiRouterSocket(io, __dirname + '/routes-socket').populateRoutes();

// auto create and use routes
var multiRouter = require('./libs/core/multiRouter.js');
new multiRouter(app, __dirname + '/routes').populateRoutes();

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

// development error handler
// will print stack trace
if (app.get('env') === 'development') {
  app.use(function (err, req, res, next) {
    res.status(err.status || 500);

    if (req.path && req.path.indexOf('api') >= 0) {
      res.json(
        {
          message: err.message,
          errors: [err.stack]
        }
      );
    }
    else {
      res.render('admin-lte/error', {
        message: err.message,
        error: err
      });
    }
  });
}

// production error handler
// no stack traces leaked to user
app.use(function (err, req, res, next) {
  res.status(err.status || 500);
  if (req.path && req.path.indexOf('api') >= 0) {
    res.json(
      {
        message: err.message,
        error: {}
      }
    );
  }
  else
    res.render('error', {
      message: err.message,
      error: {}
    });
});

module.exports = server;
<|endoftext|>


<commit_before>var express = require('express');
var exphbs  = require('express-handlebars');
var productList = require('./productList');
var products = require('./mostSolditems');
var getCategory = require('./category');
var mostSolditems = require('./leastpopular');
var listprod = require('./leastpopularproduct');
var Mostpopular = require('./SoldProduct');
var Mostcategory = require('./Mostcategory');
var app = express();

app.engine('handlebars', exphbs({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');

app.get('/', function (req, res) {
    res.render('sisonke');
});

app.get('/List', function (req, res) {
    var productName = productList.linesInFiles('./Nelisa Sales History.csv');
    res.render('productList', {product: productName});

});

app.get('/mostSolditems', function (req, res) {
  var productName =  products.productsSold('./Nelisa Sales History.csv');
  res.render('leastpopular', {product: productName});

});

 app.get('/category', function (req, res) {
   var productName = getCategory.popularProduct('./Nelisa Sales History.csv');
   res.render('category', {product: productName});
 });

 app.get('/leastpopCat', function (req, res) {
  var productName = mostSolditems.popularProduct('./Nelisa Sales History.csv');
  res.render('leastpopular', {product: productName});
 });

 app.get('/leastpopProd', function (req, res) {
  var productName = listprod.productsSold('./Nelisa Sales History.csv');
  res.render('leastpopularproduct', {product: productName});
 });

 app.get('/Mostpopular', function (req, res) {
   var productName = Mostpopular.popularProduct('./Nelisa Sales History.csv');
   res.render('SoldProduct', {product: productName});
 });

 app.get('/Mostcategory', function (req, res) {
  var productName = Mostcategory.findPopularProduct('./Nelisa Sales History.csv');
  res.render('mostcategory', {product: productName});

 });
//start the server
   var server = app.listen(3000, function () {

     var host = server.address().address;
     var port = server.address().port;

     console.log('Example app listening at http://%s:%s', host, port);

   });<commit_msg>app.js changes<commit_after>var express = require('express');
var exphbs  = require('express-handlebars');
var productList = require('./productList');
var products = require('./mostSolditems');
var getCategory = require('./category');
var mostSolditems = require('./leastpopular');
var listprod = require('./leastpopularproduct');
var Mostpopular = require('./SoldProduct');
var Mostcategory = require('./Mostcategory');
var app = express();

app.engine('handlebars', exphbs({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');

app.get('/', function (req, res) {
    res.render('sisonke');
});

app.get('/List', function (req, res) {
    var productName = productList.linesInFiles('./Nelisa Sales History.csv');
    res.render('productList', {product: productName});

});

app.get('/mostSolditems', function (req, res) {
  var productName =  products.productsSold('./Nelisa Sales History.csv');
  res.render('leastpopular', {product: productName});

});

 app.get('/category', function (req, res) {
   var productName = getCategory.popularProduct('./Nelisa Sales History.csv');
   res.render('category', {product: productName});
 });

 app.get('/leastpopCat', function (req, res) {
  var productName = mostSolditems.popularProduct('./Nelisa Sales History.csv');
  res.render('leastpopular', {product: productName});
 });

 app.get('/leastpopProd', function (req, res) {
  var productName = listprod.productsSold('./Nelisa Sales History.csv');
  res.render('leastpopularproduct', {product: productName});
 });

 app.get('/Mostpopular', function (req, res) {
   var productName = Mostpopular.popularProduct('./Nelisa Sales History.csv');
   res.render('SoldProduct', {product: productName});
 });

 app.get('/Mostcategory', function (req, res) {
  var productName = Mostcategory.findPopularProduct('./Nelisa Sales History.csv');
  res.render('mostcategory', {product: productName});

 });
//start the server
var port = process.env.PORT || 3000;
   var server = app.listen(port, function () {

     var host = server.address().address;
     var port = server.address().port;

     console.log('Example app listening at http://%s:%s', host, port);

   });<|endoftext|>


<commit_before>var config = require('./config.js');
var ip = config.ip;
var port = config.port;
var express = require('express');
var app = express();
var server = app.listen(port);
var ejs = require('ejs');
var bbcode = require('bbcode');
var io = require('socket.io').listen(server);
io.set('log level', 1);
var sys = require('sys')
var exec = require('child_process').exec;

app.set("view options", {layout: false});
app.use(express.json());
app.use(express.static(__dirname + '/public'));

process.on('SIGINT', function() {
  console.log( "\nShutting down from manual SIGINT (Ctrl-C), NOW." );
  io.sockets.emit('annouce', {message : 'SHUTTING DOWN, NOW!'});
  process.exit();
});

process.once('SIGUSR2', function () {
  gracefulShutdown(function () {
    process.kill(process.pid, 'SIGUSR2');
  });
});

function gracefulShutdown(kill){
  console.log( "\nShutting down from nodemon SIGUSR2 (RESTART) in 10 seconds..." );
  io.sockets.emit('annouce', {message : 'RESTARTING IN 10 SECONDS!'});
  setTimeout(function(){kill()}, 10000);
}

/* Thanks Reddit
app.post('/gitpull', function(req, res) {
  //GitHub push hook
  res.end();
  if()
  config.secret;
  io.sockets.emit('annouce', {message : 'SYSTEM UPDATE INITIATED...'});
  function puts(error, stdout, stderr) {sys.puts(stdout)}
  exec("git reset --hard HEAD", puts);
  exec("git pull", puts);
  var arr = req.body.commits[0].modified;
  if((arr.join(',').indexOf("app.min.js") > -1) || (arr.join(',').indexOf("app.min.css") > -1) || (arr.join(',').indexOf("index.ejs") > -1)){
    io.sockets.emit('annouce', {message : 'SYSTEM UPDATE COMPLETE, BROWSER RELOAD IS NECCESARY.'});
  } else {
    io.sockets.emit('annouce', {message : 'SYSTEM UPDATE COMPLETE, BROWSER RELOAD IS NOT NECCESARY.'});
  }
});
*/

app.get('*', function(req, res) {
  res.render('index.ejs', {
   ip: ip
 });
});

var users = [];

process.stdin.resume();
process.stdin.setEncoding('utf8');

process.stdin.on('data', function (chunk) {
 io.sockets.emit('annouce', {message : '' + chunk.toUpperCase() + ''});
});

io.sockets.on('connection', function (socket) {
  var name = 'Guest' + Math.floor(100 + Math.random() * 900);

  function broadcast(data) {
    io.sockets.emit('annouce', {message : data});
  }

  function parseServerCommand(data) {
    var res = data.message.trim().split(" ");

    if(res[0].toLowerCase() == "/nick"){
      updateName(res.slice(1,res.length).join(' '));
      return;
    }

    if(res[0].toLowerCase() == "/pm"){
      if(res.length >= 3){
        if(res[1] == 'SERVER'){
          var help = "You cannot PM the server.";
          socket.emit('annouce', {message : help});
          return;
        }
        if(findUser(res[1])){
          pm(res[1], res.slice(2, res.length).join(' '));
          return;
        } else if (findUser(res.slice(1 ,3).join(' '))){
          pm(res.slice(1 ,3).join(' '), res.slice(3, res.length).join(' '));
          return;
        } else {
          var help = "User not found for command '" + res.join(' ') + "'";
          socket.emit('annouce', {message : help});
        }
      } else {
          var help = "You must add a PM message.";
          socket.emit('annouce', {message : help});
      }
    }

    if(res[0].toLowerCase() == "/disconnect"){
      socket.disconnect();
    }

    if(res[0].toLowerCase() == "/help"){
      sendHelp();
      return;
    }

    unrecognized(res[0]);
    sendHelp();
  }

  var entityMap = {
    "&": "&",
    "<": "<",
    ">": ">",
    '"': '"',
    "'": ''',
    "/": '/'
  };

  function escapeHtml(string) {
    return String(string).replace(/[&<>"'\/]/g, function (s) {
      return entityMap[s];
    });
  }

  function removeItem(arr, item) {
    for(var i = arr.length; i--;) {
      if(arr[i][0].toString() === item[0].toString()) {
        arr.splice(i, 1);
      }
    }
  }

  function findUser(user) {
    for(var i = users.length; i--;) {
      if(users[i][0] == user) {
        return true;
      }
    }
    return false;
  }

  function findSocket(user) {
    for(var i = users.length; i--;) {
      if(users[i][0] == user) {
        return users[i][1];
      }
    }
    return 0;
  }

  function pm(dest, data){
    if(dest == name){
      var help = "You cannot PM yourself.";
      socket.emit('annouce', {message : help});
      return;
    }
    data = '<to ' + dest + '> ' + data + '</span';
    io.sockets.socket(findSocket(dest)).emit('broadcast', {client : name, message : data});
    socket.emit('pm', {client : name, message : data});
  }

  function updateName(data){
    data = escapeHtml(data).trim();
    if(findUser(data)){
      socket.emit('annouce', {message : "The nick '" + data + "' is taken!"});
      return;
    }
    if(data.toLowerCase() == "admin" || data.toLowerCase() == "server"){
      socket.emit('annouce', {message : "That nick is reserved!"});
      return;
    }
    if(data.toLowerCase().length > 25){
      socket.emit('annouce', {message : "That nick is too long!"});
      return;
    }
    oldName = name;
    name = escapeHtml(data);
    removeItem(users, [oldName, socket.id]);
    users.push([name, socket.id, true]);
    io.sockets.emit('users', users);
    socket.emit('name', {name : name});
    broadcast('' + oldName + ' has changed name to ' + data + '.');
  }

  function disconnect(data){
    socket.disconnect();
  }

  function unrecognized(data){
    var help = "Unknown command '" + data + "'.";
    socket.emit('annouce', {message : help});
  }

  function sendHelp(){
    var help = "HardOrange IRC Help - Commands:
/nick nick
/pm nick message
/clear
/disconnect
/help";
    socket.emit('annouce', {message : help});
  }

  function multiArrayIndex(arr, item){
    for(var i = 0; i < arr.length; i++) {
      if(arr[i][0].toString() == item[0].toString()) {
          return i;
       }
     }
     return -1;
  }

  //Begin Handlers
  sendHelp();

  socket.on('config', function (data){
    if(data === undefined || data === null || data.name === undefined || data.name === null){
      console.log('Malformed Config Packet');
      return;
    }

    if(data.name != ''){
      if(findUser(data.name)){
        socket.emit('annouce', {message : "The nick '" + data.name + "' is taken!"});
      } else {
        name = escapeHtml(data.name);
      }
    }
    broadcast('' + name + ' has entered chat.');
    users.push([name, socket.id, true]);
    io.sockets.emit('users', users);
    socket.emit('name', {name : name});

    //All Other Handlers

    socket.on('broadcast', function (data) {
      if(data === undefined || data === null || data.message === undefined || data.message === null){
        console.log('Malformed Broadcast Packet');
        return;
      }
      if(data.message[0] == "/") {
        parseServerCommand(data);
      } else {
        bbcode.parse(escapeHtml(data.message), function(content){
          io.sockets.emit('broadcast', {client : name, message : content});
        });
      }
    });

    socket.on('status', function (data) {
      if(data === undefined || data === null || data.status === undefined || data.status === null){
        console.log('Malformed Status Packet');
        return;
      }
      var index = multiArrayIndex(users, [name, socket.id, !data.status]);
      if(index == -1){console.log('missing user: ' + name);return;}
      users[index][2] = data.status;
      io.sockets.emit('users', users);
    });

    socket.on('disconnect', function (data) {
      removeItem(users, [name, socket.id]);
      io.sockets.emit('users', users);
      broadcast('' + name + ' has exited chat.');
    });
  });
});
<commit_msg>Required nick and message limits<commit_after>var config = require('./config.js');
var ip = config.ip;
var port = config.port;
var express = require('express');
var app = express();
var server = app.listen(port);
var ejs = require('ejs');
var bbcode = require('bbcode');
var io = require('socket.io').listen(server);
io.set('log level', 1);
var sys = require('sys')
var exec = require('child_process').exec;

app.set("view options", {layout: false});
app.use(express.json());
app.use(express.static(__dirname + '/public'));

process.on('SIGINT', function() {
  console.log( "\nShutting down from manual SIGINT (Ctrl-C), NOW." );
  io.sockets.emit('annouce', {message : 'SHUTTING DOWN, NOW!'});
  process.exit();
});

process.once('SIGUSR2', function () {
  gracefulShutdown(function () {
    process.kill(process.pid, 'SIGUSR2');
  });
});

function gracefulShutdown(kill){
  console.log( "\nShutting down from nodemon SIGUSR2 (RESTART) in 10 seconds..." );
  io.sockets.emit('annouce', {message : 'RESTARTING IN 10 SECONDS!'});
  setTimeout(function(){kill()}, 10000);
}

/* Thanks Reddit
app.post('/gitpull', function(req, res) {
  //GitHub push hook
  res.end();
  if()
  config.secret;
  io.sockets.emit('annouce', {message : 'SYSTEM UPDATE INITIATED...'});
  function puts(error, stdout, stderr) {sys.puts(stdout)}
  exec("git reset --hard HEAD", puts);
  exec("git pull", puts);
  var arr = req.body.commits[0].modified;
  if((arr.join(',').indexOf("app.min.js") > -1) || (arr.join(',').indexOf("app.min.css") > -1) || (arr.join(',').indexOf("index.ejs") > -1)){
    io.sockets.emit('annouce', {message : 'SYSTEM UPDATE COMPLETE, BROWSER RELOAD IS NECCESARY.'});
  } else {
    io.sockets.emit('annouce', {message : 'SYSTEM UPDATE COMPLETE, BROWSER RELOAD IS NOT NECCESARY.'});
  }
});
*/

app.get('*', function(req, res) {
  res.render('index.ejs', {
   ip: ip
 });
});

var users = [];

process.stdin.resume();
process.stdin.setEncoding('utf8');

process.stdin.on('data', function (chunk) {
 io.sockets.emit('annouce', {message : '' + chunk.toUpperCase() + ''});
});

io.sockets.on('connection', function (socket) {
  var name = 'Guest' + Math.floor(100 + Math.random() * 900);

  function broadcast(data) {
    io.sockets.emit('annouce', {message : data});
  }

  function parseServerCommand(data) {
    var res = data.message.trim().split(" ");

    if(res[0].toLowerCase() == "/nick"){
      updateName(res.slice(1,res.length).join(' '));
      return;
    }

    if(res[0].toLowerCase() == "/pm"){
      if(res.length >= 3){
        if(res[1] == 'SERVER'){
          var help = "You cannot PM the server.";
          socket.emit('annouce', {message : help});
          return;
        }
        if(findUser(res[1])){
          pm(res[1], res.slice(2, res.length).join(' '));
          return;
        } else if (findUser(res.slice(1 ,3).join(' '))){
          pm(res.slice(1 ,3).join(' '), res.slice(3, res.length).join(' '));
          return;
        } else {
          var help = "User not found for command '" + res.join(' ') + "'";
          socket.emit('annouce', {message : help});
        }
      } else {
          var help = "You must add a PM message.";
          socket.emit('annouce', {message : help});
      }
    }

    if(res[0].toLowerCase() == "/disconnect"){
      socket.disconnect();
    }

    if(res[0].toLowerCase() == "/help"){
      sendHelp();
      return;
    }

    unrecognized(res[0]);
    sendHelp();
  }

  var entityMap = {
    "&": "&",
    "<": "<",
    ">": ">",
    '"': '"',
    "'": ''',
    "/": '/'
  };

  function escapeHtml(string) {
    return String(string).replace(/[&<>"'\/]/g, function (s) {
      return entityMap[s];
    });
  }

  function removeItem(arr, item) {
    for(var i = arr.length; i--;) {
      if(arr[i][0].toString() === item[0].toString()) {
        arr.splice(i, 1);
      }
    }
  }

  function findUser(user) {
    for(var i = users.length; i--;) {
      if(users[i][0] == user) {
        return true;
      }
    }
    return false;
  }

  function findSocket(user) {
    for(var i = users.length; i--;) {
      if(users[i][0] == user) {
        return users[i][1];
      }
    }
    return 0;
  }

  function pm(dest, data){
    if(dest == name){
      var help = "You cannot PM yourself.";
      socket.emit('annouce', {message : help});
      return;
    }
    data = '<to ' + dest + '> ' + data + '</span';
    io.sockets.socket(findSocket(dest)).emit('broadcast', {client : name, message : data});
    socket.emit('pm', {client : name, message : data});
  }

  function updateName(data){
    data = escapeHtml(data).trim();
    if(findUser(data)){
      socket.emit('annouce', {message : "The nick '" + data + "' is taken!"});
      return;
    }
    if(data.toLowerCase() == "admin" || data.toLowerCase() == "server"){
      socket.emit('annouce', {message : "That nick is reserved!"});
      return;
    }
    if(data.toLowerCase().length > 25){
      socket.emit('annouce', {message : "That nick is too long!"});
      return;
    }
    if(data.toLowerCase().length == 0){
      socket.emit('annouce', {message : "That nick is too short!"});
      return;
    }
    oldName = name;
    name = escapeHtml(data);
    removeItem(users, [oldName, socket.id]);
    users.push([name, socket.id, true]);
    io.sockets.emit('users', users);
    socket.emit('name', {name : name});
    broadcast('' + oldName + ' has changed name to ' + data + '.');
  }

  function disconnect(data){
    socket.disconnect();
  }

  function unrecognized(data){
    var help = "Unknown command '" + data + "'.";
    socket.emit('annouce', {message : help});
  }

  function sendHelp(){
    var help = "HardOrange IRC Help - Commands:
/nick nick
/pm nick message
/clear
/disconnect
/help";
    socket.emit('annouce', {message : help});
  }

  function multiArrayIndex(arr, item){
    for(var i = 0; i < arr.length; i++) {
      if(arr[i][0].toString() == item[0].toString()) {
          return i;
       }
     }
     return -1;
  }

  //Begin Handlers
  sendHelp();

  socket.on('config', function (data){
    if(data === undefined || data === null || data.name === undefined || data.name === null){
      console.log('Malformed Config Packet');
      return;
    }

    if(data.name != ''){
      if(findUser(data.name)){
        socket.emit('annouce', {message : "The nick '" + data.name + "' is taken!"});
      } else {
        name = escapeHtml(data.name);
      }
    }
    broadcast('' + name + ' has entered chat.');
    users.push([name, socket.id, true]);
    io.sockets.emit('users', users);
    socket.emit('name', {name : name});

    //All Other Handlers

    socket.on('broadcast', function (data) {
      if(data === undefined || data === null || data.message === undefined || data.message === null){
        console.log('Malformed Broadcast Packet');
        return;
      }
      if(data.message.length > 500) {
        var help = "Your message was too long (500 character limit).";
        socket.emit('annouce', {message : help});
        return;
      }
      if(data.message[0] == "/") {
        parseServerCommand(data);
      } else {
        bbcode.parse(escapeHtml(data.message), function(content){
          io.sockets.emit('broadcast', {client : name, message : content});
        });
      }
    });

    socket.on('status', function (data) {
      if(data === undefined || data === null || data.status === undefined || data.status === null){
        console.log('Malformed Status Packet');
        return;
      }
      var index = multiArrayIndex(users, [name, socket.id, !data.status]);
      if(index == -1){console.log('missing user: ' + name);return;}
      users[index][2] = data.status;
      io.sockets.emit('users', users);
    });

    socket.on('disconnect', function (data) {
      removeItem(users, [name, socket.id]);
      io.sockets.emit('users', users);
      broadcast('' + name + ' has exited chat.');
    });
  });
});
<|endoftext|>


<commit_before>var irc = require("irc"),
    colors = require("colors");

var logger = require("./lib/log.js"),
    irc = require("./lib/irc.js");
var config = require("./config/config.js");

//tests
logger.log(config.name);

var recps = [];
var mail = [];

irc.event.on("msg", function(from, to, msg) {
    logger.log("from: " + from + ", to: " + to + ", msg: " + msg);
    if (recps.indexOf(from) != -1) {
        logger.log("user is in pending mail array");
        mail.some(function(value) {
            logger.log("nick: " + value["nick"] + ", sender: " + value["sender"] + ", msg: " + value["msg"]);
            if (recps.indexOf(value["nick"]) != -1) {
                irc.client.say(value["nick"], "Message from " + value["sender"] + ": " + value["msg"]);
            }
        });
    }

    if (msg.toLowerCase().indexOf("penguin") != -1) {
        irc.client.say(to, "ALL HAIL THE OVERLORDS");
    } else if (msg.indexOf("!") == 0) {
        if (msg.indexOf("tell") == 1) {
            var user = msg.substring(6, msg.indexOf(" ", 6));
            var message = msg.substring(msg.indexOf(" ", 6), msg.length);
            recps.push(user);
            mail.push({"nick": user, "sender": from, "msg": message});
            irc.client.say(from, "I'll pass that on when " + user + " is around.");
        }
    }
});
<commit_msg>Mail is now actually REMOVED from the array o.o<commit_after>var irc = require("irc"),
    colors = require("colors");

var logger = require("./lib/log.js"),
    irc = require("./lib/irc.js");
var config = require("./config/config.js");

//tests
logger.log(config.name);

var recps = [];
var mail = [];

irc.event.on("msg", function(from, to, msg) {
    logger.log("from: " + from + ", to: " + to + ", msg: " + msg);
    if (recps.indexOf(from) != -1) {
        logger.log("user is in pending mail array");
        mail.some(function(value, index) {
            logger.log("nick: " + value["nick"] + ", sender: " + value["sender"] + ", msg: " + value["msg"]);
            if (recps.indexOf(value["nick"]) != -1) {
                irc.client.say(value["nick"], "Message from " + value["sender"] + ": " + value["msg"]);
                recps.splice(recps.indexOf(value["nick"], value["nick"].length));
                mail.splice(index, 1);
            }
        });
    }

    if (msg.toLowerCase().indexOf("penguin") != -1) {
        irc.client.say(to, "ALL HAIL THE OVERLORDS");
    } else if (msg.indexOf("!") == 0) {
        if (msg.indexOf("tell") == 1) {
            var user = msg.substring(6, msg.indexOf(" ", 6));
            var message = msg.substring(msg.indexOf(" ", 6), msg.length);
            recps.push(user);
            mail.push({"nick": user, "sender": from, "msg": message});
            irc.client.say(from, "I'll pass that on when " + user + " is around.");
        }
    }
});
<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var TaskProvider = require('./taskprovider-mongoose').TaskProvider;

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.bodyParser());
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

var ROOT = '/todo';

var taskProvider = new TaskProvider('localhost', 27017);

app.get(ROOT, function(req, res) {
    taskProvider.findAll(function(error, docs) {
        res.render('index.jade', {
            title: 'Shared TODO',
            tasks: docs
            });
    });
});

app.get(ROOT + '/list', function(req, res) {
    taskProvider.findAll(function(err, docs) {
        res.json({tasks: docs});
    });
});

app.post(ROOT, function(req, res) {
   taskProvider.save({
        content: req.body.content,
        isCompleted: false,
        owner: 'John Doe',
        due_date: new Date()
    }, function(err, task) {
        taskProvider.findAll(function(err, tasks) {
           res.json(tasks);
        });
    });
/*  taskProvider.save({
        content: req.param('task_content'),
        isCompleted: false,
        owner: 'John Doe',
        due_date: new Date()
    }, function(error, docs) {
        res.redirect(ROOT);
    });
*/
});

app.del(ROOT + '/:todo_id', function(req, res) {
    taskProvider.remove(req.params["todo_id"], function(err, tasks) {
        if (err)
            res.send(error);

        taskProvider.findAll(function(err, tasks) {
            res.json(tasks);
        });
    });
});

app.put(ROOT + '/:todo_id', function(req, res) {
    taskProvider.completeTask(req.params["todo_id"], function(err, tasks) {
        if (err)
            res.send(error);

        taskProvider.findAll(function(err, tasks) {
            res.json(tasks);
        });
    });
});

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});
<commit_msg>Refactoring: using a closure in order to re-use the logic of getting all tasks<commit_after>
/**
 * Module dependencies.
 */

var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var TaskProvider = require('./taskprovider-mongoose').TaskProvider;

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.bodyParser());
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

var ROOT = '/todo';

var taskProvider = new TaskProvider('localhost', 27017);

app.get(ROOT, function(req, res) {
    taskProvider.findAll(function(error, docs) {
        res.render('index.jade', {
            title: 'Shared TODO',
            tasks: docs
            });
    });
});

var sendAllTasks = function(res) {
    return function(err) {
        if (err) res.send(err);
        taskProvider.findAll(function(err, tasks) {
            if (err) res.send(err);
            res.json(tasks);
        });
    };
};

app.get(ROOT + '/list', function(req, res) {
    taskProvider.findAll(function(err, docs) {
        res.json({tasks: docs});
    });
});

app.post(ROOT, function(req, res) {
   taskProvider.save({
        content: req.body.content,
        isCompleted: false,
        owner: 'John Doe',
        due_date: new Date()
    }, sendAllTasks(res));
/*  taskProvider.save({
        content: req.param('task_content'),
        isCompleted: false,
        owner: 'John Doe',
        due_date: new Date()
    }, function(error, docs) {
        res.redirect(ROOT);
    });
*/
});

app.del(ROOT + '/:todo_id', function(req, res) {
    taskProvider.remove(req.params["todo_id"], sendAllTasks(res));
});

app.put(ROOT + '/:todo_id', function(req, res) {
    taskProvider.completeTask(req.params["todo_id"], sendAllTasks(res));
});

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