<commit_before>/*
*   Copyright 2012 Comcast
*
*   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.
*/

define(['jquery', 'base'], function($, Base) {

    var Dropdown = Base('dropdown', function() {
        var self = this,
            trigger,
            handles = self.getHandle(),
            expanders = self.getExpander(),

            onTriggers = this.options.triggers.on,
            offTriggers = self.options.triggers.off,
            toggleTriggers = this.options.triggers.toggle;

        var getTriggerHandle = function(triggerData, index){
            if (triggerData.selector) {
                return triggerData.selector === 'document' ? $(document) : $(triggerData.selector);
            } else {
                return typeof index === 'undefined' ? handles : handles.eq(index);
            }
        };

        this.timers = {
            expand: [],
            collapse: [],
            throttle: []
        };

        for (trigger in onTriggers) {
            getTriggerHandle(onTriggers[trigger]).on(trigger, {delay: onTriggers[trigger].delay}, function(event){
                var index = parseInt($(this).attr('data-dropdown-index'), 10),
                    delay = event.data.delay,
                    handle = $(this),
                    trigger;

                event.preventDefault();

                for (trigger in offTriggers) {
                    handle.on(trigger, {delay: offTriggers[trigger].delay, el: handle}, function(event){
                        if (($(event.target).is(self.getExpander(index)) || $(event.target).parents(self.options.dropdownExpanderSelector).length > 0) && !$(event.target).is(event.data.el)) {
                            return true;
                        }

                        event.preventDefault();

                        self.collapse(index, event.data.delay);

                        $(this).unbind(event);
                    });
                }

                self.expand(index, delay);
            });
        }

        for (trigger in toggleTriggers) {
            getTriggerHandle(toggleTriggers[trigger]).on(trigger, {delay: toggleTriggers[trigger].delay}, function(event){
                var index = parseInt($(this).attr('data-dropdown-index'), 10),
                    delay = event.data.delay;

                self.setState(index, delay, !self.getExpander(index).hasClass(self.options.activeDropdownClass));
            });
        }

        handles.each(function(index){
            var handle = $(this),
                expander = expanders.eq(index);

            handle.attr('data-dropdown-index', index);
            expander.attr('data-dropdown-index', index);
        });

        expanders.on('mouseover', function(){
            var index = parseInt($(this).attr('data-dropdown-index'), 10);

            if (self.timers.collapse[index]){
                self.timers.collapse[index] = clearTimeout(self.timers.collapse[index]);

                $(this).on('mouseleave', {index: index}, function(event){
                    self.collapse(event.data.index, 0);
                    $(this).unbind(event);
                });
            }
        });

    });

    Dropdown.setDefaultOptions({
        dropdownHandleSelector: '[data-role="dropdown-handle"]',
        dropdownExpanderSelector: '[data-role="dropdown-content"]',

        activeDropdownClass: 'is-dropdown-active',

        throttleDelay: 300,
        triggers: {
            on: {
                mouseover: {
                    delay: 500
                }
            },
            off: {
                mouseleave: {
                    delay: 500
                }
            },
            toggle: {
                click: {
                    delay: 0
                }
            }
        }

    });

    $.extend(Dropdown.prototype, {
        getHandle: function(index){
            var handles = this.root.find(this.options.dropdownHandleSelector);

            return (typeof index !== 'undefined' && index >= 0) ? handles.eq(index) : handles;
        },

        getExpander: function(index){
            var expanders = this.root.find(this.options.dropdownExpanderSelector);

            return (typeof index !== 'undefined' && index >= 0) ? expanders.eq(index) : expanders;
        },

        setState: function(index, delay, active){
            var state = active ? 'expand' : 'collapse',
                counterState = active ? 'collapse' : 'expand';

            this.timers[counterState][index] = clearTimeout(this.timers[counterState][index]);

            if (this.timers.throttle[index] || this.timers[state][index]) {
                return;
            }

            this.timers[state][index] = setTimeout(function(i, _state, _active) {
                var expander = this.getExpander(i),
                    handle = this.getHandle(i),
                    self = this;

                this.timers[_state][i] = clearTimeout(this.timers[_state][i]);

                expander.toggleClass(this.options.activeDropdownClass, _active);
                this.getHandle(i).toggleClass(this.options.activeDropdownClass, _active);

                if (_active){
                    expander.focus();
                    handle.trigger('dropdownExpand', i);
                } else {
                    handle.trigger('dropdownCollapse', i);
                }

                if (this.options.throttleDelay > 0){
                    this.timers.throttle[i] = setTimeout(function(){
                        self.timers.throttle[i] = clearTimeout(self.timers.throttle[i]);
                    }, this.options.throttleDelay);
                }

            }.bind(this, index, state, active), delay);
        },

        expand: function(index, delay) {
            this.setState(index, delay, true);
        },

        collapse: function(index, delay) {
            this.setState(index, delay, false);
        }
    });

    return Dropdown;
});
<commit_msg>Updating Dropdown to set blur and focus events by default, not mouseover and mouseleave<commit_after>/*
*   Copyright 2012 Comcast
*
*   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.
*/

define(['jquery', 'base'], function($, Base) {

    var Dropdown = Base('dropdown', function() {
        var self = this,
            trigger,
            handles = self.getHandle(),
            expanders = self.getExpander(),

            onTriggers = this.options.triggers.on,
            offTriggers = self.options.triggers.off,
            toggleTriggers = this.options.triggers.toggle;

        var getTriggerHandle = function(triggerData, index){
            if (triggerData.selector) {
                return triggerData.selector === 'document' ? $(document) : $(triggerData.selector);
            } else {
                return typeof index === 'undefined' ? handles : handles.eq(index);
            }
        };

        this.timers = {
            expand: [],
            collapse: [],
            throttle: []
        };

        for (trigger in onTriggers) {
            getTriggerHandle(onTriggers[trigger]).on(trigger, {delay: onTriggers[trigger].delay}, function(event){
                var index = parseInt($(this).attr('data-dropdown-index'), 10),
                    delay = event.data.delay,
                    handle = $(this),
                    trigger;

                event.preventDefault();

                for (trigger in offTriggers) {
                    handle.on(trigger, {delay: offTriggers[trigger].delay, el: handle}, function(event){
                        if (($(event.target).is(self.getExpander(index)) || $(event.target).parents(self.options.dropdownExpanderSelector).length > 0) && !$(event.target).is(event.data.el)) {
                            return true;
                        }

                        event.preventDefault();

                        self.collapse(index, event.data.delay);

                        $(this).unbind(event);
                    });
                }

                self.expand(index, delay);
            });
        }

        for (trigger in toggleTriggers) {
            getTriggerHandle(toggleTriggers[trigger]).on(trigger, {delay: toggleTriggers[trigger].delay}, function(event){
                var index = parseInt($(this).attr('data-dropdown-index'), 10),
                    delay = event.data.delay;

                self.setState(index, delay, !self.getExpander(index).hasClass(self.options.activeDropdownClass));
            });
        }

        handles.each(function(index){
            var handle = $(this),
                expander = expanders.eq(index);

            handle.attr('data-dropdown-index', index);
            expander.attr('data-dropdown-index', index);
        });

        expanders.on('mouseover', function(){
            var index = parseInt($(this).attr('data-dropdown-index'), 10);

            if (self.timers.collapse[index]){
                self.timers.collapse[index] = clearTimeout(self.timers.collapse[index]);

                $(this).on('mouseleave', {index: index}, function(event){
                    self.collapse(event.data.index, 0);
                    $(this).unbind(event);
                });
            }
        });

    });

    Dropdown.setDefaultOptions({
        dropdownHandleSelector: '[data-role="dropdown-handle"]',
        dropdownExpanderSelector: '[data-role="dropdown-content"]',

        activeDropdownClass: 'is-dropdown-active',

        throttleDelay: 300,
        triggers: {
            on: {
                focus: {
                    delay: 0
                }
            },
            off: {
                blur: {
                    delay: 0
                }
            },
            toggle: {
                click: {
                    delay: 0
                }
            }
        }

    });

    $.extend(Dropdown.prototype, {
        getHandle: function(index){
            var handles = this.root.find(this.options.dropdownHandleSelector);

            return (typeof index !== 'undefined' && index >= 0) ? handles.eq(index) : handles;
        },

        getExpander: function(index){
            var expanders = this.root.find(this.options.dropdownExpanderSelector);

            return (typeof index !== 'undefined' && index >= 0) ? expanders.eq(index) : expanders;
        },

        setState: function(index, delay, active){
            var state = active ? 'expand' : 'collapse',
                counterState = active ? 'collapse' : 'expand';

            this.timers[counterState][index] = clearTimeout(this.timers[counterState][index]);

            if (this.timers.throttle[index] || this.timers[state][index]) {
                return;
            }

            this.timers[state][index] = setTimeout(function(i, _state, _active) {
                var expander = this.getExpander(i),
                    handle = this.getHandle(i),
                    self = this;

                this.timers[_state][i] = clearTimeout(this.timers[_state][i]);

                expander.toggleClass(this.options.activeDropdownClass, _active);
                this.getHandle(i).toggleClass(this.options.activeDropdownClass, _active);

                if (_active){
                    expander.focus();
                    handle.trigger('dropdownExpand', i);
                } else {
                    handle.trigger('dropdownCollapse', i);
                }

                if (this.options.throttleDelay > 0){
                    this.timers.throttle[i] = setTimeout(function(){
                        self.timers.throttle[i] = clearTimeout(self.timers.throttle[i]);
                    }, this.options.throttleDelay);
                }

            }.bind(this, index, state, active), delay);
        },

        expand: function(index, delay) {
            this.setState(index, delay, true);
        },

        collapse: function(index, delay) {
            this.setState(index, delay, false);
        }
    });

    return Dropdown;
});
<|endoftext|>


<commit_before>import React from 'react'
import PropTypes from 'prop-types'
import Helmet from 'react-helmet'
import _ from 'lodash'

