<commit_before>/*
 * Copyright (c) 2012 Massachusetts Institute of Technology, Adobe Systems
 * Incorporated, and other contributors. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, $, brackets, Mustache */

/**
 * provides events:
 *
 *  - enable & disable, when the extension should operate
 */

define(function (require, exports, module) {
    "use strict";

    var Agent              = require("Agent");
    var AgentManager       = require("AgentManager");
    var AppInit            = brackets.getModule("utils/AppInit");
    var CommandManager     = brackets.getModule("command/CommandManager");
    var Commands           = brackets.getModule("command/Commands");
    var Dialogs            = brackets.getModule("widgets/Dialogs");
    var EpochPanel         = require("EpochPanel");
    var FileCallGraphPanel = require("FileCallGraphPanel");
    var EditorInterface    = require("EditorInterface");
    var ExtensionUtils     = brackets.getModule("utils/ExtensionUtils");
    var Invitation         = require("Invitation");
    var Inspector          = brackets.getModule("LiveDevelopment/Inspector/Inspector");
    var LiveDevelopment    = brackets.getModule("LiveDevelopment/LiveDevelopment");
    var Menus              = brackets.getModule("command/Menus");
    var NativeApp          = brackets.getModule("utils/NativeApp");
    var NativeFileSystem   = brackets.getModule("file/NativeFileSystem").NativeFileSystem;
    var Panel              = require("Panel");
    var PreferencesManager = brackets.getModule("preferences/PreferencesManager");
    var ProxyProvider      = require("ProxyProvider");
    var Strings            = require("strings");
    var UI                 = require("UI");
    var Usage              = require("Usage");

    var $exports = $(exports);

    var THESEUS_VERSION = JSON.parse(require("text!package.json")).version;

    // check that node_modules is there and alert the user if it isn't
    var corruptInstallationDialogHTML = require("text!InstallationCorrupt.html");
    var corruptInstallationDialogTemplate = Mustache.render(corruptInstallationDialogHTML, {Strings : Strings});
    var nodeModulesPath = ExtensionUtils.getModulePath(module, "node_modules");
    NativeFileSystem.resolveNativeFileSystemPath(nodeModulesPath, function() {}, function() {
        var dialog = Dialogs.showModalDialogUsingTemplate(corruptInstallationDialogTemplate);
        var $dialog = dialog.getElement();
        $dialog.find(".close").on("click", dialog.close.bind(dialog));
    });

    // set up the menus

    var _modes = {
        "static" : { name: "static", displayName: "Serve files from disk" },
        "proxy" : { name: "proxy", displayName: "Proxy to localhost:3000 (experimental)" },
    };
    var _orderedModes = [_modes["static"], _modes["proxy"]];
    var DEFAULT_MODE = _modes["static"];

    var ID_THESEUS_SEND_FEEDBACK   = "brackets.theseus.sendFeedback";
    var NAME_THESEUS_SEND_FEEDBACK = "Send Theseus Feedback...";

    var ID_THESEUS_WELCOME_SCREEN   = "brackets.theseus.welcome";
    var NAME_THESEUS_WELCOME_SCREEN = "Theseus Welcome Screen...";

    var ID_THESEUS_ENABLE = "brackets.theseus.enable";
    var NAME_THESEUS_ENABLE = "Enable Theseus";

    var ID_THESEUS_DEBUG_BRACKETS = "brackets.theseus.debug-brackets";
    var NAME_THESEUS_DEBUG_BRACKETS = "Debug Brackets with Theseus";

    var ID_THESEUS_RESET_TRACE = "brackets.theseus.reset-trace";
    var NAME_THESEUS_RESET_TRACE = "Reset Theseus Trace Data (experimental)";

    var ID_THESEUS_MODES = _orderedModes.map(function (mode) { return "brackets.theseus.mode." + mode.name; });
    var NAME_THESEUS_MODES = _orderedModes.map(function (mode) { return "   Mode: " + mode.displayName; });

    // module variables

    var _enabled = false;
    var _mode = DEFAULT_MODE;
    var _prefs;

    function _enable() {
        $exports.triggerHandler("enable");
    }

    function _disable() {
        $exports.triggerHandler("disable");
    }

    function _toggleEnabled() {
        // TODO: disable or enable immediately
        _enabled = !_enabled;
        _prefs.setValue("enabled", _enabled);
        _updateMenuStates();

        if (_enabled) {
            _enable();
        } else {
            _disable();
        }
    }

    function _setMode(modeName) {
        // TODO: warn user that connection will need to be restarted
        _mode = _modes[modeName] || DEFAULT_MODE;
        _prefs.setValue("mode", _mode.name);
        _updateMenuStates();
    }

    function _setModeHandler(modeName) {
        return function () {
            _setMode(modeName);
            $exports.triggerHandler("modeChange", modeName);
        };
    }

    function _sendFeedback() {
        var params = "?";
        params += "brackets_version=" + brackets.metadata.version;
        params += "&theseus_version=" + THESEUS_VERSION;
        NativeApp.openURLInDefaultBrowser("file://" + ExtensionUtils.getModuleUrl(module, "feedback.html") + params);
    }

    function _showWelcomeScreen() {
        Invitation.showInvitation();
    }

    function _debugBrackets() {
        var _proxy;
        CommandManager.execute("debug.newBracketsWindow").then(function () {
            return ProxyProvider.getServer("/", "static");
        }).then(function (proxy) {
            _proxy = proxy;
            return Inspector.getDebuggableWindows("127.0.0.1", 9234);
        }).then(function (response) {
            var keys = Object.keys(response).sort(function (a, b) { return parseInt(a, 10) - parseInt(b, 10); });
            if (keys.length > 0) {
                // pick the last page
                var page = response[keys[keys.length - 1]];

                var redirect = function () {
                    Inspector.off("connect", redirect);
                    var redirectTo = _proxy.proxyRootURL + (window.location.pathname[0] === "/" ? window.location.pathname.slice(1) : window.location.pathname)
                    Inspector.Runtime.evaluate("window.location = " + JSON.stringify(redirectTo), function () {});
                };
                Inspector.on("connect", redirect);

                Inspector.connect(page.webSocketDebuggerUrl);
            }
        }).fail(function onFail(err) {
            console.log("debugging brackets failed: " + err);
        });
    }

    function _resetTrace() {
        AgentManager.resetTrace();
    }

    function _loadPreferences() {
        _prefs = PreferencesManager.getPreferenceStorage("com.adobe.theseus", { enabled: true, mode: "static" });
        _enabled = _prefs.getValue("enabled");
        _mode = _modes[_prefs.getValue("mode")] || DEFAULT_MODE;
    }

    function _setupMenu() {
        CommandManager.register(
            NAME_THESEUS_SEND_FEEDBACK,
            ID_THESEUS_SEND_FEEDBACK,
            _sendFeedback
        );

        CommandManager.register(
            NAME_THESEUS_WELCOME_SCREEN,
            ID_THESEUS_WELCOME_SCREEN,
            _showWelcomeScreen
        );

        CommandManager.register(
            NAME_THESEUS_ENABLE,
            ID_THESEUS_ENABLE,
            _toggleEnabled
        );

        CommandManager.register(
            NAME_THESEUS_DEBUG_BRACKETS,
            ID_THESEUS_DEBUG_BRACKETS,
            _debugBrackets
        );

        CommandManager.register(
            NAME_THESEUS_RESET_TRACE,
            ID_THESEUS_RESET_TRACE,
            _resetTrace
        );

        _orderedModes.forEach(function (mode, i) {
            CommandManager.register(
                NAME_THESEUS_MODES[i],
                ID_THESEUS_MODES[i],
                _setModeHandler(mode.name)
            );
        });

        var menu = Menus.getMenu(Menus.AppMenuBar.HELP_MENU);
        menu.addMenuDivider(Menus.LAST, null);
        menu.addMenuItem(ID_THESEUS_SEND_FEEDBACK, null, Menus.LAST, null);
        menu.addMenuItem(ID_THESEUS_WELCOME_SCREEN, null, Menus.LAST, null);

        var fileMenu = Menus.getMenu(Menus.AppMenuBar.FILE_MENU);
        fileMenu.addMenuDivider(Menus.LAST, null);
        fileMenu.addMenuItem(ID_THESEUS_ENABLE, null, Menus.LAST, null);
        _orderedModes.forEach(function (mode, i) {
            var prev = (i == 0) ? ID_THESEUS_ENABLE : ID_THESEUS_MODES[i - 1];
            fileMenu.addMenuItem(ID_THESEUS_MODES[i], null, Menus.AFTER, prev);
        });
        fileMenu.addMenuItem(ID_THESEUS_RESET_TRACE, null, Menus.AFTER, ID_THESEUS_MODES[ID_THESEUS_MODES.length - 1]);

        var debugMenu = Menus.getMenu("debug-menu");
        debugMenu.addMenuDivider(Menus.LAST, null);
        debugMenu.addMenuItem(ID_THESEUS_DEBUG_BRACKETS, null, Menus.LAST, null);

        _updateMenuStates();
    }

    function _updateMenuStates() {
        CommandManager.get(ID_THESEUS_ENABLE).setChecked(_enabled);
        _orderedModes.forEach(function (mode, i) {
            var cmd = CommandManager.get(ID_THESEUS_MODES[i]);
            cmd.setChecked(_mode.name === mode.name);
            cmd.setEnabled(_enabled);
        });
    }

    function isEnabled() {
        return _enabled;
    }

    function getModeName() {
        return _mode.name;
    }

    function _init() {
        _loadPreferences();
        _setupMenu();

        ExtensionUtils.loadStyleSheet(module, "main.less");

        Usage.init();
        ProxyProvider.init();
        Agent.init();
        AgentManager.init();
        EditorInterface.init();
        UI.init();
        Panel.init();
        EpochPanel.init();
        FileCallGraphPanel.init();

        // after a short delay, show 'Thank you!' popup if they haven't seen it
        setTimeout(function () {
            Invitation.showInvitationIfNecessary();
        }, 1000);

        $(LiveDevelopment).on("statusChange", function (e, status) {
            if (status === 1) { // "Connecting to the remote debugger"
                setTimeout(function () {
                    var $btnGoLive = $("#toolbar-go-live");

                    $btnGoLive.twipsy("hide").removeData("twipsy");
                    $btnGoLive.twipsy({
                        placement: "left",
                        trigger: "manual",
                        autoHideDelay: 5000,
                        title: function () { return "Live development has been started with Theseus in " + _mode.name.toUpperCase() + " mode." },
                    }).twipsy("show");
                }, 1000);
            }
        });

        if (_enabled) { // enable now if enabled in preferences
            _enable();
        }
    }

    // exports

    exports.isEnabled = isEnabled;
    exports.getModeName = getModeName;
    exports.version = THESEUS_VERSION;

    // initialize the extension

    AppInit.htmlReady(_init);
});
<commit_msg>disable file call graph<commit_after>/*
 * Copyright (c) 2012 Massachusetts Institute of Technology, Adobe Systems
 * Incorporated, and other contributors. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, $, brackets, Mustache */

