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

// all button event handlers
var authorizeButton = document.getElementById('authorize-button');
var signoutButton = document.getElementById('signout-button');

var startFetchingRidesButton = document.getElementById('start-fetching-button');
var stopFetchingRidesButton = document.getElementById('stop-fetching-button');
var projectsSelect = document.getElementById('project-selection');
var topicsSelect = document.getElementById('pubsub-topic-selection');

// display for data overflow
var dataStatus = queryIfDisplayed('#data-status .msg');
var DATA_STATUS_ZERO = "Not receiving any data."
var DATA_STATUS_RATE = "Receiving %% data points/s."
var DATA_STATUS_RATE_OVERLOAD = "Overload: unable to read data fast enough (%% data points/s)."
var DATA_STATUS_RATE_SEVEREOVERLOAD = "Severe overload (%% data points/s). PubSub is re-sending."

function setDataStatus(msg, datarate) {
    if (dataStatus)
        dataStatus.innerHTML = msg.replace("%%", datarate)
}

function setDollarDisplay(amount) {
    var node = queryIfDisplayed("#dollar-display")
    if (node) {
        node.innerText = formatDollars(amount)
    }
}

function updateExactDollars(amount, id, timing) {
    var existing = queryIfDisplayed("#exact-dollar-display div#windowhash-" + id)
    if (existing) {
        setExactDollarNode(existing, amount, id, timing)
    }
    else {
        var node = queryIfDisplayed("#exact-dollar-display")
        if (node) {
            var newval = document.createElement("div")
            setExactDollarNode(newval, amount, id, timing)
            node.appendChild(newval)
            newval.scrollIntoView()
        }
    }
}

function setExactDollarNode(node, amount, id, timing) {
    //console.log("Dollar amount " + amount + " " + id + " " + timing)
    node.setAttribute("dolar-amount", amount) // save value
    node.setAttribute("id", "windowhash-" + id)
    var message = ""
    if (timing == "EARLY") {
        node.className = "incomplete"
        message = "(processing)"
    }
    else if (timing == "ON_TIME") {
        node.className = ""
    }
    else if (timing == "LATE") {
        node.className = "corrected"
        message = "(updated)"
    }
    node.innerText = message + " "+ formatDollars(amount)
}

function queryIfDisplayed(id) {
    var e = document.querySelector(id)
    var visible = (e != null)
    var el = e
    while (el && el.tagName !== "BODY") {
        visible = visible && (getComputedStyle(el, null).display != 'none')
        el = el.parentNode
    }
    if (visible)
        return e
    else
        return null
}

function formatDollars(amount) {
    return amount.toLocaleString("en-US", {style: "currency", currency: "USD", maximumFractionDigits: 0})
}

setDataStatus(DATA_STATUS_ZERO)

function setStartStopButton(val) {
    var signedin = auth2.isSignedIn.get()
    if (val == "start" && signedin) {
        startFetchingRidesButton.disabled = false;
        startFetchingRidesButton.style.display = 'block';
        stopFetchingRidesButton.style.display = 'none';
    }
    if (val == "stop" && signedin) {
        stopFetchingRidesButton.disabled = false;
        startFetchingRidesButton.style.display = 'none';
        stopFetchingRidesButton.style.display = 'block';
    }
    if (val == "disabled") {
        startFetchingRidesButton.disabled = true;
        stopFetchingRidesButton.disabled = true;
    }
    if (val == "hidden") {
        startFetchingRidesButton.style.display = 'none';
        stopFetchingRidesButton.style.display = 'none';
    }
}

var app = angular.module('TaxiRidesVisualizer', []);
app.controller('ProjectTopicsController', function($scope, $timeout, projectsService, topicsService) {
    $scope.authorize = function() {
        auth2.signIn();
    };

    $scope.signout = function() {
        if (stopFetchingRidesButton.style.display == 'block') {
            $scope.stopFetching()
        };
        auth2.signOut();
        $scope.pubsub_status = "";
        setStartStopButton("hidden")
    };

    $scope.startFetching = function() {
        $scope.pubsub_status = "Creating PubSub subscription...";
        setStartStopButton("disabled")
        projectId = $scope.selectedProject.projectId
        topicId = $scope.selectedTopic.id
        createTopicPrFn = function(reason) {
            return pubsub.projects.subscriptions
                .create({
                    name: 'projects/' + projectId + '/subscriptions/' + PUBSUB_SUBSCRIPTION_NAME,
                    topic: topicId,
                    ackDeadlineSeconds: 120
                });
        };

        pubsub.projects.subscriptions
            .delete({ subscription: 'projects/' + projectId + '/subscriptions/' + PUBSUB_SUBSCRIPTION_NAME })
            .then(
                createTopicPrFn, createTopicPrFn
            ).then(
                function(response) {
                    if (auth2.isSignedIn.get()) {
                        PUBSUB_SUBSCRIPTION = response.result.name;
                        startPullingFromPubSub();
                        setStartStopButton("stop")
                        //$scope.pubsub_status = "Fetching rides...";
                        $scope.pubsub_status = "";
                        $scope.$apply();
                    }
                }
            );
    };

    $scope.stopFetching = function() {
        $scope.pubsub_status = "Deleting PubSub subscription...";
        setStartStopButton("disabled")
        stopPullingFromPubSub()
        clearStatusFn = function(resp) {
            $scope.pubsub_status = '';
            setStartStopButton("start")
            $scope.$apply();
        };
        pubsub.projects.subscriptions
            .delete({ subscription: 'projects/' + projectId + '/subscriptions/' + PUBSUB_SUBSCRIPTION_NAME })
            .then(clearStatusFn, clearStatusFn);
    };

    $scope.loadProjects = function() {
        $scope.pubsub_status = 'Checking authentication...';
        authPromise.then(function() {
            if (auth2.isSignedIn.get()) {
                $scope.pubsub_status = 'Loading projects...';
            } else {
                $scope.pubsub_status = '';
            }
            $scope.$apply();
        }).then(projectsService.getProjects).then(function(projects) {
            $scope.projects = projects;
            projectsSelect.style.display = 'block';
            $scope.pubsub_status = '';
            $scope.$apply();
        });
    };
    $scope.loadProjects();
    $scope.projectSelected = function() {
        $scope.loadTopics();
    };

    $scope.loadTopics = function () {
        //$scope.status_active = true;
        if ($scope.selectedProject != null) {
            $scope.pubsub_status = 'Loading topics...';
            topicsService.getTopics($scope.selectedProject.projectId).then(
                function (topics) {
                    $scope.topics = topics;
                    if (topics.length > 0) {
                        topicsSelect.style.display = 'block';
                        $scope.pubsub_status = '';
                    } else {
                        topicsSelect.style.display = 'none';
                        $scope.pubsub_status = 'No topics found in this project';
                    }
                }
            )
        }
    }

    $scope.topicSelected = function() {
        if ($scope.selectedTopic != null)
            setStartStopButton("start")
    };
});

app.factory('projectsService', function($q) {
    return {
        getProjects: function() {
            var deferred = $q.defer();
            authPromise.then(function() {
                if (auth2.isSignedIn.get()) {
                    var request = crm.projects.list({ pageSize: 1000 })
                    request.execute(function(resp) {
                        projects = []
                        resp.projects.forEach(function(p) {
                            if (p.lifecycleState === "ACTIVE") {
                                projects.push(p)
                            }
                        });
                        deferred.resolve(projects)
                    })
                }
            })
            return deferred.promise;
        }
    }
});

