<commit_before>var falcor = require('falcor'),
    FalcorServer = require('falcor-express'),
    bodyParser = require('body-parser'),
    express = require('express'),
    Router = require('falcor-router'),
    app = express(),
    data = {
        names: [
            {name: 'a'},
            {name: 'b'},
            {name: 'c'}
        ]
    },
    NamesRouter = Router.createClass([
        {
            route: 'names[{integers:nameIndexes}]["name"]',
            get: (pathSet) => {
                var results = [];
                pathSet.nameIndexes.forEach(function(nameIndex) {
                    if (data.names.length > nameIndex) {
                        results.push({
                            path: ['names', nameIndex, pathSet[2]],
                            value: data.names[nameIndex].name
                        })
                    }
                })
                return results
            }
        },
        {
            route: 'names.length',
            get: () => {
                return {path: ['names', 'length'], value: data.names.length}
            }
        },
        {
            route: 'names.add',
            call: (callPath, args) => {
                var newName = args[0];

                data.names.push({name: newName})

                return [
                    {
                        path: ['names', data.names.length-1, 'name'],
                        value: newName
                    },
                    {
                        path: ['names', 'length'],
                        value: data.names.length
                    }
                ]
            }
        }
    ])

app.use(bodyParser.urlencoded({extended: false}));
app.use('/model.json', FalcorServer.dataSourceRoute(() => new NamesRouter()))
app.use(express.static('.'))
app.listen(9090, (err) => {
    if (err) {
        console.error(err)
        return
    }
    console.log('navigate to http://localhost:9090')
});<commit_msg>remove redundant server-side dep<commit_after>var FalcorServer = require('falcor-express'),
    bodyParser = require('body-parser'),
    express = require('express'),
    Router = require('falcor-router'),
    app = express(),
    data = {
        names: [
            {name: 'a'},
            {name: 'b'},
            {name: 'c'}
        ]
    },
    NamesRouter = Router.createClass([
        {
            route: 'names[{integers:nameIndexes}]["name"]',
            get: (pathSet) => {
                var results = [];
                pathSet.nameIndexes.forEach(function(nameIndex) {
                    if (data.names.length > nameIndex) {
                        results.push({
                            path: ['names', nameIndex, pathSet[2]],
                            value: data.names[nameIndex].name
                        })
                    }
                })
                return results
            }
        },
        {
            route: 'names.length',
            get: () => {
                return {path: ['names', 'length'], value: data.names.length}
            }
        },
        {
            route: 'names.add',
            call: (callPath, args) => {
                var newName = args[0];

                data.names.push({name: newName})

                return [
                    {
                        path: ['names', data.names.length-1, 'name'],
                        value: newName
                    },
                    {
                        path: ['names', 'length'],
                        value: data.names.length
                    }
                ]
            }
        }
    ])

app.use(bodyParser.urlencoded({extended: false}));
app.use('/model.json', FalcorServer.dataSourceRoute(() => new NamesRouter()))
app.use(express.static('.'))
app.listen(9090, (err) => {
    if (err) {
        console.error(err)
        return
    }
    console.log('navigate to http://localhost:9090')
});
<|endoftext|>