import { compose, bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import { connectRequest } from 'redux-query'

import api from '../../../services'
import { manifestsOnDocket } from '../../../selectors'

import { Spin, Tabs, Alert, Button, Tooltip } from 'antd'
const TabPane = Tabs.TabPane

import Panels from './Panels/Panels'

import styles from './Voting.css'
@compose(
  connect(
    state => ({
      docket: manifestsOnDocket(state)
      // docket: Array.isArray(state.db.manifests)
      //   ? state.db.manifests
      //     .filter(budget => {
      //       let { docket } = budget
      //       if (docket) return docket.metrics || docket.voting || docket.decisions
      //     })
      //   : []
    }),
    dispatch => ({ api: bindActionCreators(api, dispatch) })
),
  connectRequest(() => api.get('manifests', {
    populate: [
      'items',
      'reviews',
      'decision',
      { path: 'proposal', populate: { path: 'body' } },
      { path: 'proposal', populate: { path: 'contacts' } }
    ],
    force: true
  }))
)
class Voting extends React.Component {
  static propTypes = {
    docket: PropTypes.array
  }
  render (
    { user, docket, forceRequest } = this.props
  ) {
    return (

        <Helmet title='Voting' />
        {!docket
          ? <Spin size='large' tip='Loading...' />
          : <Tabs className='tab-container' type='card'
            tabBarExtraContent={<Button type='ghost' icon='reload' onClick={forceRequest}>Refresh</Button>}
            >
            <TabPane tab='Overview' key='1' className={styles['tab-pane']}>

Reviews & Voting

Instructions here.

              <Alert type='info' banner showIcon={false}
                message='Major Changes for Ex-Officios'
                description='Permissions have been expanded to allow Ex-Officios to review proposals, sans final voting. Officios also have read access to more content in general. We are grateful for their involvement and want the web platform to reflect that.'
              />
            </TabPane>
            {docket.map((manifest, i) => (
              <TabPane key={manifest._id} className={styles['tab-pane']}
                tab={
                  <Tooltip placement='bottom' title={manifest.proposal.title}>{`
                    ${manifest.proposal.year}-${manifest.proposal.number}
                    ${manifest.type !== 'original' ? `(${manifest.type[0].toUpperCase()})` : ''}
                  `}
                  </Tooltip>
                }>
                <Panels index={i} id={manifest._id} />
              </TabPane>
            ))}
          </Tabs>
        }

    )
  }
}

export default Voting
<commit_msg>Refactoring the voting panes, better UX and performance.<commit_after>import React from 'react'
import PropTypes from 'prop-types'
import Helmet from 'react-helmet'
import _ from 'lodash'

import { compose, bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import { connectRequest } from 'redux-query'

import api from '../../../services'
import { manifestsOnDocket } from '../../../selectors'

import { Spin, Tabs, Alert, Button, Tooltip } from 'antd'
const TabPane = Tabs.TabPane

import Panels from './Panels/Panels'

import styles from './Voting.css'
@compose(
  connect(
    state => ({
      docket: manifestsOnDocket(state)
      // docket: Array.isArray(state.db.manifests)
      //   ? state.db.manifests
      //     .filter(budget => {
      //       let { docket } = budget
      //       if (docket) return docket.metrics || docket.voting || docket.decisions
      //     })
      //   : []
    }),
    dispatch => ({ api: bindActionCreators(api, dispatch) })
),
  connectRequest(() => api.get('manifests', {
    populate: [
      'items',
      'reviews',
      'decision',
      { path: 'proposal', populate: { path: 'body' } },
      { path: 'proposal', populate: { path: 'contacts' } }
    ],
    force: true
  }))
)
class Voting extends React.Component {
  static propTypes = {
    docket: PropTypes.array
  }
  render (
    { user, docket, forceRequest } = this.props
  ) {
    return (

        <Helmet title='Voting' />
        {!docket
          ? <Spin size='large' tip='Loading...' />
          : <Tabs type='mini' tabPosition='left'
            // tabBarExtraContent={<Button type='ghost' icon='reload' onClick={forceRequest}>Refresh</Button>}
            >
            <TabPane tab='Overview' key='1' className={styles['tab-pane']}>

Reviews & Voting

Instructions here.

              <Alert type='info' banner showIcon={false}
                message='Major Changes for Ex-Officios'
                description='Permissions have been expanded to allow Ex-Officios to review proposals, sans final voting. Officios also have read access to more content in general. We are grateful for their involvement and want the web platform to reflect that.'
              />
            </TabPane>
            {docket.map((manifest, i) => (
              <TabPane key={manifest._id} className={styles['tab-pane']}
                tab={
                  <Tooltip placement='bottom' title={manifest.proposal.title}>{`
                    ${manifest.proposal.year}-${manifest.proposal.number}
                    ${manifest.type !== 'original' ? `(${manifest.type[0].toUpperCase()})` : ''}
                  `}
                  </Tooltip>
                }>
                <Panels index={i} id={manifest._id} />
              </TabPane>
            ))}
          </Tabs>
        }

    )
  }
}

export default Voting
<|endoftext|>


<commit_before>// ==UserScript==
// @name                OLog
// @namespace           http://www.olog.com/
// @description         OLog Userscript
// @include             http://s*-*.ogame.gameforge.com/game/*
// @grant               GM_xmlhttpRequest
// @grant               GM_getValue
// @grant               GM_setValue
// ==/UserScript==

"use strict";

var oLogInstanceUrl = GM_getValue("settings.ologinstanceurl", "http://localhost:8080/");

var menuTable = document.getElementById("menuTable");

var oLogLi = document.createElement("li");
oLogLi.onfocus = function(c) {
    if (b(c.target).closest(".dropdown").length == 0) {
        b(".currentlySelected a").removeClass("hover");
        b(".currentlySelected").removeClass("focus");
    }
}

var oLogAnchor = document.createElement("a");
oLogAnchor.className = "menubutton";
oLogAnchor.href = "#ologsettings";
oLogAnchor.onclick = function() {
    showOLogSettings();
};

var oLogSpan = document.createElement("span");
oLogSpan.className = "textlabel"

var oLogText = document.createTextNode("OLog Settings");

oLogSpan.appendChild(oLogText);
oLogAnchor.appendChild(oLogSpan);
oLogLi.appendChild(oLogAnchor);
menuTable.appendChild(oLogLi);

if (window.location.hash === "#ologsettings") {
    showOLogSettings();
}

function showOLogSettings() {
    var menuTableLiList = menuTable.querySelectorAll("li");
    for (var i = 0; i < menuTableLiList.length; i++) {
        menuTableLiList[i].querySelector(".menubutton").classList.remove("selected");
    }

    oLogAnchor.classList.add("selected");

    var contentWrapperDiv = document.getElementById("contentWrapper");
    while (contentWrapperDiv.firstChild) {
        contentWrapperDiv.removeChild(contentWrapperDiv.firstChild);
    }

    var buttonzDiv = document.createElement("div");
    buttonzDiv.id = "buttonz";

    var headerDiv = document.createElement("div");
    headerDiv.className = "header";

    var headerH2 = document.createElement("h2");

    var headerText = document.createTextNode("OLog Settings");

    var contentDiv = document.createElement("div");
    contentDiv.className = "content";

    var fieldwrapperDiv = document.createElement("div");
    fieldwrapperDiv.className = "fieldwrapper";

    var oLogInstanceUrlLabel = document.createElement("label");
    oLogInstanceUrlLabel.className = "styled textBeefy";

    var oLogInstanceUrlText = document.createTextNode("OLog Instance URL:");

    var oLogInstanceUrlTheFieldDiv = document.createElement("div");
    oLogInstanceUrlTheFieldDiv.className = "thefield";

    var oLogInstanceUrlInput = document.createElement("input");
    oLogInstanceUrlInput.className = "textinput w200";
    oLogInstanceUrlInput.type = "text";
    oLogInstanceUrlInput.size = "30";
    oLogInstanceUrlInput.value = oLogInstanceUrl;
    oLogInstanceUrlInput.maxlength = "20";

    var settingsSaveDiv = document.createElement("div");
    settingsSaveDiv.className = "textCenter";

    var settingsSaveInput = document.createElement("input");
    settingsSaveInput.className = "btn_blue";
    settingsSaveInput.type = "submit";
    settingsSaveInput.value = "Save settings";
    settingsSaveInput.onclick = function() {
        GM_setValue("settings.ologinstanceurl", oLogInstanceUrlInput.value);
    };

    oLogInstanceUrlLabel.appendChild(oLogInstanceUrlText);
    oLogInstanceUrlTheFieldDiv.appendChild(oLogInstanceUrlInput);
    fieldwrapperDiv.appendChild(oLogInstanceUrlLabel);
    fieldwrapperDiv.appendChild(oLogInstanceUrlTheFieldDiv);

    settingsSaveDiv.appendChild(settingsSaveInput);

    contentDiv.appendChild(fieldwrapperDiv);
    contentDiv.appendChild(settingsSaveDiv);

    headerH2.appendChild(headerText);
    headerDiv.appendChild(headerH2);
    buttonzDiv.appendChild(headerDiv);
    buttonzDiv.appendChild(contentDiv);
    contentWrapperDiv.appendChild(buttonzDiv);
}

var page = getWindowVariable("currentPage");

if (page === "messages") {
    var observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            for(var i = 0; i < mutation.addedNodes.length; i++) {
                var node = mutation.addedNodes[i];
                if (node.localName === "ul" && node.classList.contains("tab_inner")) {
                    //send all messages at once such that all SR keys can be sent at once to the server
                    processMessageNodes(node.querySelectorAll(".msg"));
                }
            }
        });
    });

    observer.observe(document, { childList: true, subtree: true });
}

function processMessageNodes(nodes) {
    var reportKeys = {
        sr: [],     //spy report
        cr: [],     //combat report
        rr: [],     //recycle report
        mr: []      //missile report
    };

    for (var i = 0; i < nodes.length; i++) {
        var node = nodes[i];
        var apiElement = node.querySelector(".icon_apikey");
        if (apiElement !== null) {
            var key = node.querySelector(".icon_apikey").title;
            var type = key.substring(0, 2);
            if (reportKeys.hasOwnProperty(type)) {
                reportKeys[type].push(key);
            }
        }
    }

    console.log(reportKeys);

    postData({
        endpoint: "keys",
        data: {
            reportKeys: reportKeys
        }
    });
}

function postData(object) {
    addPlayerData(object.data);
    console.log(JSON.stringify(object.data));
    GM_xmlhttpRequest({
        method: "POST",
        url: oLogInstanceUrl + "api/userscript/" + object.endpoint,
        data: JSON.stringify(object.data),
        headers: {
            "Content-Type": "application/json"
        },
        onload: function(response) {
            console.log("load");
        },
        onerror: function(response) {
            console.log("error");
        }
    });
}

function addPlayerData(data) {
    data.serverGroup = getWindowVariable("constants.language");
    data.universe = getWindowVariable("constants.name");
    data.playerId = getWindowVariable("playerId");
    data.playerName = getWindowVariable("playerName");
}

/**
 * Returns a global variable.
 *
 * Needed because a @grant other than none puts the script
 * in a separate scope.
 *
 * @param {string} name The name of the global variable.
 */
function getWindowVariable(name) {
    return window.eval(name);
}<commit_msg>A message is now shown when the settings have been succesfully saved, closes #5.<commit_after>// ==UserScript==
// @name                OLog
// @namespace           http://www.olog.com/
// @description         OLog Userscript
// @include             http://s*-*.ogame.gameforge.com/game/*
// @grant               GM_xmlhttpRequest
// @grant               GM_getValue
// @grant               GM_setValue
// ==/UserScript==

"use strict";

var oLogInstanceUrl = GM_getValue("settings.ologinstanceurl", "http://localhost:8080/");

var menuTable = document.getElementById("menuTable");

var oLogLi = document.createElement("li");
oLogLi.onfocus = function(c) {
    if (b(c.target).closest(".dropdown").length == 0) {
        b(".currentlySelected a").removeClass("hover");
        b(".currentlySelected").removeClass("focus");
    }
}

var oLogAnchor = document.createElement("a");
oLogAnchor.className = "menubutton";
oLogAnchor.href = "#ologsettings";
oLogAnchor.onclick = function() {
    showOLogSettings();
};

var oLogSpan = document.createElement("span");
oLogSpan.className = "textlabel"

var oLogText = document.createTextNode("OLog Settings");

oLogSpan.appendChild(oLogText);
oLogAnchor.appendChild(oLogSpan);
oLogLi.appendChild(oLogAnchor);
menuTable.appendChild(oLogLi);

if (window.location.hash === "#ologsettings") {
    showOLogSettings();
}