/**
 * provides events:
 *
 *  - enable & disable, when the extension should operate
 */

define(function (require, exports, module) {
    "use strict";

    var Agent              = require("Agent");
    var AgentManager       = require("AgentManager");
    var AppInit            = brackets.getModule("utils/AppInit");
    var CommandManager     = brackets.getModule("command/CommandManager");
    var Commands           = brackets.getModule("command/Commands");
    var Dialogs            = brackets.getModule("widgets/Dialogs");
    var EpochPanel         = require("EpochPanel");
    var FileCallGraphPanel = require("FileCallGraphPanel");
    var EditorInterface    = require("EditorInterface");
    var ExtensionUtils     = brackets.getModule("utils/ExtensionUtils");
    var Invitation         = require("Invitation");
    var Inspector          = brackets.getModule("LiveDevelopment/Inspector/Inspector");
    var LiveDevelopment    = brackets.getModule("LiveDevelopment/LiveDevelopment");
    var Menus              = brackets.getModule("command/Menus");
    var NativeApp          = brackets.getModule("utils/NativeApp");
    var NativeFileSystem   = brackets.getModule("file/NativeFileSystem").NativeFileSystem;
    var Panel              = require("Panel");
    var PreferencesManager = brackets.getModule("preferences/PreferencesManager");
    var ProxyProvider      = require("ProxyProvider");
    var Strings            = require("strings");
    var UI                 = require("UI");
    var Usage              = require("Usage");

    var $exports = $(exports);

    var THESEUS_VERSION = JSON.parse(require("text!package.json")).version;

    // check that node_modules is there and alert the user if it isn't
    var corruptInstallationDialogHTML = require("text!InstallationCorrupt.html");
    var corruptInstallationDialogTemplate = Mustache.render(corruptInstallationDialogHTML, {Strings : Strings});
    var nodeModulesPath = ExtensionUtils.getModulePath(module, "node_modules");
    NativeFileSystem.resolveNativeFileSystemPath(nodeModulesPath, function() {}, function() {
        var dialog = Dialogs.showModalDialogUsingTemplate(corruptInstallationDialogTemplate);
        var $dialog = dialog.getElement();
        $dialog.find(".close").on("click", dialog.close.bind(dialog));
    });

    // set up the menus

    var _modes = {
        "static" : { name: "static", displayName: "Serve files from disk" },
        "proxy" : { name: "proxy", displayName: "Proxy to localhost:3000 (experimental)" },
    };
    var _orderedModes = [_modes["static"], _modes["proxy"]];
    var DEFAULT_MODE = _modes["static"];

    var ID_THESEUS_SEND_FEEDBACK   = "brackets.theseus.sendFeedback";
    var NAME_THESEUS_SEND_FEEDBACK = "Send Theseus Feedback...";

    var ID_THESEUS_WELCOME_SCREEN   = "brackets.theseus.welcome";
    var NAME_THESEUS_WELCOME_SCREEN = "Theseus Welcome Screen...";

    var ID_THESEUS_ENABLE = "brackets.theseus.enable";
    var NAME_THESEUS_ENABLE = "Enable Theseus";

    var ID_THESEUS_DEBUG_BRACKETS = "brackets.theseus.debug-brackets";
    var NAME_THESEUS_DEBUG_BRACKETS = "Debug Brackets with Theseus";

    var ID_THESEUS_RESET_TRACE = "brackets.theseus.reset-trace";
    var NAME_THESEUS_RESET_TRACE = "Reset Theseus Trace Data (experimental)";

    var ID_THESEUS_MODES = _orderedModes.map(function (mode) { return "brackets.theseus.mode." + mode.name; });
    var NAME_THESEUS_MODES = _orderedModes.map(function (mode) { return "   Mode: " + mode.displayName; });

    // module variables

    var _enabled = false;
    var _mode = DEFAULT_MODE;
    var _prefs;

    function _enable() {
        $exports.triggerHandler("enable");
    }

    function _disable() {
        $exports.triggerHandler("disable");
    }

    function _toggleEnabled() {
        // TODO: disable or enable immediately
        _enabled = !_enabled;
        _prefs.setValue("enabled", _enabled);
        _updateMenuStates();

        if (_enabled) {
            _enable();
        } else {
            _disable();
        }
    }

    function _setMode(modeName) {
        // TODO: warn user that connection will need to be restarted
        _mode = _modes[modeName] || DEFAULT_MODE;
        _prefs.setValue("mode", _mode.name);
        _updateMenuStates();
    }

    function _setModeHandler(modeName) {
        return function () {
            _setMode(modeName);
            $exports.triggerHandler("modeChange", modeName);
        };
    }

    function _sendFeedback() {
        var params = "?";
        params += "brackets_version=" + brackets.metadata.version;
        params += "&theseus_version=" + THESEUS_VERSION;
        NativeApp.openURLInDefaultBrowser("file://" + ExtensionUtils.getModuleUrl(module, "feedback.html") + params);
    }

    function _showWelcomeScreen() {
        Invitation.showInvitation();
    }

    function _debugBrackets() {
        var _proxy;
        CommandManager.execute("debug.newBracketsWindow").then(function () {
            return ProxyProvider.getServer("/", "static");
        }).then(function (proxy) {
            _proxy = proxy;
            return Inspector.getDebuggableWindows("127.0.0.1", 9234);
        }).then(function (response) {
            var keys = Object.keys(response).sort(function (a, b) { return parseInt(a, 10) - parseInt(b, 10); });
            if (keys.length > 0) {
                // pick the last page
                var page = response[keys[keys.length - 1]];

                var redirect = function () {
                    Inspector.off("connect", redirect);
                    var redirectTo = _proxy.proxyRootURL + (window.location.pathname[0] === "/" ? window.location.pathname.slice(1) : window.location.pathname)
                    Inspector.Runtime.evaluate("window.location = " + JSON.stringify(redirectTo), function () {});
                };
                Inspector.on("connect", redirect);

                Inspector.connect(page.webSocketDebuggerUrl);
            }
        }).fail(function onFail(err) {
            console.log("debugging brackets failed: " + err);
        });
    }

    function _resetTrace() {
        AgentManager.resetTrace();
    }

    function _loadPreferences() {
        _prefs = PreferencesManager.getPreferenceStorage("com.adobe.theseus", { enabled: true, mode: "static" });
        _enabled = _prefs.getValue("enabled");
        _mode = _modes[_prefs.getValue("mode")] || DEFAULT_MODE;
    }

    function _setupMenu() {
        CommandManager.register(
            NAME_THESEUS_SEND_FEEDBACK,
            ID_THESEUS_SEND_FEEDBACK,
            _sendFeedback
        );

        CommandManager.register(
            NAME_THESEUS_WELCOME_SCREEN,
            ID_THESEUS_WELCOME_SCREEN,
            _showWelcomeScreen
        );

        CommandManager.register(
            NAME_THESEUS_ENABLE,
            ID_THESEUS_ENABLE,
            _toggleEnabled
        );

        CommandManager.register(
            NAME_THESEUS_DEBUG_BRACKETS,
            ID_THESEUS_DEBUG_BRACKETS,
            _debugBrackets
        );

        CommandManager.register(
            NAME_THESEUS_RESET_TRACE,
            ID_THESEUS_RESET_TRACE,
            _resetTrace
        );

        _orderedModes.forEach(function (mode, i) {
            CommandManager.register(
                NAME_THESEUS_MODES[i],
                ID_THESEUS_MODES[i],
                _setModeHandler(mode.name)
            );
        });

        var menu = Menus.getMenu(Menus.AppMenuBar.HELP_MENU);
        menu.addMenuDivider(Menus.LAST, null);
        menu.addMenuItem(ID_THESEUS_SEND_FEEDBACK, null, Menus.LAST, null);
        menu.addMenuItem(ID_THESEUS_WELCOME_SCREEN, null, Menus.LAST, null);

        var fileMenu = Menus.getMenu(Menus.AppMenuBar.FILE_MENU);
        fileMenu.addMenuDivider(Menus.LAST, null);
        fileMenu.addMenuItem(ID_THESEUS_ENABLE, null, Menus.LAST, null);
        _orderedModes.forEach(function (mode, i) {
            var prev = (i == 0) ? ID_THESEUS_ENABLE : ID_THESEUS_MODES[i - 1];
            fileMenu.addMenuItem(ID_THESEUS_MODES[i], null, Menus.AFTER, prev);
        });
        fileMenu.addMenuItem(ID_THESEUS_RESET_TRACE, null, Menus.AFTER, ID_THESEUS_MODES[ID_THESEUS_MODES.length - 1]);

        var debugMenu = Menus.getMenu("debug-menu");
        debugMenu.addMenuDivider(Menus.LAST, null);
        debugMenu.addMenuItem(ID_THESEUS_DEBUG_BRACKETS, null, Menus.LAST, null);

        _updateMenuStates();
    }

    function _updateMenuStates() {
        CommandManager.get(ID_THESEUS_ENABLE).setChecked(_enabled);
        _orderedModes.forEach(function (mode, i) {
            var cmd = CommandManager.get(ID_THESEUS_MODES[i]);
            cmd.setChecked(_mode.name === mode.name);
            cmd.setEnabled(_enabled);
        });
    }

    function isEnabled() {
        return _enabled;
    }

    function getModeName() {
        return _mode.name;
    }

    function _init() {
        _loadPreferences();
        _setupMenu();

        ExtensionUtils.loadStyleSheet(module, "main.less");

        Usage.init();
        ProxyProvider.init();
        Agent.init();
        AgentManager.init();
        EditorInterface.init();
        UI.init();
        Panel.init();
        EpochPanel.init();
        // FileCallGraphPanel.init();

        // after a short delay, show 'Thank you!' popup if they haven't seen it
        setTimeout(function () {
            Invitation.showInvitationIfNecessary();
        }, 1000);

        $(LiveDevelopment).on("statusChange", function (e, status) {
            if (status === 1) { // "Connecting to the remote debugger"
                setTimeout(function () {
                    var $btnGoLive = $("#toolbar-go-live");

                    $btnGoLive.twipsy("hide").removeData("twipsy");
                    $btnGoLive.twipsy({
                        placement: "left",
                        trigger: "manual",
                        autoHideDelay: 5000,
                        title: function () { return "Live development has been started with Theseus in " + _mode.name.toUpperCase() + " mode." },
                    }).twipsy("show");
                }, 1000);
            }
        });

        if (_enabled) { // enable now if enabled in preferences
            _enable();
        }
    }

    // exports

    exports.isEnabled = isEnabled;
    exports.getModeName = getModeName;
    exports.version = THESEUS_VERSION;

    // initialize the extension

    AppInit.htmlReady(_init);
});
<|endoftext|>


<commit_before>
'use strict';