<commit_before>var Game = {
    stage: undefined,
    gameLayer: undefined,
    planets: [],
    Game: this,
    currentPlayerGroupID: undefined,
    colors: ['gray', 'green', 'yellow'],
    selectedPlanet: undefined,
    proxy: undefined,
    canvasIsDrawn: undefined,
    gameIsOver: undefined,
    conqueringShips: 50,
    percentageLabel: undefined,
    selectedPlanetIDs: [],
    Init: function () {
        Game.proxy = new GameHub('GameHub', jok.config.sid, jok.config.channel);
        Game.proxy.on('Online', this.Online.bind(this));
        Game.proxy.on('Offline', this.Offline.bind(this));
        Game.proxy.on('PlayerMove', this.PlayerMove.bind(this));
        Game.proxy.on('TableState', this.TableState.bind(this));
        Game.proxy.on('UpdatePlanetsState', this.UpdatePlanetsState.bind(this));
        Game.proxy.on('UserAuthenticated', this.UserAuthenticated.bind(this));
        Game.proxy.on('Close', this.Close.bind(this));
        Game.proxy.start();
    },

    // Server Callbacks ----------------------------------------
    Online: function () {
        console.log('server is online');
    },

    Offline: function () {
        console.log('server is offline');
    },

    PlayerMove: function (userid, fromObject, toObject, shipsCount, animationDuration) {

    },

    TableState: function (table) {

        table.players.forEach(function (player) {
            console.log(player.GroupID);
            if (player.UserID == jok.currentUserID) {
                Game.currentPlayerGroupID = player.GroupID;
            }
        });
        switch (table.Status) {
            case 0:
                console.log('joined');
                $('#Notification > .item').hide();
                $('#Notification > .item.waiting_opponent').show();
                jok.setPlayer(1, jok.currentUserID);
                $('#StarWarsImage').removeClass('minimized');
                $('#container').hide();
                break;
            case 1:
                var opponent = (table.players[0].UserID == jok.currentUserID) ? table.players[1].UserID : table.players[0].UserID;
                jok.setPlayer(1, jok.currentUserID);
                jok.setPlayer(2, opponent);
                $('#Notification > .item').hide();
                this.DrawPlanets(table.Planets);
                $('#StarWarsImage').addClass('minimized');
                $('#container').show();
                break;
            case 3:
                Game.gameIsOver = true;
                $('#Notification > .item').hide();
                $('#Notification > .item.table_finish_winner > span').html(jok.players[table.LastWinner].nick);
                $('#Notification > .item.table_finish_winner').show();
                $('#StarWarsImage').removeClass('minimized');
                $('#container').hide();
                break;
        }
    },

    UserAuthenticated: function (userid) {
        jok.currentUserID = userid;
    },

    DrawPlanets: function (remotePlanets) {
        if (Game.canvasIsDrawn != undefined) {
            return;
        }
        Game.canvasIsDrawn = true;
        this.stage = new Kinetic.Stage({
            container: 'container',
            width: 800,
            height: 600,
        });
        this.gameLayer = new Kinetic.Layer();
        this.gameLayer.clear();
        remotePlanets.forEach(function (planet) {
            var circle = new Kinetic.Circle({
                x: planet.X,
                y: planet.Y,
                radius: planet.Radius,
                fill: Game.colors[planet.GroupID],
            });
            circle.Text = new Kinetic.Text({
                text: planet.ShipCount.toString(),
                fontSize: 14,
                fontFamily: 'Calibri',
                fill: 'black'
            });
            circle.Text.setX(circle.getX() - circle.Text.getWidth() / 2);
            circle.Text.setY(circle.getY() - circle.Text.getHeight() / 2);
            circle.Text;
            circle.ShipCount = planet.ShipCount;
            circle.GroupID = planet.GroupID;
            circle.ID = planet.ID;
            circle.RemoveSelection = function () {
                this.setStroke(null);
                Game.selectedPlanet = undefined;
                Game.gameLayer.draw();
            }
            circle.OnMouseOver = function () {
                circle.setOpacity(0.7);
                Game.gameLayer.draw();
            }
            circle.OnMouseOut = function () {
                circle.setOpacity(1);
                Game.gameLayer.draw();
            }
            circle.OnClick = function (e) {
                if (Game.gameIsOver != undefined && Game.gameIsOver) {
                    return;
                }
                if (e.which == 1) {
                    if (Game.selectedPlanetIDs.indexOf(this.ID) != -1) {
                        while (Game.selectedPlanetIDs.indexOf(this.ID) > -1) {
                            this.RemoveSelection();
                            Game.selectedPlanetIDs.splice(Game.selectedPlanetIDs.indexOf(this.ID), 1);
                        }
                        return;
                    }

                    if (this.GroupID != Game.currentPlayerGroupID) {
                        Game.proxy.send('move', Game.selectedPlanetIDs, this.ID, Game.conqueringShips);
                        Game.planets.forEach(function (planet) {
                            planet.setStroke(null);
                        });
                        Game.selectedPlanetIDs = [];
                        return;
                    }

                    Game.selectedPlanetIDs.push(this.ID);
                    this.setStroke('red');
                    Game.gameLayer.draw();
                }
                else if (e.which == 3) {
                    Game.proxy.send('move', Game.selectedPlanetIDs, this.ID, Game.conqueringShips);
                    Game.planets.forEach(function (planet) {
                        planet.setStroke(null);
                    });
                    Game.selectedPlanetIDs = [];
                }
            };
            circle.on('mouseover', function () {
                circle.OnMouseOver();
            });
            circle.Text.on('mouseover', function () {
                circle.OnMouseOver();
            });
            circle.on('mouseout', function () {
                circle.OnMouseOut();
            });
            circle.on('click tap', function (e) {
                circle.OnClick(e);
            });
            circle.Text.on('click tap', function (e) {
                circle.OnClick(e);
            });
            Game.planets.push(circle);
            Game.gameLayer.add(circle);
            Game.gameLayer.add(circle.Text);
        });

        $("#Game").on('mousewheel', function (event) {
            if (event.originalEvent.wheelDelta < 0) {
                Game.DecreasePercentage();
            } else {
                Game.IncreasePercentage();
            }
        });
        $("#Game").on('DOMMouseScroll', function (event) {
            if (event.originalEvent.detail > 0) {
                Game.DecreasePercentage();
            } else {
                Game.IncreasePercentage();
            }

        });
        Game.percentageLabel = new Kinetic.Text({
            fontSize: 30,
            fontFamily: 'Calibri',
            fill: 'black',
            text: Game.conqueringShips + '%',
            x: 20,
            y: 20
        });
        Game.gameLayer.add(Game.percentageLabel);
        Game.stage.add(Game.gameLayer);
        Game.stage.draw();
    },

    IncreasePercentage: function () {
        Game.conqueringShips = Math.min(100, Game.conqueringShips + 5);
        Game.UpdatePercentage();
    },
    DecreasePercentage: function () {
        Game.conqueringShips = Math.max(10, Game.conqueringShips - 5);
        Game.UpdatePercentage();
    },
    UpdatePercentage: function () {
        Game.percentageLabel.setText(Game.conqueringShips + '%');
        Game.gameLayer.draw();
    },
    UpdatePlanetsState: function (remotePlanets) {
        //console.log(remotePlanets);
        Game.planets.forEach(function (planet) {
            for (var i = 0; i < remotePlanets.length; i++) {
                if (remotePlanets[i].ID == planet.ID) {
                    planet.ShipCount = remotePlanets[i].ShipCount;
                    planet.GroupID = remotePlanets[i].GroupID;
                    planet.Text.setText(planet.ShipCount.toString());
                    planet.Text.setX(planet.getX() - planet.Text.getWidth() / 2);
                    planet.Text.setY(planet.getY() - planet.Text.getHeight() / 2);
                    planet.setFill(Game.colors[planet.GroupID]);
                }
            }
            Game.gameLayer.draw();
        });
    },

    Close: function (reason) {
        $('#Notification > .item').hide();
        $('#Notification > .item.quit > span').html(reason);
        $('#Notification > .item.quit').show();
        $('#Game').hide();
        jok.setPlayer(1, null);
        jok.setPlayer(2, null);
    }
}
Game.Init();
<commit_msg>Close #22<commit_after>var Game = {
    stage: undefined,
    gameLayer: undefined,
    planets: [],
    Game: this,
    currentPlayerGroupID: undefined,
    colors: ['gray', 'green', 'yellow'],
    selectedPlanet: undefined,
    proxy: undefined,
    canvasIsDrawn: undefined,
    gameIsOver: undefined,
    conqueringShips: 50,
    percentageLabel: undefined,
    selectedPlanetIDs: [],
    Init: function () {
        Game.proxy = new GameHub('GameHub', jok.config.sid, jok.config.channel);
        Game.proxy.on('Online', this.Online.bind(this));
        Game.proxy.on('Offline', this.Offline.bind(this));
        Game.proxy.on('PlayerMove', this.PlayerMove.bind(this));
        Game.proxy.on('TableState', this.TableState.bind(this));
        Game.proxy.on('UpdatePlanetsState', this.UpdatePlanetsState.bind(this));
        Game.proxy.on('UserAuthenticated', this.UserAuthenticated.bind(this));
        Game.proxy.on('Close', this.Close.bind(this));
        Game.proxy.start();
    },

    // Server Callbacks ----------------------------------------
    Online: function () {
        console.log('server is online');
    },

    Offline: function () {
        console.log('server is offline');
    },

    PlayerMove: function (userid, fromObject, toObject, shipsCount, animationDuration) {

    },

    TableState: function (table) {

        table.players.forEach(function (player) {
            console.log(player.GroupID);
            if (player.UserID == jok.currentUserID) {
                Game.currentPlayerGroupID = player.GroupID;
            }
        });
        switch (table.Status) {
            case 0:
                console.log('joined');
                $('#Notification > .item').hide();
                $('#Notification > .item.waiting_opponent').show();
                jok.setPlayer(1, jok.currentUserID);
                $('#StarWarsImage').removeClass('minimized');
                $('#container').hide();
                break;
            case 1:
                var opponent = (table.players[0].UserID == jok.currentUserID) ? table.players[1].UserID : table.players[0].UserID;
                jok.setPlayer(1, jok.currentUserID);
                jok.setPlayer(2, opponent);
                $('#Notification > .item').hide();
                this.DrawPlanets(table.Planets);
                $('#StarWarsImage').addClass('minimized');
                $('#container').show();
                break;
            case 3:
                Game.gameIsOver = true;
                $('#Notification > .item').hide();
                $('#Notification > .item.table_finish_winner > span').html(jok.players[table.LastWinner].nick);
                $('#Notification > .item.table_finish_winner').show();
                $('#StarWarsImage').removeClass('minimized');
                $('#container').hide();
                break;
        }
    },

    UserAuthenticated: function (userid) {
        jok.currentUserID = userid;
    },

    DrawPlanets: function (remotePlanets) {
        if (Game.canvasIsDrawn != undefined) {
            return;
        }
        Game.canvasIsDrawn = true;
        this.stage = new Kinetic.Stage({
            container: 'container',
            width: 800,
            height: 600,
        });
        this.gameLayer = new Kinetic.Layer();
        this.gameLayer.clear();
        remotePlanets.forEach(function (planet) {
            var circle = new Kinetic.Circle({
                x: planet.X,
                y: planet.Y,
                radius: planet.Radius,
                fill: Game.colors[planet.GroupID],
            });
            circle.Text = new Kinetic.Text({
                text: planet.ShipCount.toString(),
                fontSize: 14,
                fontFamily: 'Calibri',
                fill: 'black'
            });
            circle.Text.setX(circle.getX() - circle.Text.getWidth() / 2);
            circle.Text.setY(circle.getY() - circle.Text.getHeight() / 2);
            circle.Text;
            circle.ShipCount = planet.ShipCount;
            circle.GroupID = planet.GroupID;
            circle.ID = planet.ID;
            circle.RemoveSelection = function () {
                this.setStroke(null);
                Game.selectedPlanet = undefined;
                Game.gameLayer.draw();
            }
            circle.OnMouseOver = function () {
                circle.setOpacity(0.7);
                Game.gameLayer.draw();
            }
            circle.OnMouseOut = function () {
                circle.setOpacity(1);
                Game.gameLayer.draw();
            }
            circle.OnClick = function (e) {
                if (Game.gameIsOver != undefined && Game.gameIsOver) {
                    return;
                }
                if (e.which == 1) {
                    if (Game.selectedPlanetIDs.indexOf(this.ID) != -1) {
                        while (Game.selectedPlanetIDs.indexOf(this.ID) > -1) {
                            this.RemoveSelection();
                            Game.selectedPlanetIDs.splice(Game.selectedPlanetIDs.indexOf(this.ID), 1);
                        }
                        return;
                    }

                    if (this.GroupID != Game.currentPlayerGroupID) {
                        Game.proxy.send('move', Game.selectedPlanetIDs, this.ID, Game.conqueringShips);
                        Game.planets.forEach(function (planet) {
                            planet.setStroke(null);
                        });
                        Game.selectedPlanetIDs = [];
                        return;
                    }

                    Game.selectedPlanetIDs.push(this.ID);
                    this.setStroke('red');
                    Game.gameLayer.draw();
                }
                else if (e.which == 3) {
                    Game.proxy.send('move', Game.selectedPlanetIDs, this.ID, Game.conqueringShips);
                    Game.planets.forEach(function (planet) {
                        planet.setStroke(null);
                    });
                    Game.selectedPlanetIDs = [];
                }
            };

            circle.on('mouseover', function () {
                circle.OnMouseOver();
            });
            circle.Text.on('mouseover', function () {
                circle.OnMouseOver();
            });
            circle.on('mouseout', function () {
                circle.OnMouseOut();
            });
            circle.on('click tap', function (e) {
                circle.OnClick(e);
            });
            circle.Text.on('click tap', function (e) {
                circle.OnClick(e);
            });
            Game.planets.push(circle);
            Game.gameLayer.add(circle);
            Game.gameLayer.add(circle.Text);
        });

        $("#Game").on('mousewheel', function (event) {
            if (event.originalEvent.wheelDelta < 0) {
                Game.DecreasePercentage();
            } else {
                Game.IncreasePercentage();
            }
        });
        $("#Game").on('DOMMouseScroll', function (event) {
            if (event.originalEvent.detail > 0) {
                Game.DecreasePercentage();
            } else {
                Game.IncreasePercentage();
            }

        });
        Game.percentageLabel = new Kinetic.Text({
            fontSize: 30,
            fontFamily: 'Calibri',
            fill: 'black',
            text: Game.conqueringShips + '%',
            x: 20,
            y: 20
        });
        Game.gameLayer.add(Game.percentageLabel);
        Game.stage.add(Game.gameLayer);
        Game.stage.draw();
    },

    IncreasePercentage: function () {
        Game.conqueringShips = Math.min(100, Game.conqueringShips + 5);
        Game.UpdatePercentage();
    },
    DecreasePercentage: function () {
        Game.conqueringShips = Math.max(10, Game.conqueringShips - 5);
        Game.UpdatePercentage();
    },
    UpdatePercentage: function () {
        Game.percentageLabel.setText(Game.conqueringShips + '%');
        Game.gameLayer.draw();
    },
    UpdatePlanetsState: function (remotePlanets) {
        //console.log(remotePlanets);
        Game.planets.forEach(function (planet) {
            for (var i = 0; i < remotePlanets.length; i++) {
                if (remotePlanets[i].ID == planet.ID) {
                    planet.ShipCount = remotePlanets[i].ShipCount;
                    planet.GroupID = remotePlanets[i].GroupID;
                    planet.Text.setText(planet.ShipCount.toString());
                    planet.Text.setX(planet.getX() - planet.Text.getWidth() / 2);
                    planet.Text.setY(planet.getY() - planet.Text.getHeight() / 2);
                    planet.setFill(Game.colors[planet.GroupID]);
                }
            }
            Game.gameLayer.draw();
        });
    },

    Close: function (reason) {
        $('#Notification > .item').hide();
        $('#Notification > .item.quit > span').html(reason);
        $('#Notification > .item.quit').show();
        $('#Game').hide();
        jok.setPlayer(1, null);
        jok.setPlayer(2, null);
    }
}
Game.Init();
<|endoftext|>