function showOLogSettings() {
    var menuTableLiList = menuTable.querySelectorAll("li");
    for (var i = 0; i < menuTableLiList.length; i++) {
        menuTableLiList[i].querySelector(".menubutton").classList.remove("selected");
    }

    oLogAnchor.classList.add("selected");

    var contentWrapperDiv = document.getElementById("contentWrapper");
    while (contentWrapperDiv.firstChild) {
        contentWrapperDiv.removeChild(contentWrapperDiv.firstChild);
    }

    var buttonzDiv = document.createElement("div");
    buttonzDiv.id = "buttonz";

    var headerDiv = document.createElement("div");
    headerDiv.className = "header";

    var headerH2 = document.createElement("h2");

    var headerText = document.createTextNode("OLog Settings");

    var contentDiv = document.createElement("div");
    contentDiv.className = "content";

    var fieldwrapperDiv = document.createElement("div");
    fieldwrapperDiv.className = "fieldwrapper";

    var oLogInstanceUrlLabel = document.createElement("label");
    oLogInstanceUrlLabel.className = "styled textBeefy";

    var oLogInstanceUrlText = document.createTextNode("OLog Instance URL:");

    var oLogInstanceUrlTheFieldDiv = document.createElement("div");
    oLogInstanceUrlTheFieldDiv.className = "thefield";

    var oLogInstanceUrlInput = document.createElement("input");
    oLogInstanceUrlInput.className = "textinput w200";
    oLogInstanceUrlInput.type = "text";
    oLogInstanceUrlInput.size = "30";
    oLogInstanceUrlInput.value = oLogInstanceUrl;
    oLogInstanceUrlInput.maxlength = "20";

    var settingsSaveDiv = document.createElement("div");
    settingsSaveDiv.className = "textCenter";

    var settingsSaveInput = document.createElement("input");
    settingsSaveInput.className = "btn_blue";
    settingsSaveInput.type = "submit";
    settingsSaveInput.value = "Save settings";
    settingsSaveInput.onclick = function() {
        GM_setValue("settings.ologinstanceurl", oLogInstanceUrlInput.value);
        showSuccessMessage("Settings have been saved.");
    };

    oLogInstanceUrlLabel.appendChild(oLogInstanceUrlText);
    oLogInstanceUrlTheFieldDiv.appendChild(oLogInstanceUrlInput);
    fieldwrapperDiv.appendChild(oLogInstanceUrlLabel);
    fieldwrapperDiv.appendChild(oLogInstanceUrlTheFieldDiv);

    settingsSaveDiv.appendChild(settingsSaveInput);

    contentDiv.appendChild(fieldwrapperDiv);
    contentDiv.appendChild(settingsSaveDiv);

    headerH2.appendChild(headerText);
    headerDiv.appendChild(headerH2);
    buttonzDiv.appendChild(headerDiv);
    buttonzDiv.appendChild(contentDiv);
    contentWrapperDiv.appendChild(buttonzDiv);
}

var page = getWindowVariable("currentPage");

if (page === "messages") {
    var observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            for(var i = 0; i < mutation.addedNodes.length; i++) {
                var node = mutation.addedNodes[i];
                if (node.localName === "ul" && node.classList.contains("tab_inner")) {
                    //send all messages at once such that all SR keys can be sent at once to the server
                    processMessageNodes(node.querySelectorAll(".msg"));
                }
            }
        });
    });

    observer.observe(document, { childList: true, subtree: true });
}

function processMessageNodes(nodes) {
    var reportKeys = {
        sr: [],     //spy report
        cr: [],     //combat report
        rr: [],     //recycle report
        mr: []      //missile report
    };

    for (var i = 0; i < nodes.length; i++) {
        var node = nodes[i];
        var apiElement = node.querySelector(".icon_apikey");
        if (apiElement !== null) {
            var key = node.querySelector(".icon_apikey").title;
            var type = key.substring(0, 2);
            if (reportKeys.hasOwnProperty(type)) {
                reportKeys[type].push(key);
            }
        }
    }

    console.log(reportKeys);

    postData({
        endpoint: "keys",
        data: {
            reportKeys: reportKeys
        }
    });
}

function postData(object) {
    addPlayerData(object.data);
    console.log(JSON.stringify(object.data));
    GM_xmlhttpRequest({
        method: "POST",
        url: oLogInstanceUrl + "api/userscript/" + object.endpoint,
        data: JSON.stringify(object.data),
        headers: {
            "Content-Type": "application/json"
        },
        onload: function(response) {
            console.log("load");
        },
        onerror: function(response) {
            console.log("error");
        }
    });
}

function addPlayerData(data) {
    data.serverGroup = getWindowVariable("constants.language");
    data.universe = getWindowVariable("constants.name");
    data.playerId = getWindowVariable("playerId");
    data.playerName = getWindowVariable("playerName");
}

/**
 * Returns a global variable.
 *
 * Needed because a @grant other than none puts the script
 * in a separate scope.
 *
 * @param {string} name The name of the global variable.
 */
function getWindowVariable(name) {
    return window.eval(name);
}

function showSuccessMessage(message) {
    getWindowVariable("fadeBox")(message, false);
}

function showErrorMessage(message) {
    getWindowVariable("fadeBox")(message, true);
}<|endoftext|>


<commit_before>var Period = require('./Period');
var GoalManager = require('./GoalManager');
var PenaltyShootout = require('./PenaltyShootout');
var Seed = require('./Seed');
var Time = require('./Time');

/*
 * All encompassing class to create a football match.
 */
function Match(options) {
    // Instances
    this.teamA = options.teamA; // Team
    this.teamB = options.teamB; // Team

    var paramsGoalManager = {
        teamA: this.teamA,
        teamB: this.teamB
    };

    this.goalManager = new GoalManager(paramsGoalManager);
    this.normalTimeGoals = new GoalManager(paramsGoalManager);
    this.extraTimeGoals = new GoalManager(paramsGoalManager);
    this._everyGoal = new GoalManager(paramsGoalManager);

    this.firstHalf; // Period
    this.secondHalf; // Period
    this.extraTimeFirstHalf; // Period
    this.extraTimeSecondHalf; // Period
    this.penaltyShootout; // PenaltyShootout

    // Variables
    this.extraTimeEnabled = options.extraTime || false;
    this.penaltyShootoutEnabled = options.penaltyShootout || false;
    this.seed = new Seed()
        .setValue(options.seed || Date.now());
    this.wentToExtraTime = false;
    this.wentToPenaltyShootout = false;
    this.score = [];
    this.penaltyShootoutScore = [];
    this.winner = null; // Team or null if draw
    this.startDate = options.startDate || new Date();
    this.finishDate;

    //
    this._createHalfInstances();
}

(function (proto_) {

    /*
     * Simulates the whole match.
     * Returns the match score.
     */
    proto_.simulate = function () {
        this._simulateHalfs();
        this._appendGoals();
        this._checkOtherPeriods();
        this._setScores();
        this._calculateWinner();
        this.finishDate = this.getFinishDate();

        return this.score;
    };

    /*
     * Gets the finish time.
     */
    proto_.getFinishDate = function () {
        if (!this.wentToExtraTime && !this.wentToPenaltyShootout) {
            return this.secondHalf.finishDate;
        } else if (this.wentToExtraTime && !this.wentToPenaltyShootout) {
            return this.extraTimeSecondHalf.finishDate;
        }

        return this.penaltyShootout.finishDate;
    };

    /*
     * Sets the local score properties with the scores from the goal managers.
     */
    proto_._setScores = function () {
        this.score = this.goalManager.getScore();
        this.penaltyShootoutScore = this.penaltyShootout.goalManager.getScore();

        this._everyGoal.append(this.goalManager);
    };

    /*
     * Checks to see if the match is a draw and the other periods are enabled.
     * If so, it'll attach the goals of those periods onto the match.
     */
    proto_._checkOtherPeriods = function () {
        this._checkExtraTime();
        this._checkPenaltyShootout();
    };

    proto_._checkExtraTime = function () {
        if (this.extraTimeEnabled && this._isDraw()) {
            this.wentToExtraTime = true;
            this.goalManager.append(this.extraTimeGoals);
        }
    };

    proto_._checkPenaltyShootout = function () {
        if (this.penaltyShootoutEnabled && this._isDraw()) {
            this.wentToPenaltyShootout = true;
            this.penaltyShootout.simulate();
            this._everyGoal.append(this.penaltyShootout.goalManager);
        }
    };

    /*
     * Runs the simulate method on each half.
     */
    proto_._simulateHalfs = function () {
        this.firstHalf.simulate();
        this.secondHalf.simulate();
        this.extraTimeFirstHalf.simulate();
        this.extraTimeSecondHalf.simulate();
    };

    /*
     * Appends the goals from each half, to their respective goal managers.
     */
    proto_._appendGoals = function () {
        this.normalTimeGoals.append(this.firstHalf.goalManager);
        this.normalTimeGoals.append(this.secondHalf.goalManager);
        this.extraTimeGoals.append(this.extraTimeFirstHalf.goalManager);
        this.extraTimeGoals.append(this.extraTimeSecondHalf.goalManager);

        this.goalManager.append(this.normalTimeGoals);
    };

    /*
     * Finds the winner of the match and puts their Team object in #winner.
     * Remains at null if it's a draw.
     */
    proto_._calculateWinner = function () {
        this.winner = this._everyGoal.getWinner();
    };

    /*
     * Creates the instances for each half in the game.
     */
    proto_._createHalfInstances = function () {
        this.firstHalf = this._newHalf({
            seed: 'firstHalf',
            length: 45,
            endOfPrevious: this.startDate,
            lengthAfterPrevious: 0
        });

        this.secondHalf = this._newHalf({
            seed: 'secondHalf',
            length: 45,
            endOfPrevious: this.firstHalf.finishDate,
            lengthAfterPrevious: 15
        });

        this.extraTimeFirstHalf = this._newHalf({
            seed: 'extraTimeFirstHalf',
            length: 15,
            endOfPrevious: this.secondHalf.finishDate,
            lengthAfterPrevious: 5
        });

        this.extraTimeSecondHalf = this._newHalf({
            seed: 'extraTimeSecondHalf',
            length: 15,
            endOfPrevious: this.extraTimeFirstHalf.finishDate,
            lengthAfterPrevious: 5
        });

        this.penaltyShootout = this._createPenaltyShootout({
            endOfPrevious: this.extraTimeSecondHalf.finishDate,
            lengthAfterPrevious: 5
        });
    };

    /*
     * Creates a new half (instance of Period).
     */
    proto_._newHalf = function (options) {
        var startDate = this._dateMinutesAfter(
            options.endOfPrevious,
            options.lengthAfterPrevious
        );

        return new Period({
            teamA: this.teamA,
            teamB: this.teamB,
            timeLength: new Time(options.length * 60000),
            seed: this.seed.clone().append(options.seed),
            startDate: startDate
        });
    };

    /*
     * Creates a penalty shootout.
     */
    proto_._createPenaltyShootout = function (options) {
        var startDate = this._dateMinutesAfter(
            options.endOfPrevious,
            options.lengthAfterPrevious
        );

        return new PenaltyShootout({
            teamA: this.teamA,
            teamB: this.teamB,
            seed: this.seed.clone().append(options.seed),
            startDate: startDate
        });
    }

    /*
     * Returns a `Date` that is so many minutes after the previous start time.
     */
    proto_._dateMinutesAfter = function (previousDate, minutes) {
        var date = new Date(previousDate.getTime());
        var previousMinutes = previousDate.getMinutes();

        date.setMinutes(previousMinutes + minutes);

        return date;
    };

    /*
     * Returns a boolean, whether the match is a draw or not.
     */
    proto_._isDraw = function () {
        var score = this.goalManager.getScore();

        return score[0] === score[1];
    };

}(Match.prototype));