const _ = require('lodash');
const Script = require('smooch-bot').Script;

const scriptRules = require('./script.json');

var myDate = new Date();
var groet = '';

/* hour is before noon */
if ( myDate.getHours() < 12 )
{
groet = "Goeiemorgen";
}
else  /* Hour is from noon to 5pm (actually to 5:59 pm) */
if ( myDate.getHours() >= 12 && myDate.getHours() <= 17 )
{
groet = "Goedendag";
}
else  /* the hour is after 5pm, so it is between 6pm and midnight */
if ( myDate.getHours() > 17 && myDate.getHours() <= 24 )
{
groet = "Goedenavond";
}
else  /* the hour is not between 0 and 24, so something is wrong */
{
groet = "Welkom";
}

function wait(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}

module.exports = new Script({

 processing: {
//prompt: (bot) => bot.say('...'),
 receive: () => 'processing'
 },

start: {
    receive: (bot,message) => {
        const opening = message.text.trim().toUpperCase();
        return bot.say(`${groet}, waar ben je naar op zoek? %[Starters hypotheek](postback:hypotheektype_starter) %[Nieuwe hypotheek](postback:hypotheektype_nieuw) %[Hypotheek oversluiten](postback:hypotheektype_oversluiten)`)
        .then(() => 'selecteerHypotheek');
    }
},

selecteerHypotheek: {
    receive: (bot, message) => {

      switch(message.text) {
        case 'Hoi':
            return bot.say(`${groet} waar ben je naar op zoek? %[Starters hypotheek](postback:hypotheektype_starter) %[Nieuwe hypotheek](postback:hypotheektype_nieuw) %[Hypotheek oversluiten](postback:hypotheektype_oversluiten)`)
            .then(() => '')
        case 'hoi':
            return bot.say(`${groet} waar ben je naar op zoek? %[Starters hypotheek](postback:hypotheektype_starter) %[Nieuwe hypotheek](postback:hypotheektype_nieuw) %[Hypotheek oversluiten](postback:hypotheektype_oversluiten)`)
            .then(() => '')
        case 'Starters hypotheek':
          return bot.say(`Daar help ik je graag bij. Weet je al wat voor soort woning?`)
          .then(() => bot.say(`![](http://www.bieg.nl/beeld/woningen.jpg)`))
            .then(() => bot.say(`%[Appartement](postback:hypotheekkeuze_appartement) %[Tussenwoning](postback:hypotheekkeuze_tussenwoning) %[Vrijstaand](postback:hypotheekkeuze_vrijstaand)`))
            .then(() => 'askName')
          break;
        case 'Nieuwe hypotheek':
          return bot.say(`Helaas biedt Independer momenteel alleen Starters een hypotheek aan.`)
          .then(() => bot.say(`Via onderstaande link kun je de beste hypotheekadviseur voor jou vinden. %[Hypotheek Adviseur](https://www.independer.nl/hypotheekadviseur/intro.aspx)`))
            .then(() => 'processing')
          break;
        case 'Hypotheek oversluiten':
          return bot.say(`Sorry. Momenteel biedt Independer alleen hypotheken aan voor Starters.`)
            .then(() => 'bye')
          break;
        default:
          return bot.say(`...`)
            .then(() => 'processing')
          break;
      }
    }
},
hypotheekkeuze_appartement: {
  //  prompt: (bot) => bot.say(`![](http:www.bieg.nl/beeld/appartement.jpg)`)
    receive: () => 'processing'
},
hypotheekkeuze_tussenwoning: {
//    prompt: (bot) => bot.say(`![](http:www.bieg.nl/beeld/appartement.jpg)`)
    receive: () => 'processing'
},
hypotheekkeuze_vrijstaand: {
//    prompt: (bot) => bot.say(`![](http:www.bieg.nl/beeld/appartement.jpg)`)
    receive: () => 'processing'
},
hypotheektype_nieuw: {
//    prompt: (bot) => bot.say(`Independer biedt momenteel alleen voor Starters een hypotheek. Onderstaande link bied je meer informatie %[Hypotheek Adviseur](https://www.independer.nl/hypotheekadviseur/intro.aspx)`),
    receive: () => 'bye'
},

vervolgVragen: {
  receive: (bot, message) => {
    switch(message.text) {
        case 'Appartement':
          return bot.say(`Top!`)
          .then(() => 'askName')
        break;
      default:
        return bot.say(`...`)
          .then(() => 'processing')
        break;
    }
    }
},

askName: {
    prompt: (bot) => bot.say('Top - maar met wie heb ik het genoegen?'),
    receive: (bot, message) => {
        const name = message.text;
        return bot.setProp('name', name)
            .then(() => bot.say(`Hoi ${name}. ik heb nog wat vragen voor je om verder te kunnen.`))
            .then(() => 'vervolgVragen');
    }
},

bye: {
    prompt: (bot) => bot.say('Bedankt voor je tijd'),
    receive: () => 'processing'
},

// error: {
// prompt: (bot) => bot.say('Sorry - kun je dat nog eens zeggen?  Er ging iets mis...'),
// receive: () => ''
// },

finish: {
receive: () => 'finish'
},

  speak: {
          receive: (bot, message) => {

              let upperText = message.text.trim().toUpperCase();

              function updateSilent() {
                  switch (upperText) {
                      case "CONNECT ME":
                          return bot.setProp("silent", true);
                      case "DISCONNECT":
                          return bot.setProp("silent", false);
                      default:
                          return Promise.resolve();
                  }
              }

              function getSilent() {
                  return bot.getProp("silent");
              }

              function processMessage(isSilent) {
                  if (isSilent) {
                      return Promise.resolve("speak");
                  }

                  if (!_.has(scriptRules, upperText)) {
                      return bot.say(`So, I'm good at structured conversations but stickers, emoji and sentences still confuse me. Say 'more' to chat about something else.`).then(() => 'speak');
                  }

                  var response = scriptRules[upperText];
                  var lines = response.split('\n');

                  var p = Promise.resolve();
                  _.each(lines, function(line) {
                      line = line.trim();
                      p = p.then(function() {
                          console.log(line);
                          return wait(50).then(function() {
                              return bot.say(line);
                          });
                      });
                  });

                  return p.then(() => 'speak');
              }

              return updateSilent()
                  .then(getSilent)
                  .then(processMessage);
          }
      }
});
<commit_msg>script<commit_after>
'use strict';

const _ = require('lodash');
const Script = require('smooch-bot').Script;

const scriptRules = require('./script.json');

var myDate = new Date();
var groet = '';

/* hour is before noon */
if ( myDate.getHours() < 12 )
{
groet = "Goeiemorgen";
}
else  /* Hour is from noon to 5pm (actually to 5:59 pm) */
if ( myDate.getHours() >= 12 && myDate.getHours() <= 17 )
{
groet = "Goedendag";
}
else  /* the hour is after 5pm, so it is between 6pm and midnight */
if ( myDate.getHours() > 17 && myDate.getHours() <= 24 )
{
groet = "Goedenavond";
}
else  /* the hour is not between 0 and 24, so something is wrong */
{
groet = "Welkom";
}

function wait(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}

module.exports = new Script({

 processing: {
//prompt: (bot) => bot.say('...'),
 receive: () => 'processing'
 },

start: {
    receive: (bot,message) => {
        const opening = message.text.trim().toUpperCase();
        return bot.say(`${groet}, waar ben je naar op zoek? %[Starters hypotheek](postback:hypotheektype_starter) %[Nieuwe hypotheek](postback:hypotheektype_nieuw) %[Hypotheek oversluiten](postback:hypotheektype_oversluiten)`)
        .then(() => 'selecteerHypotheek');
    }
},

selecteerHypotheek: {
    receive: (bot, message) => {

      switch(message.text) {
        case 'Hoi':
            return bot.say(`${groet} waar ben je naar op zoek? %[Starters hypotheek](postback:hypotheektype_starter) %[Nieuwe hypotheek](postback:hypotheektype_nieuw) %[Hypotheek oversluiten](postback:hypotheektype_oversluiten)`)
            .then(() => '')
        case 'hoi':
            return bot.say(`${groet} waar ben je naar op zoek? %[Starters hypotheek](postback:hypotheektype_starter) %[Nieuwe hypotheek](postback:hypotheektype_nieuw) %[Hypotheek oversluiten](postback:hypotheektype_oversluiten)`)
            .then(() => '')
        case 'Starters hypotheek':
          return bot.say(`Daar help ik je graag bij. Weet je al wat voor soort woning?`)
          .then(() => bot.say(`![](http://www.bieg.nl/beeld/woningen.jpg)`))
            .then(() => bot.say(`%[Appartement](postback:hypotheekkeuze_appartement) %[Tussenwoning](postback:hypotheekkeuze_tussenwoning) %[Vrijstaand](postback:hypotheekkeuze_vrijstaand)`))
            .then(() => 'processing')
          break;
        case 'Nieuwe hypotheek':
          return bot.say(`Helaas biedt Independer momenteel alleen Starters een hypotheek aan.`)
          .then(() => bot.say(`Via onderstaande link kun je de beste hypotheekadviseur voor jou vinden. %[Hypotheek Adviseur](https://www.independer.nl/hypotheekadviseur/intro.aspx)`))
            .then(() => 'processing')
          break;
        case 'Hypotheek oversluiten':
          return bot.say(`Sorry. Momenteel biedt Independer alleen hypotheken aan voor Starters.`)
            .then(() => 'bye')
          break;
        default:
          return bot.say(`...`)
            .then(() => 'processing')
          break;
      }
    }
},
hypotheekkeuze_appartement: {
  //  prompt: (bot) => bot.say(`![](http:www.bieg.nl/beeld/appartement.jpg)`)
    receive: () => 'processing'
},
hypotheekkeuze_tussenwoning: {
//    prompt: (bot) => bot.say(`![](http:www.bieg.nl/beeld/appartement.jpg)`)
    receive: () => 'processing'
},
hypotheekkeuze_vrijstaand: {
//    prompt: (bot) => bot.say(`![](http:www.bieg.nl/beeld/appartement.jpg)`)
    receive: () => 'processing'
},
hypotheektype_nieuw: {
//    prompt: (bot) => bot.say(`Independer biedt momenteel alleen voor Starters een hypotheek. Onderstaande link bied je meer informatie %[Hypotheek Adviseur](https://www.independer.nl/hypotheekadviseur/intro.aspx)`),
    receive: () => 'bye'
},

vervolgVragen: {
  receive: (bot, message) => {
    switch(message.text) {
        case 'Appartement':
          return bot.say(`Top!`)
          .then(() => 'askName')
        break;
      default:
        return bot.say(`...`)
          .then(() => 'processing')
        break;
    }
    }
},

askName: {
    prompt: (bot) => bot.say('Top - maar met wie heb ik het genoegen?'),
    receive: (bot, message) => {
        const name = message.text;
        return bot.setProp('name', name)
            .then(() => bot.say(`Hoi ${name}. ik heb nog wat vragen voor je om verder te kunnen.`))
            .then(() => 'vervolgVragen');
    }
},

bye: {
    prompt: (bot) => bot.say('Bedankt voor je tijd'),
    receive: () => 'processing'
},

// error: {
// prompt: (bot) => bot.say('Sorry - kun je dat nog eens zeggen?  Er ging iets mis...'),
// receive: () => ''
// },

finish: {
receive: () => 'finish'
},

  speak: {
          receive: (bot, message) => {

              let upperText = message.text.trim().toUpperCase();

              function updateSilent() {
                  switch (upperText) {
                      case "CONNECT ME":
                          return bot.setProp("silent", true);
                      case "DISCONNECT":
                          return bot.setProp("silent", false);
                      default:
                          return Promise.resolve();
                  }
              }

              function getSilent() {
                  return bot.getProp("silent");
              }

              function processMessage(isSilent) {
                  if (isSilent) {
                      return Promise.resolve("speak");
                  }

                  if (!_.has(scriptRules, upperText)) {
                      return bot.say(`So, I'm good at structured conversations but stickers, emoji and sentences still confuse me. Say 'more' to chat about something else.`).then(() => 'speak');
                  }

                  var response = scriptRules[upperText];
                  var lines = response.split('\n');

                  var p = Promise.resolve();
                  _.each(lines, function(line) {
                      line = line.trim();
                      p = p.then(function() {
                          console.log(line);
                          return wait(50).then(function() {
                              return bot.say(line);
                          });
                      });
                  });

                  return p.then(() => 'speak');
              }

              return updateSilent()
                  .then(getSilent)
                  .then(processMessage);
          }
      }
});
<|endoftext|>