<commit_before>/*jshint node: true*/
/**
 * @author lattmann / https://github.com/lattmann
 * @author pmeijer / https://github.com/pmeijer
 */

var path = require('path'),
    config = {
        addOn: {
            enable: false,
            basePaths: [path.join(__dirname, '../src/addon/core')]
        },

        authentication: {
            enable: false,
            allowGuests: false,
            guestAccount: 'anonymous',
            logOutUrl: '/',
            salts: 10
        },

        blob: {
            type: 'FS', //'FS', 'S3'
            fsDir: './blob-local-storage',
            s3: {}
        },

        client: {
            appDir: path.join(__dirname, '../src/client'),
            log: {
                level: 'debug' // To see log messages in the browser inspector set:
                               // localStorage.debug = '*' (or 'gme*', 'gme:core*')
            },
            // Used in client/WebGME.js to load initial project.
            defaultProject: {
                name: null,
                branch: null,
                node: null
            }
        },

        debug: false,

        executor: {
            enable: false,
            nonce: null,
            outputDir: './',
            workerRefreshInterval: 5000
        },

        log: {
            level: 1, // 5 = ALL, 4 = DEBUG, 3 = INFO, 2 = WARNING, 1 = ERROR, 0 = OFF
            file: 'server.log'
        },

        mongo: {
            uri: 'mongodb://127.0.0.1:27017/multi',
            options: {
                db: {
                    w: 1,
                    native_parser: true
                },
                server: {
                    auto_reconnect: true,
                    socketOptions: {keepAlive: 1},
                    poolSize: 20
                }
            }
        },

        plugin: {
            allowServerExecution: false,
            basePaths: [path.join(__dirname, '../src/plugin/coreplugins')]
        },

        requirejsPaths: {},

        rest: {
            secure: false,
            components: {}
        },

        server: {
            port: 8888,
            maxWorkers: 10,
            sessionCookieId: 'webgmeSid',
            sessionCookieSecret: 'meWebGMEez',
            log: {
                transports: [{
                    transportType: 'Console',
                    //patterns: ['gme:server:*', '-gme:server:worker*'], // ['gme:server:worker:*'], ['gme:server:*', '-gme:server:worker*']
                    options: {
                        level: 'info',
                        colorize: true,
                        timestamp: true,
                        prettyPrint: true,
                        depth: 2
                    }
                }, {
                    transportType: 'File',
                    options: {
                        name: 'info-file',
                        filename: './server.log',
                        level: 'info'
                    }
                }, {
                    transportType: 'File',
                    options: {
                        name: 'error-file',
                        filename: './server-error.log',
                        level: 'error',
                        handleExceptions: true
                    }
                }]
            },
            https: {
                enable: false,
                certificateFile: path.join(__dirname, '../certificates/sample-cert.pem'),
                keyFile: path.join(__dirname, '../certificates/sample-key.pem')
            }
        },

        socketIO: {
            reconnect: false,
            'connect timeout': 10,
            'reconnection delay': 1,
            'force new connection': true,
            transports: ['websocket']
        },

        storage: {
            autoPersist: true, // core setting
            cache: 2000,
            clientCacheSize: 2000, // overwrites cache on client
            keyType: 'plainSHA1', // 'rand160Bits', 'ZSSHA', 'plainSHA1',
            failSafe: 'memory',
            failSafeFrequency: 10000,
            timeout: 10000
        },

        visualization: {
            decoratorPaths: [path.join(__dirname, '../src/client/decorators')],
            visualizerDescriptors: [path.join(__dirname, '../src/client/js/Visualizers.json')]
        }
    };

module.exports = config;
<commit_msg>WIP log to files in a human readable format instead of json.<commit_after>/*jshint node: true*/
/**
 * @author lattmann / https://github.com/lattmann
 * @author pmeijer / https://github.com/pmeijer
 */

var path = require('path'),
    config = {
        addOn: {
            enable: false,
            basePaths: [path.join(__dirname, '../src/addon/core')]
        },

        authentication: {
            enable: false,
            allowGuests: false,
            guestAccount: 'anonymous',
            logOutUrl: '/',
            salts: 10
        },

        blob: {
            type: 'FS', //'FS', 'S3'
            fsDir: './blob-local-storage',
            s3: {}
        },

        client: {
            appDir: path.join(__dirname, '../src/client'),
            log: {
                level: 'debug' // To see log messages in the browser inspector set:
                               // localStorage.debug = '*' (or 'gme*', 'gme:core*')
            },
            // Used in client/WebGME.js to load initial project.
            defaultProject: {
                name: null,
                branch: null,
                node: null
            }
        },

        debug: false,

        executor: {
            enable: false,
            nonce: null,
            outputDir: './',
            workerRefreshInterval: 5000
        },

        log: {
            level: 1, // 5 = ALL, 4 = DEBUG, 3 = INFO, 2 = WARNING, 1 = ERROR, 0 = OFF
            file: 'server.log'
        },

        mongo: {
            uri: 'mongodb://127.0.0.1:27017/multi',
            options: {
                db: {
                    w: 1,
                    native_parser: true
                },
                server: {
                    auto_reconnect: true,
                    socketOptions: {keepAlive: 1},
                    poolSize: 20
                }
            }
        },

        plugin: {
            allowServerExecution: false,
            basePaths: [path.join(__dirname, '../src/plugin/coreplugins')]
        },

        requirejsPaths: {},

        rest: {
            secure: false,
            components: {}
        },

        server: {
            port: 8888,
            maxWorkers: 10,
            sessionCookieId: 'webgmeSid',
            sessionCookieSecret: 'meWebGMEez',
            log: {
                transports: [{
                    transportType: 'Console',
                    //patterns: ['gme:server:*', '-gme:server:worker*'], // ['gme:server:worker:*'], ['gme:server:*', '-gme:server:worker*']
                    options: {
                        level: 'info',
                        colorize: true,
                        timestamp: true,
                        prettyPrint: true,
                        depth: 2
                    }
                }, {
                    transportType: 'File',
                    options: {
                        name: 'info-file',
                        filename: './server.log',
                        level: 'info',
                        json: false
                    }
                }, {
                    transportType: 'File',
                    options: {
                        name: 'error-file',
                        filename: './server-error.log',
                        level: 'error',
                        handleExceptions: true,
                        json: false
                    }
                }]
            },
            https: {
                enable: false,
                certificateFile: path.join(__dirname, '../certificates/sample-cert.pem'),
                keyFile: path.join(__dirname, '../certificates/sample-key.pem')
            }
        },

        socketIO: {
            reconnect: false,
            'connect timeout': 10,
            'reconnection delay': 1,
            'force new connection': true,
            transports: ['websocket']
        },

        storage: {
            autoPersist: true, // core setting
            cache: 2000,
            clientCacheSize: 2000, // overwrites cache on client
            keyType: 'plainSHA1', // 'rand160Bits', 'ZSSHA', 'plainSHA1',
            failSafe: 'memory',
            failSafeFrequency: 10000,
            timeout: 10000
        },

        visualization: {
            decoratorPaths: [path.join(__dirname, '../src/client/decorators')],
            visualizerDescriptors: [path.join(__dirname, '../src/client/js/Visualizers.json')]
        }
    };

module.exports = config;
<|endoftext|>


<commit_before>import * as macro  from '../../../macro';
import vtkPolyData from '../../../Common/DataModel/PolyData';

/* global window */

// ----------------------------------------------------------------------------
// vtkSphereSource methods
// ----------------------------------------------------------------------------