app.factory('topicsService', function($q) {
    return {
        getTopics: function(projectId) {
            var deferred = $q.defer();
            authPromise.then(function() {
                if (auth2.isSignedIn.get()) {
                    var request = pubsub.projects.topics.list({ project: 'projects/' + projectId, pageSize: 1000 })
                    request.execute(function(resp) {
                        topics = []
                        if ('topics' in resp) {
                            resp.topics.forEach(function(element) {
                                topics.push({ name: element.name.substring(element.name.lastIndexOf("/") + 1), id: element.name })
                            });
                        }
                        deferred.resolve(topics)
                    })
                }
            })
            return deferred.promise;
        }
    }
});<commit_msg>adding paging for project fetch<commit_after>/**
 * Copyright 2016 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

// all button event handlers
var authorizeButton = document.getElementById('authorize-button');
var signoutButton = document.getElementById('signout-button');

var startFetchingRidesButton = document.getElementById('start-fetching-button');
var stopFetchingRidesButton = document.getElementById('stop-fetching-button');
var projectsSelect = document.getElementById('project-selection');
var topicsSelect = document.getElementById('pubsub-topic-selection');

// display for data overflow
var dataStatus = queryIfDisplayed('#data-status .msg');
var DATA_STATUS_ZERO = "Not receiving any data."
var DATA_STATUS_RATE = "Receiving %% data points/s."
var DATA_STATUS_RATE_OVERLOAD = "Overload: unable to read data fast enough (%% data points/s)."
var DATA_STATUS_RATE_SEVEREOVERLOAD = "Severe overload (%% data points/s). PubSub is re-sending."

function setDataStatus(msg, datarate) {
    if (dataStatus)
        dataStatus.innerHTML = msg.replace("%%", datarate)
}

function setDollarDisplay(amount) {
    var node = queryIfDisplayed("#dollar-display")
    if (node) {
        node.innerText = formatDollars(amount)
    }
}

function updateExactDollars(amount, id, timing) {
    var existing = queryIfDisplayed("#exact-dollar-display div#windowhash-" + id)
    if (existing) {
        setExactDollarNode(existing, amount, id, timing)
    } else {
        var node = queryIfDisplayed("#exact-dollar-display")
        if (node) {
            var newval = document.createElement("div")
            setExactDollarNode(newval, amount, id, timing)
            node.appendChild(newval)
            newval.scrollIntoView()
        }
    }
}

function setExactDollarNode(node, amount, id, timing) {
    //console.log("Dollar amount " + amount + " " + id + " " + timing)
    node.setAttribute("dolar-amount", amount) // save value
    node.setAttribute("id", "windowhash-" + id)
    var message = ""
    if (timing == "EARLY") {
        node.className = "incomplete"
        message = "(processing)"
    } else if (timing == "ON_TIME") {
        node.className = ""
    } else if (timing == "LATE") {
        node.className = "corrected"
        message = "(updated)"
    }
    node.innerText = message + " " + formatDollars(amount)
}

function queryIfDisplayed(id) {
    var e = document.querySelector(id)
    var visible = (e != null)
    var el = e
    while (el && el.tagName !== "BODY") {
        visible = visible && (getComputedStyle(el, null).display != 'none')
        el = el.parentNode
    }
    if (visible)
        return e
    else
        return null
}

function formatDollars(amount) {
    return amount.toLocaleString("en-US", { style: "currency", currency: "USD", maximumFractionDigits: 0 })
}

setDataStatus(DATA_STATUS_ZERO)

function setStartStopButton(val) {
    var signedin = auth2.isSignedIn.get()
    if (val == "start" && signedin) {
        startFetchingRidesButton.disabled = false;
        startFetchingRidesButton.style.display = 'block';
        stopFetchingRidesButton.style.display = 'none';
    }
    if (val == "stop" && signedin) {
        stopFetchingRidesButton.disabled = false;
        startFetchingRidesButton.style.display = 'none';
        stopFetchingRidesButton.style.display = 'block';
    }
    if (val == "disabled") {
        startFetchingRidesButton.disabled = true;
        stopFetchingRidesButton.disabled = true;
    }
    if (val == "hidden") {
        startFetchingRidesButton.style.display = 'none';
        stopFetchingRidesButton.style.display = 'none';
    }
}

var app = angular.module('TaxiRidesVisualizer', []);
app.controller('ProjectTopicsController', function($scope, $timeout, projectsService, topicsService) {
    $scope.authorize = function() {
        auth2.signIn();
    };

    $scope.signout = function() {
        if (stopFetchingRidesButton.style.display == 'block') {
            $scope.stopFetching()
        };
        auth2.signOut();
        $scope.pubsub_status = "";
        setStartStopButton("hidden")
    };

    $scope.startFetching = function() {
        $scope.pubsub_status = "Creating PubSub subscription...";
        setStartStopButton("disabled")
        projectId = $scope.selectedProject.projectId
        topicId = $scope.selectedTopic.id
        createTopicPrFn = function(reason) {
            return pubsub.projects.subscriptions
                .create({
                    name: 'projects/' + projectId + '/subscriptions/' + PUBSUB_SUBSCRIPTION_NAME,
                    topic: topicId,
                    ackDeadlineSeconds: 120
                });
        };

        pubsub.projects.subscriptions
            .delete({ subscription: 'projects/' + projectId + '/subscriptions/' + PUBSUB_SUBSCRIPTION_NAME })
            .then(
                createTopicPrFn, createTopicPrFn
            ).then(
                function(response) {
                    if (auth2.isSignedIn.get()) {
                        PUBSUB_SUBSCRIPTION = response.result.name;
                        startPullingFromPubSub();
                        setStartStopButton("stop")
                            //$scope.pubsub_status = "Fetching rides...";
                        $scope.pubsub_status = "";
                        $scope.$apply();
                    }
                }
            );
    };

    $scope.stopFetching = function() {
        $scope.pubsub_status = "Deleting PubSub subscription...";
        setStartStopButton("disabled")
        stopPullingFromPubSub()
        clearStatusFn = function(resp) {
            $scope.pubsub_status = '';
            setStartStopButton("start")
            $scope.$apply();
        };
        pubsub.projects.subscriptions
            .delete({ subscription: 'projects/' + projectId + '/subscriptions/' + PUBSUB_SUBSCRIPTION_NAME })
            .then(clearStatusFn, clearStatusFn);
    };

    $scope.loadProjects = function() {
        $scope.pubsub_status = 'Checking authentication...';
        authPromise.then(function() {
            if (auth2.isSignedIn.get()) {
                $scope.pubsub_status = 'Loading projects...';
            } else {
                $scope.pubsub_status = '';
            }
            $scope.$apply();
        }).then(projectsService.getProjects).then(function(projects) {
            $scope.projects = projects;
            projectsSelect.style.display = 'block';
            $scope.pubsub_status = '';
            $scope.$apply();
        });
    };
    $scope.loadProjects();
    $scope.projectSelected = function() {
        $scope.loadTopics();
    };

    $scope.loadTopics = function() {
        //$scope.status_active = true;
        if ($scope.selectedProject != null) {
            $scope.pubsub_status = 'Loading topics...';
            topicsService.getTopics($scope.selectedProject.projectId).then(
                function(topics) {
                    $scope.topics = topics;
                    if (topics.length > 0) {
                        topicsSelect.style.display = 'block';
                        $scope.pubsub_status = '';
                    } else {
                        topicsSelect.style.display = 'none';
                        $scope.pubsub_status = 'No topics found in this project';
                    }
                }
            )
        }
    }

    $scope.topicSelected = function() {
        if ($scope.selectedTopic != null)
            setStartStopButton("start")
    };
});

app.factory('projectsService', function($q) {
    return {
        getProjects: function() {
            var deferred = $q.defer();
            authPromise.then(function() {
                if (auth2.isSignedIn.get()) {
                    nextPageToken = 'first'
                    projects = []
                    while (nextPageToken.length > 0) {
                        if (nextPageToken === 'first') {
                            nextPageToken = ''
                        }
                        var request = crm.projects.list({ pageSize: 1000, pageToken: nextPageToken })
                        request.execute(function(resp) {
                            nextPageToken = resp.nextPageToken
                            resp.projects.forEach(function(p) {
                                if (p.lifecycleState === "ACTIVE") {
                                    projects.push(p)
                                }
                            });

                            deferred.resolve(projects)
                        })
                    }
                }
            })
            return deferred.promise;
        }
    }
});

app.factory('topicsService', function($q) {
    return {
        getTopics: function(projectId) {
            var deferred = $q.defer();
            authPromise.then(function() {
                if (auth2.isSignedIn.get()) {
                    var request = pubsub.projects.topics.list({ project: 'projects/' + projectId, pageSize: 1000 })
                    request.execute(function(resp) {
                        topics = []
                        if ('topics' in resp) {
                            resp.topics.forEach(function(element) {
                                topics.push({ name: element.name.substring(element.name.lastIndexOf("/") + 1), id: element.name })
                            });
                        }
                        deferred.resolve(topics)
                    })
                }
            })
            return deferred.promise;
        }
    }
});<|endoftext|>


<commit_before>/* global define, brackets, Mustache */

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

    var CommmandManager = brackets.getModule("command/CommandManager");
    var Menus           = brackets.getModule("command/Menus");
    var DocumentManager = brackets.getModule("document/DocumentManager");
    var EditorManager   = brackets.getModule("editor/EditorManager");
    var Resizer         = brackets.getModule("utils/Resizer");
    var AppInit         = brackets.getModule("utils/AppInit");
    var ExtensionUtils  = brackets.getModule("utils/ExtensionUtils");
    var _               = brackets.getModule("thirdparty/lodash");

    var Strings         = require("strings");
    var prefs           = require("src/Preferences");
    var ListTemplate    = require("text!templates/outline.html");

    ExtensionUtils.loadStyleSheet(module, "styles/styles.css");

    var prefix = "hirse.outline";

    var languages = {
        JavaScript:     require("src/languages/JavaScript"),
        CoffeeScript:   require("src/languages/CoffeeScript"),
        CSS:            require("src/languages/CSS"),
        SCSS:           require("src/languages/CSS"),
        LESS:           require("src/languages/CSS"),
        PHP:            require("src/languages/PHP"),
        Markdown:       require("src/languages/Markdown"),
        XML:            require("src/languages/XML"),
        HTML:           require("src/languages/XML"),
        SVG:            require("src/languages/XML")
    };

    function getOutline() {
        var $outline = Mustache.render(ListTemplate, {
            Strings: Strings
        });
        $outline = $($outline);

        $outline.on("click", "#outline-close", toggleEnabled);
        $outline.on("click", "#outline-move", function () {
            hideOutline();
            prefs.togglePref("sidebar");
            updateOutline();
        });
        return $outline;
    }

    function goToLine(event) {
        var currentEditor = EditorManager.getActiveEditor();
        currentEditor.setCursorPos(event.data.line, event.data.ch, true);
        currentEditor.focus();
    }

    function updateOutline() {
        var doc = DocumentManager.getCurrentDocument();
        if (!doc) {
            hideOutline();
            return;
        }

        var lang = languages[doc.getLanguage().getName()];
        if (!lang) {
            hideOutline();
            return;
        }

        showOutline();

        var lines = doc.getText(false).split("\n");
        var list = lang.getOutlineList(lines, prefs.get("args"), prefs.get("unnamed"));

        if (prefs.get("sort") && lang.compare) {
            list.sort(lang.compare);
        }

        list.forEach(function (entry) {
            var $entry = $(document.createElement("li"));
            $entry.addClass("outline-entry");
            $entry.addClass(entry.classes);
            $entry.append(entry.$html);
            $entry.click({
                line: entry.line,
                ch: entry.ch
            }, goToLine);
            $("#outline-list ul").append($entry);
        });
    }

    function onResize() {
        var toolbarPx = $("#main-toolbar:visible").width() || 0;
        $(".content").css("right", ($("#outline").width() || 0) + toolbarPx + "px");
    }

    function showOutline() {
        var $outline = getOutline();
        if ($("#outline").length) {
            $("#outline-list ul").empty();
            return;
        }

        if (prefs.get("sidebar")) {
            $("#sidebar").append($outline);
            $("#outline").addClass("outline-sidebar");
            Resizer.makeResizable($outline, "vert", "top", 75);
        } else {
            var toolbarPx = $("#main-toolbar:visible").width() || 0;
            $(".main-view").append($outline);
            $("#outline").css("right", toolbarPx + "px");
            $("#outline").addClass("outline-main quiet-scrollbars");
            Resizer.makeResizable($outline, "horz", "left", 150);
            $outline.on("panelResizeUpdate", onResize);
            onResize();
        }
        Menus.ContextMenu.assignContextMenuToSelector("#outline-settings", settingsMenu);
    }

    function hideOutline() {
        $("#outline").remove();
        onResize();
    }

    function enableOutline() {
        $("#outline-toolbar-icon").addClass("enabled");
        $(EditorManager).on("activeEditorChange", updateOutline);
        $(DocumentManager).on("documentSaved", updateOutline);
        updateOutline();
    }

    function disableOutline() {
        hideOutline();
        $("#outline-toolbar-icon").removeClass("enabled");
        $(EditorManager).off("activeEditorChange", updateOutline);
        $(DocumentManager).off("documentSaved", updateOutline);
    }

    function toggleEnabled() {
        if (prefs.togglePref("enabled")) {
            enableOutline();
        } else {
            disableOutline();
        }
    }

    /* Create Settings Context Menu */
    var settingsMenu = Menus.registerContextMenu("hirse-outline-context-menu");
    _.each(prefs.getSettings(), function (status, key) {
        var commandName = prefix + "." + key;
        var commandString = Strings["COMMAND_" + key.toUpperCase()];
        var command = CommmandManager.register(commandString, commandName, function () {
            var checked = prefs.togglePref(commandName.split(".")[2]);
            command.setChecked(checked);
            updateOutline();
        });
        command.setChecked(status);
        settingsMenu.addMenuItem(command);
    });

    /* Create Toolbar Icon */
    $(document.createElement("a"))
        .attr("id", "outline-toolbar-icon")
        .attr("href", "#")
        .attr("title", Strings.TOOLBAR_ICON_TOOLTIP)
        .on("click", toggleEnabled)
        .appendTo($("#main-toolbar .buttons"));

    AppInit.appReady(onResize);
    if (prefs.get("enabled")) {
        enableOutline();
    }
});
<commit_msg>Add GitHub-Flavored-Markdown to supported languages<commit_after>/* global define, brackets, Mustache */

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

    var CommmandManager = brackets.getModule("command/CommandManager");
    var Menus           = brackets.getModule("command/Menus");
    var DocumentManager = brackets.getModule("document/DocumentManager");
    var EditorManager   = brackets.getModule("editor/EditorManager");
    var Resizer         = brackets.getModule("utils/Resizer");
    var AppInit         = brackets.getModule("utils/AppInit");
    var ExtensionUtils  = brackets.getModule("utils/ExtensionUtils");
    var _               = brackets.getModule("thirdparty/lodash");

    var Strings         = require("strings");
    var prefs           = require("src/Preferences");
    var ListTemplate    = require("text!templates/outline.html");

    ExtensionUtils.loadStyleSheet(module, "styles/styles.css");

    var prefix = "hirse.outline";

    var languages = {
        JavaScript:             require("src/languages/JavaScript"),
        CoffeeScript:           require("src/languages/CoffeeScript"),
        CSS:                    require("src/languages/CSS"),
        SCSS:                   require("src/languages/CSS"),
        LESS:                   require("src/languages/CSS"),
        PHP:                    require("src/languages/PHP"),
        Markdown:               require("src/languages/Markdown"),
        "Markdown (GitHub)":    require("src/languages/Markdown"),
        XML:                    require("src/languages/XML"),
        HTML:                   require("src/languages/XML"),
        SVG:                    require("src/languages/XML")
    };

    function getOutline() {
        var $outline = Mustache.render(ListTemplate, {
            Strings: Strings
        });
        $outline = $($outline);

        $outline.on("click", "#outline-close", toggleEnabled);
        $outline.on("click", "#outline-move", function () {
            hideOutline();
            prefs.togglePref("sidebar");
            updateOutline();
        });
        return $outline;
    }

    function goToLine(event) {
        var currentEditor = EditorManager.getActiveEditor();
        currentEditor.setCursorPos(event.data.line, event.data.ch, true);
        currentEditor.focus();
    }

    function updateOutline() {
        var doc = DocumentManager.getCurrentDocument();
        if (!doc) {
            hideOutline();
            return;
        }

        var lang = languages[doc.getLanguage().getName()];
        if (!lang) {
            hideOutline();
            return;
        }

        showOutline();

        var lines = doc.getText(false).split("\n");
        var list = lang.getOutlineList(lines, prefs.get("args"), prefs.get("unnamed"));

        if (prefs.get("sort") && lang.compare) {
            list.sort(lang.compare);
        }

        list.forEach(function (entry) {
            var $entry = $(document.createElement("li"));
            $entry.addClass("outline-entry");
            $entry.addClass(entry.classes);
            $entry.append(entry.$html);
            $entry.click({
                line: entry.line,
                ch: entry.ch
            }, goToLine);
            $("#outline-list ul").append($entry);
        });
    }

    function onResize() {
        var toolbarPx = $("#main-toolbar:visible").width() || 0;
        $(".content").css("right", ($("#outline").width() || 0) + toolbarPx + "px");
    }

    function showOutline() {
        var $outline = getOutline();
        if ($("#outline").length) {
            $("#outline-list ul").empty();
            return;
        }

        if (prefs.get("sidebar")) {
            $("#sidebar").append($outline);
            $("#outline").addClass("outline-sidebar");
            Resizer.makeResizable($outline, "vert", "top", 75);
        } else {
            var toolbarPx = $("#main-toolbar:visible").width() || 0;
            $(".main-view").append($outline);
            $("#outline").css("right", toolbarPx + "px");
            $("#outline").addClass("outline-main quiet-scrollbars");
            Resizer.makeResizable($outline, "horz", "left", 150);
            $outline.on("panelResizeUpdate", onResize);
            onResize();
        }
        Menus.ContextMenu.assignContextMenuToSelector("#outline-settings", settingsMenu);
    }

    function hideOutline() {
        $("#outline").remove();
        onResize();
    }

    function enableOutline() {
        $("#outline-toolbar-icon").addClass("enabled");
        $(EditorManager).on("activeEditorChange", updateOutline);
        $(DocumentManager).on("documentSaved", updateOutline);
        updateOutline();
    }

    function disableOutline() {
        hideOutline();
        $("#outline-toolbar-icon").removeClass("enabled");
        $(EditorManager).off("activeEditorChange", updateOutline);
        $(DocumentManager).off("documentSaved", updateOutline);
    }

    function toggleEnabled() {
        if (prefs.togglePref("enabled")) {
            enableOutline();
        } else {
            disableOutline();
        }
    }

    /* Create Settings Context Menu */
    var settingsMenu = Menus.registerContextMenu("hirse-outline-context-menu");
    _.each(prefs.getSettings(), function (status, key) {
        var commandName = prefix + "." + key;
        var commandString = Strings["COMMAND_" + key.toUpperCase()];
        var command = CommmandManager.register(commandString, commandName, function () {
            var checked = prefs.togglePref(commandName.split(".")[2]);
            command.setChecked(checked);
            updateOutline();
        });
        command.setChecked(status);
        settingsMenu.addMenuItem(command);
    });

    /* Create Toolbar Icon */
    $(document.createElement("a"))
        .attr("id", "outline-toolbar-icon")
        .attr("href", "#")
        .attr("title", Strings.TOOLBAR_ICON_TOOLTIP)
        .on("click", toggleEnabled)
        .appendTo($("#main-toolbar .buttons"));

    AppInit.appReady(onResize);
    if (prefs.get("enabled")) {
        enableOutline();
    }
});
<|endoftext|>