<commit_before>type("ApplyForParticipationPopup", ["ServiceDialogWithButtons"], {
    _success: function(response) {
        this.onSuccess(response);
    },

    _save: function(response) {
        var self = this;
        if(self.parameterManager.check()){
            self.request(self.userData);
        }
    },

    _getButtons: function(){
        var self = this;
        return [
            [$T('OK'), function() {
                self._save();
            }, true],
            [$T('Cancel'), function(){
                self.close();
            }]
        ]
    },

    _drawUserEditable: function() {
        var self = this;
        return IndicoUtil.createFormFromMap(
                [
                 [$T('Title'), $B(Html.select({}, Html.option({}, ""), Html.option({value:'Mr.'}, $T("Mr.")), Html.option({value:'Mrs.'}, $T("Mrs.")), Html.option({value:'Ms.'}, $T("Ms.")), Html.option({value:'Dr.'}, $T("Dr.")), Html.option({value:'Prof.'}, $T("Prof."))), self.userData.accessor('title'))],
                 [$T('Family Name'), $B(self.parameterManager.add(Html.edit({style: {width: '200px'}}), 'text', false), self.userData.accessor('surName'))],
                 [$T('First Name'), $B(self.parameterManager.add(Html.edit({style: {width: '200px'}}), 'text', false), self.userData.accessor('name'))],
                 [$T('Affiliation'), $B(Html.edit({style: {width: '200px'}}), self.userData.accessor('affiliation'))],
                 [$T('Email'),  $B(self.parameterManager.add(Html.edit({style: {width: '200px'}}), 'email', false), self.userData.accessor('email'))],
                 [$T('Address'), $B(Html.textarea({style: {width: '200px'}}), self.userData.accessor('address'))],
                 [$T('Telephone'), $B(Html.edit({style: {width: '150px'}}), self.userData.accessor('phone'))],
                 [$T('Fax'), $B(Html.edit({style: {width: '150px'}}), self.userData.accessor('fax'))],
             ]);
    },

    _drawUserNotEditable: function() {
        var self = this;
        return IndicoUtil.createFormFromMap(
                [
                 [$T('Title'), self.userData.get("title")],
                 [$T('Last Name'),self.userData.get("surName")],
                 [$T('First Name'), self.userData.get("name")],
                 [$T('Email'),self.userData.get("email")],
                 [$T('Address'),self.userData.get("address")],
                 [$T('Affiliation'),self.userData.get("affiliation")],
                 [$T('Telephone'),self.userData.get("phone")],
                 [$T('Fax'),self.userData.get("fax")]
             ]);
    },

    draw: function() {
        var self = this;
        self.parameterManager = new IndicoUtil.parameterManager();
        var tabWidget = null;
        if(this.allowEdit){
            tabWidget = self._drawUserEditable();
        }
        else{
            tabWidget = self._drawUserNotEditable();
        }
        return this.ServiceDialogWithButtons.prototype.draw.call(this, tabWidget);
    }
},

    function(confId, method, title, userData, onSuccess, allowEdit) {
        this.onSuccess = any(onSuccess,positive);
        this.confId = confId;
        this.userData = $O(userData);
        this.allowEdit = any(allowEdit, true);
        var self = this;
        self.userData.set("confId",self.confId);
        this.ServiceDialogWithButtons(Indico.Urls.JsonRpcService, method, userData, title, function() {self.close();});
        self.open();
    }
);

type("BasicEmailPopup", ["ExclusivePopupWithButtons"],{

    _getButtons: function(){
        var self = this;
        return [
            [$T('Send'), function() {
                self.sendFunction();
            }],
            [$T('Cancel'), function(){
                self.close();
            }]
        ]
    },

    _drawRTWidget: function(){

        var self = this;
        // Text editor with default message
        self.rtWidget = new ParsedRichTextEditor(700, 400, 'IndicoMinimal');
        self.rtWidget.set(self.defaultText);
    },

    _drawTop: function(){
        var self = this;
        return Html.div({}, self._drawFromAddress(), self._drawToAddress(), self._drawSubject());
    },

    _drawWidget: function(){
        var self = this;
        self._drawRTWidget();
        return Html.div({}, self._drawTop(), self.rtWidget.draw(), self._drawLegends());
    },

    _drawLegends: function(){
        var self = this;
        if(_.size(self.legends) == 0){
            return null;
        }
        var legendFields = [];
        for(legend in self.legends){
            legendFields.push(Html.tr({}, Html.td({}, "{"+legend+"} :"), Html.td({}, self.legends[legend])));
        }
        return Html.div({style:{marginLeft: '20px',
                         fontStyle:'italic',
                         color:'gray'}
                  },
                  Html.div({style:{fontWeight:'bold'}}, $T("Legend:")),
                  Html.table({},legendFields));
    },

    draw: function(){
        var self = this;

        return this.ExclusivePopupWithButtons.prototype.draw.call(
                self,
                self._drawWidget()
                );
    }
},
function(title, confTitle, confId, subject, defaultText, legends){
    var self = this;
    self.confTitle = confTitle;
    self.confId = confId;
    self.defaultText = any(defaultText,"");
    self.subject = new WatchObject();
    $B(self.subject.accessor(), subject);
    self.legends = any(legends,{});

    this.ExclusivePopupWithButtons(title);
}
);

type("ParticipantsEmailPopup", ["BasicEmailPopup"],{

    _drawFromAddress: function(){
        var self = this;
        var fromField = Html.tr({},
                Html.td({width:"15%"}, Html.span({}, $T("From:"))),
                Html.td({width:"85%"}, Html.span({}, self.from))
        );

        return Html.table({width:"688px"}, fromField);
    },

    _drawToAddress: function(){
        var self = this;
        var toField = Html.tr({},
                Html.td({width:"15%"}, Html.span({}, $T("To:"))),
                Html.td({width:"85%"}, _.values(self.toParticipants).join('; '))
        );

        return Html.table({width:"688px"}, toField);
    },

    _drawSubject: function(){
        var self = this;
        var subjectField = Html.tr({},
                Html.td({width:"15%"}, Html.span({}, $T("Subject:"))),
                Html.td({width:"85%"}, $B(Html.edit({style: {width: '100%'}}), self.subject.accessor()))
        );
        return Html.table({width:"688px"}, subjectField);
    },

    _drawExtras: function(){
        legendTable = Html.table(
                {},
                Html.tr({}, Html.td({}, "{url} :"), Html.td({}, $T("field containing the url of the electronic agreement. (This field is mandatory)"))),
                Html.tr({}, Html.td({}, "{confTitle} :"), Html.td({}, $T("field containing the conference title."))),
                Html.tr({}, Html.td({}, "{name} :"), Html.td({}, $T("field containing the full name of the participant.")))
                );
        return Html.div({style:{marginLeft: '20px',
                         fontStyle:'italic',
                         color:'gray'}
                  },
                  Html.div({style:{fontWeight:'bold'}}, $T("Legend:")),
                  legendTable);
    }

},
    function(title,confTitle, confId, method, toParticipants, from, subject, defaultContent, legends, successHandler){
        var self = this;
        self.toParticipants = toParticipants;
        self.from = from;
        self.toUserIds = any(self.toUserIds,_.keys(toParticipants))
        this.sendFunction=function(){
            var killProgress = IndicoUI.Dialogs.Util.progress($T("Sending email..."));
            jsonRpc(Indico.Urls.JsonRpcService, method,
                {
                    conference : self.confId,
                    userIds: self.toUserIds,
                    subject: self.subject.get(),
                    body: self.rtWidget.get()
                },
                function(result, error){
                    if (error) {
                        killProgress();
                        IndicoUtil.errorReport(error);
                        self.close();
                    } else {
                        killProgress();
                        successHandler(result);
                        self.close();
                    }
                }
            );
        };
        this.BasicEmailPopup(title, confTitle, confId, subject, defaultContent, legends);
    }

);