export function vtkSphereSource(publicAPI, model) {
  // Set our className
  model.classHierarchy.push('vtkSphereSource');

  function requestData(inData, outData) {
    if (model.deleted) {
      return;
    }

    let dataset = outData[0];
    if (!dataset || dataset.mtime !== model.mtime) {
      const state = {};
      dataset = {
        type: 'vtkPolyData',
        mtime: model.mtime,
        metadata: {
          source: 'SphereSource',
          state,
        },
        vtkPolyData: {
          Points: {
            type: 'vtkDataArray',
            name: '_points',
            numberOfComponents: 3,
            dataType: model.pointType,
          },
          Polys: {
            type: 'vtkDataArray',
            name: '_polys',
            numberOfComponents: 1,
            dataType: 'Uint32Array',
          },
          PointData: {
            Normals: {
              type: 'vtkDataArray',
              name: 'Normals',
              numberOfComponents: 3,
              dataType: 'Float32Array',
            },
          },
        },
      };

      // Add parameter used to create dataset as metadata.state[*]
      ['radius', 'latLongTessellation', 'thetaResolution', 'startTheta', 'endTheta', 'phiResolution', 'startPhi', 'endPhi'].forEach((field) => {
        state[field] = model[field];
      });
      ['center'].forEach((field) => {
        state[field] = [].concat(model[field]);
      });

      // ----------------------------------------------------------------------
      let numPoles = 0;

      // Check data, determine increments, and convert to radians
      let thetaResolution = model.thetaResolution;
      let startTheta = (model.startTheta < model.endTheta ? model.startTheta : model.endTheta);
      startTheta *= Math.PI / 180.0;
      let endTheta = (model.endTheta > model.startTheta ? model.endTheta : model.startTheta);
      endTheta *= Math.PI / 180.0;

      let startPhi = (model.startPhi < model.endPhi ? model.startPhi : model.endPhi);
      startPhi *= Math.PI / 180.0;
      let endPhi = (model.endPhi > model.startPhi ? model.endPhi : model.startPhi);
      endPhi *= Math.PI / 180.0;

      if (Math.abs(startTheta - endTheta) < 2.0 * Math.PI) {
        ++thetaResolution;
      }
      const deltaTheta = (endTheta - startTheta) / model.thetaResolution;

      const jStart = (model.startPhi <= 0.0 ? 1 : 0);
      const jEnd = model.phiResolution + (model.endPhi >= 180.0 ? -1 : 0);

      const numPts = (model.phiResolution * thetaResolution) + 2;
      const numPolys = model.phiResolution * 2 * model.thetaResolution;

      // Points
      let pointIdx = 0;
      let points = new window[dataset.vtkPolyData.Points.dataType](numPts * 3);
      dataset.vtkPolyData.Points.values = points;
      dataset.vtkPolyData.Points.size = numPts * 3;

      // Normals
      let normals = new Float32Array(numPts * 3);
      dataset.vtkPolyData.PointData.Normals.values = normals;
      dataset.vtkPolyData.PointData.Normals.size = numPts * 3;

      // Cells
      let cellLocation = 0;
      let polys = new window[dataset.vtkPolyData.Polys.dataType](numPolys * 5); // FIXME array size
      dataset.vtkPolyData.Polys.values = polys;

      // Create north pole if needed
      if (model.startPhi <= 0.0) {
        points[(pointIdx * 3) + 0] = model.center[0];
        points[(pointIdx * 3) + 1] = model.center[1];
        points[(pointIdx * 3) + 2] = model.center[2] + model.radius;

        normals[(pointIdx * 3) + 0] = 0;
        normals[(pointIdx * 3) + 1] = 0;
        normals[(pointIdx * 3) + 2] = 1;

        pointIdx++;
        numPoles++;
      }

      // Create south pole if needed
      if (model.endPhi >= 180.0) {
        points[(pointIdx * 3) + 0] = model.center[0];
        points[(pointIdx * 3) + 1] = model.center[1];
        points[(pointIdx * 3) + 2] = model.center[2] - model.radius;

        normals[(pointIdx * 3) + 0] = 0;
        normals[(pointIdx * 3) + 1] = 0;
        normals[(pointIdx * 3) + 2] = -1;

        pointIdx++;
        numPoles++;
      }

      const phiResolution = model.phiResolution - numPoles;
      const deltaPhi = (endPhi - startPhi) / (model.phiResolution - 1);

      // Create intermediate points
      for (let i = 0; i < thetaResolution; i++) {
        const theta = startTheta + (i * deltaTheta);
        for (let j = jStart; j < jEnd; j++) {
          const phi = startPhi + (j * deltaPhi);
          const radius = model.radius * Math.sin(phi);

          normals[(pointIdx * 3) + 0] = radius * Math.cos(theta);
          normals[(pointIdx * 3) + 1] = radius * Math.sin(theta);
          normals[(pointIdx * 3) + 2] = model.radius * Math.cos(phi);

          points[(pointIdx * 3) + 0] = normals[(pointIdx * 3) + 0] + model.center[0];
          points[(pointIdx * 3) + 1] = normals[(pointIdx * 3) + 1] + model.center[1];
          points[(pointIdx * 3) + 2] = normals[(pointIdx * 3) + 2] + model.center[2];

          let norm = Math.sqrt(
            (normals[(pointIdx * 3) + 0] * normals[(pointIdx * 3) + 0]) +
            (normals[(pointIdx * 3) + 1] * normals[(pointIdx * 3) + 1]) +
            (normals[(pointIdx * 3) + 2] * normals[(pointIdx * 3) + 2]));

          norm = (norm === 0) ? 1 : norm;
          normals[(pointIdx * 3) + 0] /= norm;
          normals[(pointIdx * 3) + 1] /= norm;
          normals[(pointIdx * 3) + 2] /= norm;

          pointIdx++;
        }
      }

      // Generate mesh connectivity
      const base = phiResolution * thetaResolution;

      if (Math.abs(startTheta - endTheta) < 2.0 * Math.PI) {
        --thetaResolution;
      }

      // around north pole
      if (model.startPhi <= 0.0) {
        for (let i = 0; i < thetaResolution; i++) {
          polys[cellLocation++] = 3;
          polys[cellLocation++] = (phiResolution * i) + numPoles;
          polys[cellLocation++] = (phiResolution * (i + 1) % base) + numPoles;
          polys[cellLocation++] = 0;
        }
      }

      // around south pole
      if (model.endPhi >= 180.0) {
        const numOffset = phiResolution - 1 + numPoles;

        for (let i = 0; i < thetaResolution; i++) {
          polys[cellLocation++] = 3;
          polys[cellLocation++] = (phiResolution * i) + numOffset;
          polys[cellLocation++] = numPoles - 1;
          polys[cellLocation++] = ((phiResolution * (i + 1)) % base) + numOffset;
        }
      }

      // bands in-between poles
      for (let i = 0; i < thetaResolution; i++) {
        for (let j = 0; j < (phiResolution - 1); j++) {
          const a = (phiResolution * i) + j + numPoles;
          const b = a + 1;
          const c = (((phiResolution * (i + 1)) + j) % base) + numPoles + 1;

          if (!model.latLongTessellation) {
            polys[cellLocation++] = 3;
            polys[cellLocation++] = a;
            polys[cellLocation++] = b;
            polys[cellLocation++] = c;
            polys[cellLocation++] = 3;
            polys[cellLocation++] = a;
            polys[cellLocation++] = c;
            polys[cellLocation++] = c - 1;
          } else {
            polys[cellLocation++] = 4;
            polys[cellLocation++] = a;
            polys[cellLocation++] = b;
            polys[cellLocation++] = c;
            polys[cellLocation++] = c - 1;
          }
        }
      }

      // Squeeze
      points = points.subarray(0, pointIdx * 3);
      dataset.vtkPolyData.Points.values = points;
      dataset.vtkPolyData.Points.size = pointIdx * 3;

      normals = normals.subarray(0, pointIdx * 3);
      dataset.vtkPolyData.PointData.Normals.values = normals;
      dataset.vtkPolyData.PointData.Normals.size = pointIdx * 3;

      polys = polys.subarray(0, cellLocation);
      dataset.vtkPolyData.Polys.values = polys;
      dataset.vtkPolyData.Polys.size = cellLocation;

      // Update output
      outData[0] = vtkPolyData.newInstance(dataset);
      outData[0].getPointData().setActiveNormals('Normals');
    }
  }

  // Expose methods
  publicAPI.requestData = requestData;
}

// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------

const DEFAULT_VALUES = {
  radius: 0.5,
  latLongTessellation: false,
  thetaResolution: 8,
  startTheta: 0.0,
  endTheta: 360.0,
  phiResolution: 8,
  startPhi: 0.0,
  endPhi: 180.0,
  center: [0, 0, 0],
  pointType: 'Float32Array',
};

// ----------------------------------------------------------------------------

export function extend(publicAPI, model, initialValues = {}) {
  Object.assign(model, DEFAULT_VALUES, initialValues);

  // Build VTK API
  macro.obj(publicAPI, model);
  macro.setGet(publicAPI, model, [
    'radius',
    'latLongTessellation',
    'thetaResolution',
    'startTheta',
    'endTheta',
    'phiResolution',
    'startPhi',
    'endPhi',
  ]);
  macro.setGetArray(publicAPI, model, ['center'], 3);
  macro.algo(publicAPI, model, 0, 1);
  vtkSphereSource(publicAPI, model);
}

// ----------------------------------------------------------------------------

export const newInstance = macro.newInstance(extend);

// ----------------------------------------------------------------------------

export default { newInstance, extend };
<commit_msg>fix(SphereSource): Fix issue with new vtkPoints structure<commit_after>import * as macro  from '../../../macro';
import vtkPolyData from '../../../Common/DataModel/PolyData';
import vtkPoints from '../../../Common/Core/Points';
import vtkDataArray from '../../../Common/Core/DataArray';

// ----------------------------------------------------------------------------
// vtkSphereSource methods
// ----------------------------------------------------------------------------