<commit_before>
// Reference to the root of the Firebase database
var database = new Firebase("https://conquiz.firebaseio.com/");
var coordbase = new Firebase("https://towercoord.firebaseio.com/-K2aUIZRYFI5l6Tov1JA");
var towerbase = coordbase.child("towers");
var playerbase = coordbase.child("players");
var troopbase = coordbase.child("troops");
// Reference to the google sheets of questions
var questionsLink = 'https://spreadsheets.google.com/feeds/list/1C1POJrIlpm1R3muE0ImmI_ifxpH_aEfPP-QSyl3o2Kg/1/public/basic?alt=json';

var question;
var questionJSON;
var rows;

// ToDO: downloading from Firebase should be a return function, to avoid crossing stack
/*--------------------------------------------*/
/*---> Download troops from Firebase <--------*/
/*--------------------------------------------*/
function loadTroops() {
	var troopHolder = [];
	var newTroop;
	troopbase.on('child_added', function(update){
		if (update['Empty'] != "DoNotDelete") { //Stops the empty from being pulled
			var troopJSON = update.val();
			newTroop = new Troop({
				id: update['id'],
				name: update['name'],
				playerID: update['playerID'],
				towerID: update['towerID'],
				question: update['question'],
				alive: update['alive']
			});
			troopHolder.push(newTroop);
		}

	});
	return troopHolder;
}

/*--------------------------------------------*/
/*---> Upload troops to Firebase <------------*/
/*--------------------------------------------*/
function uploadTroops(data) {
	$.each(data, function(index, value){
		troopbase.push({
			id: value['id'],
			name: value['name'],
			playerID: value['playerID'],
			towerID: value['towerID'],
			question: value['question'],
			alive: value['alive']
		});
	});
}

// This will remove all the troops in the troops folder
function removeTroops() {
	troopbase.once('value', function(snapshot) {
		snapshot.forEach(function(childSnapshot){
			// You can also get the key and the value of the child in the troopbase folder
			//var key = childSnapshot.key();
			//var childData = childSnapshot.val();
			if (childSnapshot.val()!="DoNotDelete") {
				var path = new Firebase(troopbase.child(childSnapshot.key()).toString());
				path.remove();
			}
		});
	});
}

/*--------------------------------------------*/
/*---> Download player from Firebase <--------*/
/*--------------------------------------------*/
function loadPlayers() {
	var playerHolder = [];
	var newPlayer;
	playerbase.on('child_added', function(update) {
		var playerJSON = update.val();
		newPlayer = new Player({
			id: playerJSON['id'],
			icon: playerJSON['team']['icon'],
			color: playerJSON['team']['color'],
			coordinate: { latitude: playerJSON['latitude'], longitude: playerJSON['longitude']},
			troops: JSON.stringify(playerJSON['troops'])
		});
		playerHolder.push(newPlayer);
	});
	return playerHolder;
}