type("ParticipantsInvitePopup", ["ParticipantsEmailPopup"],{

    _drawToAddress: function(){
        var self = this;
        var to = [];
        for (p in self.toParticipants){
            to.push(self.toParticipants[p].name);
        }
        var toField = Html.tr({},
                Html.td({width:"15%"}, Html.span({}, $T("To:"))),
                Html.td({width:"85%"}, to.join("; "))
        );

        return Html.table({width:"95%"}, toField);
    }
},
    function(title,confTitle, confId, method, toParticipants, from, subject, defaultContent, legends, successHandler){
        this.toUserIds = toParticipants;
        this.ParticipantsEmailPopup(title,confTitle, confId, method, toParticipants, from, subject, defaultContent, legends, successHandler);
    }

);<commit_msg>[FIX] Extra comma (IE)<commit_after>type("ApplyForParticipationPopup", ["ServiceDialogWithButtons"], {
    _success: function(response) {
        this.onSuccess(response);
    },

    _save: function(response) {
        var self = this;
        if(self.parameterManager.check()){
            self.request(self.userData);
        }
    },

    _getButtons: function(){
        var self = this;
        return [
            [$T('OK'), function() {
                self._save();
            }, true],
            [$T('Cancel'), function(){
                self.close();
            }]
        ]
    },

    _drawUserEditable: function() {
        var self = this;
        return IndicoUtil.createFormFromMap(
                [
                 [$T('Title'), $B(Html.select({}, Html.option({}, ""), Html.option({value:'Mr.'}, $T("Mr.")), Html.option({value:'Mrs.'}, $T("Mrs.")), Html.option({value:'Ms.'}, $T("Ms.")), Html.option({value:'Dr.'}, $T("Dr.")), Html.option({value:'Prof.'}, $T("Prof."))), self.userData.accessor('title'))],
                 [$T('Family Name'), $B(self.parameterManager.add(Html.edit({style: {width: '200px'}}), 'text', false), self.userData.accessor('surName'))],
                 [$T('First Name'), $B(self.parameterManager.add(Html.edit({style: {width: '200px'}}), 'text', false), self.userData.accessor('name'))],
                 [$T('Affiliation'), $B(Html.edit({style: {width: '200px'}}), self.userData.accessor('affiliation'))],
                 [$T('Email'),  $B(self.parameterManager.add(Html.edit({style: {width: '200px'}}), 'email', false), self.userData.accessor('email'))],
                 [$T('Address'), $B(Html.textarea({style: {width: '200px'}}), self.userData.accessor('address'))],
                 [$T('Telephone'), $B(Html.edit({style: {width: '150px'}}), self.userData.accessor('phone'))],
                 [$T('Fax'), $B(Html.edit({style: {width: '150px'}}), self.userData.accessor('fax'))]
             ]);
    },

    _drawUserNotEditable: function() {
        var self = this;
        return IndicoUtil.createFormFromMap(
                [
                 [$T('Title'), self.userData.get("title")],
                 [$T('Last Name'),self.userData.get("surName")],
                 [$T('First Name'), self.userData.get("name")],
                 [$T('Email'),self.userData.get("email")],
                 [$T('Address'),self.userData.get("address")],
                 [$T('Affiliation'),self.userData.get("affiliation")],
                 [$T('Telephone'),self.userData.get("phone")],
                 [$T('Fax'),self.userData.get("fax")]
             ]);
    },

    draw: function() {
        var self = this;
        self.parameterManager = new IndicoUtil.parameterManager();
        var tabWidget = null;
        if(this.allowEdit){
            tabWidget = self._drawUserEditable();
        }
        else{
            tabWidget = self._drawUserNotEditable();
        }
        return this.ServiceDialogWithButtons.prototype.draw.call(this, tabWidget);
    }
},

    function(confId, method, title, userData, onSuccess, allowEdit) {
        this.onSuccess = any(onSuccess,positive);
        this.confId = confId;
        this.userData = $O(userData);
        this.allowEdit = any(allowEdit, true);
        var self = this;
        self.userData.set("confId",self.confId);
        this.ServiceDialogWithButtons(Indico.Urls.JsonRpcService, method, userData, title, function() {self.close();});
        self.open();
    }
);

type("BasicEmailPopup", ["ExclusivePopupWithButtons"],{

    _getButtons: function(){
        var self = this;
        return [
            [$T('Send'), function() {
                self.sendFunction();
            }],
            [$T('Cancel'), function(){
                self.close();
            }]
        ]
    },

    _drawRTWidget: function(){

        var self = this;
        // Text editor with default message
        self.rtWidget = new ParsedRichTextEditor(700, 400, 'IndicoMinimal');
        self.rtWidget.set(self.defaultText);
    },

    _drawTop: function(){
        var self = this;
        return Html.div({}, self._drawFromAddress(), self._drawToAddress(), self._drawSubject());
    },

    _drawWidget: function(){
        var self = this;
        self._drawRTWidget();
        return Html.div({}, self._drawTop(), self.rtWidget.draw(), self._drawLegends());
    },

    _drawLegends: function(){
        var self = this;
        if(_.size(self.legends) == 0){
            return null;
        }
        var legendFields = [];
        for(legend in self.legends){
            legendFields.push(Html.tr({}, Html.td({}, "{"+legend+"} :"), Html.td({}, self.legends[legend])));
        }
        return Html.div({style:{marginLeft: '20px',
                         fontStyle:'italic',
                         color:'gray'}
                  },
                  Html.div({style:{fontWeight:'bold'}}, $T("Legend:")),
                  Html.table({},legendFields));
    },

    draw: function(){
        var self = this;

        return this.ExclusivePopupWithButtons.prototype.draw.call(
                self,
                self._drawWidget()
                );
    }
},
function(title, confTitle, confId, subject, defaultText, legends){
    var self = this;
    self.confTitle = confTitle;
    self.confId = confId;
    self.defaultText = any(defaultText,"");
    self.subject = new WatchObject();
    $B(self.subject.accessor(), subject);
    self.legends = any(legends,{});

    this.ExclusivePopupWithButtons(title);
}
);

type("ParticipantsEmailPopup", ["BasicEmailPopup"],{

    _drawFromAddress: function(){
        var self = this;
        var fromField = Html.tr({},
                Html.td({width:"15%"}, Html.span({}, $T("From:"))),
                Html.td({width:"85%"}, Html.span({}, self.from))
        );

        return Html.table({width:"688px"}, fromField);
    },

    _drawToAddress: function(){
        var self = this;
        var toField = Html.tr({},
                Html.td({width:"15%"}, Html.span({}, $T("To:"))),
                Html.td({width:"85%"}, _.values(self.toParticipants).join('; '))
        );

        return Html.table({width:"688px"}, toField);
    },

    _drawSubject: function(){
        var self = this;
        var subjectField = Html.tr({},
                Html.td({width:"15%"}, Html.span({}, $T("Subject:"))),
                Html.td({width:"85%"}, $B(Html.edit({style: {width: '100%'}}), self.subject.accessor()))
        );
        return Html.table({width:"688px"}, subjectField);
    },

    _drawExtras: function(){
        legendTable = Html.table(
                {},
                Html.tr({}, Html.td({}, "{url} :"), Html.td({}, $T("field containing the url of the electronic agreement. (This field is mandatory)"))),
                Html.tr({}, Html.td({}, "{confTitle} :"), Html.td({}, $T("field containing the conference title."))),
                Html.tr({}, Html.td({}, "{name} :"), Html.td({}, $T("field containing the full name of the participant.")))
                );
        return Html.div({style:{marginLeft: '20px',
                         fontStyle:'italic',
                         color:'gray'}
                  },
                  Html.div({style:{fontWeight:'bold'}}, $T("Legend:")),
                  legendTable);
    }

},
    function(title,confTitle, confId, method, toParticipants, from, subject, defaultContent, legends, successHandler){
        var self = this;
        self.toParticipants = toParticipants;
        self.from = from;
        self.toUserIds = any(self.toUserIds,_.keys(toParticipants))
        this.sendFunction=function(){
            var killProgress = IndicoUI.Dialogs.Util.progress($T("Sending email..."));
            jsonRpc(Indico.Urls.JsonRpcService, method,
                {
                    conference : self.confId,
                    userIds: self.toUserIds,
                    subject: self.subject.get(),
                    body: self.rtWidget.get()
                },
                function(result, error){
                    if (error) {
                        killProgress();
                        IndicoUtil.errorReport(error);
                        self.close();
                    } else {
                        killProgress();
                        successHandler(result);
                        self.close();
                    }
                }
            );
        };
        this.BasicEmailPopup(title, confTitle, confId, subject, defaultContent, legends);
    }

);

type("ParticipantsInvitePopup", ["ParticipantsEmailPopup"],{

    _drawToAddress: function(){
        var self = this;
        var to = [];
        for (p in self.toParticipants){
            to.push(self.toParticipants[p].name);
        }
        var toField = Html.tr({},
                Html.td({width:"15%"}, Html.span({}, $T("To:"))),
                Html.td({width:"85%"}, to.join("; "))
        );

        return Html.table({width:"95%"}, toField);
    }
},
    function(title,confTitle, confId, method, toParticipants, from, subject, defaultContent, legends, successHandler){
        this.toUserIds = toParticipants;
        this.ParticipantsEmailPopup(title,confTitle, confId, method, toParticipants, from, subject, defaultContent, legends, successHandler);
    }

);<|endoftext|>


<commit_before>import fs from 'fs'
import path from 'path'

export const isDirectory = (file) => {
  try {
    const outputPath = path.resolve(process.cwd(), file)

    return fs.statSync(outputPath).isDirectory()
  } catch (e) {
    return false
  }
}

const replaceExtension = input => input.replace('.mjml', input.match(/(.)*\.(.)+$/g) ? '' : '.html')

const makeGuessOutputName = (outputPath) => {
  if (isDirectory(outputPath)) {
    return input => path.join(outputPath, replaceExtension(input))
  }

  return (input) => {
    if (!outputPath) {
      return replaceExtension(input)
    }

    return outputPath
  }
}

export default (outputPath) => {
  const guessOutputName = makeGuessOutputName(outputPath)

  return ({ file, mjml }) => (
    new Promise((resolve, reject) => {
      const outputName = guessOutputName(file)

      fs.writeFile(outputName, mjml, (err) => {
        if (err) {
          return reject()
        }

        return resolve()
      })
    })
  )
}
<commit_msg>add extension<commit_after>import fs from 'fs'
import path from 'path'

export const isDirectory = (file) => {
  try {
    const outputPath = path.resolve(process.cwd(), file)

    return fs.statSync(outputPath).isDirectory()
  } catch (e) {
    return false
  }
}

const replaceExtension = input => input.replace(
  '.mjml',
  input.replace('.mjml', '').match(/(.)*\.(.)+$/g) ? '' : '.html'
)

const makeGuessOutputName = (outputPath) => {
  if (isDirectory(outputPath)) {
    return input => path.join(outputPath, replaceExtension(input))
  }

  return (input) => {
    if (!outputPath) {
      return replaceExtension(input)
    }

    return outputPath
  }
}

export default (outputPath) => {
  const guessOutputName = makeGuessOutputName(outputPath)

  return ({ file, mjml }) => (
    new Promise((resolve, reject) => {
      const outputName = guessOutputName(file)

      fs.writeFile(outputName, mjml, (err) => {
        if (err) {
          return reject()
        }

        return resolve()
      })
    })
  )
}
<|endoftext|>


<commit_before>/* MIT License: https://webrtc-experiment.appspot.com/licence/ */