export function vtkSphereSource(publicAPI, model) {
  // Set our className
  model.classHierarchy.push('vtkSphereSource');

  function requestData(inData, outData) {
    if (model.deleted) {
      return;
    }

    let dataset = outData[0];
    const pointDataType = dataset ? dataset.getPoints().getData().getDataType() : 'Float32Array';
    if (!dataset || dataset.getMTime() !== model.mtime) {
      dataset = vtkPolyData.newInstance();

      // ----------------------------------------------------------------------
      let numPoles = 0;

      // Check data, determine increments, and convert to radians
      let thetaResolution = model.thetaResolution;
      let startTheta = (model.startTheta < model.endTheta ? model.startTheta : model.endTheta);
      startTheta *= Math.PI / 180.0;
      let endTheta = (model.endTheta > model.startTheta ? model.endTheta : model.startTheta);
      endTheta *= Math.PI / 180.0;

      let startPhi = (model.startPhi < model.endPhi ? model.startPhi : model.endPhi);
      startPhi *= Math.PI / 180.0;
      let endPhi = (model.endPhi > model.startPhi ? model.endPhi : model.startPhi);
      endPhi *= Math.PI / 180.0;

      if (Math.abs(startTheta - endTheta) < 2.0 * Math.PI) {
        ++thetaResolution;
      }
      const deltaTheta = (endTheta - startTheta) / model.thetaResolution;

      const jStart = (model.startPhi <= 0.0 ? 1 : 0);
      const jEnd = model.phiResolution + (model.endPhi >= 180.0 ? -1 : 0);

      const numPts = (model.phiResolution * thetaResolution) + 2;
      const numPolys = model.phiResolution * 2 * model.thetaResolution;

      // Points
      let pointIdx = 0;
      let points = new window[pointDataType](numPts * 3);

      // Normals
      let normals = new Float32Array(numPts * 3);

      // Cells
      let cellLocation = 0;
      let polys = new Uint32Array(numPolys * 5); // FIXME array size

      // Create north pole if needed
      if (model.startPhi <= 0.0) {
        points[(pointIdx * 3) + 0] = model.center[0];
        points[(pointIdx * 3) + 1] = model.center[1];
        points[(pointIdx * 3) + 2] = model.center[2] + model.radius;

        normals[(pointIdx * 3) + 0] = 0;
        normals[(pointIdx * 3) + 1] = 0;
        normals[(pointIdx * 3) + 2] = 1;

        pointIdx++;
        numPoles++;
      }

      // Create south pole if needed
      if (model.endPhi >= 180.0) {
        points[(pointIdx * 3) + 0] = model.center[0];
        points[(pointIdx * 3) + 1] = model.center[1];
        points[(pointIdx * 3) + 2] = model.center[2] - model.radius;

        normals[(pointIdx * 3) + 0] = 0;
        normals[(pointIdx * 3) + 1] = 0;
        normals[(pointIdx * 3) + 2] = -1;

        pointIdx++;
        numPoles++;
      }

      const phiResolution = model.phiResolution - numPoles;
      const deltaPhi = (endPhi - startPhi) / (model.phiResolution - 1);

      // Create intermediate points
      for (let i = 0; i < thetaResolution; i++) {
        const theta = startTheta + (i * deltaTheta);
        for (let j = jStart; j < jEnd; j++) {
          const phi = startPhi + (j * deltaPhi);
          const radius = model.radius * Math.sin(phi);

          normals[(pointIdx * 3) + 0] = radius * Math.cos(theta);
          normals[(pointIdx * 3) + 1] = radius * Math.sin(theta);
          normals[(pointIdx * 3) + 2] = model.radius * Math.cos(phi);

          points[(pointIdx * 3) + 0] = normals[(pointIdx * 3) + 0] + model.center[0];
          points[(pointIdx * 3) + 1] = normals[(pointIdx * 3) + 1] + model.center[1];
          points[(pointIdx * 3) + 2] = normals[(pointIdx * 3) + 2] + model.center[2];

          let norm = Math.sqrt(
            (normals[(pointIdx * 3) + 0] * normals[(pointIdx * 3) + 0]) +
            (normals[(pointIdx * 3) + 1] * normals[(pointIdx * 3) + 1]) +
            (normals[(pointIdx * 3) + 2] * normals[(pointIdx * 3) + 2]));

          norm = (norm === 0) ? 1 : norm;
          normals[(pointIdx * 3) + 0] /= norm;
          normals[(pointIdx * 3) + 1] /= norm;
          normals[(pointIdx * 3) + 2] /= norm;

          pointIdx++;
        }
      }

      // Generate mesh connectivity
      const base = phiResolution * thetaResolution;

      if (Math.abs(startTheta - endTheta) < 2.0 * Math.PI) {
        --thetaResolution;
      }

      // around north pole
      if (model.startPhi <= 0.0) {
        for (let i = 0; i < thetaResolution; i++) {
          polys[cellLocation++] = 3;
          polys[cellLocation++] = (phiResolution * i) + numPoles;
          polys[cellLocation++] = (phiResolution * (i + 1) % base) + numPoles;
          polys[cellLocation++] = 0;
        }
      }

      // around south pole
      if (model.endPhi >= 180.0) {
        const numOffset = phiResolution - 1 + numPoles;

        for (let i = 0; i < thetaResolution; i++) {
          polys[cellLocation++] = 3;
          polys[cellLocation++] = (phiResolution * i) + numOffset;
          polys[cellLocation++] = numPoles - 1;
          polys[cellLocation++] = ((phiResolution * (i + 1)) % base) + numOffset;
        }
      }

      // bands in-between poles
      for (let i = 0; i < thetaResolution; i++) {
        for (let j = 0; j < (phiResolution - 1); j++) {
          const a = (phiResolution * i) + j + numPoles;
          const b = a + 1;
          const c = (((phiResolution * (i + 1)) + j) % base) + numPoles + 1;

          if (!model.latLongTessellation) {
            polys[cellLocation++] = 3;
            polys[cellLocation++] = a;
            polys[cellLocation++] = b;
            polys[cellLocation++] = c;
            polys[cellLocation++] = 3;
            polys[cellLocation++] = a;
            polys[cellLocation++] = c;
            polys[cellLocation++] = c - 1;
          } else {
            polys[cellLocation++] = 4;
            polys[cellLocation++] = a;
            polys[cellLocation++] = b;
            polys[cellLocation++] = c;
            polys[cellLocation++] = c - 1;
          }
        }
      }

      // Squeeze
      points = points.subarray(0, pointIdx * 3);
      const pointsArray = vtkDataArray.newInstance({ values: points, numberOfComponents: 3 });
      dataset.getPoints().setData(pointsArray);

      normals = normals.subarray(0, pointIdx * 3);
      const normalArray = vtkDataArray.newInstance({ name: 'Normals', values: normals, numberOfComponents: 3 });
      dataset.getPointData().addArray(normalArray);

      polys = polys.subarray(0, cellLocation);
      const polysArray = vtkDataArray.newInstance({ name: '_polys', values: polys });
      dataset.setPolys(polysArray);

      // Update output
      outData[0] = dataset;
      outData[0].getPointData().setActiveNormals('Normals');
    }
  }

  // Expose methods
  publicAPI.requestData = requestData;
}

// ----------------------------------------------------------------------------
// Object factory
// ----------------------------------------------------------------------------

const DEFAULT_VALUES = {
  radius: 0.5,
  latLongTessellation: false,
  thetaResolution: 8,
  startTheta: 0.0,
  endTheta: 360.0,
  phiResolution: 8,
  startPhi: 0.0,
  endPhi: 180.0,
  center: [0, 0, 0],
  pointType: 'Float32Array',
};

// ----------------------------------------------------------------------------

export function extend(publicAPI, model, initialValues = {}) {
  Object.assign(model, DEFAULT_VALUES, initialValues);

  // Build VTK API
  macro.obj(publicAPI, model);
  macro.setGet(publicAPI, model, [
    'radius',
    'latLongTessellation',
    'thetaResolution',
    'startTheta',
    'endTheta',
    'phiResolution',
    'startPhi',
    'endPhi',
  ]);
  macro.setGetArray(publicAPI, model, ['center'], 3);
  macro.algo(publicAPI, model, 0, 1);
  vtkSphereSource(publicAPI, model);
}

// ----------------------------------------------------------------------------

export const newInstance = macro.newInstance(extend);

// ----------------------------------------------------------------------------

export default { newInstance, extend };
<|endoftext|>