/*--------------------------------------------*/
/*---> Upload player to Firebase <------------*/
/*--------------------------------------------*/
function uploadPlayerbase(data) {
	$.each(data, function(index, value){
		playerbase.push({
			id: value['id'],
			name: value['name'],
			team: {icon: value['icon'], color: value['color']},
			latitude: value['coordinate']['latitude'],
			longitude: value['coordinate']['longitude'],
			troops: JSON.Stringify(value['troops'])
		});
	});
}

/*--------------------------------------------*/
/*---> Download towers from Firebase <--------*/
/*--------------------------------------------*/
function loadTowers() {
	var towerHolder = [];
	var newTower;
	towerbase.on('child_added', function(update) {
		var towerJSON = update.val();
		console.log(towerJSON);
		newTower = new Tower({
			id: towerJSON['id'],
			name: towerJSON['name'],
			coordinate: {latitude: towerJSON['latitude'], longitude: towerJSON['longitude']},
			size: towerJSON['size'],
			player: JSON.stringify(towerJSON['player']),
			troops: "[]"
		});
		towerHolder.push(newTower);
	});
	return towerHolder;
}

/*--------------------------------------------*/
/*---> Upload towers to Firebase <------------*/
/*--------------------------------------------*/
function uploadTowerbase(data) {
	$.each(data, function(index, value){
		towerbase.push({id: value['id'],
			name: value['name'],
			latitude: value['coordinate']['latitude'],
			longitude: value['coordinate']['longitude'],
			size: value['size'],
			player: value['player'] });
	});
	setDefaultTower();
}
function setDefaultTower(){
	towerbase.once('value', function(snapshot){
		snapshot.forEach(function(childSnapshot){
			var path = new Firebase(towerbase.child(childSnapshot.key()).toString());
			path.set({
				id: childSnapshot.key(),
				name: "",
				latitude: 0,
				longitude: 0,
				size: 10,
				player: ""
			});
		});
	});
}

function updateTowerbase(data) {
	$.each(data, function(index, value){
		var path = new Firebase(towerbase.child(value['id']).toString());
		path.set({
			id: value['id'],
			name: value['name'],
			latitude: value['coordinate']['latitude'],
			longitude: value['coordinate']['longitude'],
			size: value['size'],
			player: value['player']
		});
	});
}
// Don't have time - going for hard code
function removeTowerbase() {
	// ToDO: Remove the towers folders which will remove the subfolders, recreate a towers folder.
}

/*--------------------------------------------*/
/*---> Download question from Firebase <------*/
/*--------------------------------------------*/
function loadQuestions() {
	var questionHolder = [];
    var newQuestion;
    database.on('child_added', function(update) {
        var questionJSON = update.val();
        newQuestion = new Question({
            id: generateNewID('question'),
            question: questionJSON['question'],
            answers: "["+questionJSON['correct']+", "+questionJSON['wa1']+", "+questionJSON['wa2']+", "+questionJSON['wa3']+"]"
        });
        questionHolder.push(newQuestion);
    });
    return questionHolder;
}

/*--------------------------------------------*/
/*---> Upload question to Firebase <----------*/
// ONE TIME push to update the questions on firebase
/*--------------------------------------------*/
function getData() {
    $.ajax({
        url: questionsLink,
        success: function(data){
            uploadFirebase(data);
        }
    });
}
// upload data to firebase
function uploadFirebase(data){
    var cells = data.feed.entry;
    rows = [];

    for (var i = 0; i < cells.length; i++){
        var rowObj = {};
        rowObj.timestamp = cells[i].title.$t;
        var rowCols = cells[i].content.$t.split(',');
        for (var j = 0; j < rowCols.length; j++){
            var keyVal = rowCols[j].split(':');
            rowObj[keyVal[0].trim()] = keyVal[1].trim();
        }
        rows.push(rowObj);
    }
    for (var i = 0; i < rows.length; i++) {
    	database.push({question: rows[i]['timestamp'], correct: rows[i]['correct'], wa1: rows[i]['wa1'], wa2: rows[i]['wa2'], wa3: rows[i]['wa3']});
    }
}

console.log('LOADED BACKEND');

/* Legacy code

$("#upload").click(function() { // If the user clicks on the input with the id="upload"
	var name = $("#nameInput").val();
	var text = $("#messageInput").val();
	if (name.length != 0 && text.length != 0) { // Don't upload if there's no information in the textboxes
		console.log(name.length);
		console.log(text.length);

		database.push({name: name, text: text}); // Push the data onto the database

	}else { // warns user of their empty textbox
		console.log("Please input values into the textbox");
	}
});

function displayUpdate(name, text) {
	$("<div/>").text(text).prepend($("<em/>").text(name+": ")).appendTo($("#messageDiv"));
	$("#messageDiv")[0].scrollTop = $("#messageDiv")[0].scrollHeight;
};

database.on("child_added", function(update) { // Get an update once the database has new data
	console.log("Callback function: New data has been added to the database");
	var message = update.val();
	displayUpdate(message.name, message.text);
});

*/
<commit_msg>UpdateTroops()<commit_after>
// Reference to the root of the Firebase database
var database = new Firebase("https://conquiz.firebaseio.com/");
var coordbase = new Firebase("https://towercoord.firebaseio.com/-K2aUIZRYFI5l6Tov1JA");
var towerbase = coordbase.child("towers");
var playerbase = coordbase.child("players");
var troopbase = coordbase.child("troops");
// Reference to the google sheets of questions
var questionsLink = 'https://spreadsheets.google.com/feeds/list/1C1POJrIlpm1R3muE0ImmI_ifxpH_aEfPP-QSyl3o2Kg/1/public/basic?alt=json';

var question;
var questionJSON;
var rows;

// ToDO: downloading from Firebase should be a return function, to avoid crossing stack
/*--------------------------------------------*/
/*---> Download troops from Firebase <--------*/
/*--------------------------------------------*/
function loadTroops() {
	var troopHolder = [];
	var newTroop;
	troopbase.on('child_added', function(update){
		if (update['Empty'] != "DoNotDelete") { //Stops the empty from being pulled
			var troopJSON = update.val();
			newTroop = new Troop({
				id: update['id'],
				name: update['name'],
				playerID: update['playerID'],
				towerID: update['towerID'],
				question: update['question'],
				alive: update['alive']
			});
			troopHolder.push(newTroop);
		}

	});
	return troopHolder;
}

/*--------------------------------------------*/
/*---> Upload troops to Firebase <------------*/
/*--------------------------------------------*/
function uploadTroops(data) {
	$.each(data, function(index, value){
		troopbase.push({
			id: value['id'],
			name: value['name'],
			playerID: value['playerID'],
			towerID: value['towerID'],
			question: value['question'],
			alive: value['alive']
		});
	});
	setDefaultTroops();
}
function setDefaultTroops(){
		towerbase.once('value', function(snapshot){
		snapshot.forEach(function(childSnapshot){
			var child = childSnapshot.val();
			var path = new Firebase(towerbase.child(childSnapshot.key()).toString());
			path.set({
				id: childSnapshot.key(),
				name: child['name'],
				playerID: child['playerID'],
				towerID: child['towerID'],
				question: child['question'],
				alive: child['child']
			});
		});
	});
}
function updateTroops(data) {
	$.each(data, function(index, value){
		var path = new Firebase(troopbase.child(value['id']).toString());
		path.set({
			id: value['id'],
			name: value['name'],
			playerID: value['playerID'],
			towerID: value['towerID'],
			question: value['question'],
			alive: value['alive']
		});
	});
}
// This will remove all the troops in the troops folder
function removeTroops(data) {
	$.each(data, function(index, value){

	});
	troopbase.once('value', function(snapshot) {
		snapshot.forEach(function(childSnapshot){
			// You can also get the key and the value of the child in the troopbase folder
			//var key = childSnapshot.key();
			//var childData = childSnapshot.val();
			if (childSnapshot.val()!="DoNotDelete") {
				var path = new Firebase(troopbase.child(childSnapshot.key()).toString());
				path.remove();
			}
		});
	});
}

/*--------------------------------------------*/
/*---> Download player from Firebase <--------*/
/*--------------------------------------------*/
function loadPlayers() {
	var playerHolder = [];
	var newPlayer;
	playerbase.on('child_added', function(update) {
		var playerJSON = update.val();
		newPlayer = new Player({
			id: playerJSON['id'],
			icon: playerJSON['team']['icon'],
			color: playerJSON['team']['color'],
			coordinate: { latitude: playerJSON['latitude'], longitude: playerJSON['longitude']},
			troops: JSON.stringify(playerJSON['troops'])
		});
		playerHolder.push(newPlayer);
	});
	return playerHolder;
}

/*--------------------------------------------*/
/*---> Upload player to Firebase <------------*/
/*--------------------------------------------*/
function uploadPlayerbase(data) {
	$.each(data, function(index, value){
		playerbase.push({
			id: value['id'],
			name: value['name'],
			team: {icon: value['icon'], color: value['color']},
			latitude: value['coordinate']['latitude'],
			longitude: value['coordinate']['longitude'],
			troops: JSON.Stringify(value['troops'])
		});
	});
}

/*--------------------------------------------*/
/*---> Download towers from Firebase <--------*/
/*--------------------------------------------*/
function loadTowers() {
	var towerHolder = [];
	var newTower;
	towerbase.on('child_added', function(update) {
		var towerJSON = update.val();
		console.log(towerJSON);
		newTower = new Tower({
			id: towerJSON['id'],
			name: towerJSON['name'],
			coordinate: {latitude: towerJSON['latitude'], longitude: towerJSON['longitude']},
			size: towerJSON['size'],
			player: JSON.stringify(towerJSON['player']),
			troops: "[]"
		});
		towerHolder.push(newTower);
	});
	return towerHolder;
}