module.exports = Match;
<commit_msg>Adds missing semi colon<commit_after>var Period = require('./Period');
var GoalManager = require('./GoalManager');
var PenaltyShootout = require('./PenaltyShootout');
var Seed = require('./Seed');
var Time = require('./Time');

/*
 * All encompassing class to create a football match.
 */
function Match(options) {
    // Instances
    this.teamA = options.teamA; // Team
    this.teamB = options.teamB; // Team

    var paramsGoalManager = {
        teamA: this.teamA,
        teamB: this.teamB
    };

    this.goalManager = new GoalManager(paramsGoalManager);
    this.normalTimeGoals = new GoalManager(paramsGoalManager);
    this.extraTimeGoals = new GoalManager(paramsGoalManager);
    this._everyGoal = new GoalManager(paramsGoalManager);

    this.firstHalf; // Period
    this.secondHalf; // Period
    this.extraTimeFirstHalf; // Period
    this.extraTimeSecondHalf; // Period
    this.penaltyShootout; // PenaltyShootout

    // Variables
    this.extraTimeEnabled = options.extraTime || false;
    this.penaltyShootoutEnabled = options.penaltyShootout || false;
    this.seed = new Seed()
        .setValue(options.seed || Date.now());
    this.wentToExtraTime = false;
    this.wentToPenaltyShootout = false;
    this.score = [];
    this.penaltyShootoutScore = [];
    this.winner = null; // Team or null if draw
    this.startDate = options.startDate || new Date();
    this.finishDate;

    //
    this._createHalfInstances();
}

(function (proto_) {

    /*
     * Simulates the whole match.
     * Returns the match score.
     */
    proto_.simulate = function () {
        this._simulateHalfs();
        this._appendGoals();
        this._checkOtherPeriods();
        this._setScores();
        this._calculateWinner();
        this.finishDate = this.getFinishDate();

        return this.score;
    };

    /*
     * Gets the finish time.
     */
    proto_.getFinishDate = function () {
        if (!this.wentToExtraTime && !this.wentToPenaltyShootout) {
            return this.secondHalf.finishDate;
        } else if (this.wentToExtraTime && !this.wentToPenaltyShootout) {
            return this.extraTimeSecondHalf.finishDate;
        }

        return this.penaltyShootout.finishDate;
    };

    /*
     * Sets the local score properties with the scores from the goal managers.
     */
    proto_._setScores = function () {
        this.score = this.goalManager.getScore();
        this.penaltyShootoutScore = this.penaltyShootout.goalManager.getScore();

        this._everyGoal.append(this.goalManager);
    };

    /*
     * Checks to see if the match is a draw and the other periods are enabled.
     * If so, it'll attach the goals of those periods onto the match.
     */
    proto_._checkOtherPeriods = function () {
        this._checkExtraTime();
        this._checkPenaltyShootout();
    };

    proto_._checkExtraTime = function () {
        if (this.extraTimeEnabled && this._isDraw()) {
            this.wentToExtraTime = true;
            this.goalManager.append(this.extraTimeGoals);
        }
    };

    proto_._checkPenaltyShootout = function () {
        if (this.penaltyShootoutEnabled && this._isDraw()) {
            this.wentToPenaltyShootout = true;
            this.penaltyShootout.simulate();
            this._everyGoal.append(this.penaltyShootout.goalManager);
        }
    };

    /*
     * Runs the simulate method on each half.
     */
    proto_._simulateHalfs = function () {
        this.firstHalf.simulate();
        this.secondHalf.simulate();
        this.extraTimeFirstHalf.simulate();
        this.extraTimeSecondHalf.simulate();
    };

    /*
     * Appends the goals from each half, to their respective goal managers.
     */
    proto_._appendGoals = function () {
        this.normalTimeGoals.append(this.firstHalf.goalManager);
        this.normalTimeGoals.append(this.secondHalf.goalManager);
        this.extraTimeGoals.append(this.extraTimeFirstHalf.goalManager);
        this.extraTimeGoals.append(this.extraTimeSecondHalf.goalManager);

        this.goalManager.append(this.normalTimeGoals);
    };

    /*
     * Finds the winner of the match and puts their Team object in #winner.
     * Remains at null if it's a draw.
     */
    proto_._calculateWinner = function () {
        this.winner = this._everyGoal.getWinner();
    };

    /*
     * Creates the instances for each half in the game.
     */
    proto_._createHalfInstances = function () {
        this.firstHalf = this._newHalf({
            seed: 'firstHalf',
            length: 45,
            endOfPrevious: this.startDate,
            lengthAfterPrevious: 0
        });

        this.secondHalf = this._newHalf({
            seed: 'secondHalf',
            length: 45,
            endOfPrevious: this.firstHalf.finishDate,
            lengthAfterPrevious: 15
        });

        this.extraTimeFirstHalf = this._newHalf({
            seed: 'extraTimeFirstHalf',
            length: 15,
            endOfPrevious: this.secondHalf.finishDate,
            lengthAfterPrevious: 5
        });

        this.extraTimeSecondHalf = this._newHalf({
            seed: 'extraTimeSecondHalf',
            length: 15,
            endOfPrevious: this.extraTimeFirstHalf.finishDate,
            lengthAfterPrevious: 5
        });

        this.penaltyShootout = this._createPenaltyShootout({
            endOfPrevious: this.extraTimeSecondHalf.finishDate,
            lengthAfterPrevious: 5
        });
    };

    /*
     * Creates a new half (instance of Period).
     */
    proto_._newHalf = function (options) {
        var startDate = this._dateMinutesAfter(
            options.endOfPrevious,
            options.lengthAfterPrevious
        );

        return new Period({
            teamA: this.teamA,
            teamB: this.teamB,
            timeLength: new Time(options.length * 60000),
            seed: this.seed.clone().append(options.seed),
            startDate: startDate
        });
    };

    /*
     * Creates a penalty shootout.
     */
    proto_._createPenaltyShootout = function (options) {
        var startDate = this._dateMinutesAfter(
            options.endOfPrevious,
            options.lengthAfterPrevious
        );

        return new PenaltyShootout({
            teamA: this.teamA,
            teamB: this.teamB,
            seed: this.seed.clone().append(options.seed),
            startDate: startDate
        });
    };

    /*
     * Returns a `Date` that is so many minutes after the previous start time.
     */
    proto_._dateMinutesAfter = function (previousDate, minutes) {
        var date = new Date(previousDate.getTime());
        var previousMinutes = previousDate.getMinutes();

        date.setMinutes(previousMinutes + minutes);

        return date;
    };

    /*
     * Returns a boolean, whether the match is a draw or not.
     */
    proto_._isDraw = function () {
        var score = this.goalManager.getScore();

        return score[0] === score[1];
    };

}(Match.prototype));

module.exports = Match;
<|endoftext|>


<commit_before>
var gulp = require('gulp');
var parseArgs = require('minimist');

var options = parseArgs(process.argv, {default: {
    force: false, bucket: null, profile: null}});

if (options.profile != null) {
    console.log("Using AWS profile " + options.profile);
    process.env['AWS_DEFAULT_PROFILE'] = options.profile;
}

var awspublish = require('gulp-awspublish');
var mergeStream = require('merge-stream');
var rename = require('gulp-rename');
var rimraf = require('rimraf');
var sprintf = require('sprintf');

/*
 * Publish the given source files to AWS
 * with the given headers
 */
function publishToS3(src, headers, folder, bucket) {

  if (!folder) {
    folder = "";
  }

  if (options.force) {
     rimraf.sync('./.awspublish-*');
  }

  // Config object is passed to
  // new AWS.S3() as documented here:
  //   http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#constructor-property

  if (options.bucket != null) {
      bucket = options.bucket;
  }

  var publisher = createPublisher(bucket);

  var publishStream = function(stream, headers) {
    return stream
      .pipe(rename(function(path) {
        path.dirname += "";
      }))
      .pipe(publisher.publish(headers, {force: options.force, simulate: false}))
      .pipe(publisher.cache())
      .pipe(awspublish.reporter());
  };

  return publishStream(gulp.src(src), headers);
}

/*
 * Create the AWS publisher
 */
function createPublisher(bucket) {
  // Access keys etc. are not needed in config as they
  // should be defined in the AWS credentials file.
  //
  // See:
  //   http://docs.aws.amazon.com/AWSJavaScriptSDK/guide/node-configuring.html
  //   https://www.npmjs.com/package/gulp-awspublish

  var config = {
    params: {
      'Bucket': bucket
    }
  };
  var publisher = awspublish.create(config);
  return publisher;
}

/*
 * Publish all entry points assets
 * (assets without rev urls)
 */
var epStream;
function publishEntryPoints(bucket, sourceFolder, targetFolder) {

  if (!sourceFolder) {
    sourceFolder = 'dist';
  }

  epStream = mergeStream(
    publishToS3(['./' + sourceFolder + '/**/*.html'], {}, targetFolder, bucket),
    publishToS3(['./' + sourceFolder + '/**/embed.js'], {}, targetFolder, bucket),
    publishToS3(['./' + sourceFolder + '/**/resize.js'], {}, targetFolder, bucket),
    publishToS3(['./' + sourceFolder + '/*.{png,ico}'], {}, targetFolder, bucket)
  );
  return epStream;
}

/*
 * Publish all hashed assets
 * (assets with rev urls)
 *
 * targetFolder -- folder to publish into
 * maxAge -- expiry age for header
 */
var hashedStream;
function publishHashedAssets(bucket, sourceFolder, targetFolder, maxAge) {

  if (!isFinite(maxAge)) {
    maxAge = 3600;
  }

  console.log("Using max-age " + maxAge);

  if (!sourceFolder) {
    sourceFolder = 'dist';
  }

  var headers = {
    'Cache-Control': sprintf('max-age=%d, public', maxAge)
  };
  hashedStream = publishToS3([
      './' + sourceFolder + '/**',            //
      '!./' + sourceFolder + '/**/*.html',    // note that
      '!./' + sourceFolder + '/**/embed.js',  // these
      '!./' + sourceFolder + '/**/resize.js', // are
      '!./' + sourceFolder + '/*.{png,ico}'], // exclusions
       headers, targetFolder, bucket);
  return hashedStream;
}

/*
 * Write publisher cache to speed up uploads
 */
function writeCache() {
  var publisher = createPublisher();
  return mergeStream(epStream, hashedStream)
    .pipe(publisher.cache());
}

module.exports.publishHashedAssets = publishHashedAssets;
module.exports.publishEntryPoints = publishEntryPoints;
module.exports.writeCache = writeCache;
<commit_msg>Remove the separate writeCache function<commit_after>
var gulp = require('gulp');
var parseArgs = require('minimist');

var options = parseArgs(process.argv, {default: {
    force: false, bucket: null, profile: null}});

if (options.profile != null) {
    console.log("Using AWS profile " + options.profile);
    process.env['AWS_DEFAULT_PROFILE'] = options.profile;
}