<commit_before>(function($, obviel) {
    // enter key
    var KEYCODE = 13;

    var _ = obviel.i18n.translate();

    // the application model
    var todos = {
        iface: 'todos',
        items: []
    };

    // a clear function removing a todo from the application
    var clear = function(todo) {
        for (var i = 0; i < todos.items.length; i++) {
            if (todos.items[i] === todo) {
                todos.items.splice(i, 1);
                break;
            }
        }
    };

    // create a special stats model from the todos
    var get_stats = function(todos) {
        var remaining = 0;
        var done = 0;
        var amount = 0;
        $.each(todos.items, function(index, todo) {
            if (todo.done) {
                done += 1;
            } else {
                remaining += 1;
            }
            amount += 1;
        });
        return {iface: 'stats', remaining: remaining, done: done,
                amount: amount};
    };

    // a view for the whole todos application
    obviel.view({
        iface: 'todos',
        obvt_script: 'obvt-todos',
        object_events: {
            update: 'rerender',
            update_stats: 'update_stats'
        },
        render: function() {
            $('#new-todo', this.el).focus();
            this.update_stats();
        },
        update_stats: function() {
            var stats = get_stats(this.obj);
            if (stats.amount) {
                $('#toggle-all', this.el).get(0).checked = !stats.remaining;
                $('footer', this.el).render(stats);
                $('footer', this.el).show();
            } else {
                $('footer', this.el).hide();
            }
        },
        create_on_enter: function(ev) {
            if (ev.keyCode !== KEYCODE) {
                return;
            }
            var value = $('#new-todo').val();
            if (value === '') {
                return;
            }
            this.obj.items.push({iface: 'todo', done: false, title: value});
            $(this.obj).trigger('update');
        },
        toggle_all: function() {
            var done = $('#toggle-all', this.el).get(0).checked;
            $.each(this.obj.items, function(index, item) {
                item.done = done;
            });
            $(this.obj).trigger('update');
        }
    });

    // a view for the stats
    obviel.view({
        iface: 'stats',
        obvt_script: 'obvt-todo-stats',
        clear_completed: function() {
            var new_items = [];
            $.each(todos.items, function(index, item) {
                if (!item.done) {
                    new_items.push(item);
                }
            });
            todos.items = new_items;
            $(todos).trigger('update');
        }
    });

    // a view for an individual todo item, not editable
    obviel.view({
        iface: 'todo',
        obvt_script: 'obvt-todo',
        object_events: {
            update: 'rerender'
        },
        render: function() {
            if (this.obj.done) {
                this.el.addClass('done');
            } else {
                this.el.removeClass('done');
            }
        },
        edit: function() {
            this.obj.iface = 'todo-editing';
            $(this.obj).trigger('update');
        },
        toggle: function() {
            this.obj.done = !this.obj.done;
            $(this.obj).trigger('update');
            $(todos).trigger('update_stats');
        },
        clear: function() {
            clear(this.obj);
            $(todos).trigger('update');
        }
    });

    // a view for an editable todo item
    obviel.view({
        iface: 'todo-editing',
        obvt_script: 'obvt-todo-editing',
        object_events: {
            update: 'rerender'
        },
        render: function() {
            $('input.edit', this.el).focus();
        },
        update_on_enter: function(ev) {
            if (ev.keyCode === KEYCODE) {
                this.close();
            }
        },
        close: function() {
            var value = $('input.edit', this.el).val();
            if (!value) {
                clear(this.obj);
                $(todos).trigger('update');
                return;
            }
            this.obj.title = value;
            this.obj.iface = 'todo';
            $(this.obj).trigger('update');
        }
    });

    // when the document is ready, load up languages & render the app model
    $(document).ready(function() {
        obviel.i18n.load().done(function() {
            obviel.i18n.set_locale('nl_NL').done(function() {
                $('#todoapp').render(todos);
            });
        });
    });
}(jQuery, obviel));<commit_msg>whitespace.<commit_after>(function($, obviel) {
    // enter key
    var KEYCODE = 13;

    var _ = obviel.i18n.translate();

    // the application model
    var todos = {
        iface: 'todos',
        items: []
    };
    // a clear function removing a todo from the application
    var clear = function(todo) {
        for (var i = 0; i < todos.items.length; i++) {
            if (todos.items[i] === todo) {
                todos.items.splice(i, 1);
                break;
            }
        }
    };

    // create a special stats model from the todos
    var get_stats = function(todos) {
        var remaining = 0;
        var done = 0;
        var amount = 0;
        $.each(todos.items, function(index, todo) {
            if (todo.done) {
                done += 1;
            } else {
                remaining += 1;
            }
            amount += 1;
        });
        return {iface: 'stats', remaining: remaining, done: done,
                amount: amount};
    };

    // a view for the whole todos application
    obviel.view({
        iface: 'todos',
        obvt_script: 'obvt-todos',
        object_events: {
            update: 'rerender',
            update_stats: 'update_stats'
        },
        render: function() {
            $('#new-todo', this.el).focus();
            this.update_stats();
        },
        update_stats: function() {
            var stats = get_stats(this.obj);
            if (stats.amount) {
                $('#toggle-all', this.el).get(0).checked = !stats.remaining;
                $('footer', this.el).render(stats);
                $('footer', this.el).show();
            } else {
                $('footer', this.el).hide();
            }
        },
        create_on_enter: function(ev) {
            if (ev.keyCode !== KEYCODE) {
                return;
            }
            var value = $('#new-todo').val();
            if (value === '') {
                return;
            }
            this.obj.items.push({iface: 'todo', done: false, title: value});
            $(this.obj).trigger('update');
        },
        toggle_all: function() {
            var done = $('#toggle-all', this.el).get(0).checked;
            $.each(this.obj.items, function(index, item) {
                item.done = done;
            });
            $(this.obj).trigger('update');
        }
    });

    // a view for the stats
    obviel.view({
        iface: 'stats',
        obvt_script: 'obvt-todo-stats',
        clear_completed: function() {
            var new_items = [];
            $.each(todos.items, function(index, item) {
                if (!item.done) {
                    new_items.push(item);
                }
            });
            todos.items = new_items;
            $(todos).trigger('update');
        }
    });

    // a view for an individual todo item, not editable
    obviel.view({
        iface: 'todo',
        obvt_script: 'obvt-todo',
        object_events: {
            update: 'rerender'
        },
        render: function() {
            if (this.obj.done) {
                this.el.addClass('done');
            } else {
                this.el.removeClass('done');
            }
        },
        edit: function() {
            this.obj.iface = 'todo-editing';
            $(this.obj).trigger('update');
        },
        toggle: function() {
            this.obj.done = !this.obj.done;
            $(this.obj).trigger('update');
            $(todos).trigger('update_stats');
        },
        clear: function() {
            clear(this.obj);
            $(todos).trigger('update');
        }
    });

    // a view for an editable todo item
    obviel.view({
        iface: 'todo-editing',
        obvt_script: 'obvt-todo-editing',
        object_events: {
            update: 'rerender'
        },
        render: function() {
            $('input.edit', this.el).focus();
        },
        update_on_enter: function(ev) {
            if (ev.keyCode === KEYCODE) {
                this.close();
            }
        },
        close: function() {
            var value = $('input.edit', this.el).val();
            if (!value) {
                clear(this.obj);
                $(todos).trigger('update');
                return;
            }
            this.obj.title = value;
            this.obj.iface = 'todo';
            $(this.obj).trigger('update');
        }
    });

    // when the document is ready, load up languages & render the app model
    $(document).ready(function() {
        obviel.i18n.load().done(function() {
            obviel.i18n.set_locale('nl_NL').done(function() {
                $('#todoapp').render(todos);
            });
        });
    });
}(jQuery, obviel));<|endoftext|>


<commit_before>/**
**  Events to datepicker
*/
function datePickerInit() {
  var options = $.extend(
      {},
      $.datepicker.regional["et"],
      { dateFormat: "d MM, y" }
  );
  $.datepicker.setDefaults(options);

  // $( "#datepicker").datepicker({
  //   beforeShowDay: available,
  //   prevText: '<',
  //   nextText: '>',
  //   weekStart: 1
  // });

var arrEvents = {};
var currentTitle = "";

  $.getJSON('http://kgs-ee.github.io/saal-js/javascripts/campo-json.json', function(response){

    for (var key in response) {
      //console.log(key);
      var keys = key.split("-");
      var d = new Date(keys[0], keys[1] - 1, keys[2]);
      arrEvents[d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate()] = response[key];
      //console.log(d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate());
    }

    //$("#datepicker").html("");
    $("#datepicker").datepicker({
      dateFormat : "yy-mm-dd",
      prevText : '<',
      nextText : '>',
      onChangeMonthYear: function(year, month, inst) {
        // hack default behaviour.
        setTimeout(function(){
          toggleTooltip({show:false});
        }, 0);
      },
      onSelect: function(dateText, inst) {

        //console.log(dateText);
        var parts = dateText.split("-");
        //console.log(parts);
        var clickedDate = new Date(parts[0], parts[1] - 1, parts[2]);
        //var clickedDate = new Date(dateText);
        var dateString = clickedDate.getFullYear() + "-" + (clickedDate.getMonth() + 1) + "-" + clickedDate.getDate();
        var eventsByDate = arrEvents[dateString];
        var urlTo = "";

        if (eventsByDate.length > 1) {
          urlTo = eventsByDate[0].multiUrl;
        } else {
          urlTo = eventsByDate[0].url;
        }
        window.location = urlTo;
      },
      beforeShowDay: function(date) {

        var dateString = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();

        //console.log(dateString);
        //console.log(arrEvents);
        //console.log(arrEvents["2012-9-29"]);
        var eventsByDate = arrEvents[dateString];

        var isClickable = false;
        var extraClass = "";
        var tooltip = null;

        if (eventsByDate) {
          isClickable = true;
          extraClass = "highlight";
          if (eventsByDate.length > 1) {
            extraClass += " multiple"
          }
          tooltip = "
";
          for (var e in eventsByDate) {
            var event = eventsByDate[e];
            /*console.log(event);*/
            extraClass += " " + event.extraClasses;
            var time = (event.time != "00:00") ? (event.time + " uur ") : "";
            tooltip += "
" + time + ": "  + event.name + ((event.short) ? (" - " + event.short) : "") + "
";
            tooltip += "
";
              tooltip += event.name + ((event.short) ? (" - " + event.short) : "") + "
";
              tooltip += event.client + ((event.city) ? (" - " + event.city) : "");
              tooltip += event.name + ((event.short) ? (" - " + event.short) : "") + "
";

            tooltip += "
";
          }
          tooltip += "
";
        }
        return [isClickable, extraClass, tooltip]
      }
    });
  });
}

/**
**  Calendar tooltip
*/
function calToolTip() {
  $('body').tooltip({
    selector: '[data-handler="selectDay"]',
    html: true,
    container: "body",
    placement: "bottom"
  });
}