/*--------------------------------------------*/
/*---> Upload towers to Firebase <------------*/
/*--------------------------------------------*/
function uploadTowerbase(data) {
	$.each(data, function(index, value){
		towerbase.push({id: value['id'],
			name: value['name'],
			latitude: value['coordinate']['latitude'],
			longitude: value['coordinate']['longitude'],
			size: value['size'],
			player: value['player'] });
	});
	setDefaultTower();
}
function setDefaultTower(){
	towerbase.once('value', function(snapshot){
		snapshot.forEach(function(childSnapshot){
			var path = new Firebase(towerbase.child(childSnapshot.key()).toString());
			path.set({
				id: childSnapshot.key(),
				name: "",
				latitude: 0,
				longitude: 0,
				size: 10,
				player: ""
			});
		});
	});
}

function updateTowerbase(data) {
	$.each(data, function(index, value){
		var path = new Firebase(towerbase.child(value['id']).toString());
		path.set({
			id: value['id'],
			name: value['name'],
			latitude: value['coordinate']['latitude'],
			longitude: value['coordinate']['longitude'],
			size: value['size'],
			player: value['player']
		});
	});
}
// Don't have time - going for hard code
function removeTowerbase() {
	// ToDO: Remove the towers folders which will remove the subfolders, recreate a towers folder.
}

/*--------------------------------------------*/
/*---> Download question from Firebase <------*/
/*--------------------------------------------*/
function loadQuestions() {
	var questionHolder = [];
    var newQuestion;
    database.on('child_added', function(update) {
        var questionJSON = update.val();
        newQuestion = new Question({
            id: generateNewID('question'),
            question: questionJSON['question'],
            answers: "["+questionJSON['correct']+", "+questionJSON['wa1']+", "+questionJSON['wa2']+", "+questionJSON['wa3']+"]"
        });
        questionHolder.push(newQuestion);
    });
    return questionHolder;
}

/*--------------------------------------------*/
/*---> Upload question to Firebase <----------*/
// ONE TIME push to update the questions on firebase
/*--------------------------------------------*/
function getData() {
    $.ajax({
        url: questionsLink,
        success: function(data){
            uploadFirebase(data);
        }
    });
}
// upload data to firebase
function uploadFirebase(data){
    var cells = data.feed.entry;
    rows = [];

    for (var i = 0; i < cells.length; i++){
        var rowObj = {};
        rowObj.timestamp = cells[i].title.$t;
        var rowCols = cells[i].content.$t.split(',');
        for (var j = 0; j < rowCols.length; j++){
            var keyVal = rowCols[j].split(':');
            rowObj[keyVal[0].trim()] = keyVal[1].trim();
        }
        rows.push(rowObj);
    }
    for (var i = 0; i < rows.length; i++) {
    	database.push({question: rows[i]['timestamp'], correct: rows[i]['correct'], wa1: rows[i]['wa1'], wa2: rows[i]['wa2'], wa3: rows[i]['wa3']});
    }
}

console.log('LOADED BACKEND');

/* Legacy code

$("#upload").click(function() { // If the user clicks on the input with the id="upload"
	var name = $("#nameInput").val();
	var text = $("#messageInput").val();
	if (name.length != 0 && text.length != 0) { // Don't upload if there's no information in the textboxes
		console.log(name.length);
		console.log(text.length);

		database.push({name: name, text: text}); // Push the data onto the database

	}else { // warns user of their empty textbox
		console.log("Please input values into the textbox");
	}
});

function displayUpdate(name, text) {
	$("<div/>").text(text).prepend($("<em/>").text(name+": ")).appendTo($("#messageDiv"));
	$("#messageDiv")[0].scrollTop = $("#messageDiv")[0].scrollHeight;
};

database.on("child_added", function(update) { // Get an update once the database has new data
	console.log("Callback function: New data has been added to the database");
	var message = update.val();
	displayUpdate(message.name, message.text);
});

*/
<|endoftext|>


<commit_before>var assert = require("assert");
var path = require("path");
var _ = require("underscore");
var semver = require("semver");

var expected_version= "0.0.56";

exports.install = function(opcua) {

    if (opcua.hasOwnProperty("ISA95")){
        return false; // already installed
    }

    // verify that node-opcua version is compatible
    if (semver.lt(opcua.version,expected_version)) {
        throw new Error("node-opcua-isa95 need node-opcua version to be greater" +
            " or equal than " + expected_version + ". Currently your version of node-opcua is " + opcua.version+ "" +
            " Please update node-opcua");
    }
    if (opcua.version !== expected_version) {
        console.log("warning : the expected version of node-opcua  is "+ expected_version+ " - actual version is " + opcua.version)
    }

    var Enum = opcua.Enum;//require("enum");

    var EquipmentLevel = new Enum({
        // ISA95EquipmentElementLevelEnum
        //
        // This DataType is an enumeration that defines the equipment element levels defined in ISA-95. Its values are
        // defined in a below table.
        // Note:  for enumeration DataTypes it is recommended that variables that use the enumeration also expose the EnumStrings
        //        property. This property allows a client to easily translate the enumeration (integer value) to a string for
        //        display (see OPC Part 3).
        // Table 36 – ISA95EquipmentElementLevelEnum Values
        //
        // Value              Description
        // ENTERPRISE_0       An enterprise is a collection of sites and areas and represents the top level of a role based
        //                    equipment hierarchy.
        Enterprise: 0,

        // SITE_1             A site is a physical, geographical, or logical grouping determined by the enterprise. It may contain
        //                    areas, production lines, process cells, and production units.
        Site: 1,

        // AREA_2             An area is a physical, geographical, or logical grouping determined by the site. It may contain work
        //                    centres such as process cells, production units, production lines, and storage zones.
        Area: 2,

        // PROCESSCELL_3      Process cells are the low level of equipment typically scheduled by the Level 4 and Level 3
        //                    functions for batch manufacturing processes. The definitions for process cells are
        //                    contained in IEC 61512-1.
        ProcessCell: 3,

        // UNIT_4             Units are low level of equipment typically scheduled by the Level 4 and Level 3 functions for batch
        //                    manufacturing processes and continuous manufacturing processes. The definition of the unit for batch
        //                    manufacturing processes is contained in IEC 61512-1.
        Unit: 4,

        // PRODUCTIONLINE_5   Production lines are low levels of equipment typically scheduled by the Level 4 or Level 3
        //                    functions for discrete manufacturing processes.
        ProductionLine: 5,

        // WORKCELL_6         Work cells are low levels of equipment typically scheduled by the Level 4 or Level 3 functions for
        //                    discrete manufacturing processes.
        WorkCell: 6,

        // PRODUCTIONUINT_7   Production units are the lowest level of equipment typically scheduled by the Level 4 or Level
        //                    functions for continuous manufacturing processes.
        ProductionUnit: 7,

        // STORAGEZONE_8      Storage zones are low level of material movement equipment typically scheduled by the Level 4 and
        //                    Level 3 functions for discrete, batch and continuous manufacturing processes.
        StorageZone: 8,

        // STORAGEUNIT_9      Storage units are low level of material movement equipment typically scheduled by the  Level 4 and
        //                    Level 3 functions for discrete, batch and continuous manufacturing processes.
        //                    WORKCENTER_10 Work centres are typically the grouping of equipment scheduled by the Level 4 or
        //                    Level 3 functions.
        StorageUnit: 9,
        // WORKUNIT_11        A work unit is any element of the equipment hierarchy under a work centre. Work units are the lowest
        //                    form of elements in an equipment hierarchy that are typically scheduled by Level 3 functions.
        WorkUnit: 11,

        // EQUIPMENTMODULE_12 An equipment module entity is an engineered subdivision of a process cell, a unit, or another
        //                    equipment module. The definition of the equipment module is contained in IEC61512-1.
        EquipmentModule: 12,

        // CONTROLMODULE_13   A control module entity is an engineered subdivision of a process cell, a unit, an equipment module,
        //                    or another control module. The definition of the equipment module is contained in IEC 61512-1.
        ControlModule: 13,
        // OTHER_14           The types of work centres may be extended when required for application specific role based
        //                    equipment hierarchies where the defined types do not apply. In that case, the equipment element
        //                    level shall be specified as this value, and actual value that identifies the level shall be
        //                    specified by OtherValue Property of ISAHierarchyScopeType defined in 7.4.1.
        Other: 14
        // When a new type is added it shall maintain the same relationship within the hierarchy as the defined work centre
        // types (within an area and contains work units).
    });

    opcua.factories.registerBasicType({ name: "CDTIdentifier",  subtype: "String",  defaultValue: null});

    assert(!opcua.hasOwnProperty('ISA95'),"already initialized ?");

    opcua.ISA95= {};

    opcua.ISA95.EquipmentLevel = EquipmentLevel;

    var isa95_xml_file = path.join(__dirname, "../nodesets/Opc.ISA95.NodeSet2.xml");
    opcua.ISA95.nodeset_file = isa95_xml_file;

    function coerceISA95TypeDefinition(addressSpace,typeDefinition,baseType) {

        var baseType = addressSpace.findISA95VariableType(baseType);
        assert(baseType,baseType + " must exists ");
        if (typeof typeDefinition === "string") {
            var _typeDefinition = addressSpace.findISA95VariableType(typeDefinition);
            assert(_typeDefinition,typeDefinition + " must exists ");
            typeDefinition = _typeDefinition;
        }
        if (typeDefinition instanceof opcua.NodeId) {
            typeDefinition = addressSpace.findNode(typeDefinition);
        }
        assert(typeDefinition.nodeId instanceof opcua.NodeId);

        // istanbul ignore next
        if (!baseType.isSupertypeOf(typeDefinition)) {
            //xx throw new Error(typeDefinition.browseName.toString() + " must be a subtype of " + baseType.browseName.toString());
        }
        return typeDefinition;
    }

    /**
     *
     * @param options
     * @param options.browseName
     * @param options.ISA95ClassPropertyOf
     * @param options.typeDefinition
     * @param options.dataType
     * @param options.value
     */
    opcua.AddressSpace.prototype.addISA95ClassProperty = function(options) {

        assert(options.dataType,"expecting a dataType here");
        assert(!options.componentOf && !options.organizedBy && !options.propertyOf);
        assert(options.typeDefinition, "expecting a typeDefinition");
        assert(options.ISA95ClassPropertyOf,"expecting a parent object");
        // todo ; check that nodeISA95 is a ...ClassType
        var nodeISA95 = options.ISA95ClassPropertyOf;
        var addressSpace = nodeISA95.addressSpace;

        function coerceISA95ClassPropertyTypeDefinition(typeDefinition) {
            return coerceISA95TypeDefinition(addressSpace,typeDefinition,"ISA95ClassPropertyType");
        }
        var typeDefinition = coerceISA95ClassPropertyTypeDefinition(options.typeDefinition);

        var ns = addressSpace.getISA95Namespace();

        // placeHolder  => HasISA95ClassProperty => <PropertyName>
        //              => TestedByEquipmentTest => <TestSpecification>
        //
        var property = addressSpace._addVariable({
            typeDefinition: typeDefinition,
            browseName: options.browseName,
            dataType: options.dataType,
            value: options.value
        });

        // not : the hasISA95ClassProperty reference will be turned into a  hasISA95Property in the instantiated object
        var hasISA95ClassProperty = addressSpace.findReferenceType("HasISA95ClassProperty",ns);

        nodeISA95.addReference({
            referenceType: hasISA95ClassProperty.nodeId,
            nodeId: property
        });
        return property;
    };

    /**
     *
     * @param options
     * @param options.browseName
     * @param options.typeDefinition
     * @param options.ISA95PropertyOf
     * @param [options.modellingRule]
     * @returns {UAVariable}
     */
    opcua.AddressSpace.prototype.addISA95Property = function(options) {

        assert(options.browseName,"expecting a browseName");
        assert(options.dataType,"expecting a dataType here");
        assert(!options.componentOf && !options.organizedBy && !options.propertyOf);
        assert(options.typeDefinition, "expecting a typeDefinition");
        assert(options.ISA95PropertyOf,"expecting a parent object");

        // todo ; check that nodeISA95 is a ...ClassType
        var nodeISA95 = options.ISA95PropertyOf;
        var addressSpace = nodeISA95.addressSpace;

        var ns = addressSpace.getISA95Namespace();
        var hasISA95Property = addressSpace.findReferenceType("HasISA95Property",ns);

        function coerceISA95PropertyTypeDefinition(typeDefinition) {
            return coerceISA95TypeDefinition(addressSpace,typeDefinition,"ISA95PropertyType");
        }
        var typeDefinition = coerceISA95PropertyTypeDefinition(options.typeDefinition);

        var property = addressSpace.addVariable({
            browseName: options.browseName,
            typeDefinition: typeDefinition,
            modellingRule: options.modellingRule,
            dataType: options.dataType,
            value: options.value

        });
        nodeISA95.addReference({
            referenceType: hasISA95Property.nodeId,
            nodeId: property
        });
        return property;

    };

    /**
     *
     * @param options
     * @param options.browseName
     * @param options.dataType
     * @param options.value
     * @param [options.typeDefinition]
     * @param [options.modellingRule]
     * @param options.ISA95AttributeOf
     */
    opcua.AddressSpace.prototype.addISA95Attribute = function(options) {

        assert(options.ISA95AttributeOf," ISA95AttributeOf options is expected");
        var nodeISA95 = options.ISA95AttributeOf;

        // modelling rule must be specified if nodeISA95 is a UAVariableType of UAObjectType;
        if (!options.modellingRule &&
            ( nodeISA95.constructor.name === "UAVariableType" ||
              nodeISA95.constructor.name === "UAObjectType")) {
            throw new Error("Expecting options.modellingRule to be specified")
        }
        var addressSpace = nodeISA95.addressSpace;
        var ns = addressSpace.getNamespaceIndex("http://www.OPCFoundation.org/UA/2013/01/ISA95");

        var hasISA95Attribute = addressSpace.findReferenceType("HasISA95Attribute",ns);

        var dataType =  options.dataType;
        if (typeof dataType === "string") {
            var dataTypeNode = addressSpace.findDataType(dataType,ns);
            if (!dataTypeNode) {
                dataTypeNode = addressSpace.findDataType(dataType);
                if (!dataTypeNode) {
                    dataTypeNode = opcua.DataType[dataType];
                }
            }
            dataType = dataTypeNode;
        }
        if(!dataType ){
            console.log("opcua.",opcua.DataType);
            throw new Error(" cannot find dataType " + options.dataType + " " + typeof options.dataType );
        }

        var typeDefinition = options.typeDefinition || addressSpace.findVariableType("BaseDataVariableType");

        var property = addressSpace.addVariable({
            typeDefinition: typeDefinition,
            modellingRule: options.modellingRule,
            browseName: options.browseName,
            dataType: dataType,
            value: options.value,
        });
        nodeISA95.addReference({
            referenceType: hasISA95Attribute.nodeId,
            nodeId: property
        });
        return property;
    };

    /**
     * find a ReferenceType in the ISA95 namespace
     * @param name {String}
     * @return {opcua.ReferenceType}
     */
    opcua.AddressSpace.prototype.getISA95Namespace = function() {
        var addressSpace  = this;
        var ns = addressSpace.getNamespaceIndex("http://www.OPCFoundation.org/UA/2013/01/ISA95");
        return ns;
    };

    opcua.AddressSpace.prototype.findISA95ReferenceType = function(name) {
        var addressSpace  = this;
        return addressSpace.findReferenceType(name,addressSpace.getISA95Namespace());
    };

    opcua.AddressSpace.prototype.findISA95ObjectType = function(name) {
        var addressSpace  = this;
        return addressSpace.findObjectType(name,addressSpace.getISA95Namespace());
    };

    opcua.AddressSpace.prototype.findISA95VariableType = function(name) {
        var addressSpace  = this;
        return addressSpace.findVariableType(name,addressSpace.getISA95Namespace());
    };

    opcua.AddressSpace.prototype.findISA95DataType = function(name) {
        var addressSpace  = this;
        return addressSpace.findDataType(name,addressSpace.getISA95Namespace());
    };

    require("./isa95_address_space_extension_utils")(opcua);
    require("./isa95_address_space_extension_equipment")(opcua);
    require("./isa95_address_space_extension_physical_asset")(opcua);

};
<commit_msg>update to node-opcua 0.0.57<commit_after>var assert = require("assert");
var path = require("path");
var _ = require("underscore");
var semver = require("semver");