var hangout = function (config) {
    var self = {
        userToken: uniqueToken()
    },
    channels = '--',
        isbroadcaster,
        isGetNewRoom = true,
        defaultSocket = {}, RTCDataChannels = [];

    function openDefaultSocket() {
        defaultSocket = config.openSocket({
            onmessage: onDefaultSocketResponse
        });
    }

    function onDefaultSocketResponse(response) {
        if (response.userToken == self.userToken) return;

        if (isGetNewRoom && response.roomToken && response.broadcaster) config.onRoomFound(response);

        if (response.newParticipant) onNewParticipant(response.newParticipant);

        if (response.userToken && response.joinUser == self.userToken && response.participant && channels.indexOf(response.userToken) == -1) {
            channels += response.userToken + '--';
            openSubSocket({
                isofferer: true,
                channel: response.channel || response.userToken,
                closeSocket: true
            });
        }
    }

    function getPort() {
        return Math.random() * 1000 << 10;
    }

    function openSubSocket(_config) {
        if (!_config.channel) return;
        var socketConfig = {
            channel: _config.channel,
            onmessage: socketResponse,
            onopen: function () {
                if (isofferer && !peer) initPeer();
            }
        };

        var socket = config.openSocket(socketConfig),
            isofferer = _config.isofferer,
            gotstream,
            inner = {},
            dataPorts = [getPort(), getPort()],
            peer;

        var peerConfig = {
            onICE: function (candidate) {
                socket.send({
                    userToken: self.userToken,
                    candidate: {
                        sdpMLineIndex: candidate.sdpMLineIndex,
                        candidate: JSON.stringify(candidate.candidate)
                    }
                });
            },
            onChannelOpened: onChannelOpened,
            onChannelMessage: function (event) {
                config.onChannelMessage(JSON.parse(event.data));
            }
        };

        function initPeer(offerSDP) {
            if (!offerSDP) {
                peerConfig.onOfferSDP = sendsdp;
            } else {
                peerConfig.offerSDP = offerSDP;
                peerConfig.onAnswerSDP = sendsdp;
                peerConfig.dataPorts = dataPorts;
            }
            peer = RTCPeerConnection(peerConfig);
        }

        function onChannelOpened(channel) {
            RTCDataChannels[RTCDataChannels.length] = channel;
            if (config.onChannelOpened) config.onChannelOpened(channel);

            if (isbroadcaster && channels.split('--').length > 3) {
                /* broadcasting newly connected participant for video-conferencing! */
                defaultSocket.send({
                    newParticipant: socket.channel,
                    userToken: self.userToken
                });
            }

            /* closing subsocket here on the offerer side */
            if (_config.closeSocket) socket = null;

            gotstream = true;
        }

        function sendsdp(sdp) {
            sdp = JSON.stringify(sdp);
            var part = parseInt(sdp.length / 3);

            var firstPart = sdp.slice(0, part),
                secondPart = sdp.slice(part, sdp.length - 1),
                thirdPart = '';

            if (sdp.length > part + part) {
                secondPart = sdp.slice(part, part + part);
                thirdPart = sdp.slice(part + part, sdp.length);
            }

            socket.send({
                userToken: self.userToken,
                firstPart: firstPart,

                /* sending RTCDataChannel ports alongwith sdp */
                dataPorts: dataPorts
            });

            socket.send({
                userToken: self.userToken,
                secondPart: secondPart
            });

            socket.send({
                userToken: self.userToken,
                thirdPart: thirdPart
            });
        }

        function socketResponse(response) {
            if (response.userToken == self.userToken) return;

            if (response.firstPart || response.secondPart || response.thirdPart) {
                if (response.dataPorts) inner.dataPorts = response.dataPorts;
                if (response.firstPart) {
                    inner.firstPart = response.firstPart;
                    if (inner.secondPart && inner.thirdPart) selfInvoker();
                }
                if (response.secondPart) {
                    inner.secondPart = response.secondPart;
                    if (inner.firstPart && inner.thirdPart) selfInvoker();
                }

                if (response.thirdPart) {
                    inner.thirdPart = response.thirdPart;
                    if (inner.firstPart && inner.secondPart) selfInvoker();
                }
            }

            if (response.candidate && !gotstream) {
                peer && peer.addICE({
                    sdpMLineIndex: response.candidate.sdpMLineIndex,
                    candidate: JSON.parse(response.candidate.candidate)
                });
            }
        }

        var invokedOnce = false;

        function selfInvoker() {
            if (invokedOnce) return;

            invokedOnce = true;

            inner.sdp = JSON.parse(inner.firstPart + inner.secondPart + inner.thirdPart);

            /* using random data ports to support wide connection on firefox! */
            if (isofferer) peer.addAnswerSDP(inner.sdp, inner.dataPorts);
            else initPeer(inner.sdp);
        }
    }

    function startBroadcasting() {
        defaultSocket.send({
            roomToken: self.roomToken,
            roomName: self.roomName,
            broadcaster: self.userToken
        });
        setTimeout(startBroadcasting, 3000);
    }

    function onNewParticipant(channel) {
        if (!channel || channels.indexOf(channel) != -1 || channel == self.userToken) return;
        channels += channel + '--';

        var new_channel = uniqueToken();
        openSubSocket({
            channel: new_channel,
            closeSocket: true
        });

        defaultSocket.send({
            participant: true,
            userToken: self.userToken,
            joinUser: channel,
            channel: new_channel
        });
    }

    function uniqueToken() {
        var s4 = function () {
            return Math.floor(Math.random() * 0x10000).toString(16);
        };
        return s4() + s4() + "-" + s4() + "-" + s4() + "-" + s4() + "-" + s4() + s4() + s4();
    }

    openDefaultSocket();
    return {
        createRoom: function (_config) {
            self.roomName = _config.roomName || 'Anonymous';
            self.roomToken = uniqueToken();
            self.userName = _config.userName || 'Anonymous';

            isbroadcaster = true;
            isGetNewRoom = false;
            startBroadcasting();
        },
        joinRoom: function (_config) {
            self.roomToken = _config.roomToken;
            self.userName = _config.userName || 'Anonymous';
            isGetNewRoom = false;

            openSubSocket({
                channel: self.userToken
            });

            defaultSocket.send({
                participant: true,
                userToken: self.userToken,
                joinUser: _config.joinUser
            });
        },
        send: function (data) {
            var length = RTCDataChannels.length,
                data = JSON.stringify(data);
            if (!length) return;
            for (var i = 0; i < length; i++) {
                RTCDataChannels[i].send(data);
            }
        }
    };
};<commit_msg>Missed hangout.js file in part of screen sharing<commit_after>var hangout = function (config) {
    var self = {
        userToken: uniqueToken()
    },
        channels = '--',
        isbroadcaster,
        isGetNewRoom = true,
        defaultSocket = {}, RTCDataChannels = [];

    function openDefaultSocket() {
        defaultSocket = config.openSocket({
            onmessage: onDefaultSocketResponse
        });
    }

    function onDefaultSocketResponse(response) {
        if (response.userToken == self.userToken) return;

        if (isGetNewRoom && response.roomToken && response.broadcaster) config.onRoomFound(response);

        if (response.newParticipant) onNewParticipant(response.newParticipant);

        if (response.userToken && response.joinUser == self.userToken && response.participant && channels.indexOf(response.userToken) == -1) {
            channels += response.userToken + '--';
            openSubSocket({
                isofferer: true,
                channel: response.channel || response.userToken,
                closeSocket: true
            });
        }
    }

    function getPort() {
        return Math.random() * 1000 << 10;
    }

    function openSubSocket(_config) {
        if (!_config.channel) return;
        var socketConfig = {
            channel: _config.channel,
            onmessage: socketResponse,
            onopen: function () {
                if (isofferer && !peer) initPeer();
            }
        };

        var socket = config.openSocket(socketConfig),
            isofferer = _config.isofferer,
            gotstream,
            inner = {},
            dataPorts = [getPort(), getPort()],
            peer;

        var peerConfig = {
            onICE: function (candidate) {
                socket.send({
                    userToken: self.userToken,
                    candidate: {
                        sdpMLineIndex: candidate.sdpMLineIndex,
                        candidate: JSON.stringify(candidate.candidate)
                    }
                });
            },
            onChannelOpened: onChannelOpened,
            onChannelMessage: function (event) {
                config.onChannelMessage(JSON.parse(event.data));
            }
        };

        function initPeer(offerSDP) {
            if (!offerSDP) {
                peerConfig.onOfferSDP = sendsdp;
            } else {
                peerConfig.offerSDP = offerSDP;
                peerConfig.onAnswerSDP = sendsdp;
                peerConfig.dataPorts = dataPorts;
            }
            peer = RTCPeerConnection(peerConfig);
        }

        function onChannelOpened(channel) {
            RTCDataChannels[RTCDataChannels.length] = channel;
            if (config.onChannelOpened) config.onChannelOpened(channel);

            if (isbroadcaster && channels.split('--').length > 3) {
                /* broadcasting newly connected participant for video-conferencing! */
                defaultSocket.send({
                    newParticipant: socket.channel,
                    userToken: self.userToken
                });
            }

            /* closing subsocket here on the offerer side */
            if (_config.closeSocket) socket = null;

            gotstream = true;
        }

        function sendsdp(sdp) {
            sdp = JSON.stringify(sdp);
            var part = parseInt(sdp.length / 3);

            var firstPart = sdp.slice(0, part),
                secondPart = sdp.slice(part, sdp.length - 1),
                thirdPart = '';

            if (sdp.length > part + part) {
                secondPart = sdp.slice(part, part + part);
                thirdPart = sdp.slice(part + part, sdp.length);
            }

            socket.send({
                userToken: self.userToken,
                firstPart: firstPart,

                /* sending RTCDataChannel ports alongwith sdp */
                dataPorts: dataPorts
            });

            socket.send({
                userToken: self.userToken,
                secondPart: secondPart
            });

            socket.send({
                userToken: self.userToken,
                thirdPart: thirdPart
            });
        }

        function socketResponse(response) {
            if (response.userToken == self.userToken) return;

            if (response.firstPart || response.secondPart || response.thirdPart) {
                if (response.dataPorts) inner.dataPorts = response.dataPorts;
                if (response.firstPart) {
                    inner.firstPart = response.firstPart;
                    if (inner.secondPart && inner.thirdPart) selfInvoker();
                }
                if (response.secondPart) {
                    inner.secondPart = response.secondPart;
                    if (inner.firstPart && inner.thirdPart) selfInvoker();
                }

                if (response.thirdPart) {
                    inner.thirdPart = response.thirdPart;
                    if (inner.firstPart && inner.secondPart) selfInvoker();
                }
            }

            if (response.candidate && !gotstream) {
                peer && peer.addICE({
                    sdpMLineIndex: response.candidate.sdpMLineIndex,
                    candidate: JSON.parse(response.candidate.candidate)
                });
            }
        }

        var invokedOnce = false;

        function selfInvoker() {
            if (invokedOnce) return;

            invokedOnce = true;

            inner.sdp = JSON.parse(inner.firstPart + inner.secondPart + inner.thirdPart);

            /* using random data ports to support wide connection on firefox! */
            if (isofferer) peer.addAnswerSDP(inner.sdp, inner.dataPorts);
            else initPeer(inner.sdp);
        }
    }

    function startBroadcasting() {
        defaultSocket.send({
            roomToken: self.roomToken,
            broadcaster: self.userToken
        });
        setTimeout(startBroadcasting, 3000);
    }

    function onNewParticipant(channel) {
        if (!channel || channels.indexOf(channel) != -1 || channel == self.userToken) return;
        channels += channel + '--';

        var new_channel = uniqueToken();
        openSubSocket({
            channel: new_channel,
            closeSocket: true
        });

        defaultSocket.send({
            participant: true,
            userToken: self.userToken,
            joinUser: channel,
            channel: new_channel
        });
    }

    function uniqueToken() {
        var s4 = function () {
            return Math.floor(Math.random() * 0x10000).toString(16);
        };
        return s4() + s4() + "-" + s4() + "-" + s4() + "-" + s4() + "-" + s4() + s4() + s4();
    }

    openDefaultSocket();
    return {
        createRoom: function () {
            self.roomToken = uniqueToken();

            isbroadcaster = true;
            isGetNewRoom = false;
            startBroadcasting();
        },
        joinRoom: function (_config) {
            self.roomToken = _config.roomToken;
            isGetNewRoom = false;

            openSubSocket({
                channel: self.userToken
            });

            defaultSocket.send({
                participant: true,
                userToken: self.userToken,
                joinUser: _config.joinUser
            });
        },
        send: function (data) {
            var length = RTCDataChannels.length,
                data = JSON.stringify(data);
            if (!length) return;
            for (var i = 0; i < length; i++) {
                RTCDataChannels[i].send(data);
            }
        }
    };
};<|endoftext|>