/**
**  Frontpage slider height
*/
function eventBannerHeight() {
  windowHeight = $(window).height();
  navHeight = $('.navbar-default').outerHeight(true);

  $(".event-banner figure").height(windowHeight - navHeight);
}

/**
**  Programme category dropdown
*/
function categoryDropDown() {
  var options = [];

  $( '.dropdown-menu a' ).on( 'click', function( event ) {

     var $target = $( event.currentTarget ),
         val = $target.attr( 'data-value' ),
         $inp = $target.find( 'input' ),
         idx;

     if ( ( idx = options.indexOf( val ) ) > -1 ) {
        options.splice( idx, 1 );
        setTimeout( function() { $inp.prop( 'checked', false ) }, 0);
     } else {
        options.push( val );
        setTimeout( function() { $inp.prop( 'checked', true ) }, 0);
     }

     $( event.target ).blur();

     console.log( options );
     return false;
  });
}

/**
**  Google Maps
*/
function initMap() {
  var myLatlng = new google.maps.LatLng(59.438552,24.745975);

  var mapOptions = {
    center: myLatlng,
    zoom: 18
  };

  var map = new google.maps.Map(document.getElementById('map'),
  mapOptions);

  var marker = new google.maps.Marker({
      position: myLatlng,
      map: map,
      title: 'Kanuti Gildi Saal'
  });

}

/**
**  Fancybox Gallery
*/
function fancyBoxGallery() {
  $(".fancybox").fancybox({
    padding: 0,
    helpers: {
        overlay: {
          locked: false
        }
      }
  });
}

/**
**  Read More generator
*/
function shortenTexts() {
 $(".main-text").shorten({
   moreText: 'Loe edasi',
   lessText: 'Loe vähem',
   showChars: '1000'
 });
}

$(document).ready(function() {
  datePickerInit();
  calToolTip();
  fancyBoxGallery();
  shortenTexts();
  // eventBannerHeight();
  //initMap();
  categoryDropDown();
});

$(window).load(function() {
    eventBannerHeight();
    calToolTip();
});

$(window).resize(function() {
    eventBannerHeight();
});
<commit_msg>datepicker locale<commit_after>/**
**  Events to datepicker
*/
function datePickerInit() {
  var baseHref = document.getElementsByTagName('base')[0].href;
  var options = $.extend(
      {},
      locale = ((baseHref == '/et/') ? "et" : "en");
      alert(locale);
      $.datepicker.regional["et"],
      { dateFormat: "d MM, y" }
  );
  $.datepicker.setDefaults(options);

  // $( "#datepicker").datepicker({
  //   beforeShowDay: available,
  //   prevText: '<',
  //   nextText: '>',
  //   weekStart: 1
  // });

var arrEvents = {};
var currentTitle = "";

  $.getJSON('http://kgs-ee.github.io/saal-js/javascripts/campo-json.json', function(response){

    for (var key in response) {
      //console.log(key);
      var keys = key.split("-");
      var d = new Date(keys[0], keys[1] - 1, keys[2]);
      arrEvents[d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate()] = response[key];
      //console.log(d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate());
    }

    //$("#datepicker").html("");
    $("#datepicker").datepicker({
      dateFormat : "yy-mm-dd",
      prevText : '<',
      nextText : '>',
      onChangeMonthYear: function(year, month, inst) {
        // hack default behaviour.
        setTimeout(function(){
          toggleTooltip({show:false});
        }, 0);
      },
      onSelect: function(dateText, inst) {

        //console.log(dateText);
        var parts = dateText.split("-");
        //console.log(parts);
        var clickedDate = new Date(parts[0], parts[1] - 1, parts[2]);
        //var clickedDate = new Date(dateText);
        var dateString = clickedDate.getFullYear() + "-" + (clickedDate.getMonth() + 1) + "-" + clickedDate.getDate();
        var eventsByDate = arrEvents[dateString];
        var urlTo = "";

        if (eventsByDate.length > 1) {
          urlTo = eventsByDate[0].multiUrl;
        } else {
          urlTo = eventsByDate[0].url;
        }
        window.location = urlTo;
      },
      beforeShowDay: function(date) {

        var dateString = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();

        //console.log(dateString);
        //console.log(arrEvents);
        //console.log(arrEvents["2012-9-29"]);
        var eventsByDate = arrEvents[dateString];

        var isClickable = false;
        var extraClass = "";
        var tooltip = null;

        if (eventsByDate) {
          isClickable = true;
          extraClass = "highlight";
          if (eventsByDate.length > 1) {
            extraClass += " multiple"
          }
          tooltip = "
";
          for (var e in eventsByDate) {
            var event = eventsByDate[e];
            /*console.log(event);*/
            extraClass += " " + event.extraClasses;
            var time = (event.time != "00:00") ? (event.time + " uur ") : "";
            tooltip += "
" + time + ": "  + event.name + ((event.short) ? (" - " + event.short) : "") + "
";
            tooltip += "
";
              tooltip += event.name + ((event.short) ? (" - " + event.short) : "") + "
";
              tooltip += event.client + ((event.city) ? (" - " + event.city) : "");
              tooltip += event.name + ((event.short) ? (" - " + event.short) : "") + "
";

            tooltip += "
";
          }
          tooltip += "
";
        }
        return [isClickable, extraClass, tooltip]
      }
    });
  });
}

/**
**  Calendar tooltip
*/
function calToolTip() {
  $('body').tooltip({
    selector: '[data-handler="selectDay"]',
    html: true,
    container: "body",
    placement: "bottom"
  });
}

/**
**  Frontpage slider height
*/
function eventBannerHeight() {
  windowHeight = $(window).height();
  navHeight = $('.navbar-default').outerHeight(true);

  $(".event-banner figure").height(windowHeight - navHeight);
}

/**
**  Programme category dropdown
*/
function categoryDropDown() {
  var options = [];

  $( '.dropdown-menu a' ).on( 'click', function( event ) {

     var $target = $( event.currentTarget ),
         val = $target.attr( 'data-value' ),
         $inp = $target.find( 'input' ),
         idx;

     if ( ( idx = options.indexOf( val ) ) > -1 ) {
        options.splice( idx, 1 );
        setTimeout( function() { $inp.prop( 'checked', false ) }, 0);
     } else {
        options.push( val );
        setTimeout( function() { $inp.prop( 'checked', true ) }, 0);
     }

     $( event.target ).blur();

     console.log( options );
     return false;
  });
}

/**
**  Google Maps
*/
function initMap() {
  var myLatlng = new google.maps.LatLng(59.438552,24.745975);

  var mapOptions = {
    center: myLatlng,
    zoom: 18
  };

  var map = new google.maps.Map(document.getElementById('map'),
  mapOptions);

  var marker = new google.maps.Marker({
      position: myLatlng,
      map: map,
      title: 'Kanuti Gildi Saal'
  });

}

/**
**  Fancybox Gallery
*/
function fancyBoxGallery() {
  $(".fancybox").fancybox({
    padding: 0,
    helpers: {
        overlay: {
          locked: false
        }
      }
  });
}

/**
**  Read More generator
*/
function shortenTexts() {
 $(".main-text").shorten({
   moreText: 'Loe edasi',
   lessText: 'Loe vähem',
   showChars: '1000'
 });
}

$(document).ready(function() {
  datePickerInit();
  calToolTip();
  fancyBoxGallery();
  shortenTexts();
  // eventBannerHeight();
  //initMap();
  categoryDropDown();
});

$(window).load(function() {
    eventBannerHeight();
    calToolTip();
});

$(window).resize(function() {
    eventBannerHeight();
});
<|endoftext|>


<commit_before>import webpack from 'webpack';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import ExtractTextPlugin from 'extract-text-webpack-plugin';
import path from 'path';

import ConfigBuilder from '../webpack-utilities/config-builder';
import envParser from '../webpack-utilities/env-parser';