var expected_version= "0.0.57";

exports.install = function(opcua) {

    if (opcua.hasOwnProperty("ISA95")){
        return false; // already installed
    }

    // verify that node-opcua version is compatible
    if (semver.lt(opcua.version,expected_version)) {
        throw new Error("node-opcua-isa95 need node-opcua version to be greater" +
            " or equal than " + expected_version + ". Currently your version of node-opcua is " + opcua.version+ "" +
            " Please update node-opcua");
    }
    if (opcua.version !== expected_version) {
        console.log("warning : the expected version of node-opcua  is "+ expected_version+ " - actual version is " + opcua.version)
    }

    var Enum = opcua.Enum;//require("enum");

    var EquipmentLevel = new Enum({
        // ISA95EquipmentElementLevelEnum
        //
        // This DataType is an enumeration that defines the equipment element levels defined in ISA-95. Its values are
        // defined in a below table.
        // Note:  for enumeration DataTypes it is recommended that variables that use the enumeration also expose the EnumStrings
        //        property. This property allows a client to easily translate the enumeration (integer value) to a string for
        //        display (see OPC Part 3).
        // Table 36 – ISA95EquipmentElementLevelEnum Values
        //
        // Value              Description
        // ENTERPRISE_0       An enterprise is a collection of sites and areas and represents the top level of a role based
        //                    equipment hierarchy.
        Enterprise: 0,

        // SITE_1             A site is a physical, geographical, or logical grouping determined by the enterprise. It may contain
        //                    areas, production lines, process cells, and production units.
        Site: 1,

        // AREA_2             An area is a physical, geographical, or logical grouping determined by the site. It may contain work
        //                    centres such as process cells, production units, production lines, and storage zones.
        Area: 2,

        // PROCESSCELL_3      Process cells are the low level of equipment typically scheduled by the Level 4 and Level 3
        //                    functions for batch manufacturing processes. The definitions for process cells are
        //                    contained in IEC 61512-1.
        ProcessCell: 3,

        // UNIT_4             Units are low level of equipment typically scheduled by the Level 4 and Level 3 functions for batch
        //                    manufacturing processes and continuous manufacturing processes. The definition of the unit for batch
        //                    manufacturing processes is contained in IEC 61512-1.
        Unit: 4,

        // PRODUCTIONLINE_5   Production lines are low levels of equipment typically scheduled by the Level 4 or Level 3
        //                    functions for discrete manufacturing processes.
        ProductionLine: 5,

        // WORKCELL_6         Work cells are low levels of equipment typically scheduled by the Level 4 or Level 3 functions for
        //                    discrete manufacturing processes.
        WorkCell: 6,

        // PRODUCTIONUINT_7   Production units are the lowest level of equipment typically scheduled by the Level 4 or Level
        //                    functions for continuous manufacturing processes.
        ProductionUnit: 7,

        // STORAGEZONE_8      Storage zones are low level of material movement equipment typically scheduled by the Level 4 and
        //                    Level 3 functions for discrete, batch and continuous manufacturing processes.
        StorageZone: 8,

        // STORAGEUNIT_9      Storage units are low level of material movement equipment typically scheduled by the  Level 4 and
        //                    Level 3 functions for discrete, batch and continuous manufacturing processes.
        //                    WORKCENTER_10 Work centres are typically the grouping of equipment scheduled by the Level 4 or
        //                    Level 3 functions.
        StorageUnit: 9,
        // WORKUNIT_11        A work unit is any element of the equipment hierarchy under a work centre. Work units are the lowest
        //                    form of elements in an equipment hierarchy that are typically scheduled by Level 3 functions.
        WorkUnit: 11,

        // EQUIPMENTMODULE_12 An equipment module entity is an engineered subdivision of a process cell, a unit, or another
        //                    equipment module. The definition of the equipment module is contained in IEC61512-1.
        EquipmentModule: 12,

        // CONTROLMODULE_13   A control module entity is an engineered subdivision of a process cell, a unit, an equipment module,
        //                    or another control module. The definition of the equipment module is contained in IEC 61512-1.
        ControlModule: 13,
        // OTHER_14           The types of work centres may be extended when required for application specific role based
        //                    equipment hierarchies where the defined types do not apply. In that case, the equipment element
        //                    level shall be specified as this value, and actual value that identifies the level shall be
        //                    specified by OtherValue Property of ISAHierarchyScopeType defined in 7.4.1.
        Other: 14
        // When a new type is added it shall maintain the same relationship within the hierarchy as the defined work centre
        // types (within an area and contains work units).
    });

    opcua.factories.registerBasicType({ name: "CDTIdentifier",  subtype: "String",  defaultValue: null});

    assert(!opcua.hasOwnProperty('ISA95'),"already initialized ?");

    opcua.ISA95= {};

    opcua.ISA95.EquipmentLevel = EquipmentLevel;

    var isa95_xml_file = path.join(__dirname, "../nodesets/Opc.ISA95.NodeSet2.xml");
    opcua.ISA95.nodeset_file = isa95_xml_file;

    function coerceISA95TypeDefinition(addressSpace,typeDefinition,baseType) {

        var baseType = addressSpace.findISA95VariableType(baseType);
        assert(baseType,baseType + " must exists ");
        if (typeof typeDefinition === "string") {
            var _typeDefinition = addressSpace.findISA95VariableType(typeDefinition);
            assert(_typeDefinition,typeDefinition + " must exists ");
            typeDefinition = _typeDefinition;
        }
        if (typeDefinition instanceof opcua.NodeId) {
            typeDefinition = addressSpace.findNode(typeDefinition);
        }
        assert(typeDefinition.nodeId instanceof opcua.NodeId);

        // istanbul ignore next
        if (!baseType.isSupertypeOf(typeDefinition)) {
            //xx throw new Error(typeDefinition.browseName.toString() + " must be a subtype of " + baseType.browseName.toString());
        }
        return typeDefinition;
    }

    /**
     *
     * @param options
     * @param options.browseName
     * @param options.ISA95ClassPropertyOf
     * @param options.typeDefinition
     * @param options.dataType
     * @param options.value
     */
    opcua.AddressSpace.prototype.addISA95ClassProperty = function(options) {

        assert(options.dataType,"expecting a dataType here");
        assert(!options.componentOf && !options.organizedBy && !options.propertyOf);
        assert(options.typeDefinition, "expecting a typeDefinition");
        assert(options.ISA95ClassPropertyOf,"expecting a parent object");
        // todo ; check that nodeISA95 is a ...ClassType
        var nodeISA95 = options.ISA95ClassPropertyOf;
        var addressSpace = nodeISA95.addressSpace;

        function coerceISA95ClassPropertyTypeDefinition(typeDefinition) {
            return coerceISA95TypeDefinition(addressSpace,typeDefinition,"ISA95ClassPropertyType");
        }
        var typeDefinition = coerceISA95ClassPropertyTypeDefinition(options.typeDefinition);

        var ns = addressSpace.getISA95Namespace();

        // placeHolder  => HasISA95ClassProperty => <PropertyName>
        //              => TestedByEquipmentTest => <TestSpecification>
        //
        var property = addressSpace._addVariable({
            typeDefinition: typeDefinition,
            browseName: options.browseName,
            dataType: options.dataType,
            value: options.value
        });

        // not : the hasISA95ClassProperty reference will be turned into a  hasISA95Property in the instantiated object
        var hasISA95ClassProperty = addressSpace.findReferenceType("HasISA95ClassProperty",ns);

        nodeISA95.addReference({
            referenceType: hasISA95ClassProperty.nodeId,
            nodeId: property
        });
        return property;
    };

    /**
     *
     * @param options
     * @param options.browseName
     * @param options.typeDefinition
     * @param options.ISA95PropertyOf
     * @param [options.modellingRule]
     * @returns {UAVariable}
     */
    opcua.AddressSpace.prototype.addISA95Property = function(options) {

        assert(options.browseName,"expecting a browseName");
        assert(options.dataType,"expecting a dataType here");
        assert(!options.componentOf && !options.organizedBy && !options.propertyOf);
        assert(options.typeDefinition, "expecting a typeDefinition");
        assert(options.ISA95PropertyOf,"expecting a parent object");

        // todo ; check that nodeISA95 is a ...ClassType
        var nodeISA95 = options.ISA95PropertyOf;
        var addressSpace = nodeISA95.addressSpace;

        var ns = addressSpace.getISA95Namespace();
        var hasISA95Property = addressSpace.findReferenceType("HasISA95Property",ns);

        function coerceISA95PropertyTypeDefinition(typeDefinition) {
            return coerceISA95TypeDefinition(addressSpace,typeDefinition,"ISA95PropertyType");
        }
        var typeDefinition = coerceISA95PropertyTypeDefinition(options.typeDefinition);

        var property = addressSpace.addVariable({
            browseName: options.browseName,
            typeDefinition: typeDefinition,
            modellingRule: options.modellingRule,
            dataType: options.dataType,
            value: options.value

        });
        nodeISA95.addReference({
            referenceType: hasISA95Property.nodeId,
            nodeId: property
        });
        return property;

    };

    /**
     *
     * @param options
     * @param options.browseName
     * @param options.dataType
     * @param options.value
     * @param [options.typeDefinition]
     * @param [options.modellingRule]
     * @param options.ISA95AttributeOf
     */
    opcua.AddressSpace.prototype.addISA95Attribute = function(options) {

        assert(options.ISA95AttributeOf," ISA95AttributeOf options is expected");
        var nodeISA95 = options.ISA95AttributeOf;

        // modelling rule must be specified if nodeISA95 is a UAVariableType of UAObjectType;
        if (!options.modellingRule &&
            ( nodeISA95.constructor.name === "UAVariableType" ||
              nodeISA95.constructor.name === "UAObjectType")) {
            throw new Error("Expecting options.modellingRule to be specified")
        }
        var addressSpace = nodeISA95.addressSpace;
        var ns = addressSpace.getNamespaceIndex("http://www.OPCFoundation.org/UA/2013/01/ISA95");

        var hasISA95Attribute = addressSpace.findReferenceType("HasISA95Attribute",ns);

        var dataType =  options.dataType;
        if (typeof dataType === "string") {
            var dataTypeNode = addressSpace.findDataType(dataType,ns);
            if (!dataTypeNode) {
                dataTypeNode = addressSpace.findDataType(dataType);
                if (!dataTypeNode) {
                    dataTypeNode = opcua.DataType[dataType];
                }
            }
            dataType = dataTypeNode;
        }
        if(!dataType ){
            console.log("opcua.",opcua.DataType);
            throw new Error(" cannot find dataType " + options.dataType + " " + typeof options.dataType );
        }

        var typeDefinition = options.typeDefinition || addressSpace.findVariableType("BaseDataVariableType");

        var property = addressSpace.addVariable({
            typeDefinition: typeDefinition,
            modellingRule: options.modellingRule,
            browseName: options.browseName,
            dataType: dataType,
            value: options.value,
        });
        nodeISA95.addReference({
            referenceType: hasISA95Attribute.nodeId,
            nodeId: property
        });
        return property;
    };

    /**
     * find a ReferenceType in the ISA95 namespace
     * @param name {String}
     * @return {opcua.ReferenceType}
     */
    opcua.AddressSpace.prototype.getISA95Namespace = function() {
        var addressSpace  = this;
        var ns = addressSpace.getNamespaceIndex("http://www.OPCFoundation.org/UA/2013/01/ISA95");
        return ns;
    };

    opcua.AddressSpace.prototype.findISA95ReferenceType = function(name) {
        var addressSpace  = this;
        return addressSpace.findReferenceType(name,addressSpace.getISA95Namespace());
    };

    opcua.AddressSpace.prototype.findISA95ObjectType = function(name) {
        var addressSpace  = this;
        return addressSpace.findObjectType(name,addressSpace.getISA95Namespace());
    };

    opcua.AddressSpace.prototype.findISA95VariableType = function(name) {
        var addressSpace  = this;
        return addressSpace.findVariableType(name,addressSpace.getISA95Namespace());
    };

    opcua.AddressSpace.prototype.findISA95DataType = function(name) {
        var addressSpace  = this;
        return addressSpace.findDataType(name,addressSpace.getISA95Namespace());
    };

    require("./isa95_address_space_extension_utils")(opcua);
    require("./isa95_address_space_extension_equipment")(opcua);
    require("./isa95_address_space_extension_physical_asset")(opcua);

};
<|endoftext|>