var awspublish = require('gulp-awspublish');
var mergeStream = require('merge-stream');
var rename = require('gulp-rename');
var rimraf = require('rimraf');
var sprintf = require('sprintf');

/*
 * Publish the given source files to AWS
 * with the given headers
 */
function publishToS3(src, headers, folder, bucket) {

  if (!folder) {
    folder = "";
  }

  if (options.force) {
     rimraf.sync('./.awspublish-*');
  }

  // Config object is passed to
  // new AWS.S3() as documented here:
  //   http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#constructor-property

  if (options.bucket != null) {
      bucket = options.bucket;
  }

  var publisher = createPublisher(bucket);

  var publishStream = function(stream, headers) {
    return stream
      .pipe(rename(function(path) {
        path.dirname += "";
      }))
      .pipe(publisher.publish(headers, {force: options.force, simulate: false}))
      .pipe(publisher.cache())
      .pipe(awspublish.reporter());
  };

  return publishStream(gulp.src(src), headers);
}

/*
 * Create the AWS publisher
 */
function createPublisher(bucket) {
  // Access keys etc. are not needed in config as they
  // should be defined in the AWS credentials file.
  //
  // See:
  //   http://docs.aws.amazon.com/AWSJavaScriptSDK/guide/node-configuring.html
  //   https://www.npmjs.com/package/gulp-awspublish

  var config = {
    params: {
      'Bucket': bucket
    }
  };
  var publisher = awspublish.create(config);
  return publisher;
}

/*
 * Publish all entry points assets
 * (assets without rev urls)
 */
function publishEntryPoints(bucket, sourceFolder, targetFolder) {

  if (!sourceFolder) {
    sourceFolder = 'dist';
  }

  return mergeStream(
    publishToS3(['./' + sourceFolder + '/**/*.html'], {}, targetFolder, bucket),
    publishToS3(['./' + sourceFolder + '/**/embed.js'], {}, targetFolder, bucket),
    publishToS3(['./' + sourceFolder + '/**/resize.js'], {}, targetFolder, bucket),
    publishToS3(['./' + sourceFolder + '/*.{png,ico}'], {}, targetFolder, bucket)
  );
}

/*
 * Publish all hashed assets
 * (assets with rev urls)
 *
 * targetFolder -- folder to publish into
 * maxAge -- expiry age for header
 */
function publishHashedAssets(bucket, sourceFolder, targetFolder, maxAge) {

  if (!isFinite(maxAge)) {
    maxAge = 3600;
  }

  console.log("Using max-age " + maxAge);

  if (!sourceFolder) {
    sourceFolder = 'dist';
  }

  var headers = {
    'Cache-Control': sprintf('max-age=%d, public', maxAge)
  };

  return publishToS3([
      './' + sourceFolder + '/**',            //
      '!./' + sourceFolder + '/**/*.html',    // note that
      '!./' + sourceFolder + '/**/embed.js',  // these
      '!./' + sourceFolder + '/**/resize.js', // are
      '!./' + sourceFolder + '/*.{png,ico}'], // exclusions
       headers, targetFolder, bucket);
}

/*
 * Write publisher cache to speed up uploads
 */
//function writeCache() {
//  var publisher = createPublisher();
//  console.log(epStream, hashedStream)
//  return mergeStream(epStream, hashedStream)
    //.pipe(publisher.cache());
//}

module.exports.publishHashedAssets = publishHashedAssets;
module.exports.publishEntryPoints = publishEntryPoints;
//module.exports.writeCache = writeCache;
<|endoftext|>


<commit_before>'use strict';

YUI.add('juju-topology-viewport', function(Y) {
  var views = Y.namespace('juju.views'),
      models = Y.namespace('juju.models'),
      d3ns = Y.namespace('d3');

  /**
   * Utility function to get a number from a computed style.
   * @method styleToNumber
   * @return {Int}
   */
  function styleToNumber(selector, style, defaultSize) {
    style = style || 'height';
    defaultSize = defaultSize || 0;
    return parseInt(Y.one(selector).getComputedStyle(style) || defaultSize,
                    10);
  }

  /**
   * @module topology-service
   * @class Service
   * @namespace juju.views
   **/
  var ViewportModule = Y.Base.create('ViewportModule', d3ns.Module, [], {

    events: {
      yui: {
        windowresize: 'resized'
      }
    },

    initializer: function(options) {
      ViewportModule.superclass.constructor.apply(this, arguments);
    },

    render: function() {
      var topology = this.get('component'),
          value = 100,
          currentScale = topology.get('scale');

      ViewportModule.superclass.render.apply(this, arguments);
      // Build a slider to control zoom level
      if (currentScale) {
        value = currentScale * 100;
      }
      var slider = new Y.Slider({
        min: 25,
        max: 200,
        value: value
      });
      slider.render('#slider-parent');
      slider.after('valueChange', function(evt) {
        // Don't fire a zoom if there's a zoom event already in progress;
        // that will run rescale for us.
        if (d3.event && d3.event.scale && d3.event.translate) {
          return;
        }
        topology._fire_zoom((evt.newVal - evt.prevVal) / 100);
      });
      this.slider = slider;

      return this;
    },

    update: function() {
      ViewportModule.superclass.update.apply(this, arguments);
      return this;
    },

    /**
     * Event handler for windowresize events.
     *
     * Properly scale the component to take advantage of all the space
     * provided by the viewport.
     *
     * @method resized
     **/
    resized: function(evt) {
      // start with some reasonable defaults
      var topology = this.get('component'),
          vis = topology.vis,
          container = this.get('container'),
          viewport_height = '100%',
          viewport_width = '100%',
          svg = container.one('svg'),
          width = 800,
          height = 600;

      if (container.get('winHeight') &&
          Y.one('#overview-tasks') &&
          Y.one('.navbar')) {
        // Attempt to get the viewport height minus the navbar at top and
        // control bar at the bottom. Use Y.one() to ensure that the
        // container is attached first (provides some sensible defaults)

        viewport_height = container.get('winHeight') -
            styleToNumber('#overview-tasks', 'height', 22) - //XXX
            styleToNumber('.navbar', 'height', 87) - 1; //XXX

        // Attempt to get the viewport width from the overview-tasks bar.
        viewport_width = styleToNumber('#viewport', 'width', 800); //XXX

        // Make sure we don't get sized any smaller than 800x600
        viewport_height = Math.max(viewport_height, height);
        viewport_width = Math.max(viewport_width, width);
      }
      // Set the svg sizes.
      svg.setAttribute('width', viewport_width)
        .setAttribute('height', viewport_height);

      // Get the resulting computed sizes (in the case of 100%).
      width = parseInt(svg.getComputedStyle('width'), 10);
      height = parseInt(svg.getComputedStyle('height'), 10);

      // Set the internal rect's size.
      svg.one('rect')
        .setAttribute('width', width)
        .setAttribute('height', height);
      container.one('#canvas').setStyle('height', height);
      container.one('#canvas').setStyle('width', width);

      // Reset the scale parameters
      topology.xscale.domain([-width / 2, width / 2])
        .range([0, width]);
      topology.yscale.domain([-height / 2, height / 2])
        .range([height, 0]);

      topology.width = width;
      topology.height = height;
    }

  }, {
    ATTRS: {}
  });
  views.ViewportModule = ViewportModule;
}, '0.1.0', {
  requires: [
    'd3',
    'd3-components',
    'node',
    'event',
    'juju-models',
    'juju-env'
  ]
});
<commit_msg>removed undescribed return from docstring<commit_after>'use strict';

YUI.add('juju-topology-viewport', function(Y) {
  var views = Y.namespace('juju.views'),
      models = Y.namespace('juju.models'),
      d3ns = Y.namespace('d3');

  /**
   * Utility function to get a number from a computed style.
   * @method styleToNumber
   */
  function styleToNumber(selector, style, defaultSize) {
    style = style || 'height';
    defaultSize = defaultSize || 0;
    return parseInt(Y.one(selector).getComputedStyle(style) || defaultSize,
                    10);
  }

  /**
   * @module topology-service
   * @class Service
   * @namespace juju.views
   **/
  var ViewportModule = Y.Base.create('ViewportModule', d3ns.Module, [], {

    events: {
      yui: {
        windowresize: 'resized'
      }
    },

    initializer: function(options) {
      ViewportModule.superclass.constructor.apply(this, arguments);
    },

    render: function() {
      var topology = this.get('component'),
          value = 100,
          currentScale = topology.get('scale');

      ViewportModule.superclass.render.apply(this, arguments);
      // Build a slider to control zoom level
      if (currentScale) {
        value = currentScale * 100;
      }
      var slider = new Y.Slider({
        min: 25,
        max: 200,
        value: value
      });
      slider.render('#slider-parent');
      slider.after('valueChange', function(evt) {
        // Don't fire a zoom if there's a zoom event already in progress;
        // that will run rescale for us.
        if (d3.event && d3.event.scale && d3.event.translate) {
          return;
        }
        topology._fire_zoom((evt.newVal - evt.prevVal) / 100);
      });
      this.slider = slider;

      return this;
    },

    update: function() {
      ViewportModule.superclass.update.apply(this, arguments);
      return this;
    },

    /**
     * Event handler for windowresize events.
     *
     * Properly scale the component to take advantage of all the space
     * provided by the viewport.
     *
     * @method resized
     **/
    resized: function(evt) {
      // start with some reasonable defaults
      var topology = this.get('component'),
          vis = topology.vis,
          container = this.get('container'),
          viewport_height = '100%',
          viewport_width = '100%',
          svg = container.one('svg'),
          width = 800,
          height = 600;

      if (container.get('winHeight') &&
          Y.one('#overview-tasks') &&
          Y.one('.navbar')) {
        // Attempt to get the viewport height minus the navbar at top and
        // control bar at the bottom. Use Y.one() to ensure that the
        // container is attached first (provides some sensible defaults)

        viewport_height = container.get('winHeight') -
            styleToNumber('#overview-tasks', 'height', 22) - //XXX
            styleToNumber('.navbar', 'height', 87) - 1; //XXX

        // Attempt to get the viewport width from the overview-tasks bar.
        viewport_width = styleToNumber('#viewport', 'width', 800); //XXX

        // Make sure we don't get sized any smaller than 800x600
        viewport_height = Math.max(viewport_height, height);
        viewport_width = Math.max(viewport_width, width);
      }
      // Set the svg sizes.
      svg.setAttribute('width', viewport_width)
        .setAttribute('height', viewport_height);

      // Get the resulting computed sizes (in the case of 100%).
      width = parseInt(svg.getComputedStyle('width'), 10);
      height = parseInt(svg.getComputedStyle('height'), 10);

      // Set the internal rect's size.
      svg.one('rect')
        .setAttribute('width', width)
        .setAttribute('height', height);
      container.one('#canvas').setStyle('height', height);
      container.one('#canvas').setStyle('width', width);

      // Reset the scale parameters
      topology.xscale.domain([-width / 2, width / 2])
        .range([0, width]);
      topology.yscale.domain([-height / 2, height / 2])
        .range([height, 0]);

      topology.width = width;
      topology.height = height;
    }

  }, {
    ATTRS: {}
  });
  views.ViewportModule = ViewportModule;
}, '0.1.0', {
  requires: [
    'd3',
    'd3-components',
    'node',
    'event',
    'juju-models',
    'juju-env'
  ]
});
<|endoftext|>