const baseConfig = (environnement, definedVariables) => {

    const parsedEnv = envParser(environnement);

    // Création de la config basique
    const config = new ConfigBuilder();

    config._debugInfo('logEnv', environnement);
    config._debugInfo('logParsedEnv', parsedEnv);

    // Ajout du point d'entrée
    config.addEntry(parsedEnv.ENTRY_FILE_PATH);

    // Ajout des points d'entrée pour le hot reload
    if (parsedEnv.DEV && parsedEnv.HOT_RELOAD) {
        config.addEntry(`webpack-dev-server/client?http://${parsedEnv.DEV_SERVER_HOST}:${parsedEnv.DEV_SERVER_PORT}`);
        config.addEntry('webpack/hot/only-dev-server');
    }

    // Ajout du fichier
    config.setOuputPath(parsedEnv.OUTPUT_DIR, true);
    config.setAssetsPublicPath(parsedEnv.OUTPUT_PUBLIC_PATH);
    config.setFilename(parsedEnv.npm_package_name);
    config.useSourceMaps(parsedEnv.SOURCE_MAPS);

    // Ajout des variables injectées
    config.addDefinedVariable('__DEV__', parsedEnv.DEV ? 'true' : 'false');
    config.addDefinedVariable('__ANCHOR_CLASS__', JSON.stringify(parsedEnv.ANCHOR_CLASS));
    config.addDefinedVariable('__PACKAGE_JSON_PATH__', JSON.stringify(parsedEnv.PACKAGE_JSON_PATH));
    // config.addDefinedVariable('__USER__', JSON.stringify(USER));
    config.addDefinedVariable('__PROJECT__', JSON.stringify(parsedEnv.npm_package_name));
    config.addDefinedVariable('LEGACY_SEARCH_API', JSON.stringify(parsedEnv.LEGACY_SEARCH_API));
    config.addDefinedVariable('process.env.NODE_ENV', JSON.stringify(parsedEnv.NODE_ENV));

    for (let prop in definedVariables) {
        config.addDefinedVariable(prop, definedVariables[prop]);
    }
    // GESTION DES PLUGINS
    // Les fonctions seront résolues au moment de la création de la config webpack.
    config.addPlugin(10, () => new webpack.DefinePlugin(config.getDefinedVariables()));
    config.addPlugin(20, () => new ExtractTextPlugin(config.getCssFilename()));
    // Gestion du HOT_RELOAD
    if (parsedEnv.DEV && parsedEnv.HOT_RELOAD) {
        config.addPlugin(30, new webpack.HotModuleReplacementPlugin());
    }
    // Génération d'un index HTML
    if (parsedEnv.GENERATE_HTML) {
        config.addPlugin(40, env => new HtmlWebpackPlugin({
            inject: 'body',
            templateContent: env.HTML_TEMPLATE(env)
        }));
    }
    // Gestion de la minification
    if (parsedEnv.MINIMIFY) {
        config.addPlugin(50, env => new webpack.optimize.UglifyJsPlugin({
            compressor: {
                screw_ie8: true,
                warnings: false,
                drop_console: env.DROP_CONSOLE,
                drop_debugger: true,
                passes: 2
            }
        }));
    }

    // GESTION DES LOADERS
    // Loader pour les source-map
    if (parsedEnv.SOURCE_MAPS) {
        config.addComplexLoader(10, {
            test: /\.js$/,
            enforce: 'pre',
            exclude: path.resolve(process.cwd(), './node_modules/css-loader'),
            loader: 'source-map-loader'
        });
    }
    // Loader pour Babel (transpile ES6 => ES5, exclude des node_modules, attendus en ES5)
    config.addComplexLoader(20, {
        test: /\.(js|jsx)$/,
        loader: 'babel-loader',
        exclude: path.resolve(process.cwd(), './node_modules'),
        options: {
            presets: ['babel-preset-focus']
        }
    });
    // Loader pour le SASS (Extraction du fichier JS, vers un fichier CSS indépendant, cf plugin)
    // Utilisation de PostCss ajouté
    config.addComplexLoader(30, env => ({
        test: /\.scss$/,
        use: ExtractTextPlugin.extract({
            fallback: 'style-loader',
            use: [
                {
                    loader: 'css-loader',
                    options: {
                        minimize: env.MINIMIFY ? { safe: true, sourcemap: false } : false,
                        sourceMap: false,
                        importLoaders: 1
                    }
                },
                'postcss-loader', // Options should go into postcss.config.js
                'sass-loader'
            ]
        })
    }));
    // Loader pour le CSS (Extraction du fichier JS, vers un fichier CSS indépendant, cf plugin)
    // Utilisation de PostCss ajouté
    config.addComplexLoader(40, env => ({
        test: /\.css$/,
        use: ExtractTextPlugin.extract({
            fallback: 'style-loader',
            use: [
                {
                    loader: 'css-loader',
                    options: {
                        minimize: env.MINIMIFY ? { safe: true, sourcemap: false } : false,
                        sourceMap: false,
                        importLoaders: 1
                    }
                },
                'postcss-loader' // Options should go into postcss.config.js
            ]
        })
    }));
    // Loader pour les ressources externes
    config.addSimpleLoader(50, /\.(png|jpg|jpeg|gif|ttf|eot|woff|woff2|svg)(\?.*)?$/, 'url-loader', {
        limit: 50000,
        name: '[name]_[sha512:hash:base64:7].[ext]'
    });

    return config;
};

export default baseConfig;
<commit_msg>Changing exclude to regex<commit_after>import webpack from 'webpack';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import ExtractTextPlugin from 'extract-text-webpack-plugin';
import path from 'path';

import ConfigBuilder from '../webpack-utilities/config-builder';
import envParser from '../webpack-utilities/env-parser';

const baseConfig = (environnement, definedVariables) => {

    const parsedEnv = envParser(environnement);

    // Création de la config basique
    const config = new ConfigBuilder();

    config._debugInfo('logEnv', environnement);
    config._debugInfo('logParsedEnv', parsedEnv);

    // Ajout du point d'entrée
    config.addEntry(parsedEnv.ENTRY_FILE_PATH);

    // Ajout des points d'entrée pour le hot reload
    if (parsedEnv.DEV && parsedEnv.HOT_RELOAD) {
        config.addEntry(`webpack-dev-server/client?http://${parsedEnv.DEV_SERVER_HOST}:${parsedEnv.DEV_SERVER_PORT}`);
        config.addEntry('webpack/hot/only-dev-server');
    }

    // Ajout du fichier
    config.setOuputPath(parsedEnv.OUTPUT_DIR, true);
    config.setAssetsPublicPath(parsedEnv.OUTPUT_PUBLIC_PATH);
    config.setFilename(parsedEnv.npm_package_name);
    config.useSourceMaps(parsedEnv.SOURCE_MAPS);

    // Ajout des variables injectées
    config.addDefinedVariable('__DEV__', parsedEnv.DEV ? 'true' : 'false');
    config.addDefinedVariable('__ANCHOR_CLASS__', JSON.stringify(parsedEnv.ANCHOR_CLASS));
    config.addDefinedVariable('__PACKAGE_JSON_PATH__', JSON.stringify(parsedEnv.PACKAGE_JSON_PATH));
    // config.addDefinedVariable('__USER__', JSON.stringify(USER));
    config.addDefinedVariable('__PROJECT__', JSON.stringify(parsedEnv.npm_package_name));
    config.addDefinedVariable('LEGACY_SEARCH_API', JSON.stringify(parsedEnv.LEGACY_SEARCH_API));
    config.addDefinedVariable('process.env.NODE_ENV', JSON.stringify(parsedEnv.NODE_ENV));

    for (let prop in definedVariables) {
        config.addDefinedVariable(prop, definedVariables[prop]);
    }
    // GESTION DES PLUGINS
    // Les fonctions seront résolues au moment de la création de la config webpack.
    config.addPlugin(10, () => new webpack.DefinePlugin(config.getDefinedVariables()));
    config.addPlugin(20, () => new ExtractTextPlugin(config.getCssFilename()));
    // Gestion du HOT_RELOAD
    if (parsedEnv.DEV && parsedEnv.HOT_RELOAD) {
        config.addPlugin(30, new webpack.HotModuleReplacementPlugin());
    }
    // Génération d'un index HTML
    if (parsedEnv.GENERATE_HTML) {
        config.addPlugin(40, env => new HtmlWebpackPlugin({
            inject: 'body',
            templateContent: env.HTML_TEMPLATE(env)
        }));
    }
    // Gestion de la minification
    if (parsedEnv.MINIMIFY) {
        config.addPlugin(50, env => new webpack.optimize.UglifyJsPlugin({
            compressor: {
                screw_ie8: true,
                warnings: false,
                drop_console: env.DROP_CONSOLE,
                drop_debugger: true,
                passes: 2
            }
        }));
    }

    // GESTION DES LOADERS
    // Loader pour les source-map
    if (parsedEnv.SOURCE_MAPS) {
        config.addComplexLoader(10, {
            test: /\.js$/,
            enforce: 'pre',
            exclude: /node_modules\/css-loader/,
            loader: 'source-map-loader'
        });
    }
    // Loader pour Babel (transpile ES6 => ES5, exclude des node_modules, attendus en ES5)
    config.addComplexLoader(20, {
        test: /\.(js|jsx)$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        options: {
            presets: ['babel-preset-focus']
        }
    });
    // Loader pour le SASS (Extraction du fichier JS, vers un fichier CSS indépendant, cf plugin)
    // Utilisation de PostCss ajouté
    config.addComplexLoader(30, env => ({
        test: /\.scss$/,
        use: ExtractTextPlugin.extract({
            fallback: 'style-loader',
            use: [
                {
                    loader: 'css-loader',
                    options: {
                        minimize: env.MINIMIFY ? { safe: true, sourcemap: false } : false,
                        sourceMap: false,
                        importLoaders: 1
                    }
                },
                'postcss-loader', // Options should go into postcss.config.js
                'sass-loader'
            ]
        })
    }));
    // Loader pour le CSS (Extraction du fichier JS, vers un fichier CSS indépendant, cf plugin)
    // Utilisation de PostCss ajouté
    config.addComplexLoader(40, env => ({
        test: /\.css$/,
        use: ExtractTextPlugin.extract({
            fallback: 'style-loader',
            use: [
                {
                    loader: 'css-loader',
                    options: {
                        minimize: env.MINIMIFY ? { safe: true, sourcemap: false } : false,
                        sourceMap: false,
                        importLoaders: 1
                    }
                },
                'postcss-loader' // Options should go into postcss.config.js
            ]
        })
    }));
    // Loader pour les ressources externes
    config.addSimpleLoader(50, /\.(png|jpg|jpeg|gif|ttf|eot|woff|woff2|svg)(\?.*)?$/, 'url-loader', {
        limit: 50000,
        name: '[name]_[sha512:hash:base64:7].[ext]'
    });

    return config;
};

export default baseConfig;
<|endoftext|>