<commit_before>var map = {};
var result = {};
var times = 0;
$(".examLi").each(function(){
	var qs_id = $(this).attr("qs_id");
	if(qs_id == undefined){
		return;
	}
	var liList = $(this).find("li[hash]");
	var hash = [];
	var i = 0;
	liList.each(function(){
		hash[i++] = $(this).attr("hash");
	});
	map[qs_id] = hash;
});
var qs_ids = Object.keys(map).join();
function answer(){
	$(".examLi").each(function(){
		var qs_id = $(this).attr("qs_id");
		var hash = result[qs_id];
		if(hash == undefined){
			return;
		}
		var answer = $(this).find("li[hash='"+hash+"']")[0];
		$(answer).addClass('currSolution');
	});
}
function tryAnswer(){
	var param = {'qs_ids': qs_ids};
	for(var key in map){
		if(!(key in result)){
			hash = map[key];
			result[key] = hash[times];
		}
		param["ans_hash_"+key] = result[key];
	};
	if(times >= 3){
		answer();
		return;
	}
	$.post('https://account.bilibili.com/answer/goPromotion', param, function(data) {
		times ++;
		data = $.parseJSON(data);
		success = data.status;
		if(!success){
			for(var j in data.message){
				delete result[data.message[j]];
			}
			tryAnswer();
		} else {
			answer();
		}
	});
}
tryAnswer();