<commit_before>import React from "react";
import CX from "classnames";
import { get } from "lodash-es";
import { connect } from "react-redux";
import { LinkContainer } from "react-router-bootstrap";
import { ClipLoader } from "halogenium";
import { Row, Col, Label } from "react-bootstrap";

import { getTaskDisplayName } from "../../utils";
import { Icon, RelativeTime } from "../../base/index";
import { removeAnalysis } from "../actions";
import { getCanModify } from "../../samples/selectors";

export const AnalysisItem = (props) => {

    const itemClass = CX("list-group-item spaced", {hoverable: props.ready});

    let end;

    if (props.ready) {
        if (props.canModify) {
            end = (
                <Icon
                    name="trash"
                    bsStyle="danger"
                    onClick={props.onRemove}
                    style={{fontSize: "17px"}}
                    pullRight
                />
            );
        }
    } else {
        end = (

                <ClipLoader size="14px" color="#3c8786" style={{display: "inline"}} /> In Progress

        );
    }

    const content = (

            <Row>
                <Col md={3}>
                    {getTaskDisplayName(props.algorithm)}
                </Col>
                <Col md={4}>
                    Started <RelativeTime time={props.created_at} />{props.placeholder ? null : ` by ${props.user.id}`}
                </Col>
                <Col md={1}>
                    {props.placeholder ? null : {props.index.version}}
                </Col>
                <Col md={4}>
                    {end}
                </Col>
            </Row>

    );

    if (props.placeholder) {
        return content;
    }

    return (
        <LinkContainer to={`/samples/${props.sampleId}/analyses/${props.id}`}>
            {content}
        </LinkContainer>
    );
};

const mapStateToProps = (state) => ({
    sampleId: get(state.samples.detail, "id"),
    canModify: getCanModify(state)
});

const mapDispatchToProps = (dispatch, ownProps) => ({
    onRemove: () => {
        dispatch(removeAnalysis(ownProps.id));
    }
});

export default connect(mapStateToProps, mapDispatchToProps)(AnalysisItem);
<commit_msg>Show reference name for analyses in list<commit_after>import React from "react";
import CX from "classnames";
import { get } from "lodash-es";
import { connect } from "react-redux";
import { LinkContainer } from "react-router-bootstrap";
import { ClipLoader } from "halogenium";
import { Row, Col, Label } from "react-bootstrap";

import { getTaskDisplayName } from "../../utils";
import { Icon, RelativeTime } from "../../base/index";
import { removeAnalysis } from "../actions";
import { getCanModify } from "../../samples/selectors";

export const AnalysisItem = (props) => {

    const itemClass = CX("list-group-item spaced", {hoverable: props.ready});

    let end;

    if (props.ready) {
        if (props.canModify) {
            end = (
                <Icon
                    name="trash"
                    bsStyle="danger"
                    onClick={props.onRemove}
                    style={{fontSize: "17px"}}
                    pullRight
                />
            );
        }
    } else {
        end = (

                <ClipLoader size="14px" color="#3c8786" style={{display: "inline"}} /> In Progress

        );
    }

    let reference;

    if (!props.placeholder) {
        reference = (

                {props.reference.name}

                    {props.index.version}

        );
    }

    const content = (

            <Row>
                <Col md={3}>
                    {getTaskDisplayName(props.algorithm)}
                </Col>
                <Col md={4}>
                    Started <RelativeTime time={props.created_at} />{props.placeholder ? null : ` by ${props.user.id}`}
                </Col>
                <Col md={3}>
                    {reference}
                </Col>
                <Col md={2}>
                    {end}
                </Col>
            </Row>

    );

    if (props.placeholder) {
        return content;
    }

    return (
        <LinkContainer to={`/samples/${props.sampleId}/analyses/${props.id}`}>
            {content}
        </LinkContainer>
    );
};

const mapStateToProps = (state) => ({
    sampleId: get(state.samples.detail, "id"),
    canModify: getCanModify(state)
});

const mapDispatchToProps = (dispatch, ownProps) => ({
    onRemove: () => {
        dispatch(removeAnalysis(ownProps.id));
    }
});

export default connect(mapStateToProps, mapDispatchToProps)(AnalysisItem);
<|endoftext|>


<commit_before>var p2r = require('path-to-regexp'),
    funcDeps = require('func-deps'),
    _ = require('lodash'),
    http = require('http'),
    util = require('util');

function send(status, content) {
    var args = Array.prototype.slice.apply(arguments);
    if (typeof status === 'number') {
        req.status = args.shift();
    } else {
        content = status;
    }
    res.write.apply(res, arguments);
    res.end();
}

function Injector() {
    this.providers = [];
    this.singletons = [];
    this.values = [];
    this.handlers = [];
}

Injector.prototype.handleRequest = function handleRequest(req, res) {
    res.send = send;
    var index = 0;
    var handlers = _.clone(this.handlers);
    function next() {
        if (index < handlers.length) {
            var handler = handlers[index++];
            if ('ALL' !== handler.method && handler.method !== req.method) {
                return next();
            }
            var params = handler.route.exec(req.url);
            if (null === params) {
                return next();
            }
            req.params = _.zipObject(_.pluck(handler.keys, 'name'),
                handler.route.exec(req.url).slice(1));
            handler.handleRequest(req, res, next);
        } else {
            res.write(util.format("Can't %s %s", req.method, req.url));
            res.end();
        }
    }
    next();
};

function handler(method) {
    return function(route, handleRequest) {
        if (typeof route === 'function') {
            handleRequest = route;
            route = '*';
        }
        var keys = [];
        var route = p2r(route, keys);
        this.handlers.push({
            method: method,
            keys: keys,
            route: route,
            handleRequest: handleRequest
        });
    };
}

Injector.prototype.provide = function provide(depName, provider) {
    this.providers[depName] = provider;
};

Injector.prototype.singleton = function singleton(depName, func) {
    this.singletons[depName] = func;
};

Injector.prototype.value = function value(depName, val) {
    if (val) {
        this.values[depName] = val;
    } else {
        return this.values[depName];
    }
};

Injector.prototype.use = handler('ALL');

var methods = ['get', 'post', 'put', 'patch', 'delete', 'copy',
               'head', 'options', 'link', 'unlink', 'purge', 'all'];

_.forEach(methods, function(method) {
    Injector.prototype[method] = handler(method.toUpperCase());
});

Injector.prototype.listen = function listen(port, cb) {
    http.createServer(this.handleRequest.bind(this)).listen(port);
};

module.exports = function() {
    return new Injector();
};
<commit_msg>Refactor method names and route handler adder structure<commit_after>"use strict";

var p2r = require('path-to-regexp'),
    funcDeps = require('func-deps'),
    _ = require('lodash'),
    http = require('http'),
    util = require('util');

function send(status, content) {
    var args = Array.prototype.slice.apply(arguments);
    if (typeof status === 'number') {
        req.status = args.shift();
    } else {
        content = status;
    }
    res.write.apply(res, arguments);
    res.end();
}

function RestInjector() {
    if (typeof this === 'undefined') {
        return new RestInjector();
    }
    this.providers = [];
    this.singletons = [];
    this.values = [];
    this.handlers = [];
}

RestInjector.prototype.handleRequest = function handleRequest(req, res) {
    res.send = send;
    var index = 0;
    var handlers = _.clone(this.handlers);
    function next() {
        if (index < handlers.length) {
            var handler = handlers[index++];
            if ('ALL' !== handler.method && handler.method !== req.method) {
                return next();
            }
            var params = handler.route.exec(req.url);
            if (null === params) {
                return next();
            }
            req.params = _.zipObject(_.pluck(handler.keys, 'name'),
                handler.route.exec(req.url).slice(1));
            handler.handleRequest(req, res, next);
        } else {
            res.write(util.format("Can't %s %s", req.method, req.url));
            res.end();
        }
    }
    next();
};

function addHandler(method, route, handleRequest) {
    if (_.isFunction(route) || _.isArray(route)) {
        handleRequest = route;
        route = '*';
    }
    var keys = [];
    var route = p2r(route, keys);
    this.handlers.push({
        method: method,
        keys: keys,
        route: route,
        handleRequest: handleRequest
    });
}

RestInjector.prototype.provide = function provide(depName, provider) {
    this.providers[depName] = provider;
};

RestInjector.prototype.singleton = function singleton(depName, func) {
    this.singletons[depName] = func;
};

RestInjector.prototype.value = function value(depName, val) {
    if (val) {
        this.values[depName] = val;
    } else {
        return this.values[depName];
    }
};

RestInjector.prototype.use = addHandler.bind(null, 'ALL');

var methods = ['get', 'post', 'put', 'patch', 'delete', 'copy',
               'head', 'options', 'link', 'unlink', 'purge', 'all'];

_.forEach(methods, function(method) {
    var methodUpper = method.toUpperCase();
    RestInjector.prototype[method] = function() {
        var args = [methodUpper].concat(Array.prototype.slice.apply(arguments));
        addHandler.apply(this, args);
    };
});

RestInjector.prototype.listen = function listen(port, cb) {
    http.createServer(this.handleRequest.bind(this)).listen(port);
};

module.exports = RestInjector;
<|endoftext|>


