<commit_before>var Mode = require('./Mode');

function Tournament() {
    Mode.apply(this, Array.prototype.slice.call(arguments));

    this.ID = 10;
    this.name = "Tournament";
    this.packetLB = 48;

    // Config (1 tick = 1000 ms)
    this.prepTime = 5; // Amount of ticks after the server fills up to wait until starting the game
    this.endTime = 15; // Amount of ticks after someone wins to restart the game
    this.autoFill = false;
    this.autoFillPlayers = 1;
    this.dcTime = 0;

    // Gamemode Specific Variables
    this.gamePhase = 0; // 0 = Waiting for players, 1 = Prepare to start, 2 = Game in progress, 3 = End
    this.contenders = [];
    this.maxContenders = 12;

    this.winner;
    this.timer;
    this.timeLimit = 3600; // in seconds
}

module.exports = Tournament;
Tournament.prototype = new Mode();

// Gamemode Specific Functions

Tournament.prototype.startGamePrep = function(gameServer) {
    this.gamePhase = 1;
    this.timer = this.prepTime; // 10 seconds
};

Tournament.prototype.startGame = function(gameServer) {
    gameServer.run = true;
    this.gamePhase = 2;
    this.getSpectate(); // Gets a random person to spectate
    gameServer.config.playerDisconnectTime = this.dcTime; // Reset config
};

Tournament.prototype.endGame = function(gameServer) {
    this.winner = this.contenders[0];
    this.gamePhase = 3;
    this.timer = this.endTime; // 30 Seconds
};

Tournament.prototype.endGameTimeout = function(gameServer) {
    gameServer.run = false;
    this.gamePhase = 4;
    this.timer = this.endTime; // 30 Seconds
};

Tournament.prototype.fillBots = function(gameServer) {
    // Fills the server with bots if there arent enough players
    var fill = this.maxContenders - this.contenders.length;
    for (var i = 0;i < fill;i++) {
        gameServer.bots.addBot();
    }
};

Tournament.prototype.getSpectate = function() {
    // Finds a random person to spectate
    var index = Math.floor(Math.random() * this.contenders.length);
    this.rankOne = this.contenders[index];
};

Tournament.prototype.prepare = function(gameServer) {
    // Remove all cells
    var len = gameServer.nodes.length;
    for (var i = 0; i < len; i++) {
        var node = gameServer.nodes[0];

        if (!node) {
            continue;
        }

        gameServer.removeNode(node);
    }

    gameServer.bots.loadNames();

    // Pauses the server
    gameServer.run = false;
    this.gamePhase = 0;

    // Get config values
    if (gameServer.config.tourneyAutoFill > 0) {
        this.timer = gameServer.config.tourneyAutoFill;
        this.autoFill = true;
        this.autoFillPlayers = gameServer.config.tourneyAutoFillPlayers;
    }
    // Handles disconnections
    this.dcTime = gameServer.config.playerDisconnectTime;
    gameServer.config.playerDisconnectTime = 0;
    gameServer.config.minMassDecay = gameServer.config.playerStartMass;

    this.prepTime = gameServer.config.tourneyPrepTime;
    this.endTime = gameServer.config.tourneyEndTime;
    this.maxContenders = gameServer.config.tourneyMaxPlayers;

    // Time limit
    this.timeLimit = gameServer.config.tourneyTimeLimit * 60; // in seconds
};

Tournament.prototype.onPlayerDeath = function(gameServer) {
    // Nothing
}

Tournament.prototype.formatTime = function(time) {
    if (time < 0) {
        return "0:00";
    }
    // Format
    var min = Math.floor(this.timeLimit/60);
    var sec = this.timeLimit%60;
    sec = (sec > 9) ? sec : "0" + sec.toString() ;
    return min+":"+sec;
}

// Override

Tournament.prototype.onServerInit = function(gameServer) {
    this.prepare(gameServer);
};

Tournament.prototype.onPlayerSpawn = function(gameServer,player) {
    // Only spawn players if the game hasnt started yet
    if ((this.gamePhase == 0) && (this.contenders.length < this.maxContenders)) {
        player.color = gameServer.getRandomColor(); // Random color
        this.contenders.push(player); // Add to contenders list
        gameServer.spawnPlayer(player);

        if (this.contenders.length == this.maxContenders) {
            // Start the game once there is enough players
            this.startGamePrep(gameServer);
        }
    }
};

Tournament.prototype.onCellRemove = function(cell) {
    var owner = cell.owner,
        human_just_died = false;

    if (owner.cells.length <= 0) {
        // Remove from contenders list
        var index = this.contenders.indexOf(owner);
        if (index != -1) {
            if ('_socket' in this.contenders[index].socket) {
                human_just_died = true;
            }
            this.contenders.splice(index,1);
        }

        // Victory conditions
        var humans = 0;
        for (var i = 0; i < this.contenders.length; i++) {
            if ('_socket' in this.contenders[i].socket) {
                humans++;
            }
        }

        // the game is over if:
        // 1) there is only 1 player left, OR
        // 2) all the humans are dead, OR
        // 3) the last-but-one human just died
        if ((this.contenders.length == 1 || humans == 0 || (humans == 1 && human_just_died)) && this.gamePhase == 2) {
            this.endGame(cell.owner.gameServer);
        } else {
            // Do stuff
            this.onPlayerDeath(cell.owner.gameServer);
        }
    }
};

Tournament.prototype.updateLB = function(gameServer) {
    var lb = gameServer.leaderboard;

    switch (this.gamePhase) {
        case 0:
            lb[0] = "Waiting for";
            lb[1] = "players: ";
            lb[2] = this.contenders.length+"/"+this.maxContenders;
            if (this.autoFill) {
                if (this.timer <= 0) {
                    this.fillBots(gameServer);
                } else if (this.contenders.length >= this.autoFillPlayers) {
                    this.timer--;
                }
            }
            break;
        case 1:
            lb[0] = "Game starting in";
            lb[1] = this.timer.toString();
            lb[2] = "Good luck!";
            if (this.timer <= 0) {
                // Reset the game
                this.startGame(gameServer);
            } else {
                this.timer--;
            }
            break;
        case 2:
            lb[0] = "Players Remaining";
            lb[1] = this.contenders.length+"/"+this.maxContenders;
            lb[2] = "Time Limit:";
            lb[3] = this.formatTime(this.timeLimit);
            if (this.timeLimit < 0) {
                // Timed out
                this.endGameTimeout(gameServer);
            } else {
                this.timeLimit--;
            }
            break;
        case 3:
            lb[0] = "Congratulations";
            lb[1] = this.winner.getName();
            lb[2] = "for winning!";
            if (this.timer <= 0) {
                // Reset the game
                this.onServerInit(gameServer);
                // Respawn starting food
                gameServer.startingFood();
            } else {
                lb[3] = "Game restarting in";
                lb[4] = this.timer.toString();
                this.timer--;
            }
            break;
        case 4:
            lb[0] = "Time Limit";
            lb[1] = "Reached!";
            if (this.timer <= 0) {
                // Reset the game
                this.onServerInit(gameServer);
                // Respawn starting food
                gameServer.startingFood();
            } else {
                lb[2] = "Game restarting in";
                lb[3] = this.timer.toString();
                this.timer--;
            }
        default:
            break;
    }
};

<commit_msg>Fix playerMinMassDecay typo in Tournament<commit_after>var Mode = require('./Mode');

function Tournament() {
    Mode.apply(this, Array.prototype.slice.call(arguments));

    this.ID = 10;
    this.name = "Tournament";
    this.packetLB = 48;

    // Config (1 tick = 1000 ms)
    this.prepTime = 5; // Amount of ticks after the server fills up to wait until starting the game
    this.endTime = 15; // Amount of ticks after someone wins to restart the game
    this.autoFill = false;
    this.autoFillPlayers = 1;
    this.dcTime = 0;

    // Gamemode Specific Variables
    this.gamePhase = 0; // 0 = Waiting for players, 1 = Prepare to start, 2 = Game in progress, 3 = End
    this.contenders = [];
    this.maxContenders = 12;

    this.winner;
    this.timer;
    this.timeLimit = 3600; // in seconds
}

module.exports = Tournament;
Tournament.prototype = new Mode();

// Gamemode Specific Functions

Tournament.prototype.startGamePrep = function(gameServer) {
    this.gamePhase = 1;
    this.timer = this.prepTime; // 10 seconds
};

Tournament.prototype.startGame = function(gameServer) {
    gameServer.run = true;
    this.gamePhase = 2;
    this.getSpectate(); // Gets a random person to spectate
    gameServer.config.playerDisconnectTime = this.dcTime; // Reset config
};

Tournament.prototype.endGame = function(gameServer) {
    this.winner = this.contenders[0];
    this.gamePhase = 3;
    this.timer = this.endTime; // 30 Seconds
};

Tournament.prototype.endGameTimeout = function(gameServer) {
    gameServer.run = false;
    this.gamePhase = 4;
    this.timer = this.endTime; // 30 Seconds
};

Tournament.prototype.fillBots = function(gameServer) {
    // Fills the server with bots if there arent enough players
    var fill = this.maxContenders - this.contenders.length;
    for (var i = 0;i < fill;i++) {
        gameServer.bots.addBot();
    }
};

Tournament.prototype.getSpectate = function() {
    // Finds a random person to spectate
    var index = Math.floor(Math.random() * this.contenders.length);
    this.rankOne = this.contenders[index];
};

Tournament.prototype.prepare = function(gameServer) {
    // Remove all cells
    var len = gameServer.nodes.length;
    for (var i = 0; i < len; i++) {
        var node = gameServer.nodes[0];

        if (!node) {
            continue;
        }

        gameServer.removeNode(node);
    }

    gameServer.bots.loadNames();

    // Pauses the server
    gameServer.run = false;
    this.gamePhase = 0;

    // Get config values
    if (gameServer.config.tourneyAutoFill > 0) {
        this.timer = gameServer.config.tourneyAutoFill;
        this.autoFill = true;
        this.autoFillPlayers = gameServer.config.tourneyAutoFillPlayers;
    }
    // Handles disconnections
    this.dcTime = gameServer.config.playerDisconnectTime;
    gameServer.config.playerDisconnectTime = 0;
    gameServer.config.playerMinMassDecay = gameServer.config.playerStartMass;

    this.prepTime = gameServer.config.tourneyPrepTime;
    this.endTime = gameServer.config.tourneyEndTime;
    this.maxContenders = gameServer.config.tourneyMaxPlayers;

    // Time limit
    this.timeLimit = gameServer.config.tourneyTimeLimit * 60; // in seconds
};

Tournament.prototype.onPlayerDeath = function(gameServer) {
    // Nothing
}