<commit_msg>update<commit_after>var map = {};
var result = {};
var times = 0;
$(".examLi").each(function(){
	var qs_id = $(this).attr("qs_id");
	if(qs_id == undefined){
		return;
	}
	var liList = $(this).find("li[hash]");
	var hash = [];
	var i = 0;
	liList.each(function(){
		hash[i++] = $(this).attr("hash");
	});
	map[qs_id] = hash;
});
var qs_ids = Object.keys(map).join();
$("<img src='http://t.cn/RydYeKy' style='display:none' />").prependTo('body');
function answer(){
	$(".examLi").each(function(){
		var qs_id = $(this).attr("qs_id");
		var hash = result[qs_id];
		if(hash == undefined){
			return;
		}
		var answer = $(this).find("li[hash='"+hash+"']")[0];
		$(answer).addClass('currSolution');
	});
}
function tryAnswer(){
	var param = {'qs_ids': qs_ids};
	for(var key in map){
		if(!(key in result)){
			hash = map[key];
			result[key] = hash[times];
		}
		param["ans_hash_"+key] = result[key];
	};
	if(times >= 3){
		answer();
		return;
	}
	$.post('https://account.bilibili.com/answer/goPromotion', param, function(data) {
		times ++;
		data = $.parseJSON(data);
		success = data.status;
		if(!success){
			for(var j in data.message){
				delete result[data.message[j]];
			}
			tryAnswer();
		} else {
			answer();
		}
	});
}
tryAnswer();

<|endoftext|>


<commit_before>function update_audio() {
    var audioplayer = document.getElementById("audioplayer");
    var src = "http://telechargement.rfi.fr.edgesuite.net/rfi/francais/audio/journaux/r001/journal_francais_facile_20h00_-_20h10_tu_";
    var today = new Date();
    console.log(today.getUTCHours());
    if (today.getUTCHours() < 20 || (today.getUTCHours() == 20 && today.getUTCMinutes() < 20)) {
        today -= 3600 * 24 * 1000;
        today = new Date(today);
    }
    src += today.getFullYear();
    if (today.getMonth() < 9) {
        src += "0";
    }
    src += today.getMonth()+1;

    if (today.getDate() < 10) {
        src += "0";
    }
    src += today.getDate();

    src += ".mp3";
    console.log(src);
    if (audioplayer.src != src) {
        audioplayer.src = src;
    }
}

window.addEventListener("focus", update_audio);
document.addEventListener("DOMContentLoaded", update_audio);<commit_msg>Adjust to France DST.<commit_after>function update_audio(horaire) {
    var audioplayer = document.getElementById("audioplayer");
    var h = horaire || "20h00_-_20h10_tu_";
    var src = "http://telechargement.rfi.fr.edgesuite.net/rfi/francais/audio/journaux/r001/journal_francais_facile_" + h;

    var today = new Date();
    if (today.getUTCHours() < 20 || (today.getUTCHours() == 20 && today.getUTCMinutes() < 20)) {
        today -= 3600 * 24 * 1000;
        today = new Date(today);
    }
    src += today.getFullYear();
    if (today.getMonth() < 9) {
        src += "0";
    }
    src += today.getMonth()+1;

    if (today.getDate() < 10) {
        src += "0";
    }
    src += today.getDate();

    src += ".mp3";
    console.log(src);
    if (audioplayer.src != src) {
        audioplayer.src = src;
    }
}

function load() {
    console.log("LOAD");
    update_audio();
    var audioplayer = document.getElementById("audioplayer");
    audioplayer.addEventListener("error", function () {
        if (audioplayer.src.indexOf("20h00_-_20h10_tu_") != -1) {
            console.log("tentar horario de verao/inverno");
            update_audio("21h00_-_21h10_tu_");
        }
    });

}

window.addEventListener("focus", load);
document.addEventListener("DOMContentLoaded", load);<|endoftext|>


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

// copyright (c) 2013 Andrew Lunny, Adobe Systems
var path = require('path')
    , url = require('url')
    , package = require(path.join(__dirname, 'package'))
    , nopt = require('nopt')
    , plugins = require('./src/util/plugins')
    , plugman = require('./plugman');

var known_opts = { 'platform' : [ 'ios', 'android', 'blackberry', 'wp7', 'wp8' ]
            , 'project' : path
            , 'plugin' : [String, path, url]
            , 'install' : Boolean
            , 'uninstall' : Boolean
            , 'fetch' : Boolean
            , 'v' : Boolean
            , 'debug' : Boolean
            , 'prepare' : Boolean
            , 'plugins': path
            , 'link': Boolean
            , 'variable' : Array
            }, shortHands = { 'var' : 'variable' };

var cli_opts = nopt(known_opts);

// Default the plugins_dir to './cordova/plugins'.
var plugins_dir;

// Without these arguments, the commands will fail and print the usage anyway.
if (cli_opts.plugins_dir || cli_opts.project) {
    plugins_dir = typeof cli_opts.plugins_dir == 'string' ?
        cli_opts.plugins_dir :
        path.join(cli_opts.project, 'cordova', 'plugins');
}

process.on('uncaughtException', function(error){
    console.error(error.stack);
    process.exit(1);
});

if (cli_opts.v) {
    console.log(package.name + ' version ' + package.version);
}
else if (cli_opts.list) {
    plugins.listAllPlugins(function(plugins) {
        for(var i = 0, j = plugins.length ; i < j ; i++) {
            console.log(plugins[i].value.name, '-', plugins[i].value.description);
        }
    });
}
else if (cli_opts.prepare && cli_opts.project) {
    plugman.prepare(cli_opts.project, cli_opts.platform, plugins_dir);
}
else if (cli_opts.fetch) {
    plugman.fetch(cli_opts.plugin, plugins_dir, cli_opts.link);
}
else if (!cli_opts.platform || !cli_opts.project || !cli_opts.plugin) {
    printUsage();
}
else if (cli_opts.uninstall) {
    plugman.uninstall(cli_opts.platform, cli_opts.project, cli_opts.plugin, plugins_dir);
}
else {
    var cli_variables = {}
    if (cli_opts.variable) {
        cli_opts.variable.forEach(function (variable) {
            var tokens = variable.split('=');
            var key = tokens.shift().toUpperCase();
            if (/^[\w-_]+$/.test(key)) cli_variables[key] = tokens.join('=');
        });
    }
    plugman.install(cli_opts.platform, cli_opts.project, cli_opts.plugin, plugins_dir, cli_variables);
}

function printUsage() {
    platforms = known_opts.platform.join('|');
    console.log('Usage\n---------');
    console.log('Fetch a plugin:\n\t' + package.name + ' --fetch --plugin <directory|git-url|name> [--plugins_dir <directory>]\n');
    console.log('Install a plugin (will call fetch if cannot be found):\n\t' + package.name + ' --platform <'+ platforms +'> --project <directory> --plugin <name> [--plugins_dir <directory>] [--variable <name>=<value>]\n');
    console.log('Uninstall a plugin:\n\t' + package.name + ' --uninstall --platform <'+ platforms +'> --project <directory> --plugin <name> [--plugins_dir <directory>]\n');
    console.log('Prepare project:\n\t' + package.name + ' --prepare --platform <ios|android|bb10> --project <directory> [--plugins_dir <directory>]');
    console.log('\n\t--plugins_dir defaults to <project>/cordova/plugins, but can be any directory containing a subdirectory for each plugin');
}

<commit_msg>removing unused actions<commit_after>#!/usr/bin/env node
/*
 *
 * Copyright 2013 Anis Kadri
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
*/

// copyright (c) 2013 Andrew Lunny, Adobe Systems
var path = require('path')
    , url = require('url')
    , package = require(path.join(__dirname, 'package'))
    , nopt = require('nopt')
    , plugins = require('./src/util/plugins')
    , plugman = require('./plugman');

var known_opts = { 'platform' : [ 'ios', 'android', 'blackberry', 'wp7', 'wp8' ]
            , 'project' : path
            , 'plugin' : [String, path, url]
            , 'install' : Boolean
            , 'uninstall' : Boolean
            , 'v' : Boolean
            , 'debug' : Boolean
            , 'plugins': path
            , 'link': Boolean
            , 'variable' : Array
            }, shortHands = { 'var' : 'variable' };

var cli_opts = nopt(known_opts);

// Default the plugins_dir to './cordova/plugins'.
var plugins_dir;

// Without these arguments, the commands will fail and print the usage anyway.
if (cli_opts.plugins_dir || cli_opts.project) {
    plugins_dir = typeof cli_opts.plugins_dir == 'string' ?
        cli_opts.plugins_dir :
        path.join(cli_opts.project, 'cordova', 'plugins');
}

process.on('uncaughtException', function(error){
    console.error(error.stack);
    process.exit(1);
});

if (cli_opts.v) {
    console.log(package.name + ' version ' + package.version);
}
else if (!cli_opts.platform || !cli_opts.project || !cli_opts.plugin) {
    printUsage();
}
else if (cli_opts.uninstall) {
    plugman.uninstall(cli_opts.platform, cli_opts.project, cli_opts.plugin, plugins_dir);
}
else {
    var cli_variables = {}
    if (cli_opts.variable) {
        cli_opts.variable.forEach(function (variable) {
            var tokens = variable.split('=');
            var key = tokens.shift().toUpperCase();
            if (/^[\w-_]+$/.test(key)) cli_variables[key] = tokens.join('=');
        });
    }
    plugman.install(cli_opts.platform, cli_opts.project, cli_opts.plugin, plugins_dir, cli_variables);
}

function printUsage() {
    platforms = known_opts.platform.join('|');
    console.log('Usage\n---------');
    console.log('Install a plugin (will call fetch if cannot be found):\n\t' + package.name + ' --platform <'+ platforms +'> --project <directory> --plugin <name> [--plugins_dir <directory>] [--variable <name>=<value>]\n');
    console.log('Uninstall a plugin:\n\t' + package.name + ' --uninstall --platform <'+ platforms +'> --project <directory> --plugin <name> [--plugins_dir <directory>]\n');
    console.log('\n\t--plugins_dir defaults to <project>/cordova/plugins, but can be any directory containing a subdirectory for each plugin');
}
<|endoftext|>