<commit_before>(function (global, factory) {
  if (typeof module === "object" && typeof module.exports === "object") {
    // CMD
    // all dependencies need to passed as parameters manually,
    // will not require here.
    module.exports = factory;
  } else if (typeof define === 'function' && define.amd) {
    // AMD. Register as sk
    // TODO how to define the jquery plugin here?
    define('sk', ['jsface', 'jquery'], factory);
  } else {
    // in browser, global is window.
    // all dependencies were loaded already.
    // bootstrap and jquery's plugin are all attached to jquery,
    // expose $sk and all components to window.
    factory(global, jsface, jQuery);
  }
}(typeof window !== "undefined" ? window : this, function (window, jsface, jQuery, DO_NOT_EXPOSE_SK_TO_GLOBAL) {
  var _sk = window.$sk;
  var $sk = {};
  window.$sk = $sk;

  $sk.noConflict = function () {
    window.$sk = _sk;
    return $sk;
  };

  // insert all source code here
  // sk body here
  $sk.a = function (array) {
    return jQuery.isArray(array) ? array : [];
  };

  //just true return true, other return false
  $sk.b = function (boolean) {
    return String(boolean) == "true" && boolean != "true" && boolean;
  };

  $sk.d = function (date, defaultDate) {
    var rtnDate = defaultDate ? defaultDate : new Date();
    return (date instanceof Date) ? (date.toString() == "Invalid Date" ? rtnDate : date) : rtnDate;
  };

  //can be to Number than return value of number, other return 0
  $sk.n = function (number) {
    return isNaN(Number(number)) ? 0 : Number(number);
  };

  $sk.inValid = function (obj) {
    if (obj == undefined || obj == null || isNaN(obj) ) {
      return false;
    } else {
      return true;
    }
  };

  $sk.o = function (object) {
    return jQuery.isPlainObject(object) ? object : {};
  };

  $sk.s = function (string) {
    return String(string);
  };

  // reset to old $sk
  if (typeof DO_NOT_EXPOSE_SK_TO_GLOBAL != 'undefined' && DO_NOT_EXPOSE_SK_TO_GLOBAL == true) {
    window.$sk = _sk;
  }
  return $sk;
}));
<commit_msg>Update sk.js<commit_after>(function (global, factory) {
  if (typeof module === "object" && typeof module.exports === "object") {
    // CMD
    // all dependencies need to passed as parameters manually,
    // will not require here.
    module.exports = factory;
  } else if (typeof define === 'function' && define.amd) {
    // AMD. Register as sk
    // TODO how to define the jquery plugin here?
    define('sk', ['jsface', 'jquery'], factory);
  } else {
    // in browser, global is window.
    // all dependencies were loaded already.
    // bootstrap and jquery's plugin are all attached to jquery,
    // expose $sk and all components to window.
    factory(global, jsface, jQuery);
  }
}(typeof window !== "undefined" ? window : this, function (window, jsface, jQuery, DO_NOT_EXPOSE_SK_TO_GLOBAL) {
  var _sk = window.$sk;
  var $sk = {};
  window.$sk = $sk;

  $sk.noConflict = function () {
    window.$sk = _sk;
    return $sk;
  };

  // insert all source code here
  // sk body here
  $sk.a = function (array) {
    return jQuery.isArray(array) ? array : [];
  };

  //just true return true, other return false
  $sk.b = function (boolean) {
    return String(boolean) == "true" && boolean != "true" && boolean;
  };

  $sk.d = function (date, defaultDate) {
    var rtnDate = defaultDate ? defaultDate : new Date();
    return (date instanceof Date) ? (date.toString() == "Invalid Date" ? rtnDate : date) : rtnDate;
  };

  //can be to Number than return value of number, other return 0
  $sk.n = function (number) {
    return isNaN(Number(number)) ? 0 : Number(number);
  };

  $sk.inValid = function (obj) {
    if (obj == undefined || obj == null || isNaN(obj) || (obj instanceof Date && obj == "Invalid Date")) {
      return false;
    } else {
      return true;
    }
  };

  $sk.o = function (object) {
    return jQuery.isPlainObject(object) ? object : {};
  };

  $sk.s = function (string) {
    return String(string);
  };

  // reset to old $sk
  if (typeof DO_NOT_EXPOSE_SK_TO_GLOBAL != 'undefined' && DO_NOT_EXPOSE_SK_TO_GLOBAL == true) {
    window.$sk = _sk;
  }
  return $sk;
}));
<|endoftext|>


<commit_before>var util = require('util');
var youtube_node = require('youtube-node');
var AuthDetails = require("./auth.json");

function YoutubePlugin () {
	this.youtube = new youtube_node();
	this.youtube.setKey(AuthDetails.youtube_api_key);
};

YoutubePlugin.prototype.respond = function (query, channel, bot) {
	this.youtube.search(query, 1, function(error, result) {
				if (!result || !result.items || result.items.length < 1) {
					bot.sendMessage(channel, "I couldn't find a video for: " + query);
				} else {
					bot.sendMessage(channel, "http://www.youtube.com/watch?v=" + result.items[0].id.videoId );
				}
		});
};

module.exports = YoutubePlugin;
<commit_msg>Update<commit_after>var util = require('util');
var youtube_node = require('youtube-node');
var AuthDetails = require("./config.json");

function YoutubePlugin () {
	this.youtube = new youtube_node();
	this.youtube.setKey(AuthDetails.youtube_api_key);
};

YoutubePlugin.prototype.respond = function (query, channel, bot) {
	this.youtube.search(query, 1, function(error, result) {
				if (!result || !result.items || result.items.length < 1) {
					bot.sendMessage(channel, "I couldn't find a video for: " + query);
				} else {
					bot.sendMessage(channel, "http://www.youtube.com/watch?v=" + result.items[0].id.videoId );
				}
		});
};

module.exports = YoutubePlugin;
<|endoftext|>


<commit_before>;(function(exports) {
  exports.ui = {};
  exports.ui.tutor = {
    hide: function() {
      $('#tutor').hide();
    },

    displayCode: function(code) {
      $('#tutor').html("Write " + code + " below");
    },

    displayMessage: function(text) {
      $('#tutor').text(text);
    }
  };

  exports.ui.tipper = {
    displayMessage: function(text) {
      $('#tips').text(text);
    }
  };
})(typeof exports === 'undefined' ? this : exports)
<commit_msg>Remove tipper UI.<commit_after>;(function(exports) {
  exports.ui = {};
  exports.ui.tutor = {
    hide: function() {
      $('#tutor').hide();
    },

    displayCode: function(code) {
      $('#tutor').html("Write " + code + " below");
    },

    displayMessage: function(text) {
      $('#tutor').text(text);
    }
  };
})(typeof exports === 'undefined' ? this : exports)
<|endoftext|>


<commit_before>var http        = require("http");
var ip          = require("ip");
var request     = require("request");
var hostaddress = ip.address();

// remove the first two elements as they contain the node and vf commands
//process.argv.pop()
//process.argv.pop()

process.argv.shift()
process.argv.shift()
var firstArg =  process.argv.shift()

var useHost = hostaddress
var usePort = 80
if (firstArg == '--host') {
    useHost = process.argv.shift()
    firstArg =  process.argv.shift()
}
//console.log("Connecting to: " + useHost + ":" + usePort);

//console.log (process.argv)
if (!firstArg) {
    console.log(`
VisiFile commands:

> vf
This command. Enter this to see this menu. If you are a developer
then you may have enter "vf" as "node src/vf.js"

> vf test
See if VisiFile is installed on your local computer on port 80

> vf ls
See which computers have VisiFile installed on them. Example
output may be:
User: root, 192.168.0.101:80
: in which case you can:
1) enter "vf --host 192.168.0.101:80 main" at the command prompt
2) enter 192.168.0.101:80 into a web Browser to view VisiFile
3) enter 192.168.0.101:80/main into a Rest API client such as Postman

> vf drivers
Show the available drivers

> vf --host 192.168.0.101:80 drivers
Show the drivers on the machine located at 192.168.0.101:80

> vf home
Show the main details of the running VisiFile
`)

} else if (firstArg == 'ls') {

    getListOfHosts(function(serversReturned) {
        if (serversReturned.length == 0) {
            console.log("No VisiFile Servers started on your Intranet")
        } else {
            for (var x = 0; x < serversReturned.length ; x++) {
                console.log("User: "+serversReturned[x].username + ", " + serversReturned[x].internal_host + ":"+serversReturned[x].internal_port)
            }
        }
    })

} else if (firstArg == 'main') {
    findMainServer(function(serverName) {
        console.log(serverName)
    })

} else {
    process.argv.unshift(firstArg)
    //options.query.a = process.argv

    var args = process.argv

    //console.log("Args JSON: " + JSON.stringify(args,null,2))

    var args2 = encodeURI(JSON.stringify(args))
    //console.log("Args seralized: " + args2)

    var options = {
      host: extractHostname(useHost),
      port: getPort(useHost),
      path: '/vf?a=' + args2,
      method: 'GET'
    };

    var req = http.request(options, function(res) {
      res.setEncoding('utf8');
      res.on('data', function (chunk) {
          var result = JSON.parse(chunk)
        console.log(result.OK);
      });
    });

    req.on('error', function(e) {
      console.log('problem with request: ' + e.message);
    });

    req.end();
}

function serialize(obj) {
  var str = [];
  for (var p in obj)
    if (obj.hasOwnProperty(p)) {
      str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
    }
  return str.join("&");
}

function lsFn(servers, index, callbackFn) {
    //console.log("Trying lookup server: " + servers[index])

    var remoteServerUrl =   'http://' + servers[index]  +
                            "/get_intranet_servers?time=" + new Date().getTime();

    request({
        uri: remoteServerUrl,
        method: "GET",
        timeout: 10000,
        agent: false,
        followRedirect: true,
        maxRedirects: 10
  },
  function(error, response, body) {
      var servers2 = servers
      if (error) {
          console.log("Error opening central server: " + error);
          var nextIndex = index + 1
          if (nextIndex < servers2.length) {
              lsFn(servers2, index + 1, callbackFn)
          }
    } else {
        var servers2 = []
        var returned= eval( "(" + body + ")");
        for (var i = 0 ; i < returned.allServers.length; i++) {
            //console.log('got server ' + i)
            //console.log(JSON.stringify(returned.allServers[i],null,2))
            var tt = new Object();
            tt.username = returned.allServers[i].client_user_name;
            tt.internal_host = returned.allServers[i].internal_host;
            tt.internal_port = returned.allServers[i].internal_port;
            tt.via           = returned.allServers[i].via;
            servers2.push(tt)
        };
        callbackFn(servers2)

    }
  });

}

function extractHostname(url) {
    var hostname;
    //find & remove protocol (http, ftp, etc.) and get hostname

    if (url.indexOf("://") > -1) {
        hostname = url.split('/')[2];
    }
    else {
        hostname = url.split('/')[0];
    }

    //find & remove port number
    hostname = hostname.split(':')[0];
    //find & remove "?"
    hostname = hostname.split('?')[0];

    return hostname;
}