Tournament.prototype.formatTime = function(time) {
    if (time < 0) {
        return "0:00";
    }
    // Format
    var min = Math.floor(this.timeLimit/60);
    var sec = this.timeLimit%60;
    sec = (sec > 9) ? sec : "0" + sec.toString() ;
    return min+":"+sec;
}

// Override

Tournament.prototype.onServerInit = function(gameServer) {
    this.prepare(gameServer);
};

Tournament.prototype.onPlayerSpawn = function(gameServer,player) {
    // Only spawn players if the game hasnt started yet
    if ((this.gamePhase == 0) && (this.contenders.length < this.maxContenders)) {
        player.color = gameServer.getRandomColor(); // Random color
        this.contenders.push(player); // Add to contenders list
        gameServer.spawnPlayer(player);

        if (this.contenders.length == this.maxContenders) {
            // Start the game once there is enough players
            this.startGamePrep(gameServer);
        }
    }
};

Tournament.prototype.onCellRemove = function(cell) {
    var owner = cell.owner,
        human_just_died = false;

    if (owner.cells.length <= 0) {
        // Remove from contenders list
        var index = this.contenders.indexOf(owner);
        if (index != -1) {
            if ('_socket' in this.contenders[index].socket) {
                human_just_died = true;
            }
            this.contenders.splice(index,1);
        }

        // Victory conditions
        var humans = 0;
        for (var i = 0; i < this.contenders.length; i++) {
            if ('_socket' in this.contenders[i].socket) {
                humans++;
            }
        }

        // the game is over if:
        // 1) there is only 1 player left, OR
        // 2) all the humans are dead, OR
        // 3) the last-but-one human just died
        if ((this.contenders.length == 1 || humans == 0 || (humans == 1 && human_just_died)) && this.gamePhase == 2) {
            this.endGame(cell.owner.gameServer);
        } else {
            // Do stuff
            this.onPlayerDeath(cell.owner.gameServer);
        }
    }
};

Tournament.prototype.updateLB = function(gameServer) {
    var lb = gameServer.leaderboard;

    switch (this.gamePhase) {
        case 0:
            lb[0] = "Waiting for";
            lb[1] = "players: ";
            lb[2] = this.contenders.length+"/"+this.maxContenders;
            if (this.autoFill) {
                if (this.timer <= 0) {
                    this.fillBots(gameServer);
                } else if (this.contenders.length >= this.autoFillPlayers) {
                    this.timer--;
                }
            }
            break;
        case 1:
            lb[0] = "Game starting in";
            lb[1] = this.timer.toString();
            lb[2] = "Good luck!";
            if (this.timer <= 0) {
                // Reset the game
                this.startGame(gameServer);
            } else {
                this.timer--;
            }
            break;
        case 2:
            lb[0] = "Players Remaining";
            lb[1] = this.contenders.length+"/"+this.maxContenders;
            lb[2] = "Time Limit:";
            lb[3] = this.formatTime(this.timeLimit);
            if (this.timeLimit < 0) {
                // Timed out
                this.endGameTimeout(gameServer);
            } else {
                this.timeLimit--;
            }
            break;
        case 3:
            lb[0] = "Congratulations";
            lb[1] = this.winner.getName();
            lb[2] = "for winning!";
            if (this.timer <= 0) {
                // Reset the game
                this.onServerInit(gameServer);
                // Respawn starting food
                gameServer.startingFood();
            } else {
                lb[3] = "Game restarting in";
                lb[4] = this.timer.toString();
                this.timer--;
            }
            break;
        case 4:
            lb[0] = "Time Limit";
            lb[1] = "Reached!";
            if (this.timer <= 0) {
                // Reset the game
                this.onServerInit(gameServer);
                // Respawn starting food
                gameServer.startingFood();
            } else {
                lb[2] = "Game restarting in";
                lb[3] = this.timer.toString();
                this.timer--;
            }
        default:
            break;
    }
};

<|endoftext|>


<commit_before>require('../../support/test_helper');

var assert = require('../../support/assert');
var TestClient = require('../../support/test-client');

describe('dataview error cases', function() {

    afterEach(function(done) {
        if (this.testClient) {
            this.testClient.drain(done);
        } else {
            done();
        }
    });

    describe('generic errors', function() {
        var ERROR_RESPONSE = {
            status: 400,
            headers: {
                'Content-Type': 'application/json; charset=utf-8'
            }
        };

        function createMapConfig(dataviews) {
            return {
                version: '1.5.0',
                layers: [
                    {
                        "type": "cartodb",
                        "options": {
                            "source": {
                                "id": "HEAD"
                            },
                            "cartocss": "#points { marker-width: 10; marker-fill: red; }",
                            "cartocss_version": "2.3.0"
                        }
                    }
                ],
                dataviews: dataviews,
                analyses: [
                    {
                        "id": "HEAD",
                        "type": "source",
                        "params": {
                            "query": "select null::geometry the_geom_webmercator, x from generate_series(0,1000) x"
                        }
                    }
                ]
            };
        }

        it('should fail when invalid dataviews object is provided, string case', function(done) {
            var mapConfig = createMapConfig("wadus-string");
            this.testClient = new TestClient(mapConfig, 1234);
            this.testClient.getLayergroup({ response: ERROR_RESPONSE }, function(err, errObj) {
                assert.ok(!err, err);

                assert.deepEqual(errObj.errors, [ '"dataviews" must be a valid JSON object: "string" type found' ]);

                done();
            });
        });

        it('should fail when invalid dataviews object is provided, array case', function(done) {
            var mapConfig = createMapConfig([]);
            this.testClient = new TestClient(mapConfig, 1234);
            this.testClient.getLayergroup({ response: ERROR_RESPONSE }, function(err, errObj) {
                assert.ok(!err, err);

                assert.deepEqual(errObj.errors, [ '"dataviews" must be a valid JSON object: "array" type found' ]);

                done();
            });
        });

        it('should work with empty but valid objects', function(done) {
            var mapConfig = createMapConfig({});
            this.testClient = new TestClient(mapConfig, 1234);
            this.testClient.getLayergroup(function(err, layergroup) {
                assert.ok(!err, err);

                assert.ok(layergroup);
                assert.ok(layergroup.layergroupid);

                done();
            });
        });
    });

    describe('pg_typeof', function() {

        afterEach(function(done) {
            if (this.testClient) {
                this.testClient.drain(done);
            } else {
                done();
            }
        });

        function createMapConfig(query) {
            query = query || 'select * from populated_places_simple_reduced';

            return {
                version: '1.5.0',
                layers: [
                    {
                        type: 'mapnik',
                        options: {
                            sql: query,
                            cartocss: '#layer0 { marker-fill: red; marker-width: 10; }',
                            cartocss_version: '2.0.1',
                            source: { id: "a0" }
                        }
                    }
                ],
                analyses: [{
                    id: "a0",
                    type: "source",
                    params: {
                        query: query
                    }
                }],
                dataviews:  {
                    aggregation_count_dataview: {
                        type: "aggregation",
                        source: { id: "a0" },
                        options: {
                            column: "adm0name",
                            aggregation: "count",
                            aggregationColumn: "adm0name"
                        }
                    },

                    formula_count_dataview: {
                        type: 'formula',
                        source: { id: "a0" },
                        options: {
                            column: 'adm0_a3',
                            operation: 'count'
                        }
                    },
                }
            };
        }

        it('should work without filters', function(done) {
            this.testClient = new TestClient(createMapConfig());
            this.testClient.getDataview('aggregation_count_dataview', { own_filter: 0 }, function(err, result) {
                assert.ifError(err);
                done();
            });
        });

        it('should work with filters', function(done) {
            var params = {
                filters: {
                    dataviews: {aggregation_count_dataview: {accept: ['Canada']}}
                }
            };

            this.testClient = new TestClient(createMapConfig());
            this.testClient.getDataview('aggregation_count_dataview', params, function(err, result) {
                assert.ifError(err);
                done();
            });
        });

        it('should return an error if the column used by dataview does not exist', function(done) {
            const query = 'select cartodb_id, the_geom, the_geom_webmercator from populated_places_simple_reduced';

            const expectedResponse = {
                status: 404,
                headers: {
                    'Content-Type': 'application/json; charset=utf-8'
                }
            };

            const expectedResponseBody = {
                errors:['column "adm0name" does not exist'],
                errors_with_context:[{
                    type:'unknown',
                    message:'column "adm0name" does not exist'
                }]
            };

            this.testClient = new TestClient(createMapConfig(query));
            this.testClient.getDataview('aggregation_count_dataview', { response: expectedResponse }, function(err, result) {
                assert.ifError(err);
                assert.deepEqual(result, expectedResponseBody);
                done();
            });
        });

        it('should return an error if query row equals to 0', function(done) {
            const query = 'select * from populated_places_simple_reduced limit 0';

            this.testClient = new TestClient(createMapConfig(query));
            this.testClient.getDataview('aggregation_count_dataview', { own_filter: 0 }, function(err, result) {
                assert.ifError(err);
                done();
            });
        });

    });
});
<commit_msg>testing expected result with pg_typeof undefined<commit_after>require('../../support/test_helper');

var assert = require('../../support/assert');
var TestClient = require('../../support/test-client');

