<commit_before>var app = app || {};

app.UserEditView = Backbone.View.extend({
    template: _.template($('#user-edit-template').html()),
    tagName: 'div',
    className: 'user-edit',

    events: {
        'keyup .search': 'onUsersKeyUp',
        'click #user-select-btn': 'onUserSelectBtnClick',
        'click .save-permissions-btn': 'onSaveClick',
        'click #clear-console': 'onClearConsoleClick',
        'click .export-permissions': 'onExportBtnClick',
        'click .purge-user-btn': 'onPurgeBtnClick',
        'click .search-clear' : 'onSearchClear'
    },

    initialize: function(options) {
        Backbone.pubSub.on('user:selected-permissions-fetched', this.onSelectedPermissionsFetched, this);
        this.state_map = {
            user_permissions: null,
            pendingSaves: 0,
            pendingRemoves: 0,
            totalUpdates: 0,
            progressUpdateRatio: 0,
            currentProgress: 0,
            failed: {
                add: [],
                remove: [],
                purge: []
            },
            success: {
                add: [],
                remove: [],
                purge: []
            }
        }

    },

    select: function(e) {
        Backbone.pubSub.trigger('user:select', this.model);
    },

    render: function() {
        this.$el.html(this.template(this.model.toJSON()));
        this.$users = this.$('#users');
        this.$user_search_container = this.$('.search-container');
        this.$user_search = this.$('.search');
        this.$user_attributes = this.$('.user-attr');
        this.$name = this.$('#name');
        this.$name_container = this.$('#name-container');
        this.$messages = this.$('.messages');
        this.$notify = this.$('.notify');
        this.$progress_meter = this.$('.meter');
        this.$progressbar = this.$('.progress');
        this.$progress_text = this.$('.current-progress');
        this.$search_clear = this.$('.search-clear');
        this.$search = this.$('.search');
        if (this.model.get('name') == '') {
            this.$name.text('Select a User');
        }

        this.libraryViewUsers = new app.LibraryUserView({
            el: this.$users[0],
            collection: app.UserCollection,
            itemView: app.UserView
        });

        this.libraryViewUsers.render();

        Backbone.pubSub.on('user:select', this.userSelect, this);
        if (this.model.get('id') != '') {
            this.userSelect(this.model, false);
        }
        return this;
    },

    search: function() {
        var val = this.$user_search.val(),
            options,
            searchAllAttributes = false;

        //check for search operand character '~'
        if (val.indexOf('~') == 0) {
            //set val to exclude '~'
            val = val.substring(1);
            searchAllAttributes = true;
        }

        options = (searchAllAttributes ? {
            val: val
        } : {
            key: 'name',
            val: val
        });

        if(val.length > 0 ){
             this.$search_clear.removeClass('hidden');
        } else {
            this.$search_clear.addClass('hidden');
        }

        Backbone.pubSub.trigger('library_users:search', options);
    },
    onUserSelectBtnClick: function(e) {

        (function(that) {
            setTimeout(function() {
                that.$user_search.focus();
            }, 0);
        })(this);
    },
    onSearchClear: function(e){
        this.$search.val('');
        this.$search.trigger('keyup');
        e.stopPropagation();
         this.$user_search.focus();
    },
    onUsersKeyUp: function(e) {
        this.search();
    },
    onSelectedPermissionsFetched: function(selected_permissions) {
        var user_permissions = new Backbone.Collection(this.model.get('permissions')),
            user_permission_index,
            add_permissions_arr = [],
            remove_permissions_arr = [],
            user = this.model.attributes;

        //iterate through selected permissions
        selected_permissions.forEach(function(permission) {
            //check if permissions is in user permissions
            //user_permission_index = user_permissions_arr.indexOf(permission);
            user_permission = user_permissions.findWhere({
                name: permission
            });
            if (typeof user_permission !== 'undefined') {
                //remove permission from user permissions
                user_permissions.remove(user_permission);

            } else {
                //add permission to add permission array
                add_permissions_arr.push(permission);
            }
        });
        this.state_map.user_permissions = user_permissions;
        //set remove permissions to the remaining user permissions...for contextual reasons
        remove_permissions_arr = user_permissions.map(function(obj) {
                return obj.get('name');
            }),

            //set state map variables
            this.state_map.pendingSaves = add_permissions_arr.length;
        this.state_map.pendingRemoves = remove_permissions_arr.length;
        this.state_map.totalUpdates = this.state_map.pendingRemoves + this.state_map.pendingSaves;
        this.state_map.progressUpdateRatio = 100 / this.state_map.totalUpdates;
        if (add_permissions_arr.length == 0 && remove_permissions_arr.length == 0) {
            return;
        }

        this.$messages.append('' + app.utility.getDateTime() + '
Modifying [' + user.name + ']\'s permissions
');
        //add user permissions
        if (add_permissions_arr.length > 0) {
            (function(that) {
                app.data.modifyPermissions(add_permissions_arr, 0, user, app.config.url, 'add', function(results) {
                    that.processPermissionModify(results);
                });
            })(this);
        }
        //remove user permissions
        if (remove_permissions_arr.length > 0) {
            (function(that) {
                app.data.modifyPermissions(remove_permissions_arr, 0, user, app.config.url, 'remove', function(results) {
                    that.processPermissionModify(results);
                });
            })(this);
        }
    },

    onSaveClick: function(e) {
        this.resetStateMap();
        //update progress bar
        this.$progress_meter.width('0%');
        this.$progress_text.text('0%');
        //publish user selected event
        Backbone.pubSub.trigger('user:save-permissions');
    },

    onClearConsoleClick: function(e) {
        this.clearConsole();
    },

    onExportBtnClick: function(e) {
        var permissions = this.model.get('permissions'),
        ua = window.navigator.userAgent,
         msie = ua.indexOf("MSIE "),
         permissionsElement;

    if (msie > 0) {     // If Internet Explorer, return version number
        permissionsElement = '
' + this.model.get('name') + '\'s Permissions

';
        permissionsElement += permissions.reduce(function(memo, obj){
            return (typeof memo == "string" ? memo :  '
' + memo.name + '
') + '
' + obj.name + '
';
        });
        permissionsElement += '
';
        app.utility.printToNewWindow(permissionsElement);
    } else {
        app.utility.JSONToCSVConvertor(permissions, this.model.get('name') + ' Permissions', true);
     }

    },

    onPurgeBtnClick: function(e) {
        var user = this.model.attributes;

        this.$messages.append('' + app.utility.getDateTime() + '
' + message + '
');
        this.$messages.scrollTop(this.$messages[0].scrollHeight);
        (function(that){
            app.data.removeUserFromWeb(app.config.url, user, function(results) {
                this.$messages.append('' + app.utility.getDateTime() + '
Modifying [' + user.name + ']\'s permissions
');
            });
        })(this);
    },

    onRemoveUserComplete: function(results) {
        var type = results.type,
            data = results.data,
            name = this.model.get('name'),
            message = '';

        if (type != 'error') {
            message = 'Succesfully removed ' + name + ' from site.';
        } else {
            message = 'Unsuccessfully removed ' + name + ' from site.';
        }

        this.$messages.append('' + app.utility.getDateTime() + '' + message + '
');
    },

    clearConsole: function() {
        this.$messages.html('');
    },

    processPermissionModify: function(results) {
        var operation = results.operation,
            type = results.type,
            data = results.data,
            permission = results.permission,
            message = '',
            class_map = {
                'success': 'success',
                'error': 'error'
            };

        if (type == 'success') {
            this.state_map.success[operation].push(permission);
            message = '['+ permission + '] succesfully ' + (operation == 'add' ? 'added.' : 'removed.');
        } else { //error
            this.state_map.failed[operation].push(permission);
            message = 'Unable to ' + operation + ' [' + permission + '].'
        }
        this.updateProgress(operation);
        this.$messages.append('' + app.utility.getDateTime() + '
' + message + '
');
        this.$messages.scrollTop(this.$messages[0].scrollHeight);
        if (this.state_map.pendingSaves == 0 && this.state_map.pendingRemoves == 0) {
            this.permissionModifyComplete();
        }
    },
    permissionModifyComplete: function() {
        var user = this.model;
        this.$messages.append('' + app.utility.getDateTime() + '
Completed modifying [' + user.get('name') + ']\'s permissions
');
        this.$messages.scrollTop(this.$messages[0].scrollHeight);

        this.userSelect(user, true);
    },
    updateProgress: function(operation) {
        this.state_map.currentProgress += this.state_map.progressUpdateRatio;
        //clip progress if needed
        this.state_map.currentProgress = (this.state_map.currentProgress >= 100 ? 100 : this.state_map.currentProgress);
        this.state_map.pendingRemoves -= (operation == 'remove' ? 1 : 0);
        this.state_map.pendingSaves -= (operation == 'add' ? 1 : 0);

        //update progress bar
        this.$progress_meter.width(this.state_map.currentProgress + '%');
        this.$progress_text.text(this.state_map.currentProgress + '%');
    },
    resetStateMap: function() {
        this.state_map.pendingRemoves = 0;
        this.state_map.pendingSaves = 0;
        this.state_map.pendingSaves = 0;
        this.state_map.pendingRemoves = 0;
        this.state_map.totalUpdates = 0;
        this.state_map.progressUpdateRatio = 0;
        this.state_map.failed.add = [];
        this.state_map.failed.remove = [];
        this.state_map.failed.purge = [];
        this.state_map.success.add = [];
        this.state_map.success.remove = [];
        this.state_map.success.purge = [];
    },
    userSelect: function(user, options) {

        if (!user.hasOwnProperty('attributes')) {
            return;
        }
        this.model = user;
        this.$user_attributes.each(function(i, el) {
            $(el).val(user.attributes[el.id]);
        });

        if (!user.attributes.hasOwnProperty('loginname')) {
            return false;
        }

        //fetch user permissions
        this.getUserPermissions(user.attributes.loginname);

        //update message
        this.$messages.append('' + app.utility.getDateTime() + '
Fetching [' + this.model.get('name') + ']\'s permissions
');
        this.$messages.scrollTop(this.$messages[0].scrollHeight);
        //update progress bar
        this.$progress_meter.width('0%');
        this.$progress_text.text('0%');
        //publish user selected event
        //set router
        if (options && options.route) {
            app.router.navigate('edit/' + user.attributes.loginname.replace('/', '\\'), false);
            Backbone.pubSub.trigger('user:selected');
        } else {
            app.router.navigate('edit/' + user.attributes.loginname.replace('/', '\\'), false);
             Backbone.pubSub.trigger('user:selected');
        }

    },
    getUserPermissions: function(loginname) {
        (function(that) {
            app.data.getPermissions(app.config.url, loginname, function(results) {
                //format results
                results = app.utility.processData(results);
                //set selected user model permissions
                that.model.set({
                    permissions: results
                });
                //publish results globally
                Backbone.pubSub.trigger('user:permissions-fetched', results);
                that.$messages.append('' + app.utility.getDateTime() + '
Completed fetching [' + that.model.get('name') + ']\'s permissions
');
                that.$messages.scrollTop(that.$messages[0].scrollHeight);
                that.$progress_meter.width('100%');
                that.$progress_text.text('100%');
            });
        })(this);
    },
    toggleUserDropdown: function() {
        if (this.$name_container.is(':visible')) {
            this.$name_container.hide();
            this.$user_search_container.show();
            this.$users.show();
            this.$user_search.focus();
            this.$users.height(function(index, height) {
                return (window.innerHeight - $(this).offset().top) * 0.9;
            });

            this.$users.width(function(index, height) {
                return (window.innerWidth - $(this).offset().left) * 0.9;
            });
        } else {
            this.$name_container.show();
            this.$user_search_container.hide();
            this.$users.hide();
        }
    }
});
<commit_msg>fixed user route change<commit_after>var app = app || {};

app.UserEditView = Backbone.View.extend({
    template: _.template($('#user-edit-template').html()),
    tagName: 'div',
    className: 'user-edit',

    events: {
        'keyup .search': 'onUsersKeyUp',
        'click #user-select-btn': 'onUserSelectBtnClick',
        'click .save-permissions-btn': 'onSaveClick',
        'click #clear-console': 'onClearConsoleClick',
        'click .export-permissions': 'onExportBtnClick',
        'click .purge-user-btn': 'onPurgeBtnClick',
        'click .search-clear' : 'onSearchClear'
    },

    initialize: function(options) {
        Backbone.pubSub.on('user:selected-permissions-fetched', this.onSelectedPermissionsFetched, this);
        this.state_map = {
            user_permissions: null,
            pendingSaves: 0,
            pendingRemoves: 0,
            totalUpdates: 0,
            progressUpdateRatio: 0,
            currentProgress: 0,
            failed: {
                add: [],
                remove: [],
                purge: []
            },
            success: {
                add: [],
                remove: [],
                purge: []
            }
        }

    },

    select: function(e) {
        Backbone.pubSub.trigger('user:select', this.model);
    },

    render: function() {
        this.$el.html(this.template(this.model.toJSON()));
        this.$users = this.$('#users');
        this.$user_search_container = this.$('.search-container');
        this.$user_search = this.$('.search');
        this.$user_attributes = this.$('.user-attr');
        this.$name = this.$('#name');
        this.$name_container = this.$('#name-container');
        this.$messages = this.$('.messages');
        this.$notify = this.$('.notify');
        this.$progress_meter = this.$('.meter');
        this.$progressbar = this.$('.progress');
        this.$progress_text = this.$('.current-progress');
        this.$search_clear = this.$('.search-clear');
        this.$search = this.$('.search');
        if (this.model.get('name') == '') {
            this.$name.text('Select a User');
        }

        this.libraryViewUsers = new app.LibraryUserView({
            el: this.$users[0],
            collection: app.UserCollection,
            itemView: app.UserView
        });

        this.libraryViewUsers.render();

        Backbone.pubSub.on('user:select', this.userSelect, this);
        if (this.model.get('id') != '') {
            this.userSelect(this.model, false);
        }
        return this;
    },

    search: function() {
        var val = this.$user_search.val(),
            options,
            searchAllAttributes = false;

        //check for search operand character '~'
        if (val.indexOf('~') == 0) {
            //set val to exclude '~'
            val = val.substring(1);
            searchAllAttributes = true;
        }

        options = (searchAllAttributes ? {
            val: val
        } : {
            key: 'name',
            val: val
        });

        if(val.length > 0 ){
             this.$search_clear.removeClass('hidden');
        } else {
            this.$search_clear.addClass('hidden');
        }

        Backbone.pubSub.trigger('library_users:search', options);
    },
    onUserSelectBtnClick: function(e) {

        (function(that) {
            setTimeout(function() {
                that.$user_search.focus();
            }, 0);
        })(this);
    },
    onSearchClear: function(e){
        this.$search.val('');
        this.$search.trigger('keyup');
        e.stopPropagation();
         this.$user_search.focus();
    },
    onUsersKeyUp: function(e) {
        this.search();
    },
    onSelectedPermissionsFetched: function(selected_permissions) {
        var user_permissions = new Backbone.Collection(this.model.get('permissions')),
            user_permission_index,
            add_permissions_arr = [],
            remove_permissions_arr = [],
            user = this.model.attributes;

        //iterate through selected permissions
        selected_permissions.forEach(function(permission) {
            //check if permissions is in user permissions
            //user_permission_index = user_permissions_arr.indexOf(permission);
            user_permission = user_permissions.findWhere({
                name: permission
            });
            if (typeof user_permission !== 'undefined') {
                //remove permission from user permissions
                user_permissions.remove(user_permission);

            } else {
                //add permission to add permission array
                add_permissions_arr.push(permission);
            }
        });
        this.state_map.user_permissions = user_permissions;
        //set remove permissions to the remaining user permissions...for contextual reasons
        remove_permissions_arr = user_permissions.map(function(obj) {
                return obj.get('name');
            }),

            //set state map variables
            this.state_map.pendingSaves = add_permissions_arr.length;
        this.state_map.pendingRemoves = remove_permissions_arr.length;
        this.state_map.totalUpdates = this.state_map.pendingRemoves + this.state_map.pendingSaves;
        this.state_map.progressUpdateRatio = 100 / this.state_map.totalUpdates;
        if (add_permissions_arr.length == 0 && remove_permissions_arr.length == 0) {
            return;
        }

        this.$messages.append('' + app.utility.getDateTime() + '
Modifying [' + user.name + ']\'s permissions
');
        //add user permissions
        if (add_permissions_arr.length > 0) {
            (function(that) {
                app.data.modifyPermissions(add_permissions_arr, 0, user, app.config.url, 'add', function(results) {
                    that.processPermissionModify(results);
                });
            })(this);
        }
        //remove user permissions
        if (remove_permissions_arr.length > 0) {
            (function(that) {
                app.data.modifyPermissions(remove_permissions_arr, 0, user, app.config.url, 'remove', function(results) {
                    that.processPermissionModify(results);
                });
            })(this);
        }
    },

    onSaveClick: function(e) {
        this.resetStateMap();
        //update progress bar
        this.$progress_meter.width('0%');
        this.$progress_text.text('0%');
        //publish user selected event
        Backbone.pubSub.trigger('user:save-permissions');
    },

    onClearConsoleClick: function(e) {
        this.clearConsole();
    },

    onExportBtnClick: function(e) {
        var permissions = this.model.get('permissions'),
        ua = window.navigator.userAgent,
         msie = ua.indexOf("MSIE "),
         permissionsElement;

    if (msie > 0) {     // If Internet Explorer, return version number
        permissionsElement = '
' + this.model.get('name') + '\'s Permissions

';
        permissionsElement += permissions.reduce(function(memo, obj){
            return (typeof memo == "string" ? memo :  '
' + memo.name + '
') + '
' + obj.name + '
';
        });
        permissionsElement += '
';
        app.utility.printToNewWindow(permissionsElement);
    } else {
        app.utility.JSONToCSVConvertor(permissions, this.model.get('name') + ' Permissions', true);
     }

    },

    onPurgeBtnClick: function(e) {
        var user = this.model.attributes;

        this.$messages.append('' + app.utility.getDateTime() + '
' + message + '
');
        this.$messages.scrollTop(this.$messages[0].scrollHeight);
        (function(that){
            app.data.removeUserFromWeb(app.config.url, user, function(results) {
                this.$messages.append('' + app.utility.getDateTime() + '
Modifying [' + user.name + ']\'s permissions
');
            });
        })(this);
    },

    onRemoveUserComplete: function(results) {
        var type = results.type,
            data = results.data,
            name = this.model.get('name'),
            message = '';

        if (type != 'error') {
            message = 'Succesfully removed ' + name + ' from site.';
        } else {
            message = 'Unsuccessfully removed ' + name + ' from site.';
        }

        this.$messages.append('' + app.utility.getDateTime() + '' + message + '
');
    },

    clearConsole: function() {
        this.$messages.html('');
    },

    processPermissionModify: function(results) {
        var operation = results.operation,
            type = results.type,
            data = results.data,
            permission = results.permission,
            message = '',
            class_map = {
                'success': 'success',
                'error': 'error'
            };

        if (type == 'success') {
            this.state_map.success[operation].push(permission);
            message = '['+ permission + '] succesfully ' + (operation == 'add' ? 'added.' : 'removed.');
        } else { //error
            this.state_map.failed[operation].push(permission);
            message = 'Unable to ' + operation + ' [' + permission + '].'
        }
        this.updateProgress(operation);
        this.$messages.append('' + app.utility.getDateTime() + '
' + message + '
');
        this.$messages.scrollTop(this.$messages[0].scrollHeight);
        if (this.state_map.pendingSaves == 0 && this.state_map.pendingRemoves == 0) {
            this.permissionModifyComplete();
        }
    },
    permissionModifyComplete: function() {
        var user = this.model;
        this.$messages.append('' + app.utility.getDateTime() + '
Completed modifying [' + user.get('name') + ']\'s permissions
');
        this.$messages.scrollTop(this.$messages[0].scrollHeight);

        this.userSelect(user, true);
    },
    updateProgress: function(operation) {
        this.state_map.currentProgress += this.state_map.progressUpdateRatio;
        //clip progress if needed
        this.state_map.currentProgress = (this.state_map.currentProgress >= 100 ? 100 : this.state_map.currentProgress);
        this.state_map.pendingRemoves -= (operation == 'remove' ? 1 : 0);
        this.state_map.pendingSaves -= (operation == 'add' ? 1 : 0);

        //update progress bar
        this.$progress_meter.width(this.state_map.currentProgress + '%');
        this.$progress_text.text(this.state_map.currentProgress + '%');
    },
    resetStateMap: function() {
        this.state_map.pendingRemoves = 0;
        this.state_map.pendingSaves = 0;
        this.state_map.pendingSaves = 0;
        this.state_map.pendingRemoves = 0;
        this.state_map.totalUpdates = 0;
        this.state_map.progressUpdateRatio = 0;
        this.state_map.failed.add = [];
        this.state_map.failed.remove = [];
        this.state_map.failed.purge = [];
        this.state_map.success.add = [];
        this.state_map.success.remove = [];
        this.state_map.success.purge = [];
    },
    userSelect: function(user, options) {

        if (!user.hasOwnProperty('attributes')) {
            return;
        }
        this.model = user;
        this.$user_attributes.each(function(i, el) {
            $(el).val(user.attributes[el.id]);
        });

        if (!user.attributes.hasOwnProperty('loginname')) {
            return false;
        }

        //fetch user permissions
        this.getUserPermissions(user.attributes.loginname);

        //update message
        this.$messages.append('' + app.utility.getDateTime() + '
Fetching [' + this.model.get('name') + ']\'s permissions
');
        this.$messages.scrollTop(this.$messages[0].scrollHeight);
        //update progress bar
        this.$progress_meter.width('0%');
        this.$progress_text.text('0%');
        //publish user selected event
        //set router
        if (options && options.route) {
            app.router.navigate('edit/user/' + user.attributes.loginname.replace('/', '\\'), false);
            Backbone.pubSub.trigger('user:selected');
        } else {
            app.router.navigate('edit/user/' + user.attributes.loginname.replace('/', '\\'), false);
             Backbone.pubSub.trigger('user:selected');
        }

    },
    getUserPermissions: function(loginname) {
        (function(that) {
            app.data.getPermissions(app.config.url, loginname, function(results) {
                //format results
                results = app.utility.processData(results);
                //set selected user model permissions
                that.model.set({
                    permissions: results
                });
                //publish results globally
                Backbone.pubSub.trigger('user:permissions-fetched', results);
                that.$messages.append('' + app.utility.getDateTime() + '
Completed fetching [' + that.model.get('name') + ']\'s permissions
');
                that.$messages.scrollTop(that.$messages[0].scrollHeight);
                that.$progress_meter.width('100%');
                that.$progress_text.text('100%');
            });
        })(this);
    },
    toggleUserDropdown: function() {
        if (this.$name_container.is(':visible')) {
            this.$name_container.hide();
            this.$user_search_container.show();
            this.$users.show();
            this.$user_search.focus();
            this.$users.height(function(index, height) {
                return (window.innerHeight - $(this).offset().top) * 0.9;
            });

            this.$users.width(function(index, height) {
                return (window.innerWidth - $(this).offset().left) * 0.9;
            });
        } else {
            this.$name_container.show();
            this.$user_search_container.hide();
            this.$users.hide();
        }
    }
});
<|endoftext|>


<commit_before>#! /usr/env babel-node

const {cd, ls, exec, pwd} = require('shelljs');
const originalDirectory = pwd();

const packages = ls(`${__dirname}/../packages/*`).map(location => ({
  location,
  manifest: require(`${location}/package.json`),
}));

packages.forEach(({location}) => {
  cd(`"${location}"`);
  exec('npm link');
});

const isOurPackage = /^parametric-svg-/;
packages.forEach((
  {location, manifest: {dependencies = {}, devDependencies = {}}}
) => {
  cd(`"${location}"`);
  exec('npm install');

  Object.keys(dependencies).concat(Object.keys(devDependencies))
    .filter(name => isOurPackage.test(name))
    .forEach(name => exec(`npm link ${name}`));
});

cd(originalDirectory);
<commit_msg>Use `child_process.execSync`<commit_after>#! /usr/env babel-node

const {ls} = require('shelljs');
const {execSync} = require('child_process');

const packages = ls(`${__dirname}/../packages/*`).map(cwd => ({
  cwd,
  manifest: require(`${cwd}/package.json`),
}));

packages.forEach(({cwd}) => {
  execSync('npm link', {cwd});
});

const isOurPackage = /^parametric-svg-/;
packages.forEach((
  {cwd, manifest: {dependencies = {}, devDependencies = {}}}
) => {
  execSync('npm install', {cwd});

  Object.keys(dependencies).concat(Object.keys(devDependencies))
    .filter(name => isOurPackage.test(name))
    .forEach(name => execSync(`npm link ${name}`, {cwd}));
});
<|endoftext|>


<commit_before>var gulp     = require('gulp'),
	sequence = require('run-sequence').use(gulp),
	plugins  = require('gulp-load-plugins')(),
	clean    = require('del'),
	shared   = require('../shared'),
	config   = require('../config'),
	id       = 'dist',
	task     = config.tasks[id];

module.exports = gulp;

gulp.task(id, function(callback) {
	return sequence(id + ':lint', id + ':clean', id + ':build', callback);
});

gulp.task(id + ':lint', function() {
	return gulp.src(task.watch)
		.pipe(plugins.eslint())
		.pipe(plugins.eslint.format());
});

gulp.task(id + ':clean', function(callback) {
	return clean(task.clean, callback);
});

gulp.task(id + ':build', function() {
	return gulp.src(task.watch)
		.pipe(plugins.sourcemaps.init())
		.pipe(plugins.plumber({ errorHandler: shared.handleError}))
		.pipe(plugins.uglify({ preserveComments: 'none' }))
		.pipe(plugins.insert.transform(shared.transform))
		.pipe(plugins.chmod(shared.rights))
		.pipe(plugins.size({ showFiles: true, gzip: true }))
		.pipe(plugins.sourcemaps.write('.'))
		.pipe(gulp.dest(task.dest));
});<commit_msg>fix uglify failing<commit_after>var gulp     = require('gulp'),
	sequence = require('run-sequence').use(gulp),
	plugins  = require('gulp-load-plugins')(),
	clean    = require('del'),
	shared   = require('../shared'),
	config   = require('../config'),
	id       = 'dist',
	task     = config.tasks[id];

module.exports = gulp;

gulp.task(id, function(callback) {
	return sequence(id + ':lint', id + ':clean', id + ':build', callback);
});

gulp.task(id + ':lint', function() {
	return gulp.src(task.watch)
		.pipe(plugins.eslint())
		.pipe(plugins.eslint.format());
});

gulp.task(id + ':clean', function(callback) {
	return clean(task.clean, callback);
});

gulp.task(id + ':build', function() {
	return gulp.src(task.watch)
		.pipe(plugins.sourcemaps.init())
		.pipe(plugins.plumber({ errorHandler: shared.handleError}))
		.pipe(plugins.uglify())
		.pipe(plugins.insert.transform(shared.transform))
		.pipe(plugins.chmod(shared.rights))
		.pipe(plugins.size({ showFiles: true, gzip: true }))
		.pipe(plugins.sourcemaps.write('.'))
		.pipe(gulp.dest(task.dest));
});
<|endoftext|>


<commit_before>/**
 * @module  uifactory/tabbedbar
 * @author  Flavio De Stefano <flavio.destefano@caffeinalab.com>
 */

module.exports = function(args) {
	args = args || {};
	_.defaults(args, {
		height: 34,
		tintColor: '#000',
		labelStyle: {},
		borderColor: args.tintColor,
		borderWidth: 1,
		borderRadius: 10
	});

	var $this = Ti.UI.createView(args);

	var labels = [];
	var labelIndex = 0;
	var UIWrapLabels = null;

	$this.getLabels = function() {
		return labels;
	};

	$this.setLabels = function(lbls) {
		labels = [];
		_.each(lbls, function(l){
			labels.push(_.isObject(l) ? l.title : l);
		});

		var width = Math.floor(100 / labels.length) + '%';
		var $wrap = Ti.UI.createView({
			layout: 'horizontal',
		});

		_.each(labels, function(l, i) {

			var lblArgs = _.extend({
				color: $this.color || $this.tintColor,
				font: $this.font,
			}, $this.labelStyle, {
				title: l,
				index: i,
				width: width,
				height: Ti.UI.FILL,
				left: 0,
				right: -1
			});

			$wrap.add(Ti.UI.createButton(lblArgs));
		});

		if (UIWrapLabels !== null) $this.remove(UIWrapLabels);
		$this.add($wrap);
		UIWrapLabels = $wrap;
	};

	$this.getIndex = function() {
		return labelIndex;
	};

	$this.setIndex = function(i) {
		i = parseInt(i, 10);
		if (!_.isNumber(i)) {
			Ti.API.error('UIFactory.Tabbedbar: new index value is not a number');
			return;
		}

		labelIndex = +i;
		_.each(UIWrapLabels && UIWrapLabels.children ? UIWrapLabels.children : [], function($c, i) {
			if (+i === labelIndex) {
				$c.applyProperties({
					backgroundColor: $this.tintColor,
					color: $this.activeColor || $this.backgroundColor || '#fff',
					active: false
				});
			} else {
				$c.applyProperties({
					backgroundColor: 'transparent',
					color: $this.color || $this.tintColor,
					active: true
				});
			}
		});
	};

	//////////////////////
	// Parse arguments //
	//////////////////////

	$this.addEventListener('click', function(e){
		if (e.source.index == null) return;
		$this.setIndex(+e.source.index);
	});

	if (args.labels != null) $this.setLabels(args.labels);
	$this.setIndex(args.index || 0);

	return $this;
};<commit_msg>Fixing Math.floor on TabbedBar<commit_after>/**
 * @module  uifactory/tabbedbar
 * @author  Flavio De Stefano <flavio.destefano@caffeinalab.com>
 */

module.exports = function(args) {
	args = args || {};
	_.defaults(args, {
		height: 34,
		tintColor: '#000',
		labelStyle: {},
		borderColor: args.tintColor,
		borderWidth: 1,
		borderRadius: 10
	});

	var $this = Ti.UI.createView(args);

	var labels = [];
	var labelIndex = 0;
	var UIWrapLabels = null;

	$this.getLabels = function() {
		return labels;
	};

	$this.setLabels = function(lbls) {
		labels = [];
		_.each(lbls, function(l) {
			labels.push(_.isObject(l) ? l.title : l);
		});

		var width = Math.floor(100 / labels.length);
		var latest_width = width + (100 - (width * labels.length));

		var $wrap = Ti.UI.createView({
			layout: 'horizontal',
		});

		_.each(labels, function(title, index) {
			var lblArgs = _.extend({
				color: $this.color || $this.tintColor,
				font: $this.font,
			}, $this.labelStyle, {
				title: title,
				index: index,
				// we have to fix the latest width because and floor(100/3)*3 = 99 < 100
				width: (index == labels.length-1 ? latest_width : width) + '%',
				height: Ti.UI.FILL,
				left: 0,
				right: -1
			});

			$wrap.add(Ti.UI.createButton(lblArgs));
		});

		if (UIWrapLabels !== null) $this.remove(UIWrapLabels);
		$this.add($wrap);
		UIWrapLabels = $wrap;
	};

	$this.getIndex = function() {
		return labelIndex;
	};

	$this.setIndex = function(i) {
		i = parseInt(i, 10);
		if (!_.isNumber(i)) {
			Ti.API.error('UIFactory.Tabbedbar: new index value is not a number');
			return;
		}

		labelIndex = +i;
		_.each(UIWrapLabels && UIWrapLabels.children ? UIWrapLabels.children : [], function($c, i) {
			if (+i === labelIndex) {
				$c.applyProperties({
					backgroundColor: $this.tintColor,
					color: $this.activeColor || $this.backgroundColor || '#fff',
					active: false
				});
			} else {
				$c.applyProperties({
					backgroundColor: 'transparent',
					color: $this.color || $this.tintColor,
					active: true
				});
			}
		});
	};

	//////////////////////
	// Parse arguments //
	//////////////////////

	$this.addEventListener('click', function(e){
		if (e.source.index == null) return;
		$this.setIndex(+e.source.index);
	});

	if (args.labels != null) $this.setLabels(args.labels);
	$this.setIndex(args.index || 0);

	return $this;
};<|endoftext|>


<commit_before>import del from 'del'
import { task, src, dest, series } from 'gulp'
import loadPlugins from 'gulp-load-plugins'
import webpack from 'webpack'

import config from '../../config'
import webpackConfig from '../../build/webpack.config'

const g = loadPlugins()
const { log, PluginError } = g.util

task('clean-docs', () => del(config.paths.docsDist()))

task('generate-docs-json', () => {
  const gulpReactDocgen = require('../plugins/gulp-react-docgen')

  return src([
    `${config.paths.src()}/addons/**/*.js`,
    `${config.paths.src()}/elements/**/*.js`,
    `${config.paths.src()}/collections/**/*.js`,
    `${config.paths.src()}/modules/**/*.js`,
    `${config.paths.src()}/views/**/*.js`,
  ])
    // do not remove the function keyword
    // we need 'this' scope here
    .pipe(g.plumber(function handleError(err) {
      log(err.toString())
      this.emit('end')
    }))
    .pipe(gulpReactDocgen())
    .pipe(dest(config.paths.docsSrc()))
})

task('webpack-docs', (cb) => {
  const compiler = webpack(webpackConfig)

  compiler.run((err, stats) => {
    const { errors, warnings } = stats.toJson()

    log(stats.toString(config.compiler_stats))

    if (err) {
      log('Webpack compiler encountered a fatal error.')
      throw new PluginError('webpack', err.toString())
    }
    if (errors.length > 0) {
      log('Webpack compiler encountered errors.')
      throw new PluginError('webpack', errors.toString())
    }
    if (warnings.length > 0 && config.compiler_fail_on_warning) {
      throw new PluginError('webpack', warnings.toString())
    }

    cb(err)
  })
})

task('docs', series('clean-docs', 'generate-docs-json', 'webpack-docs'))
<commit_msg>fix(docs): build 404.html<commit_after>import del from 'del'
import { task, src, dest, series } from 'gulp'
import loadPlugins from 'gulp-load-plugins'
import webpack from 'webpack'

import config from '../../config'
import webpackConfig from '../../build/webpack.config'

const g = loadPlugins()
const { log, PluginError } = g.util

task('clean-docs', () => del(config.paths.docsDist()))

task('generate-docs-json', () => {
  const gulpReactDocgen = require('../plugins/gulp-react-docgen')

  return src([
    `${config.paths.src()}/addons/**/*.js`,
    `${config.paths.src()}/elements/**/*.js`,
    `${config.paths.src()}/collections/**/*.js`,
    `${config.paths.src()}/modules/**/*.js`,
    `${config.paths.src()}/views/**/*.js`,
  ])
  // do not remove the function keyword
  // we need 'this' scope here
    .pipe(g.plumber(function handleError(err) {
      log(err.toString())
      this.emit('end')
    }))
    .pipe(gulpReactDocgen())
    .pipe(dest(config.paths.docsSrc()))
})

task('webpack-docs', (cb) => {
  const compiler = webpack(webpackConfig)

  compiler.run((err, stats) => {
    const { errors, warnings } = stats.toJson()

    log(stats.toString(config.compiler_stats))

    if (err) {
      log('Webpack compiler encountered a fatal error.')
      throw new PluginError('webpack', err.toString())
    }
    if (errors.length > 0) {
      log('Webpack compiler encountered errors.')
      throw new PluginError('webpack', errors.toString())
    }
    if (warnings.length > 0 && config.compiler_fail_on_warning) {
      throw new PluginError('webpack', warnings.toString())
    }

    cb(err)
  })
})

task('docs-html', (cb) => {
  return src(config.paths.docsSrc('404.html'))
    .pipe(dest(config.paths.docsDist()))
})

task('docs', series('clean-docs', 'generate-docs-json', 'webpack-docs', 'docs-html'))
<|endoftext|>


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

	//node packages
	var fs = require('fs');
	var path = require('path');
	var j = path.join;
	var glob = require('glob');
	var hogan = require('hogan.js');
	var serveStatic = require('serve-static');
	var connect = require('connect');

	//stream/gulp related
	var merge = require('merge-stream');
	var es = require('event-stream');
	var gulp = require('gulp');

	module.exports = function(gulp, plugins, C) {

		gulp.task('watch', function () {
			gulp.watch(j(C.SRC, C.MODULE_MASK, '/*.scss'), ['sass']);
			gulp.watch(j(C.SRC, C.MODULE_MASK, C.MODULE_HTML), ['copy', 'vulcanize']);
			gulp.watch(j(C.SRC, C.SHARED, '**'), ['copy']);
		});

		gulp.task('index', function() {
			var modules = glob.sync(j(C.MODULE_MASK,"/index.html"), {cwd:C.SRC});
			var moduleList = modules.map(function(name) { return name.replace('/index.html',''); });
			var moduleMap = {modules: moduleList};
			var templatePath = j(C.TEMPLATES, '/index_template.html');
			var templateString = fs.readFileSync(templatePath, 'utf8');
			var template = hogan.compile(templateString);
			var index = template.render(moduleMap);
			fs.writeFileSync(j(C.BUILD,'index.html'), index);
		});

		gulp.task('server', function() {
			var server = connect()
				.use('/bower_components', serveStatic(C.BOWER))
				.use(serveStatic(C.BUILD))
				.listen(C.LIVE_PORT);

			gulp.src(__filename)
				.pipe(plugins.open({
					uri: 'http://localhost:'+C.LIVE_PORT
				}));
		});

		gulp.task('live', ['build', 'index', 'watch', 'server']);

		gulp.task('watch:docs', function() {
			gulp.watch([j(C.DOCS,'/**/*.md'), C.SRC + '**/doc.json'], ['docs:templates']);
		});

		gulp.task('server:docs', function() {
			var server = connect()
				.use(serveStatic(C.BUILD_DOCS))
				.listen(C.DOCS_PORT);

			gulp.src(__filename)
				.pipe(plugins.open({
					uri: 'http://localhost:'+C.DOCS_PORT
				}));
		});

		gulp.task('live:docs', ['watch:docs', 'server:docs']);

	};
})();
<commit_msg>Watch module index files<commit_after>(function() {
	'use strict';

	//node packages
	var fs = require('fs');
	var path = require('path');
	var j = path.join;
	var glob = require('glob');
	var hogan = require('hogan.js');
	var serveStatic = require('serve-static');
	var connect = require('connect');

	//stream/gulp related
	var merge = require('merge-stream');
	var es = require('event-stream');
	var gulp = require('gulp');

	module.exports = function(gulp, plugins, C) {

		gulp.task('watch', function () {
			gulp.watch(j(C.SRC, C.MODULE_MASK, '/*.scss'), ['sass']);
			gulp.watch(j(C.SRC, C.MODULE_MASK, C.MODULE_HTML), ['copy', 'vulcanize']);
			gulp.watch(j(C.SRC, C.MODULE_MASK, 'index.html'), ['copy']);
			gulp.watch(j(C.SRC, C.SHARED, '**'), ['copy']);
		});

		gulp.task('index', function() {
			var modules = glob.sync(j(C.MODULE_MASK,"/index.html"), {cwd:C.SRC});
			var moduleList = modules.map(function(name) { return name.replace('/index.html',''); });
			var moduleMap = {modules: moduleList};
			var templatePath = j(C.TEMPLATES, '/index_template.html');
			var templateString = fs.readFileSync(templatePath, 'utf8');
			var template = hogan.compile(templateString);
			var index = template.render(moduleMap);
			fs.writeFileSync(j(C.BUILD,'index.html'), index);
		});

		gulp.task('server', function() {
			var server = connect()
				.use('/bower_components', serveStatic(C.BOWER))
				.use(serveStatic(C.BUILD))
				.listen(C.LIVE_PORT);

			gulp.src(__filename)
				.pipe(plugins.open({
					uri: 'http://localhost:'+C.LIVE_PORT
				}));
		});

		gulp.task('live', ['build', 'index', 'watch', 'server']);

		gulp.task('watch:docs', function() {
			gulp.watch([j(C.DOCS,'/**/*.md'), C.SRC + '**/doc.json'], ['docs:templates']);
		});

		gulp.task('server:docs', function() {
			var server = connect()
				.use(serveStatic(C.BUILD_DOCS))
				.listen(C.DOCS_PORT);

			gulp.src(__filename)
				.pipe(plugins.open({
					uri: 'http://localhost:'+C.DOCS_PORT
				}));
		});

		gulp.task('live:docs', ['watch:docs', 'server:docs']);

	};
})();
<|endoftext|>


<commit_before>renderTable();

var timeblocks;
var courselist_arr;

function renderTable()
{
    timeblocks = [];
    var scheduleTable = document.getElementById("scheduleTable");scheduleTable.className = "schedule";
    // 8:00 through 21:00 is all we care about since no classes run earlier/later
    for(var i = 8; i < 21; i++)
    {
        var timeblock = document.createElement("tbody");
        timeblock.className = "timeblock-no";
        var hour = i % 12;
        hour = hour ? hour : 12;
        timeblocks[i] = timeblock;
        for(var mins = 0; mins < 60; mins += 15)
        {
            var timeblock_row = document.createElement("tr");
            if(mins == 0) // since the header rowspans by 4, you only need one of these to cover all four slots
            {
                var timeblock_row_header = document.createElement("td");
                timeblock_row_header.className = "time";
                timeblock_row_header.rowSpan = 4;
                timeblock_row_header.innerHTML = hour + ":00";
                timeblock_row.appendChild(timeblock_row_header);
                timeblock_row.className = "first-child";
            }

            for(var day = 0; day < 7; day++)
            {
                var timeblock_row_day = document.createElement("td");
                timeblock_row_day.className = "Day" + day;
                timeblock_row.appendChild(timeblock_row_day);
            }

            timeblock.appendChild(timeblock_row);
        }
        scheduleTable.appendChild(timeblock);
    }
}

var req;
// set up the AJAX object
// branch for native XMLHttpRequest object
if (window.XMLHttpRequest) {
    req = new XMLHttpRequest();
    // branch for IE/Windows ActiveX version
    } else if (window.ActiveXObject) {
    req = new ActiveXObject("Microsoft.XMLHTTP");
}

document.getElementById("termlist").onchange = termChange;
document.getElementById("courselist").onchange = courseChange;

function courseChange()
{
    var courseselect = document.getElementById('courselist');
    // destroy all unsaved classes
    DestroyUnsaved();
    var courseinfo = courseselect.options[courseselect.selectedIndex]['courseinfo'];
    var new_course = new Course(courseinfo);
    new_course.Render();
}

function processCourseReqChange()
{
    var courseselect = document.getElementById('courselist');
    var loadingbox = document.getElementById('loadingbox');

    if(req.readyState == 4)
    {
        if(req.status == 200)
        {
            var response = req.responseXML.documentElement;
            var courses = response.getElementsByTagName('Course');

            for(var course = 0; course < courses.length; ++course)
            {
                var newcourse = document.createElement('option');
                newcourse.text = courses[course].getAttribute("Section") + ": " + courses[course].getAttribute("Title");
                newcourse.value = courses[course].getAttribute("CallNumber");
                newcourse['courseinfo'] = courses[course];

                courselist_arr.push(newcourse);

                try {
                    courseselect.add(newcourse, null);
                } catch(ex) {
                    courseselect.add(newcourse);
                }
            }
        }
        else
        {
            alert("There was a problem retrieving the XML data:\n" + req.statusText);
        }
        courseselect.className = "";

        if(loadingbox !== null)
            loadingbox.className = "";

        do_filtering();
    }
    else
    {
        courseselect.className = "loading";
        if(loadingbox !== null)
            loadingbox.className = "loading";
    }
}

function courseClear()
{
    var courseselect = document.getElementById('courselist');
    // clear out the courses
    for(var courseopt = 0; courseopt < courseselect.options.length; )
    {
        if(courseopt == 'length')
            break;
        courseselect.remove(courseopt);
    }
}

function termChange()
{
    var termselect = document.getElementById("termlist");
    var termcode = termselect.options[termselect.selectedIndex].value;
    var courseselect = document.getElementById('courselist');
    // destroy all unsaved classes
    DestroyUnsaved();
    // clear out the course list
    courseClear(); // clear the box
    courselist_arr = []; // clear the array
    document.getElementById("course-search").value = "Search...";
    document.getElementById("course-search").className = "default";
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
    // branch for IE/Windows ActiveX version
    } else if (window.ActiveXObject) {
        req = new ActiveXObject("Microsoft.XMLHTTP");
    }
    req.onreadystatechange = processCourseReqChange;
    req.open("GET", "core/core.php?cmd=getxml&term=" + termcode, true);
    req.send(null);
}

function processTermReqChange()
{
    if(req.readyState == 4)
    {
        if(req.status == 200)
        {
            response = req.responseXML.documentElement;
            var terms = response.getElementsByTagName('Term');
            termselect = document.getElementById("termlist");
            termselect.remove(0);
            for(var term = 0; term < terms.length; ++term)
            {
                newopt = document.createElement("option");
                newopt.value = terms[term].getAttribute('Code');
                newopt.text = terms[term].getAttribute('Name') + " (" + newopt.value + ")";
                if(newopt.value == start_term)
                    newopt.selected = true;
                try {
                    termselect.add(newopt, null);
                } catch(ex) {
                    termselect.add(newopt);
                }
            }
            termselect.selectedIndex = termselect.options.length - 1;
            if (window.XMLHttpRequest) {
                req = new XMLHttpRequest();
            // branch for IE/Windows ActiveX version
            } else if (window.ActiveXObject) {
                req = new ActiveXObject("Microsoft.XMLHTTP");
            }
            //req.onreadystatechange = processCourseReqChange;
            termChange();
        }
        else
        {
            alert("There was a problem retrieving the XML data...\n" + req.statusText);
        }
    }
}

document.getElementById("course-search").value = "Search...";

document.getElementById("course-search").onfocus = function()
{
    this.className = "";
    if(this.value == "Search...")
        this.value = "";
}

document.getElementById("course-search").onblur = function()
{
    if(this.value == "")
    {
        this.className = "default";
        this.value = "Search...";
    }
}

function do_filtering()
{
    var courseselect = document.getElementById('courselist');
    var searchbox = document.getElementById('course-search');
    var closed = document.getElementById('closed-checkbox');
    var cancelled = document.getElementById('cancelled-checkbox');
    var conflicts = document.getElementById('conflicts-checkbox');

    // clear out the course select box
    courseClear();

    for(var course = 0; course < courselist_arr.length; ++course)
    {
        courseinfo = courselist_arr[course]['courseinfo'];
        if(
            (searchbox.value == "Search..."
                || courseinfo.getAttribute('Title').toLowerCase().indexOf(
                    searchbox.value.toLowerCase()) != -1
                || courseinfo.getAttribute('Instructor1').toLowerCase().indexOf(
                    searchbox.value.toLowerCase()) != -1
                || courseinfo.getAttribute('CallNumber').indexOf(
                    searchbox.value) != -1
                || courseinfo.getAttribute('Section').toLowerCase().indexOf(
                    searchbox.value.toLowerCase()) != -1
                )
            && (closed.checked || courseinfo.getAttribute('Status') != 'C')
            && (cancelled.checked || courseinfo.getAttribute('Cancelled') != 'X')
            )
        {
            try {
                courseselect.add(courselist_arr[course], null);
            } catch(ex) {
                courseselect.add(courselist_arr[course]);
            }
        }
    }
}

var filtering_timeout = 0;

document.getElementById("course-search").onkeyup = function()
{
    clearTimeout(filtering_timeout);
    filtering_timeout = setTimeout('do_filtering();', 200);
}

document.getElementById('closed-checkbox').onchange = document.getElementById('cancelled-checkbox').onchange = document.getElementById('conflicts-checkbox').onchange = do_filtering;

var start_term = null;

function downloadTerms_callback(term)
{
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
    // branch for IE/Windows ActiveX version
    } else if (window.ActiveXObject) {
        req = new ActiveXObject("Microsoft.XMLHTTP");
    }
    start_term = term;
    req.onreadystatechange = processTermReqChange;
    req.open("GET", "core/core.php?cmd=terms", true);
    req.send(null);
}

Persist.init(downloadTerms_callback);
<commit_msg>Delete scheduler.js<commit_after><|endoftext|>


<commit_before>
Dashboard = function () {
    this.internal_networks = "";

    this.initialize = function () {
        // Retrieve internal domains
        var url = "json/rpc/get_internal_networks.php";
        var params = {};
        $.getJSON(url, params, function (data, textStatus, jqXHR) {
            internal_networks = data;
            add_time_window_control_listeners();
            plot_incoming_attacks_plot(internal_networks);
            load_attacks_table(INCOMING, 1); // second parameter '1' means it's called from dashboard
            load_attacks_table(OUTGOING, 1); // second parameter '1' means it's called from dashboard
            load_top_targets_table(COMPROMISE);
            load_top_targets_table(BRUTEFORCE);
        });
    };

    return this;
};

function add_time_window_control_listeners () {
    // Select 'Week' as default, i.e., if none has been selected
    if ($('.btn.active').length == 0) {
        $('.btn:contains(\"Week\")').addClass('active');
    }

    // General button handling
    $('.btn-group .btn').click(function () {
        // Check which button was selected before
        var prev_button_text = $('.btn-group .btn.active').text();

        // Do nothing if the already active button was clicked
        if ($(this).text() == prev_button_text) return;

        // Remove 'active' class from previously selected item(s)
        $('.btn-group .btn').removeClass('active');

        // Add 'active' class to newly selected item
        $(this).addClass('active');

        // Show loading message
        $('#attacks-plot ~ div.loading').show();
        $('#attacks-plot-header').hide();
        $('#attacks-plot').hide();

        // Replot 'incoming attacks' plot based on newly selected time window
        plot_incoming_attacks_plot($(this).text().toLowerCase());
    });
}

function load_attacks_table (type, calledFromDashboard) {
    var url;
    var action;
    calledFromDashboard = typeof calledFromDashboard !== 'undefined' ? calledFromDashboard : false;
    console.log("calledFromDashboard: " + calledFromDashboard);

    action = 'incoming';
    url = "json/data/get_attacks.php";

    var params = {};
    if (type != INCOMING) {
        params['outgoing'] = 1;
        action = 'outgoing';
    }
    console.log('load_attacks_table with params:' + params);

    $.getJSON(url, params, function (data, textStatus, jqXHR) {
        var table = $('
').addClass('list');
        var head = $('
');
        var body = $('
');
        head.append(
            $('').text('Phases'),
            $('').text('Active'),
            $('').text('Attacker'),
            $('').text('Start time'),
            $('').text('Targets')
        ).appendTo(head);

        if (data.data.length == 0) {
            $('
').append(
                $('').text("No data available...")
            ).appendTo(body);
        } else {
            $.each(data.data, function () {
                var phases = $('
').addClass('phases').append(
                    $('
').addClass('phase scan'),
                    $('
').addClass('phase bruteforce'),
                    $('
').addClass('phase compromise')
                );
                var this_attack = this;
                // Phases
                this.certainty = parseFloat(this.certainty);
                if ($.inArray(this.certainty, [ 0.25, 0.5, 0.75 ]) != -1) {
                    phases.find('.scan').addClass('on');
                }
                if ($.inArray(this.certainty, [ 0.4, 0.5, 0.65, 0.75 ]) >= 0) {
                    phases.find('.bruteforce').addClass('on');
                }
                if ($.inArray(this.certainty, [ 0.65, 0.75 ]) >= 0) {
                    phases.find('.compromise').addClass('on');
                }

                // Date
                var date = new Date(this.start_time * 1000);
                var active_span = "";
                if (this.ongoing) {
                    active_span = "";
                }
                var tr = $('
').append(
                    $('').append(phases),
                    //$('').html(""),
                    $('').addClass('active').html(active_span),
                    $('').append($('')
                            .addClass('ip-addr')
                            //.attr('href', '#')
                            .text(this.attacker)
                            .click(function () {
                                var url = "json/html/get_host_details.php";
                                var params = {
                                    'host': $(this).text()
                                }
                                $.getJSON(url, params, function (data, textStatus, jqXHR) {
                                    // Overwrite modal title using Javascript, since Bootstrap uses a completely different element for modal headers and bodies
                                    $('#host-details h4.modal-title').text("Host details for " + params['host']);

                                    // Insert pre-rendered HTML into body
                                    $('#host-details div.modal-body').html(data.data);
                                    $('#host-details').modal({
                                        show: true
                                    });
                                });
                            })),
                    $('').text(date.toString("ddd. MMM d, yyyy HH:mm")),
                    $('').text(this.target_count)
                ).appendTo(body);
                tr.data('href', 'index.php?action=' + action + '&attack_id=' + this_attack.attack_id);
                tr.attr('data-id', this_attack.attack_id);
                console.log("wrote data-id");
                tr.click(function () {
                    if(calledFromDashboard) {
                        loadPage($(this).data('href'));
                    } else {
                        loadAttackDetails($(this).data('href'));
                        loadAttackTargets($(this).data('href'));
                        $(this).addClass("selected").siblings().removeClass("selected");
                    }
                });
            });
        }

        head.appendTo(table);
        body.appendTo(table);

        if (type == INCOMING) {
            // Hide loading message and show divs related to plot
            $('#incoming-attacks-table ~ div.loading').hide();
            $('#incoming-attacks-table').show();
            table.appendTo($('#incoming-attacks-table'));
        } else {
            // Hide loading message and show divs related to plot
            $('#outgoing-attacks-table ~ div.loading').hide();
            $('#outgoing-attacks-table').show();
            table.appendTo($('#outgoing-attacks-table'));
        }
        if (attack_id !== undefined) {
            $('tr[data-id='+attack_id+']').addClass("selected").siblings().removeClass("selected");
        }
    });
}

function _handle_get_attack_details (data) {
    $('#attack-details h1').text("Attack details of " + data.data[0]['attacker_ip']);
    var details_table;
    details_table = "
\

\
                            Attacker	derp	\
                            Start time	nu	\
                            Total flows	heelveelK	\
                            Total bytes	meerK	\

\

\

\

";
    $('#attack-details-content').html(details_table);

}

function load_top_targets_table (type) {
    var url;

    if (type == BRUTEFORCE) {
        url = "json/data/get_top_targets_bruteforce.php";
    } else {
        url = "json/data/get_top_targets_compromise.php";
    }

    var params = {};

    $.getJSON(url, params, function (data, textStatus, jqXHR) {
        var table = $('
').addClass('list');
        var head = $('
');
        var body = $('
');
        head.append(
            $('').text('Target'),
            $('').text('Attacks'),
            $('').text('Compromises')
        ).appendTo(head);

        if (data.data.length == 0) {
            $('
').append(
                $('').text("No data available...")
            ).appendTo(body);
        } else {
            $.each(data.data, function () {
                $('
').append(
                    $('').append($('')
                        .addClass('ip-addr')
                        .attr('href', '#')
                        .text(this.target))
                        .click(function () {
                            var url = "json/html/get_host_details.php";
                            var params = {
                                'host': $(this).text()
                            }
                            $.getJSON(url, params, function (data, textStatus, jqXHR) {
                                // Overwrite modal title using Javascript, since Bootstrap uses a completely different element for modal headers and bodies
                                $('#host-details h4.modal-title').text("Host details for " + params['host']);

                                // Insert pre-rendered HTML into body
                                $('#host-details div.modal-body').html(data.data);
                                $('#host-details').modal({
                                    show: true
                                });
                            });
                        }),
                    $('').text(this.attack_count),
                    $('').text(this.compromise_count)
                ).appendTo(body);
            });
        }

        head.appendTo(table);
        body.appendTo(table);

        if (type == BRUTEFORCE) {
            // Hide loading message and show divs related to plot
            $('#top-targets-bruteforce-table ~ div.loading').hide();
            $('#top-targets-bruteforce-table').show();
            table.appendTo($('#top-targets-bruteforce-table'));
        } else {
            // Hide loading message and show divs related to plot
            $('#top-targets-compromise-table ~ div.loading').hide();
            $('#top-targets-compromise-table').show();
            table.appendTo($('#top-targets-compromise-table'));
        }
    });
}

function plot_incoming_attacks_plot (internal_networks, period) {
    if (typeof(period) === 'undefined') {
        period = 'week';
    }

    var url = "json/data/get_incoming_attacks_plot.php";
    var now = parseInt((new Date().getTime()) / 1000);
    var max_start_time = now;

    var min_start_time;
    if (period == 'day') {
        min_start_time = now - (24 * 60 * 60);
    } else if (period == 'month') {
        min_start_time = now - (30 * 24 * 60 * 60);
    } else {
        min_start_time = now - (7 * 24 * 60 * 60);
    }

    var params = {
        'min_start_time': min_start_time, // Go 7 days back in time
        'max_start_time': max_start_time
    };

    $.getJSON(url, params, function (data, textStatus, jqXHR) {
        // Scan attacks
        var plot_scan_data = new Array();
        plot_scan_data['label'] = "Scan";
        plot_scan_data['color'] = "rgb(26, 150, 212)";
        plot_scan_data['data'] = new Array();
        $.each(data.data.scan, function (time, attacks) {
            plot_scan_data['data'].push([time * 1000, attacks]);
        });

        // Brute-force attacks
        var plot_bruteforce_data = new Array();
        plot_bruteforce_data['label'] = "Brute-force";
        plot_bruteforce_data['color'] = "rgb(250, 100, 45)";
        plot_bruteforce_data['data'] = new Array();
        $.each(data.data.bruteforce, function (time, attacks) {
            plot_bruteforce_data['data'].push([time * 1000, attacks]);
        });

        // Compromise attacks
        var plot_compromise_data = new Array();
        plot_compromise_data['label'] = "Compromise";
        plot_compromise_data['color'] = "rgb(220, 0, 8)";
        plot_compromise_data['data'] = new Array();
        $.each(data.data.compromise, function (time, attacks) {
            plot_compromise_data['data'].push([time * 1000, attacks]);
        });

        var last_day = -1;
        var options = {
            bars: {
                backgroundColor: null,
                show: true
            },
            lines: {
                show: false,
                steps: false
            },
            grid: {
                hoverable: true,
                clickable: true,
                borderWidth: 0
            },
            series: {
                stack: true
            },
            legend: {
                container: $('#attacks-plot-legend'),
                noColumns: 3,
                labelFormatter: function (label, series) {
                    return "" + label + '';
                }
            },
            xaxis: {
                mode: "time",
                min: min_start_time * 1000,
                max: max_start_time * 1000,
                twelveHourClock : false,
                tickFormatter: function (val, axis) {
                    var date = new Date();
                    date.setTime(val);
                    var label = "";
                    var week = (max_start_time - min_start_time >= 604800);

                    // 'date > Dashboard.getStartTime()' is there to make sure that selected date is actually visible
                    if (date.getDate() != last_day && date > min_start_time * 1000) {
                        last_day = date.getDate();
                        var months = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun",
                                "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ];
                        label += date.getDate() + " " + months[date.getMonth()];

                        if (!week) {
                            label += ",
";
                        }
                    }

                    if (!week) {
                        var minutes = date.getMinutes();
                        if (minutes < 10) {
                            minutes = "0" + minutes;
                        }
                        label += date.getHours() + ":" + minutes;
                    }

                    return label;
                },
                tickLength: 0
            },
            yaxis: {
                min: 0,
                minTickSize: 1,
                tickDecimals: 0
            }
        };

        // Hide loading message and show divs related to plot
        $('#attacks-plot ~ div.loading').hide();
        $('#attacks-plot-header').show();
        $('#attacks-plot').show();

        $.plot($('#attacks-plot'),
                [ plot_scan_data, plot_bruteforce_data, plot_compromise_data ], options);
    });
}

// Constants
var BRUTEFORCE = 1;
var COMPROMISE = 2;
var INCOMING = 1;
var OUTGOING = 2;
<commit_msg>Prevent modal and page switch from happening at the same time<commit_after>
Dashboard = function () {
    this.internal_networks = "";

    this.initialize = function () {
        // Retrieve internal domains
        var url = "json/rpc/get_internal_networks.php";
        var params = {};
        $.getJSON(url, params, function (data, textStatus, jqXHR) {
            internal_networks = data;
            add_time_window_control_listeners();
            plot_incoming_attacks_plot(internal_networks);
            load_attacks_table(INCOMING, 1); // second parameter '1' means it's called from dashboard
            load_attacks_table(OUTGOING, 1); // second parameter '1' means it's called from dashboard
            load_top_targets_table(COMPROMISE);
            load_top_targets_table(BRUTEFORCE);
        });
    };

    return this;
};

function add_time_window_control_listeners () {
    // Select 'Week' as default, i.e., if none has been selected
    if ($('.btn.active').length == 0) {
        $('.btn:contains(\"Week\")').addClass('active');
    }

    // General button handling
    $('.btn-group .btn').click(function () {
        // Check which button was selected before
        var prev_button_text = $('.btn-group .btn.active').text();

        // Do nothing if the already active button was clicked
        if ($(this).text() == prev_button_text) return;

        // Remove 'active' class from previously selected item(s)
        $('.btn-group .btn').removeClass('active');

        // Add 'active' class to newly selected item
        $(this).addClass('active');

        // Show loading message
        $('#attacks-plot ~ div.loading').show();
        $('#attacks-plot-header').hide();
        $('#attacks-plot').hide();

        // Replot 'incoming attacks' plot based on newly selected time window
        plot_incoming_attacks_plot($(this).text().toLowerCase());
    });
}

function load_attacks_table (type, calledFromDashboard) {
    var url;
    var action;
    calledFromDashboard = typeof calledFromDashboard !== 'undefined' ? calledFromDashboard : false;
    console.log("calledFromDashboard: " + calledFromDashboard);

    action = 'incoming';
    url = "json/data/get_attacks.php";

    var params = {};
    if (type != INCOMING) {
        params['outgoing'] = 1;
        action = 'outgoing';
    }
    console.log('load_attacks_table with params:' + params);

    $.getJSON(url, params, function (data, textStatus, jqXHR) {
        var table = $('
').addClass('list');
        var head = $('
');
        var body = $('
');
        head.append(
            $('').text('Phases'),
            $('').text('Active'),
            $('').text('Attacker'),
            $('').text('Start time'),
            $('').text('Targets')
        ).appendTo(head);

        if (data.data.length == 0) {
            $('
').append(
                $('').text("No data available...")
            ).appendTo(body);
        } else {
            $.each(data.data, function () {
                var phases = $('
').addClass('phases').append(
                    $('
').addClass('phase scan'),
                    $('
').addClass('phase bruteforce'),
                    $('
').addClass('phase compromise')
                );
                var this_attack = this;
                // Phases
                this.certainty = parseFloat(this.certainty);
                if ($.inArray(this.certainty, [ 0.25, 0.5, 0.75 ]) != -1) {
                    phases.find('.scan').addClass('on');
                }
                if ($.inArray(this.certainty, [ 0.4, 0.5, 0.65, 0.75 ]) >= 0) {
                    phases.find('.bruteforce').addClass('on');
                }
                if ($.inArray(this.certainty, [ 0.65, 0.75 ]) >= 0) {
                    phases.find('.compromise').addClass('on');
                }

                // Date
                var date = new Date(this.start_time * 1000);
                var active_span = "";
                if (this.ongoing) {
                    active_span = "";
                }
                var tr = $('
').append(
                    $('').append(phases),
                    //$('').html(""),
                    $('').addClass('active').html(active_span),
                    $('').append($('')
                            .addClass('ip-addr')
                            //.attr('href', '#')
                            .text(this.attacker)
                            .click(function (e) {
                                e.stopPropagation();
                                var url = "json/html/get_host_details.php";
                                var params = {
                                    'host': $(this).text()
                                }
                                $.getJSON(url, params, function (data, textStatus, jqXHR) {
                                    // Overwrite modal title using Javascript, since Bootstrap uses a completely different element for modal headers and bodies
                                    $('#host-details h4.modal-title').text("Host details for " + params['host']);

                                    // Insert pre-rendered HTML into body
                                    $('#host-details div.modal-body').html(data.data);
                                    $('#host-details').modal({
                                        show: true
                                    });
                                });
                            })),
                    $('').text(date.toString("ddd. MMM d, yyyy HH:mm")),
                    $('').text(this.target_count)
                ).appendTo(body);
                tr.data('href', 'index.php?action=' + action + '&attack_id=' + this_attack.attack_id);
                tr.attr('data-id', this_attack.attack_id);
                console.log("wrote data-id");
                tr.click(function () {
                    if(calledFromDashboard) {
                        loadPage($(this).data('href'));
                    } else {
                        loadAttackDetails($(this).data('href'));
                        loadAttackTargets($(this).data('href'));
                        $(this).addClass("selected").siblings().removeClass("selected");
                    }
                });
            });
        }

        head.appendTo(table);
        body.appendTo(table);

        if (type == INCOMING) {
            // Hide loading message and show divs related to plot
            $('#incoming-attacks-table ~ div.loading').hide();
            $('#incoming-attacks-table').show();
            table.appendTo($('#incoming-attacks-table'));
        } else {
            // Hide loading message and show divs related to plot
            $('#outgoing-attacks-table ~ div.loading').hide();
            $('#outgoing-attacks-table').show();
            table.appendTo($('#outgoing-attacks-table'));
        }
        if (attack_id !== undefined) {
            $('tr[data-id='+attack_id+']').addClass("selected").siblings().removeClass("selected");
        }
    });
}

function _handle_get_attack_details (data) {
    $('#attack-details h1').text("Attack details of " + data.data[0]['attacker_ip']);
    var details_table;
    details_table = "
\

\
                            Attacker	derp	\
                            Start time	nu	\
                            Total flows	heelveelK	\
                            Total bytes	meerK	\

\

\

\

";
    $('#attack-details-content').html(details_table);

}

function load_top_targets_table (type) {
    var url;

    if (type == BRUTEFORCE) {
        url = "json/data/get_top_targets_bruteforce.php";
    } else {
        url = "json/data/get_top_targets_compromise.php";
    }

    var params = {};

    $.getJSON(url, params, function (data, textStatus, jqXHR) {
        var table = $('
').addClass('list');
        var head = $('
');
        var body = $('
');
        head.append(
            $('').text('Target'),
            $('').text('Attacks'),
            $('').text('Compromises')
        ).appendTo(head);

        if (data.data.length == 0) {
            $('
').append(
                $('').text("No data available...")
            ).appendTo(body);
        } else {
            $.each(data.data, function () {
                $('
').append(
                    $('').append($('')
                        .addClass('ip-addr')
                        .attr('href', '#')
                        .text(this.target))
                        .click(function () {
                            var url = "json/html/get_host_details.php";
                            var params = {
                                'host': $(this).text()
                            }
                            $.getJSON(url, params, function (data, textStatus, jqXHR) {
                                // Overwrite modal title using Javascript, since Bootstrap uses a completely different element for modal headers and bodies
                                $('#host-details h4.modal-title').text("Host details for " + params['host']);

                                // Insert pre-rendered HTML into body
                                $('#host-details div.modal-body').html(data.data);
                                $('#host-details').modal({
                                    show: true
                                });
                            });
                        }),
                    $('').text(this.attack_count),
                    $('').text(this.compromise_count)
                ).appendTo(body);
            });
        }

        head.appendTo(table);
        body.appendTo(table);

        if (type == BRUTEFORCE) {
            // Hide loading message and show divs related to plot
            $('#top-targets-bruteforce-table ~ div.loading').hide();
            $('#top-targets-bruteforce-table').show();
            table.appendTo($('#top-targets-bruteforce-table'));
        } else {
            // Hide loading message and show divs related to plot
            $('#top-targets-compromise-table ~ div.loading').hide();
            $('#top-targets-compromise-table').show();
            table.appendTo($('#top-targets-compromise-table'));
        }
    });
}

function plot_incoming_attacks_plot (internal_networks, period) {
    if (typeof(period) === 'undefined') {
        period = 'week';
    }

    var url = "json/data/get_incoming_attacks_plot.php";
    var now = parseInt((new Date().getTime()) / 1000);
    var max_start_time = now;

    var min_start_time;
    if (period == 'day') {
        min_start_time = now - (24 * 60 * 60);
    } else if (period == 'month') {
        min_start_time = now - (30 * 24 * 60 * 60);
    } else {
        min_start_time = now - (7 * 24 * 60 * 60);
    }

    var params = {
        'min_start_time': min_start_time, // Go 7 days back in time
        'max_start_time': max_start_time
    };

    $.getJSON(url, params, function (data, textStatus, jqXHR) {
        // Scan attacks
        var plot_scan_data = new Array();
        plot_scan_data['label'] = "Scan";
        plot_scan_data['color'] = "rgb(26, 150, 212)";
        plot_scan_data['data'] = new Array();
        $.each(data.data.scan, function (time, attacks) {
            plot_scan_data['data'].push([time * 1000, attacks]);
        });

        // Brute-force attacks
        var plot_bruteforce_data = new Array();
        plot_bruteforce_data['label'] = "Brute-force";
        plot_bruteforce_data['color'] = "rgb(250, 100, 45)";
        plot_bruteforce_data['data'] = new Array();
        $.each(data.data.bruteforce, function (time, attacks) {
            plot_bruteforce_data['data'].push([time * 1000, attacks]);
        });

        // Compromise attacks
        var plot_compromise_data = new Array();
        plot_compromise_data['label'] = "Compromise";
        plot_compromise_data['color'] = "rgb(220, 0, 8)";
        plot_compromise_data['data'] = new Array();
        $.each(data.data.compromise, function (time, attacks) {
            plot_compromise_data['data'].push([time * 1000, attacks]);
        });

        var last_day = -1;
        var options = {
            bars: {
                backgroundColor: null,
                show: true
            },
            lines: {
                show: false,
                steps: false
            },
            grid: {
                hoverable: true,
                clickable: true,
                borderWidth: 0
            },
            series: {
                stack: true
            },
            legend: {
                container: $('#attacks-plot-legend'),
                noColumns: 3,
                labelFormatter: function (label, series) {
                    return "" + label + '';
                }
            },
            xaxis: {
                mode: "time",
                min: min_start_time * 1000,
                max: max_start_time * 1000,
                twelveHourClock : false,
                tickFormatter: function (val, axis) {
                    var date = new Date();
                    date.setTime(val);
                    var label = "";
                    var week = (max_start_time - min_start_time >= 604800);

                    // 'date > Dashboard.getStartTime()' is there to make sure that selected date is actually visible
                    if (date.getDate() != last_day && date > min_start_time * 1000) {
                        last_day = date.getDate();
                        var months = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun",
                                "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ];
                        label += date.getDate() + " " + months[date.getMonth()];

                        if (!week) {
                            label += ",
";
                        }
                    }

                    if (!week) {
                        var minutes = date.getMinutes();
                        if (minutes < 10) {
                            minutes = "0" + minutes;
                        }
                        label += date.getHours() + ":" + minutes;
                    }

                    return label;
                },
                tickLength: 0
            },
            yaxis: {
                min: 0,
                minTickSize: 1,
                tickDecimals: 0
            }
        };

        // Hide loading message and show divs related to plot
        $('#attacks-plot ~ div.loading').hide();
        $('#attacks-plot-header').show();
        $('#attacks-plot').show();

        $.plot($('#attacks-plot'),
                [ plot_scan_data, plot_bruteforce_data, plot_compromise_data ], options);
    });
}

// Constants
var BRUTEFORCE = 1;
var COMPROMISE = 2;
var INCOMING = 1;
var OUTGOING = 2;
<|endoftext|>


<commit_before>const {Pool} = require('pg');

function makeCreateQuery(dbName) {
  if (dbName === 'swipe-right-db') return 'CREATE DATABASE "swipe-right-db";';
  if (dbName === 'swipe-right-db-test') return 'CREATE DATABASE "swipe-right-db-test";';
  throw new Error('unexpected database name: ', dbName);
}

function createDatabase(databaseName) {
  const pool = new Pool();
  const sql = makeCreateQuery(databaseName);
  console.log(`Creating database ${databaseName}...`);
  return pool.query(sql);
}

function createTables(database) {
  const pool = new Pool({database});
  const sql = `
    CREATE TABLE interactions (
      id serial primary key,
      interaction jsonb,
      session jsonb,
      timestampz timestamptz
    );
    CREATE TABLE links (
      id serial primary key,
      email text,
      link text,
      timestampz timestamptz
    );
    CREATE TABLE whitelist (
      id serial primary key,
      email text
    );`;
  console.log(`Creating tables...`);
  return pool.query(sql);
}

// Create a new database for test or development mode, and
// create the tables for the database.
//
// Usage:
// yarn db-create-test swipe-right-db-test
// yarn db-create-test swipe-right-db
const databaseName = process.argv[2];
createDatabase(databaseName)
  .then(results => createTables(databaseName))
  .then(results => {
    console.log('Done.');
    process.exit(0); // eslint-disable-line no-process-exit
  })
  .catch(err => {
    console.log('error', err)
    process.exit(1); // eslint-disable-line no-process-exit
  });

<commit_msg>Fix linter error<commit_after>const {Pool} = require('pg');

function makeCreateQuery(dbName) {
  if (dbName === 'swipe-right-db') return 'CREATE DATABASE "swipe-right-db";';
  if (dbName === 'swipe-right-db-test') return 'CREATE DATABASE "swipe-right-db-test";';
  throw new Error('unexpected database name: ', dbName);
}

function createDatabase(databaseName) {
  const pool = new Pool();
  const sql = makeCreateQuery(databaseName);
  console.log(`Creating database ${databaseName}...`);
  return pool.query(sql);
}

function createTables(database) {
  const pool = new Pool({database});
  const sql = `
    CREATE TABLE interactions (
      id serial primary key,
      interaction jsonb,
      session jsonb,
      timestampz timestamptz
    );
    CREATE TABLE links (
      id serial primary key,
      email text,
      link text,
      timestampz timestamptz
    );
    CREATE TABLE whitelist (
      id serial primary key,
      email text
    );`;
  console.log(`Creating tables...`);
  return pool.query(sql);
}

// Create a new database for test or development mode, and
// create the tables for the database.
//
// Usage:
// yarn db-create-test swipe-right-db-test
// yarn db-create-test swipe-right-db
const databaseName = process.argv[2];
createDatabase(databaseName)
  .then(results => createTables(databaseName))
  .then(results => {
    console.log('Done.');
    process.exit(0); // eslint-disable-line no-process-exit
  })
  .catch(err => {
    console.log('error', err);
    process.exit(1); // eslint-disable-line no-process-exit
  });

<|endoftext|>


<commit_before>import axios from 'axios'

const URL = 'http://127.0.0.1:3003/api/todo'

export const changeDescription = event => ({
    type: 'DESCRIPTION_CHANGED',
    payload: event.target.value
})

export const search = event => {
    request = axios.get(`${URL}?sort=-createdAt`)
    return {
        type: 'TODO_SEARCHED',
        payload: request
    }
}<commit_msg>remove event in the action search<commit_after>import axios from 'axios'

const URL = 'http://127.0.0.1:3003/api/todo'

export const changeDescription = event => ({
    type: 'DESCRIPTION_CHANGED',
    payload: event.target.value
})

export const search = () => {
    request = axios.get(`${URL}?sort=-createdAt`)
    return {
        type: 'TODO_SEARCHED',
        payload: request
    }
}<|endoftext|>