function getPort(url) {
    url = url.match(/^(([a-z]+:)?(\/\/)?[^\/]+).*$/)[1] || url;
    var parts = url.split(':'),
        port = parseInt(parts[parts.length - 1], 10);
    if(parts[0] === 'http' && (isNaN(port) || parts.length < 3)) {
        return 80;
    }
    if(parts[0] === 'https' && (isNaN(port) || parts.length < 3)) {
        return 443;
    }
    if(parts.length === 1 || isNaN(port)) return 80;
    return port;
}

function findMainServer(callbackFn) {

    getListOfHosts(function(serversReturned) {
        if (serversReturned.length == 0) {
            callbackFn("No VisiFile Servers started on your Intranet")
        } else {
            var mainServer = serversReturned[0].username + ", " + serversReturned[0].internal_host + ":"+serversReturned[0].internal_port

            for (var x = 1; x < serversReturned.length ; x++) {
                if (serversReturned[x].internal_host == hostaddress) {
                     mainServer = serversReturned[x].username + ", " + serversReturned[x].internal_host + ":"+serversReturned[x].internal_port
                }
            }
            callbackFn(mainServer)

        }
    })
}

function getListOfHosts(callbackFn) {
    var serversToTry = [
                           "visifile.com"  ,
                           ip.address() + ":" +  80,
                           ip.address() + ":" +  3000,
                           "127.0.0.1:80"
                       ]

    lsFn(serversToTry, 0, function(serversReturned) {
        callbackFn(serversReturned)
    })
}
<commit_msg>Better message if no VisiFile server running<commit_after>var http        = require("http");
var ip          = require("ip");
var request     = require("request");
var hostaddress = ip.address();

// remove the first two elements as they contain the node and vf commands
//process.argv.pop()
//process.argv.pop()

process.argv.shift()
process.argv.shift()
var firstArg =  process.argv.shift()

var useHost = hostaddress
var usePort = 80
if (firstArg == '--host') {
    useHost = process.argv.shift()
    firstArg =  process.argv.shift()
}
//console.log("Connecting to: " + useHost + ":" + usePort);

//console.log (process.argv)
if (!firstArg) {
    console.log(`
VisiFile commands:

> vf
This command. Enter this to see this menu. If you are a developer
then you may have enter "vf" as "node src/vf.js"

> vf test
See if VisiFile is installed on your local computer on port 80

> vf ls
See which computers have VisiFile installed on them. Example
output may be:
User: root, 192.168.0.101:80
: in which case you can:
1) enter "vf --host 192.168.0.101:80 main" at the command prompt
2) enter 192.168.0.101:80 into a web Browser to view VisiFile
3) enter 192.168.0.101:80/main into a Rest API client such as Postman

> vf drivers
Show the available drivers

> vf --host 192.168.0.101:80 drivers
Show the drivers on the machine located at 192.168.0.101:80

> vf home
Show the main details of the running VisiFile
`)

} else if (firstArg == 'ls') {

    getListOfHosts(function(serversReturned) {
        if (serversReturned.length == 0) {
            console.log("No VisiFile Servers started on your Intranet")
        } else {
            for (var x = 0; x < serversReturned.length ; x++) {
                console.log("User: "+serversReturned[x].username + ", " + serversReturned[x].internal_host + ":"+serversReturned[x].internal_port)
            }
        }
    })

} else if (firstArg == 'main') {
    findMainServer(function(serverName) {
        console.log(serverName)
    })

} else {
    process.argv.unshift(firstArg)
    //options.query.a = process.argv

    var args = process.argv

    //console.log("Args JSON: " + JSON.stringify(args,null,2))

    var args2 = encodeURI(JSON.stringify(args))
    //console.log("Args seralized: " + args2)

    var options = {
      host: extractHostname(useHost),
      port: getPort(useHost),
      path: '/vf?a=' + args2,
      method: 'GET'
    };

    var req = http.request(options, function(res) {
      res.setEncoding('utf8');
      res.on('data', function (chunk) {
          var result = JSON.parse(chunk)
        console.log(result.OK);
      });
    });

    req.on('error', function(e) {
      console.log('problem with request: ' + e.message);
    });

    req.end();
}

function serialize(obj) {
  var str = [];
  for (var p in obj)
    if (obj.hasOwnProperty(p)) {
      str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
    }
  return str.join("&");
}

function lsFn(servers, index, callbackFn) {
    //console.log("Trying lookup server: " + servers[index])

    var remoteServerUrl =   'http://' + servers[index]  +
                            "/get_intranet_servers?time=" + new Date().getTime();

    request({
        uri: remoteServerUrl,
        method: "GET",
        timeout: 10000,
        agent: false,
        followRedirect: true,
        maxRedirects: 10
  },
  function(error, response, body) {
      var servers2 = servers
      if (error) {
          console.log("Error opening central server: " + error);
          var nextIndex = index + 1
          if (nextIndex < servers2.length) {
              lsFn(servers2, index + 1, callbackFn)
          }
    } else {
        var servers2 = []
        var returned= eval( "(" + body + ")");
        for (var i = 0 ; i < returned.allServers.length; i++) {
            //console.log('got server ' + i)
            //console.log(JSON.stringify(returned.allServers[i],null,2))
            var tt = new Object();
            tt.username = returned.allServers[i].client_user_name;
            tt.internal_host = returned.allServers[i].internal_host;
            tt.internal_port = returned.allServers[i].internal_port;
            tt.via           = returned.allServers[i].via;
            servers2.push(tt)
        };
        callbackFn(servers2)

    }
  });

}

function extractHostname(url) {
    var hostname;
    //find & remove protocol (http, ftp, etc.) and get hostname

    if (url.indexOf("://") > -1) {
        hostname = url.split('/')[2];
    }
    else {
        hostname = url.split('/')[0];
    }

    //find & remove port number
    hostname = hostname.split(':')[0];
    //find & remove "?"
    hostname = hostname.split('?')[0];

    return hostname;
}

function getPort(url) {
    url = url.match(/^(([a-z]+:)?(\/\/)?[^\/]+).*$/)[1] || url;
    var parts = url.split(':'),
        port = parseInt(parts[parts.length - 1], 10);
    if(parts[0] === 'http' && (isNaN(port) || parts.length < 3)) {
        return 80;
    }
    if(parts[0] === 'https' && (isNaN(port) || parts.length < 3)) {
        return 443;
    }
    if(parts.length === 1 || isNaN(port)) return 80;
    return port;
}

function findMainServer(callbackFn) {

    getListOfHosts(function(serversReturned) {
        if (serversReturned.length == 0) {
            callbackFn("No main VisiFile Server as none running on your Intranet")
        } else {
            var mainServer = serversReturned[0].username + ", " + serversReturned[0].internal_host + ":"+serversReturned[0].internal_port

            for (var x = 1; x < serversReturned.length ; x++) {
                if (serversReturned[x].internal_host == hostaddress) {
                     mainServer = serversReturned[x].username + ", " + serversReturned[x].internal_host + ":"+serversReturned[x].internal_port
                }
            }
            callbackFn(mainServer)

        }
    })
}

function getListOfHosts(callbackFn) {
    var serversToTry = [
                           "visifile.com"  ,
                           ip.address() + ":" +  80,
                           ip.address() + ":" +  3000,
                           "127.0.0.1:80"
                       ]

    lsFn(serversToTry, 0, function(serversReturned) {
        callbackFn(serversReturned)
    })
}
<|endoftext|>


<commit_before>/**
 * Prepros
 * (c) Subash Pathak
 * sbshpthk@gmail.com
 * License: MIT
 */

/*jshint browser: true, node: true, unused: false, globalstrict:true*/
/*global angular */

'use strict';

var prepros = angular.module('prepros', []).config(function ($routeProvider, $compileProvider) {

    //Sanitize unsafe url
    $compileProvider.urlSanitizationWhitelist(/^\s*(file):/);

    //Routers
    $routeProvider
        .when('/home', {path: 'home'})
        .when('/files/:pid', {path: 'files'})
        .when('/files/:pid/:fid', {path: 'files'})
        .when('/log', {path : 'log'})
        .otherwise({redirectTo: '/home'});
});<commit_msg>comment<commit_after>/**
 * Prepros
 * (c) Subash Pathak
 * sbshpthk@gmail.com
 * License: MIT
 */

/*jshint browser: true, node: true, unused: false, globalstrict:true*/
/*global angular */

'use strict';

var prepros = angular.module('prepros', []).config(function ($routeProvider, $compileProvider) {

    //Whitelist file urls
    $compileProvider.urlSanitizationWhitelist(/^\s*(file):/);

    //Routers
    $routeProvider
        .when('/home', {path: 'home'})
        .when('/files/:pid', {path: 'files'})
        .when('/files/:pid/:fid', {path: 'files'})
        .when('/log', {path : 'log'})
        .otherwise({redirectTo: '/home'});
});<|endoftext|>


<commit_before>/**
 * Created by lfernandes on 01.06.17.
 */
'use strict';

//require
let Ajv = require('ajv');
let ajv = Ajv({
    verbose: true,
    allErrors: true
}); // options can be passed, e.g. {allErrors: true}

//build schema
const question = {
    type: 'object',
    properties: {
        _id: {
            type: 'number'
        },
        related_object: {   // "deck" / "slide" / ... (?)
            type: 'string'
        },
        related_object_id: {   // id of the related object
            type: 'number'
        },
        question: {
            type: 'string'
        },
        user_id: {
            type: 'string' //TODO check lowercase
        },
        choices: {
            type: 'array',
            items: {
              type: 'string'
            }
        },
        difficulty: {
            type: 'number',
            minimum: 1,
            maximum: 5
        }
    },
    required: ['_id', 'related_object', 'related_object_id', 'question', 'user_id', 'choices']
};

//export
module.exports = ajv.compile(question);
<commit_msg>Embedding choices in the question model.<commit_after>/**
 * Created by lfernandes on 01.06.17.
 */
'use strict';

//require
let Ajv = require('ajv');
let ajv = Ajv({
    verbose: true,
    allErrors: true
}); // options can be passed, e.g. {allErrors: true}

//build schema
const question = {
    type: 'object',
    properties: {
        _id: {
            type: 'number'
        },
        related_object: {   // "deck" / "slide" / ... (?)
            type: 'string'
        },
        related_object_id: {   // id of the related object
            type: 'number'
        },
        question: {
            type: 'string'
        },
        user_id: {
            type: 'string' //TODO check lowercase
        },
        choices: {
            type: 'array',
            items: {
                type: 'object',
                properties: {
                    _id: {
                        type: 'number'
                    },
                    choice: {
                        type: 'string'
                    },
                    is_correct: {
                        type: 'boolean' //TODO check lowercase
                    },
                    explanation: {
                        type: 'string'
                    }
                }
            }
        },
        difficulty: {
            type: 'number',
            minimum: 1,
            maximum: 5
        }
    },
    required: ['_id', 'related_object', 'related_object_id', 'question', 'user_id', 'choices']
};

//export
module.exports = ajv.compile(question);
<|endoftext|>


<commit_before>// Models

var Feature = Backbone.Model.extend({});
var Value = Backbone.Model.extend({});

var FeatureList = Backbone.Collection.extend({ model: Feature });
var ValueList = Backbone.Collection.extend({ model: Value });

// Model views