describe('dataview error cases', function() {

    afterEach(function(done) {
        if (this.testClient) {
            this.testClient.drain(done);
        } else {
            done();
        }
    });

    describe('generic errors', function() {
        var ERROR_RESPONSE = {
            status: 400,
            headers: {
                'Content-Type': 'application/json; charset=utf-8'
            }
        };

        function createMapConfig(dataviews) {
            return {
                version: '1.5.0',
                layers: [
                    {
                        "type": "cartodb",
                        "options": {
                            "source": {
                                "id": "HEAD"
                            },
                            "cartocss": "#points { marker-width: 10; marker-fill: red; }",
                            "cartocss_version": "2.3.0"
                        }
                    }
                ],
                dataviews: dataviews,
                analyses: [
                    {
                        "id": "HEAD",
                        "type": "source",
                        "params": {
                            "query": "select null::geometry the_geom_webmercator, x from generate_series(0,1000) x"
                        }
                    }
                ]
            };
        }

        it('should fail when invalid dataviews object is provided, string case', function(done) {
            var mapConfig = createMapConfig("wadus-string");
            this.testClient = new TestClient(mapConfig, 1234);
            this.testClient.getLayergroup({ response: ERROR_RESPONSE }, function(err, errObj) {
                assert.ok(!err, err);

                assert.deepEqual(errObj.errors, [ '"dataviews" must be a valid JSON object: "string" type found' ]);

                done();
            });
        });

        it('should fail when invalid dataviews object is provided, array case', function(done) {
            var mapConfig = createMapConfig([]);
            this.testClient = new TestClient(mapConfig, 1234);
            this.testClient.getLayergroup({ response: ERROR_RESPONSE }, function(err, errObj) {
                assert.ok(!err, err);

                assert.deepEqual(errObj.errors, [ '"dataviews" must be a valid JSON object: "array" type found' ]);

                done();
            });
        });

        it('should work with empty but valid objects', function(done) {
            var mapConfig = createMapConfig({});
            this.testClient = new TestClient(mapConfig, 1234);
            this.testClient.getLayergroup(function(err, layergroup) {
                assert.ok(!err, err);

                assert.ok(layergroup);
                assert.ok(layergroup.layergroupid);

                done();
            });
        });
    });

    describe('pg_typeof', function() {

        afterEach(function(done) {
            if (this.testClient) {
                this.testClient.drain(done);
            } else {
                done();
            }
        });

        function createMapConfig(query) {
            query = query || 'select * from populated_places_simple_reduced';

            return {
                version: '1.5.0',
                layers: [
                    {
                        type: 'mapnik',
                        options: {
                            sql: query,
                            cartocss: '#layer0 { marker-fill: red; marker-width: 10; }',
                            cartocss_version: '2.0.1',
                            source: { id: "a0" }
                        }
                    }
                ],
                analyses: [{
                    id: "a0",
                    type: "source",
                    params: {
                        query: query
                    }
                }],
                dataviews:  {
                    aggregation_count_dataview: {
                        type: "aggregation",
                        source: { id: "a0" },
                        options: {
                            column: "adm0name",
                            aggregation: "count",
                            aggregationColumn: "adm0name"
                        }
                    }
                }
            };
        }

        it('should work without filters', function(done) {
            this.testClient = new TestClient(createMapConfig());
            this.testClient.getDataview('aggregation_count_dataview', { own_filter: 0 }, function(err) {
                assert.ifError(err);
                done();
            });
        });

        it('should work with filters', function(done) {
            var params = {
                filters: {
                    dataviews: {aggregation_count_dataview: {accept: ['Canada']}}
                }
            };

            this.testClient = new TestClient(createMapConfig());
            this.testClient.getDataview('aggregation_count_dataview', params, function(err) {
                assert.ifError(err);
                done();
            });
        });

        it('should return an error if the column used by dataview does not exist', function(done) {
            const query = 'select cartodb_id, the_geom, the_geom_webmercator from populated_places_simple_reduced';

            const params = {
                response: {
                    status: 404,
                    headers: {
                        'Content-Type': 'application/json; charset=utf-8'
                    }
                }
            };

            const expectedResponseBody = {
                errors:['column "adm0name" does not exist'],
                errors_with_context:[{
                    type:'unknown',
                    message:'column "adm0name" does not exist'
                }]
            };

            this.testClient = new TestClient(createMapConfig(query));
            this.testClient.getDataview('aggregation_count_dataview', params, function(err, result) {
                assert.ifError(err);
                assert.deepEqual(result, expectedResponseBody);
                done();
            });
        });

        it('should not fail if query does not return rows', function(done) {
            const query = 'select * from populated_places_simple_reduced limit 0';

            const expectedResponseBody = {
                aggregation: 'count',
                count: 0,
                nulls: 0,
                nans: 0,
                infinities: 0,
                min: 0,
                max: 0,
                categoriesCount: 0,
                categories: [],
                type: 'aggregation'
            };

            this.testClient = new TestClient(createMapConfig(query));
            this.testClient.getDataview('aggregation_count_dataview', { own_filter: 0 }, function(err, result) {
                assert.ifError(err);
                assert.deepEqual(result, expectedResponseBody);
                done();
            });
        });

    });
});
<|endoftext|>


<commit_before>import LayersHelper from 'helpers/LayersHelper';
import React, {PropTypes} from 'react';
import text from 'js/languages';
import DatePicker from 'react-datepicker';
import moment from 'moment';
import 'react-datepicker/dist/react-datepicker.css';

export default class FiresControls extends React.Component {

  static contextTypes = {
    language: PropTypes.string.isRequired,
    map: PropTypes.object.isRequired
  };

  constructor(props) {
    super(props);

    const currentDate = new Date();
    const oneYearAgo = currentDate.setFullYear(currentDate.getFullYear() - 1);
    const max = new Date();

    this.min = moment(oneYearAgo);
    this.max = moment(max);
    this.fireOptions = [
      {label: '24HR', value: '0'},
      {label: '48HR', value: '1'},
      {label: '72HR', value: '2'},
      {label: '7D', value: '3'}
    ];
    this.state = {
      customRange: false,
      activeFireOption: '0',
      activeFireOptionLabel: '24HR'
    };
  }

  componentDidUpdate(prevProps, prevState, prevContext) {

    if (prevProps.startDate !== this.props.startDate || prevProps.endDate !== this.props.endDate) {
      LayersHelper.updateFiresLayerDefinitions(this.props.startDate, this.props.endDate, this.props.layer);
    }

    // Anytime the map changes to a new map, update that here
    const {map} = this.context;
    if (prevContext.map !== map && prevContext.map.loaded) {
      const signal = map.on('update-end', () => {
        signal.remove();
        LayersHelper.updateFiresLayerDefinitions(this.props.startDate, this.props.endDate, this.props.layer);
      });
    }
  }

  handleStartChange = (startDate) => {
    this.props.updateStartDate(startDate);
  }

  handleEndChange = (endDate) => {
    this.props.updateEndDate(endDate);
  }

  renderActiveFireOptions = fireOptions => {
    return fireOptions.map((fireOption, index) => {
      return <option key={`option-${index}`} value={fireOption.value}>{fireOption.label}</option>;
    });
  };

  updateActiveFires = (evt, fireOptions) => {
    LayersHelper.updateFiresLayerDefinitions(this.props.startDate, this.props.endDate, this.props.layer, evt.target.value);
    this.setState({
      activeFireOption: evt.target.value,
      activeFireOptionLabel: fireOptions[evt.target.value].label
    });
  };

  render () {
    const { startDate, endDate } = this.props;
    const {language} = this.context;
    const {customRange, activeFireOption, activeFireOptionLabel} = this.state;
    return (

              <select
                className="pointer"
                value={activeFireOption}
                onChange={evt => this.updateActiveFires(evt, this.fireOptions)}
              >
              {this.renderActiveFireOptions(this.fireOptions)}
              </select>

{activeFireOptionLabel}

 this.setState({
              customRange: !customRange
            })}
          >
            Custom Range

          {customRange &&

                  {text[language].TIMELINE_START}
                  <DatePicker
                    customInput={<StartButton />}
                    showMonthDropdown
                    showYearDropdown
                    dropdownMode="select"
                    todayButton='Jump to today'
                    minDate={this.min}
                    maxDate={moment(endDate)}
                    selected={moment(startDate)}
                    onChange={this.handleStartChange}
                  />

                  {text[language].TIMELINE_END}
                  <DatePicker
                    customInput={<EndButton />}
                    showMonthDropdown
                    showYearDropdown
                    dropdownMode="select"
                    todayButton='Jump to today'
                    minDate={moment(startDate)}
                    maxDate={this.max}
                    selected={moment(endDate)}
                    onChange={this.handleEndChange}
                  />

          }

    );
  }
}

const StartButton = ({ onClick, value }) => (
  <button
    className='fa-button sml white pointer'
    onClick={onClick}
  >
    {value}
  </button>
);

const EndButton = ({ onClick, value }) => (
  <button
    className='fa-button sml white pointer'
    onClick={onClick}
  >
    {value}
  </button>
);
<commit_msg>Update label names<commit_after>import LayersHelper from 'helpers/LayersHelper';
import React, {PropTypes} from 'react';
import text from 'js/languages';
import DatePicker from 'react-datepicker';
import moment from 'moment';
import 'react-datepicker/dist/react-datepicker.css';

export default class FiresControls extends React.Component {

  static contextTypes = {
    language: PropTypes.string.isRequired,
    map: PropTypes.object.isRequired
  };

  constructor(props) {
    super(props);

    const currentDate = new Date();
    const oneYearAgo = currentDate.setFullYear(currentDate.getFullYear() - 1);
    const max = new Date();

    this.min = moment(oneYearAgo);
    this.max = moment(max);
    this.fireOptions = [
      {label: 'Past 24 hours', value: '0'},
      {label: 'Past 48 hours', value: '1'},
      {label: 'Past 72 hours', value: '2'},
      {label: 'Past Week', value: '3'}
    ];
    this.state = {
      customRange: false,
      activeFireOption: '0',
      activeFireOptionLabel: '24HR'
    };
  }

  componentDidUpdate(prevProps, prevState, prevContext) {

    if (prevProps.startDate !== this.props.startDate || prevProps.endDate !== this.props.endDate) {
      LayersHelper.updateFiresLayerDefinitions(this.props.startDate, this.props.endDate, this.props.layer);
    }

    // Anytime the map changes to a new map, update that here
    const {map} = this.context;
    if (prevContext.map !== map && prevContext.map.loaded) {
      const signal = map.on('update-end', () => {
        signal.remove();
        LayersHelper.updateFiresLayerDefinitions(this.props.startDate, this.props.endDate, this.props.layer);
      });
    }
  }

  handleStartChange = (startDate) => {
    this.props.updateStartDate(startDate);
  }

  handleEndChange = (endDate) => {
    this.props.updateEndDate(endDate);
  }

  renderActiveFireOptions = fireOptions => {
    return fireOptions.map((fireOption, index) => {
      return <option key={`option-${index}`} value={fireOption.value}>{fireOption.label}</option>;
    });
  };

  updateActiveFires = (evt, fireOptions) => {
    LayersHelper.updateFiresLayerDefinitions(this.props.startDate, this.props.endDate, this.props.layer, evt.target.value);
    this.setState({
      activeFireOption: evt.target.value,
      activeFireOptionLabel: fireOptions[evt.target.value].label
    });
  };

  render () {
    const { startDate, endDate } = this.props;
    const {language} = this.context;
    const {customRange, activeFireOption, activeFireOptionLabel} = this.state;
    return (

              <select
                className="pointer"
                value={activeFireOption}
                onChange={evt => this.updateActiveFires(evt, this.fireOptions)}
              >
              {this.renderActiveFireOptions(this.fireOptions)}
              </select>

{activeFireOptionLabel}

 this.setState({
              customRange: !customRange
            })}
          >
            Custom Range

          {customRange &&

                  {text[language].TIMELINE_START}
                  <DatePicker
                    customInput={<StartButton />}
                    showMonthDropdown
                    showYearDropdown
                    dropdownMode="select"
                    todayButton='Jump to today'
                    minDate={this.min}
                    maxDate={moment(endDate)}
                    selected={moment(startDate)}
                    onChange={this.handleStartChange}
                  />

                  {text[language].TIMELINE_END}
                  <DatePicker
                    customInput={<EndButton />}
                    showMonthDropdown
                    showYearDropdown
                    dropdownMode="select"
                    todayButton='Jump to today'
                    minDate={moment(startDate)}
                    maxDate={this.max}
                    selected={moment(endDate)}
                    onChange={this.handleEndChange}
                  />

          }

    );
  }
}