<commit_before>/*
 * This file is part of mesamatrix.
 *
 * Copyright (C) 2014 Romain "Creak" Failliot.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

function fillZeros(number, size) {
    var absNum = String(Math.abs(number));
    var numZeros = size - absNum.length;
    var res = "";
    if(number < 0)
        res = "-";
    res += Array(numZeros + 1).join("0") + absNum;
    return res;
}

function getLocalDate(text) {
    var eventDate = new Date(text);
    var year = eventDate.getFullYear();
    var month = fillZeros(eventDate.getMonth() + 1, 2);
    var day = fillZeros(eventDate.getDate(), 2);
    var hours = fillZeros(eventDate.getHours(), 2);
    var minutes = fillZeros(eventDate.getMinutes(), 2);
    var seconds = fillZeros(eventDate.getSeconds(), 2);
    var timezoneOffset = -eventDate.getTimezoneOffset();
    var timezoneMinutes = Math.abs(timezoneOffset);
    var timezoneHours = Math.floor(timezoneMinutes / 60);
    timezoneMinutes -= timezoneHours * 60;
    timezoneHours = fillZeros(timezoneHours, 2);
    timezoneMinutes = fillZeros(timezoneMinutes, 2);
    if(timezoneMinutes >= 0)
        timezoneHours = "+" + timezoneHours;
    return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds + " (GMT " + timezoneHours + timezoneMinutes + ")";
}

function getRelativeDate(text) {
    const MINS_IN_HOUR = 60;
    const MINS_IN_DAY = 1440;       // 60 * 24
    const MINS_IN_WEEK = 10080;     // 60 * 24 * 7
    const MINS_IN_MONTH = 43200;    // 60 * 24 * 30

    var eventDate = new Date(text);
    var relTimeInMin = (Date.now() - eventDate.getTime()) / (1000 * 60);

    if(relTimeInMin < 5)               // Less than 5 minutes ago
        return "just now";

    if(relTimeInMin < MINS_IN_HOUR) {
        return Math.round(((relTimeInMin / MINS_IN_HOUR) / 5) * 5) + " minutes";
    }

    if(relTimeInMin < MINS_IN_DAY) {
        var numHours = Math.round(relTimeInMin / MINS_IN_HOUR);
        return numHours + " " + (numHours == 1 ? "hour" : "hours");
    }

    if(relTimeInMin < MINS_IN_WEEK) {
        var numDays = Math.round(relTimeInMin / MINS_IN_DAY);
        return numDays + " " + (numDays == 1 ? "day" : "days");
    }

    if(relTimeInMin < MINS_IN_MONTH) {
        var numWeeks = Math.round(relTimeInMin / MINS_IN_WEEK);
        return numWeeks + " " + (numWeeks == 1 ? "week" : "weeks");
    }

    if(relTimeInMin < MINS_IN_MONTH * 3) {
        var numMonths = Math.round(relTimeInMin / MINS_IN_MONTH);
        return numMonths + " " + (numMonths == 1 ? "month" : "months");
    }

    var year = eventDate.getFullYear();
    var month = fillZeros(eventDate.getMonth() + 1, 2);
    var day = fillZeros(eventDate.getDate(), 2);
    return year + "-" + month + "-" + day;
}

function gaussian(x, a, b, c) {
    return a * Math.exp(- Math.pow(x - b, 2) / (2 * Math.pow(c, 2)));
}

$(document).ready(function() {
    // Convert to relative date.
    $('.toRelativeDate').each(function() {
        $(this).text(getRelativeDate($(this).data('timestamp')));
    });

    // Convert to local date.
    $('.toLocalDate').each(function() {
        $(this).text(getLocalDate($(this).data('timestamp')));
    });

    // Add tipsy for the footnote.
    $('.footnote').tipsy({gravity: 'w', fade: true});

    // adjust the opacity of the 'modified' text based on age
    var timeConst = 1.2e7;
    $('.task span').each(function() {
        var timeDiff = (Date.now()/1000) - $(this).data('timestamp');
        $(this).css('opacity', gaussian(timeDiff, 1, 0, timeConst));
    });

    // Change mesa score color based on completion
    $('.hCellDriverScore').each(function() {
        var blend = Math.round($(this).data('score'));
        if (blend == 100) {
            $(this).addClass('hCellDriverScore-done');
        }
        else if (blend < 75) {
            $(this).addClass('hCellDriverScore-notyet');
        }
        else {
            $(this).addClass('hCellDriverScore-almost');
        }
    });

    $('.matrix').delegate('td', 'mouseover mouseleave', function(e) {
        // Should highlight row
        var row = $(this).parent();
        var highlightRow = row.hasClass('extension');

        // Should highlight column
        var columnIdx = $(this).index();
        var highlightCol = $('.matrix colgroup').eq(columnIdx).hasClass('hl');
        if (highlightCol) {
            highlightCol = $(this).hasClass('task');
            if (!highlightCol)
                highlightCol = $(this).hasClass('hCellHeader') && !$(this).attr('colspan');
        }

        if (e.type == 'mouseover') {
            if (row.hasClass('extension')) {
                row.find('td').each(function() {
                    $(this).addClass('hover');
                });
            }
            if (highlightCol) {
                $('.matrix .extension td:nth-child(' + (columnIdx + 1) + ')').each(function() {
                    $(this).addClass('hover');
                });
            }
        }
        else {
            if (highlightRow) {
                row.find('td').each(function() {
                    $(this).removeClass('hover');
                });
            }
            if (highlightCol) {
                $('.matrix .extension td:nth-child(' + (columnIdx + 1) + ')').each(function() {
                    $(this).removeClass("hover");
                });
            }
        }
    });
});
<commit_msg>Fix highlighting of both GL and Vk table columns<commit_after>/*
 * This file is part of mesamatrix.
 *
 * Copyright (C) 2014 Romain "Creak" Failliot.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

function fillZeros(number, size) {
    var absNum = String(Math.abs(number));
    var numZeros = size - absNum.length;
    var res = "";
    if(number < 0)
        res = "-";
    res += Array(numZeros + 1).join("0") + absNum;
    return res;
}

function getLocalDate(text) {
    var eventDate = new Date(text);
    var year = eventDate.getFullYear();
    var month = fillZeros(eventDate.getMonth() + 1, 2);
    var day = fillZeros(eventDate.getDate(), 2);
    var hours = fillZeros(eventDate.getHours(), 2);
    var minutes = fillZeros(eventDate.getMinutes(), 2);
    var seconds = fillZeros(eventDate.getSeconds(), 2);
    var timezoneOffset = -eventDate.getTimezoneOffset();
    var timezoneMinutes = Math.abs(timezoneOffset);
    var timezoneHours = Math.floor(timezoneMinutes / 60);
    timezoneMinutes -= timezoneHours * 60;
    timezoneHours = fillZeros(timezoneHours, 2);
    timezoneMinutes = fillZeros(timezoneMinutes, 2);
    if(timezoneMinutes >= 0)
        timezoneHours = "+" + timezoneHours;
    return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds + " (GMT " + timezoneHours + timezoneMinutes + ")";
}

function getRelativeDate(text) {
    const MINS_IN_HOUR = 60;
    const MINS_IN_DAY = 1440;       // 60 * 24
    const MINS_IN_WEEK = 10080;     // 60 * 24 * 7
    const MINS_IN_MONTH = 43200;    // 60 * 24 * 30

    var eventDate = new Date(text);
    var relTimeInMin = (Date.now() - eventDate.getTime()) / (1000 * 60);

    if(relTimeInMin < 5)               // Less than 5 minutes ago
        return "just now";

    if(relTimeInMin < MINS_IN_HOUR) {
        return Math.round(((relTimeInMin / MINS_IN_HOUR) / 5) * 5) + " minutes";
    }

    if(relTimeInMin < MINS_IN_DAY) {
        var numHours = Math.round(relTimeInMin / MINS_IN_HOUR);
        return numHours + " " + (numHours == 1 ? "hour" : "hours");
    }

    if(relTimeInMin < MINS_IN_WEEK) {
        var numDays = Math.round(relTimeInMin / MINS_IN_DAY);
        return numDays + " " + (numDays == 1 ? "day" : "days");
    }

    if(relTimeInMin < MINS_IN_MONTH) {
        var numWeeks = Math.round(relTimeInMin / MINS_IN_WEEK);
        return numWeeks + " " + (numWeeks == 1 ? "week" : "weeks");
    }

    if(relTimeInMin < MINS_IN_MONTH * 3) {
        var numMonths = Math.round(relTimeInMin / MINS_IN_MONTH);
        return numMonths + " " + (numMonths == 1 ? "month" : "months");
    }

    var year = eventDate.getFullYear();
    var month = fillZeros(eventDate.getMonth() + 1, 2);
    var day = fillZeros(eventDate.getDate(), 2);
    return year + "-" + month + "-" + day;
}

function gaussian(x, a, b, c) {
    return a * Math.exp(- Math.pow(x - b, 2) / (2 * Math.pow(c, 2)));
}

$(document).ready(function() {
    // Convert to relative date.
    $('.toRelativeDate').each(function() {
        $(this).text(getRelativeDate($(this).data('timestamp')));
    });

    // Convert to local date.
    $('.toLocalDate').each(function() {
        $(this).text(getLocalDate($(this).data('timestamp')));
    });

    // Add tipsy for the footnote.
    $('.footnote').tipsy({gravity: 'w', fade: true});

    // adjust the opacity of the 'modified' text based on age
    var timeConst = 1.2e7;
    $('.task span').each(function() {
        var timeDiff = (Date.now()/1000) - $(this).data('timestamp');
        $(this).css('opacity', gaussian(timeDiff, 1, 0, timeConst));
    });

    // Change mesa score color based on completion
    $('.hCellDriverScore').each(function() {
        var blend = Math.round($(this).data('score'));
        if (blend == 100) {
            $(this).addClass('hCellDriverScore-done');
        }
        else if (blend < 75) {
            $(this).addClass('hCellDriverScore-notyet');
        }
        else {
            $(this).addClass('hCellDriverScore-almost');
        }
    });

    $('.matrix').delegate('td', 'mouseover mouseleave', function(e) {
        // Get cell, row and table elements
        var cell = $(this);
        var row = cell.closest('tr');

        // Should highlight row
        var highlightRow = row.hasClass('extension');

        // Should highlight column
        var columnIdx = cell.index();
        var highlightCol = $('.matrix colgroup').eq(columnIdx).hasClass('hl');
        if (highlightCol) {
            highlightCol = cell.hasClass('task');
            if (!highlightCol)
                highlightCol = cell.hasClass('hCellHeader') && !cell.attr('colspan');
        }

        if (e.type == 'mouseover') {
            if (highlightRow) {
                row.find('td').each(function() {
                    $(this).addClass('hover');
                });
            }
            if (highlightCol) {
                var table = row.closest('table');
                table.find('.extension td:nth-child(' + (columnIdx + 1) + ')').each(function() {
                    $(this).addClass('hover');
                });
            }
        }
        else {
            if (highlightRow) {
                row.find('td').each(function() {
                    $(this).removeClass('hover');
                });
            }
            if (highlightCol) {
                var table = row.closest('table');
                table.find('.extension td:nth-child(' + (columnIdx + 1) + ')').each(function() {
                    $(this).removeClass("hover");
                });
            }
        }
    });
});
<|endoftext|>