var FeatureView = Backbone.View.extend({
  render: function() {
    this._renderName();
    this._renderDescription();
    this._renderTypeForm();
    this._renderTargetListHeading();
    this._renderTargets();
    this._renderTargetForm();
    return this;
  },
  _renderName: function() {
    var nameTemplate = _.template('
<%= name %>
');
    var node = $(nameTemplate({ name: this.model.get('name') }));
    this.$el.append(node);
  },
  _renderDescription: function() {
    var descriptionTemplate = _.template('
<%= description %>
');
    var node = $(descriptionTemplate({
      description: this.model.get('description')
    }));
    this.$el.append(node);
  },
  _renderTypeForm: function() {
    var typeFormTemplate = _.template(
      '<form role="form">' +
        '
' +
        '<input type="radio" name="type" value="complex" />complex' +
        '
' +
        '
' +
        '<input type="radio" name="type" value="atomic" />atomic' +
        '
' +
        '</form>');
    var node = $(typeFormTemplate());
    node.find('input[value="' + this.model.get('type') + '"]').check();
    this.$el.append(node);
  },
  _renderTargetListHeading: function() {
    var targetListHeadingTemplate = _.template('
<%= heading %>
');
    var heading;
    if (this.model.get('type') === 'complex') {
      heading = 'Features permitted in substructure:';
    } else {
      heading = 'Permitted values:';
    }
    var node = $(targetListHeadingTemplate({ heading: heading }));
    this.$el.append(node);
  },
  _renderTargets: function() {
    var targetListTemplate = _.template(
      '<% _.each(targets, function(target) { %>' +
        '
<%= target %>
' +
        '<% }); %>');
    var node = $(targetListTemplate({ targets: this.model.get('targets') }));
    this.$el.append(node);
  },
  _renderTargetForm: function() {
    var targetFormTemplate = _.template(
      '<form role="form">' +
        '
Drop <%= targetType %> here ...
' +
        '</form>');
    var targetType;
    if (this.model.get('type') === 'complex') {
      targetType = 'feature';
    } else {
      targetType = 'value';
    }
    var node = ($(targetFormTemplate({ targetType: targetType })));
    this.$el.append(node);
  },
});

var FeatureItemView = Backbone.View.extend({
  className: 'feature-item',
  render: function() {
    var attributes = this.model.toJSON();
    this.$el.attr('id', this.model.id);
    this.$el.attr('data-name', attributes['name']);
    this.$el.attr('data-type', attributes['type']);
    this.$el.attr('data-description', attributes['description']);
    this.$el.attr('data-targets', attributes['targets']);
    this.$el.text(attributes['name']);
    return this;
  },
});

var ValueItemView = Backbone.View.extend({
  className: 'value-item',
  render: function() {
    var name = this.model.get('name');
    this.$el.attr('id', this.model.id);
    this.$el.attr('data-name', name);
    this.$el.text(name);
    return this;
  },
});

// Collection views

var FeatureListView = Backbone.View.extend({
  events: {
    'click .feature-item': 'dispatcher',
    'mouseenter .feature-item': 'highlight',
    'mouseleave .feature-item': 'unhighlight',
    'unselect-all': 'unselectAll',
  },
  dispatcher: function(e) { this.select(e); this.showEditBlock(e); },
  select: function(e) {
    this.$el.trigger('unselect-all');
    $(e.currentTarget).addClass('selected');
  },
  unselectAll: function() {
    this.$el.find('.selected').removeClass('selected');
  },
  showEditBlock: function(e) {
    var featureID = e.currentTarget.id;
    var feature = this.collection.get(featureID);
    var featureView = new FeatureView({ model: feature });
    featureView.render();
    $('#interaction-block').html(featureView.$el.html());
  },
  highlight: function(e) { $(e.currentTarget).addClass('highlighted'); },
  unhighlight: function(e) { $(e.currentTarget).removeClass('highlighted'); },
  render: function() {
    this.collection.forEach(this.addFeatureItem, this);
  },
  addFeatureItem: function(featureItem) {
    var featureItemView = new FeatureItemView({ model: featureItem });
    this.$el.append(featureItemView.render().$el);
  }
});

var ValueListView = Backbone.View.extend({
  render: function() {
    this.collection.forEach(this.addValue, this);
  },
  addValue: function(valueItem) {
    var valueView = new ValueItemView({ model: valueItem }); // Should be a ValueItemView!
    this.$el.append(valueView.render().$el);
  }
});

$(document).ready(function() {

  var interactionBlock = $('#interaction-block');
  var newFeatureBlock = $('#new-feature-block');
  var newFeatureButton = $('#new-feature-button');

  newFeatureBlock.hide();

  newFeatureButton.on('click', function() {
    interactionBlock.html(newFeatureBlock.html());
  });

  var featureItems = $('.feature-item');
  var valueItems = $('.value-item');

  var featureList = new FeatureList();
  var valueList = new ValueList();

  featureItems.each(function() {
    var item = $(this);
    var name = item.data('name');
    var feature = new Feature({
      id: name,
      name: name,
      type: item.data('type'),
      description: item.data('description'),
      targets: item.dataToArray('targets'),
    });
    featureList.add(feature);
  });

  valueItems.each(function() {
    var item = $(this);
    var name = item.data('name');
    var value = new Value({
      id: name,
      name: name,
    });
    valueList.add(value);
  });

  var featureListView = new FeatureListView({
    id: 'feature-list',
    collection: featureList,
  });

  featureListView.render();
  $('#feature-list').replaceWith(featureListView.$el);

  var valueListView = new ValueListView({
    id: 'value-list',
    collection: valueList,
  });

  valueListView.render();
  $('#value-list').replaceWith(valueListView.$el);

});
<commit_msg>WIP: Use (emptied) `#interaction-block` as a FeatureView's `el` by default.<commit_after>// Models

var Feature = Backbone.Model.extend({});
var Value = Backbone.Model.extend({});

var FeatureList = Backbone.Collection.extend({ model: Feature });
var ValueList = Backbone.Collection.extend({ model: Value });

// Model views

var FeatureView = Backbone.View.extend({
  render: function() {
    this.$el.empty();
    this._renderName();
    this._renderDescription();
    this._renderTypeForm();
    this._renderTargetListHeading();
    this._renderTargets();
    this._renderTargetForm();
    return this;
  },
  _renderName: function() {
    var nameTemplate = _.template('
<%= name %>
');
    var node = $(nameTemplate({ name: this.model.get('name') }));
    this.$el.append(node);
  },
  _renderDescription: function() {
    var descriptionTemplate = _.template('
<%= description %>
');
    var node = $(descriptionTemplate({
      description: this.model.get('description')
    }));
    this.$el.append(node);
  },
  _renderTypeForm: function() {
    var typeFormTemplate = _.template(
      '<form role="form">' +
        '
' +
        '<input type="radio" name="type" value="complex" />complex' +
        '
' +
        '
' +
        '<input type="radio" name="type" value="atomic" />atomic' +
        '
' +
        '</form>');
    var node = $(typeFormTemplate());
    node.find('input[value="' + this.model.get('type') + '"]').check();
    this.$el.append(node);
  },
  _renderTargetListHeading: function() {
    var targetListHeadingTemplate = _.template('
<%= heading %>
');
    var heading;
    if (this.model.get('type') === 'complex') {
      heading = 'Features permitted in substructure:';
    } else {
      heading = 'Permitted values:';
    }
    var node = $(targetListHeadingTemplate({ heading: heading }));
    this.$el.append(node);
  },
  _renderTargets: function() {
    var targetListTemplate = _.template(
      '<% _.each(targets, function(target) { %>' +
        '
<%= target %>
' +
        '<% }); %>');
    var node = $(targetListTemplate({ targets: this.model.get('targets') }));
    this.$el.append(node);
  },
  _renderTargetForm: function() {
    var targetFormTemplate = _.template(
      '<form role="form">' +
        '
Drop <%= targetType %> here ...
' +
        '</form>');
    var targetType;
    if (this.model.get('type') === 'complex') {
      targetType = 'feature';
    } else {
      targetType = 'value';
    }
    var node = ($(targetFormTemplate({ targetType: targetType })));
    this.$el.append(node);
  },
});

var FeatureItemView = Backbone.View.extend({
  className: 'feature-item',
  render: function() {
    var attributes = this.model.toJSON();
    this.$el.attr('id', this.model.id);
    this.$el.attr('data-name', attributes['name']);
    this.$el.attr('data-type', attributes['type']);
    this.$el.attr('data-description', attributes['description']);
    this.$el.attr('data-targets', attributes['targets']);
    this.$el.text(attributes['name']);
    return this;
  },
});

var ValueItemView = Backbone.View.extend({
  className: 'value-item',
  render: function() {
    var name = this.model.get('name');
    this.$el.attr('id', this.model.id);
    this.$el.attr('data-name', name);
    this.$el.text(name);
    return this;
  },
});

// Collection views

var FeatureListView = Backbone.View.extend({
  events: {
    'click .feature-item': 'dispatcher',
    'mouseenter .feature-item': 'highlight',
    'mouseleave .feature-item': 'unhighlight',
    'unselect-all': 'unselectAll',
  },
  dispatcher: function(e) { this.select(e); this.showEditBlock(e); },
  select: function(e) {
    this.$el.trigger('unselect-all');
    $(e.currentTarget).addClass('selected');
  },
  unselectAll: function() {
    this.$el.find('.selected').removeClass('selected');
  },
  showEditBlock: function(e) {
    var featureID = e.currentTarget.id;
    var feature = this.collection.get(featureID);
    var featureView = new FeatureView({ model: feature });
    featureView.setElement($('#interaction-block'));
    featureView.render();
  },
  highlight: function(e) { $(e.currentTarget).addClass('highlighted'); },
  unhighlight: function(e) { $(e.currentTarget).removeClass('highlighted'); },
  render: function() {
    this.collection.forEach(this.addFeatureItem, this);
  },
  addFeatureItem: function(featureItem) {
    var featureItemView = new FeatureItemView({ model: featureItem });
    this.$el.append(featureItemView.render().$el);
  }
});

var ValueListView = Backbone.View.extend({
  render: function() {
    this.collection.forEach(this.addValue, this);
  },
  addValue: function(valueItem) {
    var valueView = new ValueItemView({ model: valueItem }); // Should be a ValueItemView!
    this.$el.append(valueView.render().$el);
  }
});

$(document).ready(function() {

  var interactionBlock = $('#interaction-block');
  var newFeatureBlock = $('#new-feature-block');
  var newFeatureButton = $('#new-feature-button');

  newFeatureBlock.hide();

  newFeatureButton.on('click', function() {
    interactionBlock.html(newFeatureBlock.html());
  });

  var featureItems = $('.feature-item');
  var valueItems = $('.value-item');

  var featureList = new FeatureList();
  var valueList = new ValueList();

  featureItems.each(function() {
    var item = $(this);
    var name = item.data('name');
    var feature = new Feature({
      id: name,
      name: name,
      type: item.data('type'),
      description: item.data('description'),
      targets: item.dataToArray('targets'),
    });
    featureList.add(feature);
  });

  valueItems.each(function() {
    var item = $(this);
    var name = item.data('name');
    var value = new Value({
      id: name,
      name: name,
    });
    valueList.add(value);
  });

  var featureListView = new FeatureListView({
    id: 'feature-list',
    collection: featureList,
  });

  featureListView.render();
  $('#feature-list').replaceWith(featureListView.$el);

  var valueListView = new ValueListView({
    id: 'value-list',
    collection: valueList,
  });

  valueListView.render();
  $('#value-list').replaceWith(valueListView.$el);

});
<|endoftext|>