const StartButton = ({ onClick, value }) => (
  <button
    className='fa-button sml white pointer'
    onClick={onClick}
  >
    {value}
  </button>
);

const EndButton = ({ onClick, value }) => (
  <button
    className='fa-button sml white pointer'
    onClick={onClick}
  >
    {value}
  </button>
);
<|endoftext|>


<commit_before>'use strict';

var appFrame   = require('../../bellows/pages/appFrame.js');
var body     = require('../../bellows/pages/pageBody.js');
afterEach(function() {
  //browser.ignoreSyncronization = true;
  appFrame.errorMessage.isPresent().then(function(isPresent) {
    if (isPresent) {
      appFrame.errorMessage.getText().then(function(message) {
        if (message.indexOf('Oh. Exception') != -1) {
          message = "PHP API error on this page: " + message;
          expect(message).toEqual(''); // fail the test
        }
      });
    }
  });
  body.phpError.isPresent().then(function(isPresent) {
    if (isPresent) {
      body.phpError.getText().then(function(message) {
        message = "PHP Error present on this page:" + message;
        expect(message).toEqual(''); // fail the test
      });
    }
  });

  // output JS console errors and fail tests
  browser.manage().logs().get('browser').then(function(browserLog) {
    if (browserLog.length > 0) {
      for (var i=0;i<browserLog.length;i++) {
        var message = browserLog[i].message;
        if (message.indexOf('\n') != -1) {
          message = message.substring(0, message.indexOf('\n'));
        }
        if (/angular\.js .* TypeError: undefined is not a function/.test(message)) {
          // we ignore errors of this type caused by Angular being unloaded prematurely on page refreshes (since it's not a real error)

        } else if (/rangy-1\.3alpha\.772/.test(message)) {
          // we ignore rangy errors because we are lazy and don't want to upgrade to the latest rangy atm (but we really should upgrade at some point) - cjh 2015-02
        } else {
          message = "Browser Console JS Error: " + message;
          expect(message).toEqual(''); // fail the test
        }

      }
    }
  });
  //browser.ignoreSyncronization = false;
});<commit_msg>fix E2E Browser Console error message to display all lines of message formated<commit_after>'use strict';

var appFrame   = require('../../bellows/pages/appFrame.js');
var body     = require('../../bellows/pages/pageBody.js');
afterEach(function() {
  //browser.ignoreSyncronization = true;
  appFrame.errorMessage.isPresent().then(function(isPresent) {
    if (isPresent) {
      appFrame.errorMessage.getText().then(function(message) {
        if (message.indexOf('Oh. Exception') != -1) {
          message = "PHP API error on this page: " + message;
          expect(message).toEqual(''); // fail the test
        }
      });
    }
  });
  body.phpError.isPresent().then(function(isPresent) {
    if (isPresent) {
      body.phpError.getText().then(function(message) {
        message = "PHP Error present on this page:" + message;
        expect(message).toEqual(''); // fail the test
      });
    }
  });

  // output JS console errors and fail tests
  browser.manage().logs().get('browser').then(function(browserLog) {
    if (browserLog.length > 0) {
      for (var i=0;i<browserLog.length;i++) {
        var message = browserLog[i].message;
        if (message.indexOf('\n') != -1) {

          // place CR between lines
          message = message.split('\n').join("\n");
        }
        if (/angular\.js .* TypeError: undefined is not a function/.test(message)) {
          // we ignore errors of this type caused by Angular being unloaded prematurely on page refreshes (since it's not a real error)

        } else if (/rangy-1\.3alpha\.772/.test(message)) {
          // we ignore rangy errors because we are lazy and don't want to upgrade to the latest rangy atm (but we really should upgrade at some point) - cjh 2015-02
        } else {
          message = "\n\nBrowser Console JS Error: \n" + message + "\n\n";
          expect(message).toEqual(''); // fail the test
        }

      }
    }
  });
  //browser.ignoreSyncronization = false;
});<|endoftext|>


<commit_before>var streams=${ streams }
var params = { allowScriptAccess: "always", bgcolor: "#cccccc", wmode: "transparent", allowFullScreen: "true" };
var atts = { id: "myytplayer" };

// If the user doesn't have flash, use the HTML5 Video instead. YouTube's
// iFrame API which supports HTML5 is still developmental so it is not default
if (swfobject.hasFlashPlayerVersion("10.1")){
  swfobject.embedSWF(document.location.protocol +  "//www.youtube.com/apiplayer?enablejsapi=1&playerapiid=ytplayer?wmode=transparent",
        "ytapiplayer", "640", "385", "8", null, null, params, atts);
} else {

  //end of this URL may need &origin=http://..... once pushed to production to prevent XSS
  $("#html5_player").attr("src", document.location.protocol +  "//www.youtube.com/embed/" + streams["1.0"] + "?enablejsapi=1&controls=0");
  $("#html5_player").show();

  var tag = document.createElement('script');
  tag.src = document.location.protocol +  "//www.youtube.com/player_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
  // Make sure the callback is called once API ready, YT seems to be buggy
  loadHTML5Video();
}
var captions=0;
$("#slider").slider({slide:function(event,ui){seek_slide('slide',event.originalEvent,ui.value);},
                     stop:function(event,ui){seek_slide('stop',event.originalEvent,ui.value);}});

function good() {
    window['console'].log(ytplayer.getCurrentTime());
}

ajax_video=good;

loadNewVideo(streams["1.0"], ${ position });

function add_speed(key, stream) {
  var id = 'speed_' + stream;

  $("#video_speeds").append('
'+key+'x
');

  $("#"+id).click(function(){
    change_video_speed(key, stream);
    $(this).siblings().removeClass("active");
    $(this).addClass("active");
  });
}

var l=[]
for (var key in streams) {
    l.push(key);
}

function sort_by_value(a,b) {
    var x=parseFloat(a);
    var y=parseFloat(b);
    var r=((x < y) ? -1 : ((x > y) ? 1 : 0));
    return r;
}

l.sort(sort_by_value);

for(var i=0; i<l.length; i++) {
    add_speed(l[i], streams[l[i]])
}

function toggleVideo(){
  if ($("#video_control").hasClass("play")){
    play();
    $("#video_control").removeClass().addClass("pause");
  } else {
    pause();
    $("#video_control").removeClass().addClass("play");
  }
}

$("#video_control").click(toggleVideo);

// space bar to pause video
$(".video-wrapper").keyup(function(e){
  active = document.activeElement;
  if (e.which == 32) {
    e.preventDefault();
    $("#video_control").click();
  }
});
<commit_msg>add active class to 1.0 speed video when page first loaded.<commit_after>var streams=${ streams }
var params = { allowScriptAccess: "always", bgcolor: "#cccccc", wmode: "transparent", allowFullScreen: "true" };
var atts = { id: "myytplayer" };

// If the user doesn't have flash, use the HTML5 Video instead. YouTube's
// iFrame API which supports HTML5 is still developmental so it is not default
if (swfobject.hasFlashPlayerVersion("10.1")){
  swfobject.embedSWF(document.location.protocol +  "//www.youtube.com/apiplayer?enablejsapi=1&playerapiid=ytplayer?wmode=transparent",
        "ytapiplayer", "640", "385", "8", null, null, params, atts);
} else {

  //end of this URL may need &origin=http://..... once pushed to production to prevent XSS
  $("#html5_player").attr("src", document.location.protocol +  "//www.youtube.com/embed/" + streams["1.0"] + "?enablejsapi=1&controls=0");
  $("#html5_player").show();

  var tag = document.createElement('script');
  tag.src = document.location.protocol +  "//www.youtube.com/player_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
  // Make sure the callback is called once API ready, YT seems to be buggy
  loadHTML5Video();
}
var captions=0;
$("#slider").slider({slide:function(event,ui){seek_slide('slide',event.originalEvent,ui.value);},
                     stop:function(event,ui){seek_slide('stop',event.originalEvent,ui.value);}});

function good() {
    window['console'].log(ytplayer.getCurrentTime());
}

ajax_video=good;

loadNewVideo(streams["1.0"], ${ position });

function add_speed(key, stream) {
  var id = 'speed_' + stream;

  //TODO: this should be smarter and know which video is first selected when we have
  // video speed as an option/parameter per user that is saved
  if (key == 1.0) {
    $("#video_speeds").append('
'+key+'x
');
  } else {
    $("#video_speeds").append('
'+key+'x
');
  }

  $("#"+id).click(function(){
    change_video_speed(key, stream);
    $(this).siblings().removeClass("active");
    $(this).addClass("active");
  });
}

var l=[]
for (var key in streams) {
    l.push(key);
}

function sort_by_value(a,b) {
    var x=parseFloat(a);
    var y=parseFloat(b);
    var r=((x < y) ? -1 : ((x > y) ? 1 : 0));
    return r;
}

l.sort(sort_by_value);

for(var i=0; i<l.length; i++) {
    add_speed(l[i], streams[l[i]])
}

function toggleVideo(){
  if ($("#video_control").hasClass("play")){
    play();
    $("#video_control").removeClass().addClass("pause");
  } else {
    pause();
    $("#video_control").removeClass().addClass("play");
  }
}

$("#video_control").click(toggleVideo);

// space bar to pause video
$(".video-wrapper").keyup(function(e){
  active = document.activeElement;
  if (e.which == 32) {
    e.preventDefault();
    $("#video_control").click();
  }
});
<|endoftext|>


<commit_before>import os from "os"
import fs from "fs"
import http from "http"

import express from "express"
import expressWinston from "express-winston"
import compression from "compression"
import log from "winston"

import load from "../library/load"

export const controllers = [];
export const component = module.exports || {};
export const env = process.env.NODE_ENV || "develop";

log.info(`booting a component on ${os.hostname()}`);
log.info(`${component.name} @ ${component.version}`);
log.info(`configured ${env} as NODE_ENV environment`);

export const service = express();

service.use(compression());

service.use(expressWinston.logger({
    winstonInstance: log,
    expressFormat: true,
    colorize: true,
}));

const tsFormat = () => (new Date()).toLocaleString();

log.remove(log.transports.Console).add(log.transports.Console, {
    humanReadableUnhandledException: true,
    handleExceptions: true,
    colorize: true,
    timestamp: tsFormat,
});

// this will load all controllers in the service/ directory via the
// require-all library; those must be named as *Controller.js files;
load(service, {
    dirname: __dirname,
    resolve: function (exported) {
        let symbol = exported.default.name;
        log.debug(`loading controller ${symbol}`);
        let item = new exported.default(service);
        item.register && item.register(service);
        controllers.push(item)
        return item
    }
});

export const unsecuredServer = http.createServer(service);

for (let controller of controllers) {
    controller.wired && controller.wired(service);
}

var port = 8500;
if (require.main == module) {
    unsecuredServer.listen(port);
}

log.info(`Server started on ${port}`);

<commit_msg>Handle 404 error<commit_after>import os from "os"
import fs from "fs"
import http from "http"

import express from "express"
import expressWinston from "express-winston"
import compression from "compression"
import log from "winston"

import load from "../library/load"

export const controllers = [];
export const component = module.exports || {};
export const env = process.env.NODE_ENV || "develop";

log.info(`booting a component on ${os.hostname()}`);
log.info(`${component.name} @ ${component.version}`);
log.info(`configured ${env} as NODE_ENV environment`);

export const service = express();

service.use(compression());

service.use(expressWinston.logger({
    winstonInstance: log,
    expressFormat: true,
    colorize: true,
}));

const tsFormat = () => (new Date()).toLocaleString();

log.remove(log.transports.Console).add(log.transports.Console, {
    humanReadableUnhandledException: true,
    handleExceptions: true,
    colorize: true,
    timestamp: tsFormat,
});

// this will load all controllers in the service/ directory via the
// require-all library; those must be named as *Controller.js files;
load(service, {
    dirname: __dirname,
    resolve: function (exported) {
        let symbol = exported.default.name;
        log.debug(`loading controller ${symbol}`);
        let item = new exported.default(service);
        item.register && item.register(service);
        controllers.push(item)
        return item
    }
});

export const unsecuredServer = http.createServer(service);

for (let controller of controllers) {
    controller.wired && controller.wired(service);
}

// Handle 404 Error
service.use(function(req, res, next){
    res.status(404);
    res.send({ error: "Not found" });
    return;
});

var port = 8500;
if (require.main == module) {
    unsecuredServer.listen(port);
}

log.info(`Server started on ${port}`);

<|endoftext|>


<commit_before>var _ = require('underscore');
var util = require('cdb.core.util');
var View = require('../../core/view');
var OverlaysFactory = require('../../vis/overlays-factory');
var overlayContainerTemplate = require('./overlays-container.tpl');

var CONTAINED_OVERLAYS = ['attribution', 'fullscreen', 'limits', 'logo', 'search', 'zoom'];

var OverlaysView = View.extend({

  initialize: function (deps) {
    if (!deps.overlaysCollection) throw new Error('overlaysCollection is required');
    if (!deps.visModel) throw new Error('visModel is required');
    if (!deps.visView) throw new Error('visView is required');
    if (!deps.mapModel) throw new Error('mapModel is required');
    if (!deps.mapView) throw new Error('mapView is required');

    this._overlaysCollection = deps.overlaysCollection;
    this._visModel = deps.visModel;
    this._visView = deps.visView;
    this._mapModel = deps.mapModel;
    this._mapView = deps.mapView;

    this._overlayViews = [];
    this._overlaysFactory = new OverlaysFactory({
      mapModel: this._mapModel,
      mapView: this._mapView,
      visView: this._visView
    });

    this._visModel.on('change:loading', this._toggleLoaderOverlay, this);

    this._overlaysCollection.on('add remove change', this.render, this);

    this.$el.append(overlayContainerTemplate());
  },

  render: function () {
    this._clearOverlays();
    this._renderOverlays();
    return this;
  },

  _clearOverlays: function () {
    while (this._overlayViews.length !== 0) {
      this._overlayViews.pop().clean();
    }
  },

  _renderOverlays: function () {
    var overlays = this._overlaysCollection.toJSON();

    // Sort the overlays by its internal order
    overlays = _.sortBy(overlays, function (overlay) {
      return overlay.order === null ? Number.MAX_VALUE : overlay.order;
    });

    _(overlays).each(function (data) {
      this._renderOverlay(data);
    }, this);
  },

  _renderOverlay: function (overlay) {
    var overlayView = this._createOverlayView(overlay);
    if (overlayView) {
      overlayView.render();
      if (this._isGlobalOverlay(overlay)) {
        this.$el.append(overlayView.el);
      } else {
        this._overlayContainer().append(overlayView.el);
      }
      this.addView(overlayView);
      this._overlayViews.push(overlayView);

      // IE<10 doesn't support the Fullscreen API
      var type = overlay.type;
      if (type === 'fullscreen' && util.browser.ie && util.browser.ie.version <= 10) return;
    }
  },

  _createOverlayView: function (overlay) {
    return this._overlaysFactory.create(overlay.type, overlay, {
      visView: this._visView,
      map: this._mapModel
    });
  },

  _isGlobalOverlay: function (overlay) {
    return CONTAINED_OVERLAYS.indexOf(overlay.type) === -1;
  },

  _overlayContainer: function () {
    return this.$('.CDB-OverlayContainer');
  },

  _toggleLoaderOverlay: function () {
    var loaderOverlay = this._getLoaderOverlay();
    if (loaderOverlay) {
      if (this._visModel.get('loading')) {
        loaderOverlay.show();
      } else {
        loaderOverlay.hide();
      }
    }
  },

  _getLoaderOverlay: function () {
    return this._getOverlayViewByType('loader');
  },

  _getOverlayViewByType: function (type) {
    return _(this._overlayViews).find(function (v) {
      return v.type === type;
    });
  },

  clean: function () {
    View.prototype.clean.apply(this);
    this._clearOverlays();
  }
});

module.exports = OverlaysView;
<commit_msg>Rename deps to opts<commit_after>var _ = require('underscore');
var util = require('cdb.core.util');
var View = require('../../core/view');
var OverlaysFactory = require('../../vis/overlays-factory');
var overlayContainerTemplate = require('./overlays-container.tpl');

var CONTAINED_OVERLAYS = ['attribution', 'fullscreen', 'limits', 'logo', 'search', 'zoom'];

var OverlaysView = View.extend({

  initialize: function (deps) {
    if (!opts.overlaysCollection) throw new Error('overlaysCollection is required');
    if (!opts.visModel) throw new Error('visModel is required');
    if (!opts.visView) throw new Error('visView is required');
    if (!opts.mapModel) throw new Error('mapModel is required');
    if (!opts.mapView) throw new Error('mapView is required');

    this._overlaysCollection = opts.overlaysCollection;
    this._visModel = opts.visModel;
    this._visView = opts.visView;
    this._mapModel = opts.mapModel;
    this._mapView = opts.mapView;

    this._overlayViews = [];
    this._overlaysFactory = new OverlaysFactory({
      mapModel: this._mapModel,
      mapView: this._mapView,
      visView: this._visView
    });

    this._visModel.on('change:loading', this._toggleLoaderOverlay, this);

    this._overlaysCollection.on('add remove change', this.render, this);

    this.$el.append(overlayContainerTemplate());
  },

  render: function () {
    this._clearOverlays();
    this._renderOverlays();
    return this;
  },

  _clearOverlays: function () {
    while (this._overlayViews.length !== 0) {
      this._overlayViews.pop().clean();
    }
  },

  _renderOverlays: function () {
    var overlays = this._overlaysCollection.toJSON();

    // Sort the overlays by its internal order
    overlays = _.sortBy(overlays, function (overlay) {
      return overlay.order === null ? Number.MAX_VALUE : overlay.order;
    });

    _(overlays).each(function (data) {
      this._renderOverlay(data);
    }, this);
  },

  _renderOverlay: function (overlay) {
    var overlayView = this._createOverlayView(overlay);
    if (overlayView) {
      overlayView.render();
      if (this._isGlobalOverlay(overlay)) {
        this.$el.append(overlayView.el);
      } else {
        this._overlayContainer().append(overlayView.el);
      }
      this.addView(overlayView);
      this._overlayViews.push(overlayView);

      // IE<10 doesn't support the Fullscreen API
      var type = overlay.type;
      if (type === 'fullscreen' && util.browser.ie && util.browser.ie.version <= 10) return;
    }
  },

  _createOverlayView: function (overlay) {
    return this._overlaysFactory.create(overlay.type, overlay, {
      visView: this._visView,
      map: this._mapModel
    });
  },

  _isGlobalOverlay: function (overlay) {
    return CONTAINED_OVERLAYS.indexOf(overlay.type) === -1;
  },

  _overlayContainer: function () {
    return this.$('.CDB-OverlayContainer');
  },

  _toggleLoaderOverlay: function () {
    var loaderOverlay = this._getLoaderOverlay();
    if (loaderOverlay) {
      if (this._visModel.get('loading')) {
        loaderOverlay.show();
      } else {
        loaderOverlay.hide();
      }
    }
  },

  _getLoaderOverlay: function () {
    return this._getOverlayViewByType('loader');
  },

  _getOverlayViewByType: function (type) {
    return _(this._overlayViews).find(function (v) {
      return v.type === type;
    });
  },

  clean: function () {
    View.prototype.clean.apply(this);
    this._clearOverlays();
  }
});

module.exports = OverlaysView;
<|endoftext|>


<commit_before>class CalendarTiler {
    static isString(value) {
        return typeof value === 'string' || value instanceof String;
    }

    static sortAppointments(a, b) {
        return a.start - b.start || b.end - a.end;
    }

    static initializeTilingSubArray(initialValue, length) {
        let i,
            array = [];

        for (i = length - 1; i >= 0; --i) {
            array.push(typeof initialValue !== 'undefined' ? initialValue : []);
        }

        return array;
    }

    static getTail(head, array) {
        let i;

        for (i = head + 1; i < array.length; ++i) {
            if (array[i] !== -1) {
                return i;
            }
        }

        return array.length;
    }

    static getFirstIndexOf(val, array) {
        let i;

        for (i = 0; i < array.length; ++i) {
            if (array[i] === val) {
                return i;
            }
        }

        return -1;
    }

    constructor(appointments, tileParameters) {
        if (!Array.isArray(appointments)) {
            throw 'CalendarTiler constructor, 1st argument - appointments: expects array.';
        }

        if (tileParameters !== Object(tileParameters)) {
            throw 'CalendarTiler constructor, 2nd argument - tileParameters: expects object.';
        }

        this.tileParameters = this.mapTileParameters(tileParameters);
        this.appointments = this.copyRelevantAppointmentData(appointments);
        this.tiling = this.initializeTiling();
        this.initialize();
    }

    mapTileParameters(tileParameters) {
        let usesDuration = this.isString(tileParameters.duration);

        return {
            usesDuration: usesDuration,
            id: this.isString(tileParameters.id) ? tileParameters.id : 'id',
            start: this.isString(tileParameters.start) ? tileParameters.start : 'start',
            delineator: usesDuration ? tileParameters.duration : (this.isString(tileParameters.end) ? tileParameters.end : 'end')
        };
    }

    getAppointmentEnd(appointment) {
        if (this.tileParameters.usesDuration) {
            return appointment[this.tileParameters.start] + appointment[this.tileParameters.duration];
        }

        return appointment[this.tileParameters.end];
    }

    copyRelevantAppointmentData(appointments) {
        let i,
            values = [];

        for (i = appointments.length - 1; i >= 0; --i) {
            values.push({
                id: appointments[i][this.tileParameters.id],
                start: appointments[i][this.tileParameters.start],
                end: this.getAppointmentEnd(appointments[i])
            });
        }

        return values.sort(this.sortAppointments);
    }

    initializeTiling() {
        let appointmentsLength = this.appointments.length;

        return {
            front: this.initializeTilingSubArray(appointmentsLength),
            back: this.initializeTilingSubArray(appointmentsLength),
            tBack: this.initializeTilingSubArray(appointmentsLength, -1),
            tFront: this.initializeTilingSubArray(appointmentsLength),
            dx: this.initializeTilingSubArray(appointmentsLength, 1),
            x: this.initializeTilingSubArray(appointmentsLength, 0)
        };
    }

    initialize() {
        let j,
            k;

        if (this.appointments.length > 0) {
            for (j = 0; j < this.appointments.length; ++j) {
                for (k = j + 1; k < this.appointments.length; ++k) {
                    if (this.appointments[k].start < this.appointments[j].end) {
                        this.tiling.front[j].push(k);
                    }
                }

                for (k = 0; k < j; ++k) {
                    if (this.appointments[k].end > this.appointments[j].start) {
                        this.tiling.back[j].push(k);
                    }
                }
            }

            this.buildTBack();
        }

        return {
            dx: this.tiling.dx,
            x: this.tiling.x
        };
    }

    buildTBack() {
        let next,
            head,
            tail,
            path;

        while (this.getFirstIndexOf(-1, this.tiling.tBack) > -1) {
            head = this.getFirstIndexOf(-1, this.tiling.tBack);
            tail = this.getTail(head, this.tiling.tBack);
            path = (head > 0 ? this.tiling.tBack[head - 1].concat([head - 1]) : []);

            while (head < tail) {
                this.tiling.tBack[head] = path;
                next = this.tiling.front[head][this.tiling.front[head].length - 1];
                head = (next ? (next >= tail ? tail : next + 1) : head + 1);
            }
        }

        this.buildTFront();
    }

    buildTFront() {
        let i,
            j,
            next;

        for (i = 0; i < this.tiling.tFront.length; ++i) {
            if (this.tiling.back[i].length === this.tiling.tBack[i].length) {
                if (this.tiling.front[i].length > 0 && this.tiling.tBack[this.tiling.front[i][0]].length > this.tiling.tBack[i].length) {
                    this.tiling.tFront[i].push(this.tiling.front[i][0]);
                }
            } else {
                next = next || this.findNextTFrontFromBack(i, tiling);

                if (this.tiling.front[i].length > 0 && this.getFirstIndexOf(next, this.tiling.back[this.tiling.front[i][0]]) > -1) {
                    if (this.tiling.tBack[this.tiling.front[i][0]].length < this.tiling.tBack[i].length) {
                        this.tiling.tFront[i].push(next);
                        next = null;
                    } else {
                        this.tiling.tFront[i].push(this.tiling.front[i][0]);
                    }
                } else {
                    this.tiling.tFront[i].push(next);
                    next = null;
                }
            }
        }

        this.expandRemainingTFront();
    }

    findNextTFrontFromBack(index) {
        let i,
            j,
            back,
            minFront;

        for (i = 0; i < this.tiling.back[index].length; ++i) {
            back = this.tiling.back[index][i];
            if (this.getFirstIndexOf(back, this.tiling.tBack[index]) === -1) {
                this.expandTFront(back);
                minFront = minFront || back;

                if (back !== minFront && (this.getFirstIndexOf(minFront, this.tiling.tFront[back]) > -1 || this.sharesLinchPin(minFront, back))) {
                    minFront = back;
                }
            }
        }

        return minFront;
    }

    sharesLinchPin(minFront, index) {
        let j,
            tBack = this.tiling.tBack[minFront],
            linchPin = tBack[tBack.length - 1];

        if (linchPin && this.getFirstIndexOf(linchPin, this.tiling.tFront[index]) > -1) {
            return true;
        }

        return false;
    }

    expandTFront(index) {
        if (this.tiling.tFront[index].length === 1) {
            let next = this.tiling.tFront[this.tiling.tFront[index][0]][0];

            while (next) {
                this.tiling.tFront[index].push(next);
                if (this.tiling.tFront[next].length > 0) {
                    next = this.tiling.tFront[next][0];
                } else {
                    return;
                }
            }
        }
    }

    expandRemainingTFront() {
        let i,
            next;

        for (i = 0; i < this.tiling.tFront.length; ++i) {
            this.expandTFront(i);
        }

        this.calculateDxs();
    }

    calculateDxs() {
        let i,
            j,
            chain,
            width,
            unset;

        for (i = 0; i < this.tiling.tBack.length; ++i) {
            if (this.tiling.dx[i] === 1) {
                if (this.tiling.tFront[i].length === 0) {
                    for (j = 0; j < this.tiling.tBack[i].length; ++j) {
                        this.tiling.dx[i] -= this.tiling.dx[this.tiling.tBack[i][j]];
                    }
                } else {
                    chain = this.findLongestChainThroughNode(i);
                    unset = 0;
                    width = 0;

                    for (j = 0; j < chain.length; ++j) {
                        if (this.tiling.dx[chain[j]] < 1) {
                            width += this.tiling.dx[chain[j]];
                        } else {
                            ++unset;
                        }
                    }

                    this.tiling.dx[i] = (1 - width) / unset;
                }
            }
        }

        this.calculateXs();
    }

    findLongestChainThroughNode(index) {
        let i,
            chain = this.tiling.tBack[index].concat([index]).concat(this.tiling.tFront[index]);

        for (i = index; i < this.tiling.front[index].length; ++i) {
            if ((this.getFirstIndexOf(index, this.tiling.tBack[i]) > -1 || this.getFirstIndexOf(index, this.tiling.tFront[i]) > -1)
                    && this.tiling.tBack[i].length + this.tiling.tFront[i].length + 1 > chain.length) {
                chain = this.tiling.tBack[i].concat([i]).concat(this.tiling.tFront[i]);
            }
        }

        return chain;
    }

    calculateXs() {
        let i,
            last;

        for (i = 1; i < this.tiling.dx.length; ++i) {
            if (this.tiling.tBack[i].length > 0) {
                last = this.tiling.tBack[i][this.tiling.tBack[i].length - 1];
                this.tiling.x[i] = this.tiling.x[last] + this.tiling.dx[last];
            }
        }
    }
}<commit_msg>Look who has unused variables and forgot a 'this' keyword ... this guy<commit_after>class CalendarTiler {
    static isString(value) {
        return typeof value === 'string' || value instanceof String;
    }

    static sortAppointments(a, b) {
        return a.start - b.start || b.end - a.end;
    }

    static initializeTilingSubArray(initialValue, length) {
        let i,
            array = [];

        for (i = length - 1; i >= 0; --i) {
            array.push(typeof initialValue !== 'undefined' ? initialValue : []);
        }

        return array;
    }

    static getTail(head, array) {
        let i;

        for (i = head + 1; i < array.length; ++i) {
            if (array[i] !== -1) {
                return i;
            }
        }

        return array.length;
    }

    static getFirstIndexOf(val, array) {
        let i;

        for (i = 0; i < array.length; ++i) {
            if (array[i] === val) {
                return i;
            }
        }

        return -1;
    }

    constructor(appointments, tileParameters) {
        if (!Array.isArray(appointments)) {
            throw 'CalendarTiler constructor, 1st argument - appointments: expects array.';
        }

        if (tileParameters !== Object(tileParameters)) {
            throw 'CalendarTiler constructor, 2nd argument - tileParameters: expects object.';
        }

        this.tileParameters = this.mapTileParameters(tileParameters);
        this.appointments = this.copyRelevantAppointmentData(appointments);
        this.tiling = this.initializeTiling();
        this.initialize();
    }

    mapTileParameters(tileParameters) {
        let usesDuration = this.isString(tileParameters.duration);

        return {
            usesDuration: usesDuration,
            id: this.isString(tileParameters.id) ? tileParameters.id : 'id',
            start: this.isString(tileParameters.start) ? tileParameters.start : 'start',
            delineator: usesDuration ? tileParameters.duration : (this.isString(tileParameters.end) ? tileParameters.end : 'end')
        };
    }

    getAppointmentEnd(appointment) {
        if (this.tileParameters.usesDuration) {
            return appointment[this.tileParameters.start] + appointment[this.tileParameters.duration];
        }

        return appointment[this.tileParameters.end];
    }

    copyRelevantAppointmentData(appointments) {
        let i,
            values = [];

        for (i = appointments.length - 1; i >= 0; --i) {
            values.push({
                id: appointments[i][this.tileParameters.id],
                start: appointments[i][this.tileParameters.start],
                end: this.getAppointmentEnd(appointments[i])
            });
        }

        return values.sort(this.sortAppointments);
    }

    initializeTiling() {
        let appointmentsLength = this.appointments.length;

        return {
            front: this.initializeTilingSubArray(appointmentsLength),
            back: this.initializeTilingSubArray(appointmentsLength),
            tBack: this.initializeTilingSubArray(appointmentsLength, -1),
            tFront: this.initializeTilingSubArray(appointmentsLength),
            dx: this.initializeTilingSubArray(appointmentsLength, 1),
            x: this.initializeTilingSubArray(appointmentsLength, 0)
        };
    }

    initialize() {
        let j,
            k;

        if (this.appointments.length > 0) {
            for (j = 0; j < this.appointments.length; ++j) {
                for (k = j + 1; k < this.appointments.length; ++k) {
                    if (this.appointments[k].start < this.appointments[j].end) {
                        this.tiling.front[j].push(k);
                    }
                }

                for (k = 0; k < j; ++k) {
                    if (this.appointments[k].end > this.appointments[j].start) {
                        this.tiling.back[j].push(k);
                    }
                }
            }

            this.buildTBack();
        }

        return {
            dx: this.tiling.dx,
            x: this.tiling.x
        };
    }

    buildTBack() {
        let next,
            head,
            tail,
            path;

        while (this.getFirstIndexOf(-1, this.tiling.tBack) > -1) {
            head = this.getFirstIndexOf(-1, this.tiling.tBack);
            tail = this.getTail(head, this.tiling.tBack);
            path = (head > 0 ? this.tiling.tBack[head - 1].concat([head - 1]) : []);

            while (head < tail) {
                this.tiling.tBack[head] = path;
                next = this.tiling.front[head][this.tiling.front[head].length - 1];
                head = (next ? (next >= tail ? tail : next + 1) : head + 1);
            }
        }

        this.buildTFront();
    }

    buildTFront() {
        let i,
            next;

        for (i = 0; i < this.tiling.tFront.length; ++i) {
            if (this.tiling.back[i].length === this.tiling.tBack[i].length) {
                if (this.tiling.front[i].length > 0 && this.tiling.tBack[this.tiling.front[i][0]].length > this.tiling.tBack[i].length) {
                    this.tiling.tFront[i].push(this.tiling.front[i][0]);
                }
            } else {
                next = next || this.findNextTFrontFromBack(i, this.tiling);

                if (this.tiling.front[i].length > 0 && this.getFirstIndexOf(next, this.tiling.back[this.tiling.front[i][0]]) > -1) {
                    if (this.tiling.tBack[this.tiling.front[i][0]].length < this.tiling.tBack[i].length) {
                        this.tiling.tFront[i].push(next);
                        next = null;
                    } else {
                        this.tiling.tFront[i].push(this.tiling.front[i][0]);
                    }
                } else {
                    this.tiling.tFront[i].push(next);
                    next = null;
                }
            }
        }

        this.expandRemainingTFront();
    }

    findNextTFrontFromBack(index) {
        let i,
            back,
            minFront;

        for (i = 0; i < this.tiling.back[index].length; ++i) {
            back = this.tiling.back[index][i];
            if (this.getFirstIndexOf(back, this.tiling.tBack[index]) === -1) {
                this.expandTFront(back);
                minFront = minFront || back;

                if (back !== minFront && (this.getFirstIndexOf(minFront, this.tiling.tFront[back]) > -1 || this.sharesLinchPin(minFront, back))) {
                    minFront = back;
                }
            }
        }

        return minFront;
    }

    sharesLinchPin(minFront, index) {
        let tBack = this.tiling.tBack[minFront],
            linchPin = tBack[tBack.length - 1];

        if (linchPin && this.getFirstIndexOf(linchPin, this.tiling.tFront[index]) > -1) {
            return true;
        }

        return false;
    }

    expandTFront(index) {
        if (this.tiling.tFront[index].length === 1) {
            let next = this.tiling.tFront[this.tiling.tFront[index][0]][0];

            while (next) {
                this.tiling.tFront[index].push(next);
                if (this.tiling.tFront[next].length > 0) {
                    next = this.tiling.tFront[next][0];
                } else {
                    return;
                }
            }
        }
    }

    expandRemainingTFront() {
        let i;

        for (i = 0; i < this.tiling.tFront.length; ++i) {
            this.expandTFront(i);
        }

        this.calculateDxs();
    }

    calculateDxs() {
        let i,
            j,
            chain,
            width,
            unset;

        for (i = 0; i < this.tiling.tBack.length; ++i) {
            if (this.tiling.dx[i] === 1) {
                if (this.tiling.tFront[i].length === 0) {
                    for (j = 0; j < this.tiling.tBack[i].length; ++j) {
                        this.tiling.dx[i] -= this.tiling.dx[this.tiling.tBack[i][j]];
                    }
                } else {
                    chain = this.findLongestChainThroughNode(i);
                    unset = 0;
                    width = 0;

                    for (j = 0; j < chain.length; ++j) {
                        if (this.tiling.dx[chain[j]] < 1) {
                            width += this.tiling.dx[chain[j]];
                        } else {
                            ++unset;
                        }
                    }

                    this.tiling.dx[i] = (1 - width) / unset;
                }
            }
        }

        this.calculateXs();
    }

    findLongestChainThroughNode(index) {
        let i,
            chain = this.tiling.tBack[index].concat([index]).concat(this.tiling.tFront[index]);

        for (i = index; i < this.tiling.front[index].length; ++i) {
            if ((this.getFirstIndexOf(index, this.tiling.tBack[i]) > -1 || this.getFirstIndexOf(index, this.tiling.tFront[i]) > -1)
                    && this.tiling.tBack[i].length + this.tiling.tFront[i].length + 1 > chain.length) {
                chain = this.tiling.tBack[i].concat([i]).concat(this.tiling.tFront[i]);
            }
        }

        return chain;
    }

    calculateXs() {
        let i,
            last;

        for (i = 1; i < this.tiling.dx.length; ++i) {
            if (this.tiling.tBack[i].length > 0) {
                last = this.tiling.tBack[i][this.tiling.tBack[i].length - 1];
                this.tiling.x[i] = this.tiling.x[last] + this.tiling.dx[last];
            }
        }
    }
}<|endoftext|>


<commit_before>angular.module('webtools').controller('fmController', ['$scope', 'fmModel', 'fmService', '$interval', function ($scope, fmModel, fmService, $interval) {
    $scope.fmModel = fmModel;

    var intervalScanner;

    $scope.init = function () {
        fmService.getSettings();
        fmService.getSectionsList();

        $scope.scanStatus();
    }

    $scope.resetSettings = function () {
        fmService.resetSettings();
    }
    $scope.saveSettings = function () {
        fmService.setSettings();
    }

    $scope.scanStart = function (section) {
        fmModel.selectedSection = section;
        fmService.scanSection(fmModel.selectedSection.key);
    }

    $scope.scanStatus = function () {
        intervalScanner = $interval(function () {
            fmService.getStatus(function () {
                if (!fmModel.scanning) {
                    $interval.cancel(intervalScanner);
                }
            });
        }, 100);
    }

    $scope.scanResult = function () {
        fmService.getResult();
    }

    $scope.scanStop = function () {
        $interval.cancel(intervalScanner);
        fmService.abort();
    }

    $scope.init();
}]);<commit_msg>FM Forgot call to func...<commit_after>angular.module('webtools').controller('fmController', ['$scope', 'fmModel', 'fmService', '$interval', function ($scope, fmModel, fmService, $interval) {
    $scope.fmModel = fmModel;

    var intervalScanner;

    $scope.init = function () {
        fmService.getSettings();
        fmService.getSectionsList();

        $scope.scanStatus();
    }

    $scope.resetSettings = function () {
        fmService.resetSettings();
    }
    $scope.saveSettings = function () {
        fmService.setSettings();
    }

    $scope.scanStart = function (section) {
        fmModel.selectedSection = section;
        fmService.scanSection(fmModel.selectedSection.key);

        $scope.scanStatus();
    }

    $scope.scanStatus = function () {
        intervalScanner = $interval(function () {
            fmService.getStatus(function () {
                if (!fmModel.scanning) {
                    $interval.cancel(intervalScanner);
                }
            });
        }, 100);
    }

    $scope.scanResult = function () {
        fmService.getResult();
    }

    $scope.scanStop = function () {
        $interval.cancel(intervalScanner);
        fmService.abort();
    }

    $scope.init();
}]);<|endoftext|>


<commit_before>;(function($) {
        if (!$.suggest) {
            alert("$.suggest required");
        }

        $.suggest("suggestterm",
                  $.extend(
                		  true,
                		  {},
                		  $.suggest.suggest.prototype,
                		  {
                			  create_item: function(data,response_data) {
	                             var css = this.options.css;

	                             var li = $("
").addClass(css.item);
	                             var name = $("
").addClass(css.item_name)
	                                 .append($("")
	                                 .append($.suggest.strongify(data.name,response_data.prefix)));
	                             // this converts html escaped strings like "&"
	                             // back to "&"
	                             data.name = name.text();
	                             li.append(name);
	                             name.prepend($("
").addClass(css.item_type).text(data.id));
	                             //TODO very smelly hack to disable cache
	                             $.suggest.cache = {};
	                             return li;
	                         },

	                         request: function(value, cursor) {
	                        	 var self = this,
	                        	 o = this.options;

	                        	 var data = {};
	                        	 var query = value;
	                             data[o.query_param_name] = query;

	                             clearTimeout(this.request.timeout);
                    	    	 data["prefix"] = query;
                    	    	 data["type_strict"] = "classes";
                    	    	 data["type"] = theProject.id;

                    	    	 var url = o.service_url + o.service_path + "?" + $.param(data, true);
	                             var ajax_options = {
	                            		 url: o.service_url + o.service_path,
	                            	     data: data,
	                            	     traditional: true,
                            	        error: function(xhr) {
                            	            self.status_error();
                            	            self.trackEvent(self.name, "request", "error", {
                            	              url: this.url,
                            	              response: xhr ? xhr.responseText : ''
                            	            });
                            	            self.input.trigger("fb-error", Array.prototype.slice.call(arguments));
                            	          },
                            	          complete: function(xhr) {
                            	            if (xhr) {
                            	              self.trackEvent(self.name, "request", "tid",
                            	              xhr.getResponseHeader("X-Metaweb-TID"));
                            	            }
                            	          },
                            	        success: function(data) {
                            	            $.suggest.cache[url] = data;
                            	            data.prefix = value;  // keep track of prefix to match up response with input value
                            	            self.response(data, cursor ? cursor : -1);
                            	          },
                            	          dataType: "json",
                            	          cache: true
	                             };
	                             this.request.timeout = setTimeout(function() {
	                                 $.ajax(ajax_options);
	                               }, o.xhr_delay);

	                         },
	                         flyout_request:function(data){
	                             var self = this;

	                             var o = this.options,
	                             sug_data = this.flyoutpane.data("data.suggest");
	                             if (sug_data && data.id === sug_data.id) {
	                                 if (!this.flyoutpane.is(":visible")) {
	                                     var s = this.get_selected();
	                                     this.flyout_position(s);
	                                     this.flyoutpane.show();
	                                     this.input.trigger("fb-flyoutpane-show", this);
	                                 }
	                                 return;
	                             }

	                             // check $.suggest.flyout.cache
	                             var cached = $.suggest.flyout.cache[data.id];
	                             if (cached) {
	                                 this.flyout_response(cached);
	                                 return;
	                             }

	                             clearTimeout(this.flyout_request.timeout);
	                             this.flyout_request.timeout =
	                                 setTimeout(function(){self.flyout_response(data);}, o.xhr_delay);

	                         },

	                         flyout_response:function(data){
	                             var o = this.options,
	                             p = this.pane,
	                             s = this.get_selected() || [];
	                             if (p.is(":visible") && s.length) {
	                                 var sug_data = s.data("data.suggest");
	                                 if (sug_data && data.id === sug_data.id) {
	                                     this.flyoutpane.html('
' + data.description + '
');
	                                     this.flyout_position(s);
	                                     this.flyoutpane.show()
	                                         .data("data.suggest", sug_data);
	                                     this.input.trigger("fb-flyoutpane-show", this);
	                                 }
	                             }
	                         }
                       }));

     $.extend($.suggest.suggestterm, {
         defaults:  $.extend(
        		 true,
        		 {},
        		 $.suggest.suggest.defaults,
        		 {
        			 service_url: "",
        			 service_path: "command/rdf-extension/suggest-term",
        			 flyout_service_path: "command/rdf-extension/suggest-term",
        			 type_strict:"classes",
        			 suggest_new:"Add it",
        			 cache:false,
        			 //             soft:true,
        			 nomatch:'No suggested matches. (Shift + Enter) to add it'
         })
     });

})(jQuery);
<commit_msg>Fixed message when there are no matches<commit_after>;(function($) {
        if (!$.suggest) {
            alert("$.suggest required");
        }

        $.suggest("suggestterm",
                  $.extend(
                		  true,
                		  {},
                		  $.suggest.suggest.prototype,
                		  {
                			  create_item: function(data,response_data) {
	                             var css = this.options.css;

	                             var li = $("
").addClass(css.item);
	                             var name = $("
").addClass(css.item_name)
	                                 .append($("")
	                                 .append($.suggest.strongify(data.name,response_data.prefix)));
	                             // this converts html escaped strings like "&"
	                             // back to "&"
	                             data.name = name.text();
	                             li.append(name);
	                             name.prepend($("
").addClass(css.item_type).text(data.id));
	                             //TODO very smelly hack to disable cache
	                             $.suggest.cache = {};
	                             return li;
	                         },

	                         request: function(value, cursor) {
	                        	 var self = this,
	                        	 o = this.options;

	                        	 var data = {};
	                        	 var query = value;
	                             data[o.query_param_name] = query;

	                             clearTimeout(this.request.timeout);
                    	    	 data["prefix"] = query;
                    	    	 data["type_strict"] = "classes";
                    	    	 data["type"] = theProject.id;

                    	    	 var url = o.service_url + o.service_path + "?" + $.param(data, true);
	                             var ajax_options = {
	                            		 url: o.service_url + o.service_path,
	                            	     data: data,
	                            	     traditional: true,
                            	        error: function(xhr) {
                            	            self.status_error();
                            	            self.trackEvent(self.name, "request", "error", {
                            	              url: this.url,
                            	              response: xhr ? xhr.responseText : ''
                            	            });
                            	            self.input.trigger("fb-error", Array.prototype.slice.call(arguments));
                            	          },
                            	          complete: function(xhr) {
                            	            if (xhr) {
                            	              self.trackEvent(self.name, "request", "tid",
                            	              xhr.getResponseHeader("X-Metaweb-TID"));
                            	            }
                            	          },
                            	        success: function(data) {
                            	            $.suggest.cache[url] = data;
                            	            data.prefix = value;  // keep track of prefix to match up response with input value
                            	            self.response(data, cursor ? cursor : -1);
                            	          },
                            	          dataType: "json",
                            	          cache: true
	                             };
	                             this.request.timeout = setTimeout(function() {
	                                 $.ajax(ajax_options);
	                               }, o.xhr_delay);

	                         },
	                         flyout_request:function(data){
	                             var self = this;

	                             var o = this.options,
	                             sug_data = this.flyoutpane.data("data.suggest");
	                             if (sug_data && data.id === sug_data.id) {
	                                 if (!this.flyoutpane.is(":visible")) {
	                                     var s = this.get_selected();
	                                     this.flyout_position(s);
	                                     this.flyoutpane.show();
	                                     this.input.trigger("fb-flyoutpane-show", this);
	                                 }
	                                 return;
	                             }

	                             // check $.suggest.flyout.cache
	                             var cached = $.suggest.flyout.cache[data.id];
	                             if (cached) {
	                                 this.flyout_response(cached);
	                                 return;
	                             }

	                             clearTimeout(this.flyout_request.timeout);
	                             this.flyout_request.timeout =
	                                 setTimeout(function(){self.flyout_response(data);}, o.xhr_delay);

	                         },

	                         flyout_response:function(data){
	                             var o = this.options,
	                             p = this.pane,
	                             s = this.get_selected() || [];
	                             if (p.is(":visible") && s.length) {
	                                 var sug_data = s.data("data.suggest");
	                                 if (sug_data && data.id === sug_data.id) {
	                                     this.flyoutpane.html('
' + data.description + '
');
	                                     this.flyout_position(s);
	                                     this.flyoutpane.show()
	                                         .data("data.suggest", sug_data);
	                                     this.input.trigger("fb-flyoutpane-show", this);
	                                 }
	                             }
	                         }
                       }));

     $.extend($.suggest.suggestterm, {
         defaults:  $.extend(
        		 true,
        		 {},
        		 $.suggest.suggest.defaults,
        		 {
        			 service_url: "",
        			 service_path: "command/rdf-extension/suggest-term",
        			 flyout_service_path: "command/rdf-extension/suggest-term",
        			 type_strict:"classes",
        			 suggest_new:"Add it",
        			 cache:false,
        			 //             soft:true,
        			 nomatch:  {
        				 title: 'No suggested matches. (Shift + Enter) to add it',
        				 heading: null,
        				 tips: null
        				 }
         })
     });

})(jQuery);
<|endoftext|>


<commit_before>
function loadUrl(newLocation)
{
  window.location = newLocation;
  return false;
}
<commit_msg>Update setup.js<commit_after>
function loadUrl(newLocation)
{
  window.location = newLocation;
  return false;
}

function injectJS(path)
{

    var script = document.createElement('script');
    script.onload = function() {
      onStart();
    };
    script.src = path;
    document.getElementsByTagName('head')[0].appendChild(script);
}

<|endoftext|>


<commit_before>'use strict';

const version = 'v0.01::';
const staticCacheName = version + 'static';

function updateStaticCache() {
    return caches.open(staticCacheName)
        .then( cache => {
            // These items must be cached for the Service Worker to complete installation
            return cache.addAll([
                '/~jason/meta/scripts/global.js',
                '/~jason/meta/styles/global.css',
                '/~jason/meta/fonts/Open-Sans-700/Open-Sans-700.ttf',
                '/~jason/meta/fonts/Open-Sans-700/Open-Sans-700.woff',
                '/~jason/meta/fonts/Open-Sans-regular/Open-Sans-regular.ttf',
                '/~jason/meta/fonts/Open-Sans-regular/Open-Sans-regular.woff',
                '/~jason/meta/img/catalog-card.png',
                '/~jason/meta/img/catalog-card-small.png',
                '/~jason/meta/img/clark-profile.jpg',
                '/~jason/meta/img/dog.jpg',
                '/~jason/meta/inc/footer.html',
                '/~jason/meta/inc/header.html',
                '/~jason/404.html',
                '/~jason/about.html',
                '/~jason/code.html',
                '/~jason/contact.html',
                '/~jason/index.html',
                '/~jason/resume.html',
                '/~jason/search.html',
                '/~jason/sitemap.html',
                '/~jason/talks.html',
                '/~jason/files/clark-jason-cv.pdf',
                '/',
                '/~jason/offline.html'
            ]);
        });
}

// Remove caches whose name is no longer valid
function clearOldCaches() {
    return caches.keys()
        .then( keys => {
            return Promise.all(keys
                .filter(key => key.indexOf(version) !== 0)
                .map(key => caches.delete(key))
            );
        });
}

self.addEventListener('install', event => {
    event.waitUntil(updateStaticCache()
        .then( () => self.skipWaiting() )
    );
});

self.addEventListener('activate', event => {
    event.waitUntil(clearOldCaches()
        .then( () => self.clients.claim() )
    );
});

self.addEventListener('fetch', event => {
    let request = event.request;
    let url = new URL(request.url);

    // Ignore requests to some directories
    if (request.url.indexOf('/~jason/dev/') !== -1 || request.url.indexOf('/~jason/files/') !== -1) {
        return;
    }

    // Look in the cache first, fall back to the network, finally offline page
    event.respondWith(
        caches.match(request)
            .then(response => {
                // CACHE
                return response || fetch(request)
                    .then( response => {
                        // NETWORK
                        return response;
                    })
            })
            .catch(function () {
                return caches.match(request)
                    .then(function (response) {
                        return response || caches.match('/~jason/offline.html');
                    })
            })
    );
});
<commit_msg>standardized whitespace and comments<commit_after>'use strict';
const version = 'v0.01::';
const staticCacheName = version + 'static';

function updateStaticCache() {
  return caches.open(staticCacheName).then(cache => {
    // these items must be cached for the Service Worker to complete installation
    return cache.addAll([
      '/~jason/meta/scripts/global.js',
      '/~jason/meta/styles/global.css',
      '/~jason/meta/fonts/Open-Sans-700/Open-Sans-700.ttf',
      '/~jason/meta/fonts/Open-Sans-700/Open-Sans-700.woff',
      '/~jason/meta/fonts/Open-Sans-regular/Open-Sans-regular.ttf',
      '/~jason/meta/fonts/Open-Sans-regular/Open-Sans-regular.woff',
      '/~jason/meta/img/catalog-card.png',
      '/~jason/meta/img/catalog-card-small.png',
      '/~jason/meta/img/clark-profile.jpg',
      '/~jason/meta/img/dog.jpg',
      '/~jason/meta/inc/footer.html',
      '/~jason/meta/inc/header.html',
      '/~jason/404.html',
      '/~jason/about.html',
      '/~jason/code.html',
      '/~jason/contact.html',
      '/~jason/index.html',
      '/~jason/resume.html',
      '/~jason/search.html',
      '/~jason/sitemap.html',
      '/~jason/talks.html',
      '/~jason/files/clark-jason-cv.pdf',
      '/',
      '/~jason/offline.html'
    ]);
  });
}
// remove caches whose name is no longer valid
function clearOldCaches() {
  return caches.keys().then(keys => {
    return Promise.all(keys.filter(key => key.indexOf(version) !== 0).map(key => caches.delete(key)));
  });
}
self.addEventListener('install', event => {
  event.waitUntil(updateStaticCache().then(() => self.skipWaiting()));
});
self.addEventListener('activate', event => {
  event.waitUntil(clearOldCaches().then(() => self.clients.claim()));
});
self.addEventListener('fetch', event => {
  let request = event.request;
  let url = new URL(request.url);
  // ignore requests to some directories
  if (request.url.indexOf('/~jason/dev/') !== -1 || request.url.indexOf('/~jason/files/') !== -1) {
    return;
  }
  // look in the cache first, fall back to the network, finally offline page
  event.respondWith(caches.match(request).then(response => {
    // CACHE
    return response || fetch(request).then(response => {
      // NETWORK
      return response;
    })
  }).catch(function() {
    return caches.match(request).then(function(response) {
      return response || caches.match('/~jason/offline.html');
    })
  }));
});<|endoftext|>