<commit_before>/* See license.txt for terms of usage */

"use strict";

const self = require("sdk/self");

const { Cu, Ci } = require("chrome");
const { Trace, TraceError } = require("../core/trace.js").get(module.id);
const { loadSheet, removeSheet } = require("sdk/stylesheet/utils");
const { EventTarget } = require("sdk/event/target");
const { Class } = require("sdk/core/heritage");
const { Locale } = require("../core/locale.js");
const { BaseOverlay } = require("../chrome/base-overlay.js");
const { Theme } = require("../chrome/theme.js");
const { Win } = require("../core/window.js");
const { ToggleSideBarButton } = require("../chrome/toggle-sidebar-button.js");
const { RuleViewOverlay } = require("./rule-view-overlay.js");
const { ComputedViewOverlay } = require("./computed-view-overlay.js");
const { FontInspectorOverlay } = require("./font-inspector-overlay.js");
const { LayoutViewOverlay } = require("./layout-view-overlay.js");
const { AnimationInspectorOverlay } = require("./animation-inspector-overlay.js");

const { Services } = Cu.import("resource://gre/modules/Services.jsm", {});
const { devtools } = Cu.import("resource://gre/modules/devtools/Loader.jsm", {});
const { SelectorSearch } = devtools["require"]("devtools/inspector/selector-search");

/**
 * @overlay This object is responsible for the Inspector panel
 * customization.
 *
 * It should append DOM side panel displaying properties of the
 * selected node (if Firebug theme is activated). Blocked by:
 * New API: WalkerFront.getObjectActorFromNodeActor()
 * https://bugzilla.mozilla.org/show_bug.cgi?id=1035742
 */
const InspectorOverlay = Class(
/** @lends InspectorOverlay */
{
  extends: BaseOverlay,

  searchable: true,

  // Initialization
  initialize: function(options) {
    BaseOverlay.prototype.initialize.apply(this, arguments);

    Trace.sysout("inspectorOverlay.initialize;", options);
  },

  onBuild: function(options) {
    BaseOverlay.prototype.onBuild.apply(this, arguments);

    Trace.sysout("inspectorOverlay.onBuild;", options.panel);

    this.onMarkupViewRender = this.onMarkupViewRender.bind(this);
    this.onMarkupViewLoaded = this.onMarkupViewLoaded.bind(this);

    // Handle MarkupView events.
    this.panel.on("markupview-render", this.onMarkupViewRender);
    this.panel.on("markuploaded", this.onMarkupViewLoaded);

    this.originalsetupSearchBox = this.panel.setupSearchBox;
  },

  onReady: function(options) {
    BaseOverlay.prototype.onReady.apply(this, arguments);

    Trace.sysout("inspectorOverlay.onReady;", options);

    // Register selection change listener.
    this.onNodeSelected = this.onNodeSelected.bind(this);
    this.panel.selection.on("new-node-front", this.onNodeSelected);

    if (Theme.isFirebugActive()) {
      this.updateSearchBox(true);
    }
  },

  destroy: function() {
    if (!this.panel) {
      return;
    }

    this.panel.off("markupview-render", this.onMarkupViewRender);
    this.panel.off("markuploaded", this.onMarkupViewLoaded);
  },

  // Side panels

  hasSidePanels: function() {
    return true;
  },

  setupSidePanels: function() {
    if (Theme.isFirebugActive()) {
      BaseOverlay.prototype.setupSidePanels.apply(this, arguments);
    }
  },

  getSideOverlays: function() {
    return [
      {id: "ruleview", ctor: RuleViewOverlay},
      {id: "computedview", ctor: ComputedViewOverlay},
      {id: "fontinspector", ctor: FontInspectorOverlay},
      {id: "layoutview", ctor: LayoutViewOverlay},
      {id: "animationinspector", ctor: AnimationInspectorOverlay},
    ];
  },

  // Events

  onNodeSelected: function() {
    // Bail out if the panel is destroyed.
    if (!this.panel.toolbox) {
      return;
    }

    Trace.sysout("inspectorOverlay.onNodeSelected;",
      this.panel.selection);

    this.updateDomPanel(this.panel.selection.nodeFront);
  },

  updateDomPanel: function(nodeFront) {
    // xxxHonza: Attaching to the current thread at this moment
    // breaks the inspector highlighter.
    // See also: https://github.com/firebug/firebug.next/issues/150

    // Make sure we are attached to backend thread.
    /*let target = this.toolbox.target;
    target.activeTab.attachThread({}, (response, threadClient) => {

      // Make sure the inspector is initialized.
      this.toolbox.initInspector().then(() => {
        Trace.sysout("inspectorOverlay.onNodeSelected; nodeFront",
          nodeFront);

        let walker = this.toolbox.walker;

        // xxxHonza: Platform API needed, patch attached to the following bug:
        // Bug 1035742 - New API: WalkerFront.getObjectActorFromNodeActor()
        if (typeof walker.getObjectActorFromNodeActor == "undefined") {
          return;
        }

        // Get object grip from inspector's front node.
        walker.getObjectActorFromNodeActor(nodeFront).then(grip => {
          Trace.sysout("inspectorOverlay.onNodeSelected; grip", grip);

          // Refresh appropriate side panel
          // xxxHonza: dup from ConsoleOverlay, we need generic API
          for (let panel of this.sidePanels.values()) {
            if (panel.supportsObject(options.objectActor)) {
              panel.refresh(options.objectActor);
            }
          }
        });
      });
    });*/
  },

  onMarkupViewRender: function(eventId, node, type, data, options) {
    // xxxHonza: just testing markup view customization
    let value;
    let nodeFront = data.node;

    switch (type) {
    case "element":
      value = nodeFront.nodeName;
      break;
    case "attribute":
      value = data.attrName;
      break;
    case "comment":
      value = nodeFront.shortValue;
      break;
    case "container":
      value = type;
      break;
    }

    // xxxHonza: blocked by issue #1
    /*Trace.sysout("inspectorOverlay.onMarkupViewRender; " + type +
      ", " + value, {
      html: node.innerHTML,
      node: node,
      data: data,
      type: type,
      options: options
    });*/

    if (type != "element") {
      return;
    }

    let xpath = "";
    while (nodeFront) {
      let name = nodeFront.tagName ? nodeFront.tagName : "";
      xpath = name + "/" + xpath;
      nodeFront = nodeFront._parent;
    }

    node.setAttribute("title", xpath.toLowerCase());
  },

  onMarkupViewLoaded: function() {
    Trace.sysout("inspectorOverlay.onMarkupViewLoaded;");
  },

  onApplyTheme: function(iframeWin, oldTheme) {
    Trace.sysout("inspectorOverlay.onApplyTheme; " + iframeWin.inspector,
      iframeWin);

    // xxxHonza: for now we don't need default theme, but
    // this is rather a hack FIX ME.
    let doc = iframeWin.document;
    let classList = doc.documentElement.classList;
    classList.remove("theme-light");

    loadSheet(iframeWin, "chrome://firebug/skin/inspector.css", "author");
    loadSheet(iframeWin, "chrome://firebug-os/skin/inspector.css", "author");

    Theme.customizeSideBarSplitter(iframeWin, true);

    // Create side bar toggle button.
    Win.loaded(iframeWin).then(doc => {
      this.toggleSideBar = new ToggleSideBarButton({
        panel: this,
        toolbar: doc.getElementById("inspector-toolbar"),
      });

      this.updateSearchBox(true);
    });

    this.setupSidePanels();
  },

  onUnapplyTheme: function(iframeWin, newTheme) {
    removeSheet(iframeWin, "chrome://firebug/skin/inspector.css", "author");
    removeSheet(iframeWin, "chrome://firebug-os/skin/inspector.css", "author");

    // Remove splitter customization
    Theme.customizeSideBarSplitter(iframeWin, false);

    this.toggleSideBar.destroy();

    this.removeSidePanels();

    Win.loaded(iframeWin).then(doc => {
      this.updateSearchBox(false);
    });
  },

  // Framework events

  onShow: function() {
    BaseOverlay.prototype.onShow.apply(this, arguments);

    if (Theme.isFirebugActive()) {
      this.updateSearchBox(true);
    }
  },

  onHide: function() {
    BaseOverlay.prototype.onHide.apply(this, arguments);

    // Unapply search-box customization when the Inspector panel
    // is hidden (unselected). The search box is shared among
    // panels and other customozation can apply.
    this.updateSearchBox(false);
  },

  // Search

  updateSearchBox: function(apply) {
    Win.loaded(this.chrome.toolbox.doc.defaultView).then(() => {
      if (!this.panel) {
        return;
      }

      let doc = this.getPanelDocument();
      let searchInput = doc.querySelector("#inspector-searchbox");

      if (apply) {
        this.chrome.searchBox.setValue(searchInput.value);

        this.panel.setupSearchBox = this.setupSearchBox.bind(
          this.panel, this.chrome);
      } else {
        this.panel.setupSearchBox = this.originalsetupSearchBox;
      }

      this.panel.setupSearchBox();
    });
  },

  /**
   * xxxHonza: monkey patch for the {@InspectorPanel} that connects
   * the panel to the shared search box UI.
   */
  setupSearchBox: function(chrome) {
    // Initiate the selectors search object.
    if (this.searchSuggestions) {
      this.searchSuggestions.destroy();
      this.searchSuggestions = null;
    }

    this.searchBox = chrome.searchBox.getInputBox();
    this.searchSuggestions = new SelectorSearch(this, this.searchBox);
  }
});

// Exports from this module
exports.InspectorOverlay = InspectorOverlay;
<commit_msg>Simplify the Inspector panel overlay<commit_after>/* See license.txt for terms of usage */

"use strict";

const self = require("sdk/self");

const { Cu, Ci } = require("chrome");
const { Trace, TraceError } = require("../core/trace.js").get(module.id);
const { loadSheet, removeSheet } = require("sdk/stylesheet/utils");
const { EventTarget } = require("sdk/event/target");
const { Class } = require("sdk/core/heritage");
const { Locale } = require("../core/locale.js");
const { BaseOverlay } = require("../chrome/base-overlay.js");
const { Theme } = require("../chrome/theme.js");
const { Win } = require("../core/window.js");
const { ToggleSideBarButton } = require("../chrome/toggle-sidebar-button.js");
const { RuleViewOverlay } = require("./rule-view-overlay.js");
const { ComputedViewOverlay } = require("./computed-view-overlay.js");
const { FontInspectorOverlay } = require("./font-inspector-overlay.js");
const { LayoutViewOverlay } = require("./layout-view-overlay.js");
const { AnimationInspectorOverlay } = require("./animation-inspector-overlay.js");

const { Services } = Cu.import("resource://gre/modules/Services.jsm", {});
const { devtools } = Cu.import("resource://gre/modules/devtools/Loader.jsm", {});
const { SelectorSearch } = devtools["require"]("devtools/inspector/selector-search");

/**
 * @overlay This object is responsible for the Inspector panel
 * customization.
 *
 * It should append DOM side panel displaying properties of the
 * selected node (if Firebug theme is activated). Blocked by:
 * New API: WalkerFront.getObjectActorFromNodeActor()
 * https://bugzilla.mozilla.org/show_bug.cgi?id=1035742
 */
const InspectorOverlay = Class(
/** @lends InspectorOverlay */
{
  extends: BaseOverlay,

  searchable: true,

  // Initialization
  initialize: function(options) {
    BaseOverlay.prototype.initialize.apply(this, arguments);

    Trace.sysout("inspectorOverlay.initialize;", options);
  },

  onBuild: function(options) {
    BaseOverlay.prototype.onBuild.apply(this, arguments);

    Trace.sysout("inspectorOverlay.onBuild;", options.panel);

    this.originalsetupSearchBox = this.panel.setupSearchBox;
  },

  onReady: function(options) {
    BaseOverlay.prototype.onReady.apply(this, arguments);

    Trace.sysout("inspectorOverlay.onReady;", options);

    if (Theme.isFirebugActive()) {
      this.updateSearchBox(true);
    }
  },

  destroy: function() {
  },

  // Side panels

  hasSidePanels: function() {
    return true;
  },

  setupSidePanels: function() {
    if (Theme.isFirebugActive()) {
      BaseOverlay.prototype.setupSidePanels.apply(this, arguments);
    }
  },

  getSideOverlays: function() {
    return [
      {id: "ruleview", ctor: RuleViewOverlay},
      {id: "computedview", ctor: ComputedViewOverlay},
      {id: "fontinspector", ctor: FontInspectorOverlay},
      {id: "layoutview", ctor: LayoutViewOverlay},
      {id: "animationinspector", ctor: AnimationInspectorOverlay},
    ];
  },

  // Events

  onApplyTheme: function(iframeWin, oldTheme) {
    Trace.sysout("inspectorOverlay.onApplyTheme; " + iframeWin.inspector,
      iframeWin);

    // xxxHonza: for now we don't need default theme, but
    // this is rather a hack FIX ME.
    let doc = iframeWin.document;
    let classList = doc.documentElement.classList;
    classList.remove("theme-light");

    loadSheet(iframeWin, "chrome://firebug/skin/inspector.css", "author");
    loadSheet(iframeWin, "chrome://firebug-os/skin/inspector.css", "author");

    Theme.customizeSideBarSplitter(iframeWin, true);

    // Create side bar toggle button.
    Win.loaded(iframeWin).then(doc => {
      this.toggleSideBar = new ToggleSideBarButton({
        panel: this,
        toolbar: doc.getElementById("inspector-toolbar"),
      });

      this.updateSearchBox(true);
    });

    this.setupSidePanels();
  },

  onUnapplyTheme: function(iframeWin, newTheme) {
    removeSheet(iframeWin, "chrome://firebug/skin/inspector.css", "author");
    removeSheet(iframeWin, "chrome://firebug-os/skin/inspector.css", "author");

    // Remove splitter customization
    Theme.customizeSideBarSplitter(iframeWin, false);

    this.toggleSideBar.destroy();

    this.removeSidePanels();

    Win.loaded(iframeWin).then(doc => {
      this.updateSearchBox(false);
    });
  },

  // Framework events

  onShow: function() {
    BaseOverlay.prototype.onShow.apply(this, arguments);

    if (Theme.isFirebugActive()) {
      this.updateSearchBox(true);
    }
  },

  onHide: function() {
    BaseOverlay.prototype.onHide.apply(this, arguments);

    // Unapply search-box customization when the Inspector panel
    // is hidden (unselected). The search box is shared among
    // panels and other customization can apply.
    this.updateSearchBox(false);
  },

  // Search

  updateSearchBox: function(apply) {
    Win.loaded(this.chrome.toolbox.doc.defaultView).then(() => {
      if (!this.panel) {
        return;
      }

      let doc = this.getPanelDocument();
      let searchInput = doc.querySelector("#inspector-searchbox");

      if (apply) {
        this.chrome.searchBox.setValue(searchInput.value);

        this.panel.setupSearchBox = this.setupSearchBox.bind(
          this.panel, this.chrome);
      } else {
        this.panel.setupSearchBox = this.originalsetupSearchBox;
      }

      this.panel.setupSearchBox();
    });
  },

  /**
   * xxxHonza: monkey patch for the {@InspectorPanel} that connects
   * the panel to the shared search box UI.
   */
  setupSearchBox: function(chrome) {
    // Initiate the selectors search object.
    if (this.searchSuggestions) {
      this.searchSuggestions.destroy();
      this.searchSuggestions = null;
    }

    this.searchBox = chrome.searchBox.getInputBox();
    this.searchSuggestions = new SelectorSearch(this, this.searchBox);
  }
});

// Exports from this module
exports.InspectorOverlay = InspectorOverlay;
<|endoftext|>


<commit_before>var Session = require('./models/session.js');
var Languages = require('./models/languages.js');
var Language = require('./models/language.js');
var Translate = require('./translations.js');
var Mongo = require('./db/mongo.js');

exports.notACommand = function (userInput) {
    return !checkDifferentFromAllLanguages(Translate.getCommand, userInput) &&
        !checkDifferentFromAllLanguages(Translate.startAlertCommand, userInput) &&
        !checkDifferentFromAllLanguages(Translate.stopAlertCommand, userInput) &&
        !checkDifferentFromAllLanguages(Translate.helpCommand, userInput) &&
        !checkDifferentFromAllLanguages(Translate.donateCommand, userInput) &&
        !checkDifferentFromAllLanguages(Translate.languageCommand, userInput)
}

checkDifferentFromAllLanguages = function(command, userInput) {
    let hasOccurence = false;
    Object.keys(command).forEach(function(key,index) {
        if(command[key] == userInput) hasOccurence = true;
    });
    return hasOccurence;
}

exports.isValidNumber = function (str) {
    return isValidNumber(str);
}

function isValidNumber(str){
    var number = Math.floor(Number(str));
    return String(number) === str && number > 0;
}

exports.isValidInterval = function (str) {
    if(str.indexOf('-') === -1){
        return false;
    }
    var start = str.substr(0, str.indexOf('-'));
    var end = str.substr(str.indexOf('-') + 1, str.length)
    return isValidNumber(start) && isValidNumber(end);
}

exports.isEmpty = function (obj) {
    for (var key in obj) {
        if (obj.hasOwnProperty(key))
            return false;
    }
    return true;
}

exports.getUserSession = function (sessions, msg, translations) {
    var chat = msg.chat ? msg.chat : msg.from;
    let userSession = sessions.find(function (session) {
        return session.chatId === chat.id;
    }) || new Session();
    userSession.chatId = chat.id;
    userSession.firstName = chat.first_name;
    Object.keys(translations).forEach(function(key,index) {
        translations[key].forEach(function(userId) {
            if(userId === chat.id) userSession.userLanguage = key;
        });
    });
    if(!userSession.userLanguage) {
        userSession.userLanguage = this.parseLanguage(msg.from.language_code);
        translations[userSession.userLanguage].push(chat.id);
    }
    return userSession;
}

exports.parseLanguage = function(languageCode){
    return Languages.languages[languageCode.split("-")[0]]["native"][0];
}

exports.pushInSessions = function (sessions, session) {
    if (sessions.length == 0) sessions.push(session);
    else {
        var sessionIdx = sessions.findIndex(function (element) {
            return session.chatId == element.chatId;
        });
        if (sessionIdx == -1) sessions.push(session);
        else sessions[sessionIdx] = session;
    }
}

exports.removeSession = function (sessions, session) {
    if (sessions.length == 0) return;
    var sessionIdx = sessions.findIndex(function (element) {
        return session.chatId == element.chatId;
    });
    if (sessionIdx != -1) sessions.splice(sessionIdx, 1);
}

exports.isAmbiguousTitle = function(name){
    // returns true if the name contains 4 number between brackets (e.g.: (2344))
    var firstBracket = name.indexOf("(");
    var secondBracket = name.indexOf(")");
    if(secondBracket > -1 && firstBracket > -1 ){
        var number = name.substring(firstBracket, secondBracket);
        return this.isValidNumber(number)
    }else{
        return false;
    }
}

exports.resetValues = function (session) {
    session.choosingSeries = false;
    session.choosingSeason = false;
    session.choosingEpisode = false;
    session.choosingLanguage = false;
    session.chosenSeries = {};
    session.chosenSeason = undefined;
    session.chosenEpisode = undefined;
    session.ambiguousSeries = {};

    session.choosingSeriesAlert = false,
        session.choosingLanguageAlert = false,
        session.choosenSeriesAlert = {},
        session.ambiguousSeriesAlert = {}
    session.chosenLanguagesAlert = []
    session.deletingAlert = false
}

exports.handleChosenSeries = function (chosenSeries, session, sessions) {
    session.choosenSeries = chosenSeries;
    this.resetValues(session);
    session.choosingSeason = true;
    this.pushInSessions(sessions, session);
}

exports.handleChosenSeriesAlert = function (chosenSeries, session, sessions) {
    session.choosenSeriesAlert = chosenSeries;
    this.resetValues(session);
    session.choosingLanguageAlert = true;
    this.pushInSessions(sessions, session);
}

exports.languageAlreadyPresent = function (list, language) {
    return list.indexOf(language) > -1;
}

exports.getLanguageFromKey = function (key) {
    var lan = Languages.languages;
    var language = Languages.languages[key];
    return new Language({
        code: key,
        int: language.int[0],
        native: language.native[0]
    });
}<commit_msg>fixed badInteractionmessage<commit_after>var Session = require('./models/session.js');
var Languages = require('./models/languages.js');
var Language = require('./models/language.js');
var Translate = require('./translations.js');
var Mongo = require('./db/mongo.js');

exports.notACommand = function (userInput) {
    return !checkDifferentFromAllLanguages(Translate.getCommand, userInput) &&
        !checkDifferentFromAllLanguages(Translate.startAlertCommand, userInput) &&
        !checkDifferentFromAllLanguages(Translate.stopAlertCommand, userInput) &&
        !checkDifferentFromAllLanguages(Translate.helpCommand, userInput) &&
        !checkDifferentFromAllLanguages(Translate.donateCommand, userInput) &&
        !checkDifferentFromAllLanguages(Translate.languageCommand, userInput)
}

checkDifferentFromAllLanguages = function(command, userInput) {
    let hasOccurence = false;
    Object.keys(command).forEach(function(key,index) {
        if(command[key] == userInput) hasOccurence = true;
    });
    return hasOccurence;
}

exports.isValidNumber = function (str) {
    return isValidNumber(str);
}

function isValidNumber(str){
    var number = Math.floor(Number(str));
    return String(number) === str && number > 0;
}

exports.isValidInterval = function (str) {
    if(str.indexOf('-') === -1){
        return false;
    }
    var start = str.substr(0, str.indexOf('-'));
    var end = str.substr(str.indexOf('-') + 1, str.length)
    return isValidNumber(start) && isValidNumber(end);
}

exports.isEmpty = function (obj) {
    for (var key in obj) {
        if (obj.hasOwnProperty(key))
            return false;
    }
    return true;
}

exports.checkSessionEmpty = function(session){
    return !session.choosingUserLanguage
        && !session.choosingSeries
        && !session.choosingSeason
        && !session.choosingEpisode
        && !session.choosingLanguage
        && !session.choosingSeriesAlert
        && !session.choosingLanguageAlert
        && !session.deletingAlert
        && !session.confirmDelete;
}

exports.getUserSession = function (sessions, msg, translations) {
    var chat = msg.chat ? msg.chat : msg.from;
    let userSession = sessions.find(function (session) {
        return session.chatId === chat.id;
    }) || new Session();
    userSession.chatId = chat.id;
    userSession.firstName = chat.first_name;
    Object.keys(translations).forEach(function(key,index) {
        translations[key].forEach(function(userId) {
            if(userId === chat.id) userSession.userLanguage = key;
        });
    });
    if(!userSession.userLanguage) {
        userSession.userLanguage = this.parseLanguage(msg.from.language_code);
        translations[userSession.userLanguage].push(chat.id);
    }
    return userSession;
}

exports.parseLanguage = function(languageCode){
    return Languages.languages[languageCode.split("-")[0]]["native"][0];
}

exports.pushInSessions = function (sessions, session) {
    if (sessions.length == 0) sessions.push(session);
    else {
        var sessionIdx = sessions.findIndex(function (element) {
            return session.chatId == element.chatId;
        });
        if (sessionIdx == -1) sessions.push(session);
        else sessions[sessionIdx] = session;
    }
}

exports.removeSession = function (sessions, session) {
    if (sessions.length == 0) return;
    var sessionIdx = sessions.findIndex(function (element) {
        return session.chatId == element.chatId;
    });
    if (sessionIdx != -1) sessions.splice(sessionIdx, 1);
}

exports.isAmbiguousTitle = function(name){
    // returns true if the name contains 4 number between brackets (e.g.: (2344))
    var firstBracket = name.indexOf("(");
    var secondBracket = name.indexOf(")");
    if(secondBracket > -1 && firstBracket > -1 ){
        var number = name.substring(firstBracket, secondBracket);
        return this.isValidNumber(number)
    }else{
        return false;
    }
}

exports.resetValues = function (session) {
    session.choosingSeries = false;
    session.choosingSeason = false;
    session.choosingEpisode = false;
    session.choosingLanguage = false;
    session.chosenSeries = {};
    session.chosenSeason = undefined;
    session.chosenEpisode = undefined;
    session.ambiguousSeries = {};

    session.choosingSeriesAlert = false,
        session.choosingLanguageAlert = false,
        session.choosenSeriesAlert = {},
        session.ambiguousSeriesAlert = {}
    session.chosenLanguagesAlert = []
    session.deletingAlert = false
}

exports.handleChosenSeries = function (chosenSeries, session, sessions) {
    session.choosenSeries = chosenSeries;
    this.resetValues(session);
    session.choosingSeason = true;
    this.pushInSessions(sessions, session);
}

exports.handleChosenSeriesAlert = function (chosenSeries, session, sessions) {
    session.choosenSeriesAlert = chosenSeries;
    this.resetValues(session);
    session.choosingLanguageAlert = true;
    this.pushInSessions(sessions, session);
}

exports.languageAlreadyPresent = function (list, language) {
    return list.indexOf(language) > -1;
}

exports.getLanguageFromKey = function (key) {
    var lan = Languages.languages;
    var language = Languages.languages[key];
    return new Language({
        code: key,
        int: language.int[0],
        native: language.native[0]
    });
}<|endoftext|>


<commit_before>var gulp = require('gulp'),
    karma = require('gulp-karma'),
    gutil = require('gulp-util'),
    Server = require('karma').Server;

// function getTestFiles () {

//     var dirPrefix = 'test/spec/',
//         test;

//     if (test = gutil.env.run) {
//         return dirPrefix + test + '.js';
//     } else {
//         return dirPrefix + '*.js';
//     }
// }

function getTestFiles () {

    var toRun = gutil.env.run;

    if (toRun) {
        if (toRun.indexOf('/') !== -1) {
            toRun = 'test/spec/' + toRun + '.js'
        } else {
            toRun = 'test/spec/' + toRun + '/*.js';
        }
    } else {
        toRun = 'test/spec/**/**/*.js';
    }

    return toRun

    // return testFiles.map( function (filePath) {
    //     return filePath = basePath + filePath;
    // });

}

// gulp.task('test', function (done) {
//     new Server({
//         configFile: '../../../test/karma.conf.js'
//     }, done).start();
// });

gulp.task('test', function (done) {

    var files = [
        'node_modules/jquery/dist/jquery.js',
        'pub/dollar.js',
        'test/mock_dom.html',
        'test/mock_dom.js',
        'test/spec_helpers.js',
        getTestFiles()
    ];

    // Be sure to return the stream
    return gulp.src(files)
        .pipe(karma({
            configFile: 'test/karma.conf.js',
            action: 'run',
            env: gutil.env
        }))
        .on('error', function (err) {
            gutil.beep();
        });
});

gulp.task('quickcompare', function (done) {
    return new Server({
        configFile: '../../../test/quickcompare/quick.karma.conf.js'
    }, done).start();
});
<commit_msg>IW: cleanup<commit_after>var gulp = require('gulp'),
    karma = require('gulp-karma'),
    gutil = require('gulp-util'),
    Server = require('karma').Server;

function getTestFiles () {

    var toRun = gutil.env.run;

    if (toRun) {
        if (toRun.indexOf('/') !== -1) {
            toRun = 'test/spec/' + toRun + '.js'
        } else {
            toRun = 'test/spec/' + toRun + '/*.js';
        }
    } else {
        toRun = 'test/spec/**/**/*.js';
    }

    return toRun

}

// gulp.task('test', function (done) {
//     new Server({
//         configFile: '../../../test/karma.conf.js'
//     }, done).start();
// });

gulp.task('test', function (done) {

    var files = [
        'node_modules/jquery/dist/jquery.js',
        'pub/dollar.js',
        'test/mock_dom.html',
        'test/mock_dom.js',
        'test/spec_helpers.js',
        getTestFiles()
    ];

    // Be sure to return the stream
    return gulp.src(files)
        .pipe(karma({
            configFile: 'test/karma.conf.js',
            action: 'run',
            env: gutil.env
        }))
        .on('error', function (err) {
            gutil.beep();
        });
});

gulp.task('quickcompare', function (done) {
    return new Server({
        configFile: '../../../test/quickcompare/quick.karma.conf.js'
    }, done).start();
});
<|endoftext|>


<commit_before>const _ = require('lodash');

let attributeCounter = 0;

function init() {
  attributeCounter = 0;
}

function getElementName(element) {
  let selector = element.name;
  if (selector === '_') {
    selector = '*';
  }
  if ('attributes' in element) {
    const actualAttributes = _filterExtraAttributes(element.attributes);
    selector += getAttributeSelectors(actualAttributes);
  }
  return escapeSpecialCharacters(selector);
}

function getChildName(child) {
  let childName = child.name;
  if (childName === '_') {
    childName = '*';
  }
  if ('attributes' in child) {
    const actualAttributes = _filterExtraAttributes(child.attributes);
    childName += getAttributeSelectors(actualAttributes);
  }
  if (childName !== '*') {
    childName = escapeSpecialCharacters(childName);
  }
  return childName;
}

function getAttributeSelectors(attributes) {
  let attributesSelector = '';
  _.forEach(attributes, (attribute) => {
    const idx = attribute.value.indexOf('*');
    // Attribute value equals to a value
    if (idx === -1) {
      attributesSelector += `[${attribute.name}="${attribute.value}"]`;
    }
    // Attribute value starts with a value
    else if (idx === attribute.value.length - 1) {
      attributesSelector += `[${attribute.name}^="${attribute.value.split('*')[0]}"]`;
    }
    // Attribute value ends with a value
    else if (idx === 0) {
      attributesSelector += `[${attribute.name}$="${attribute.value.split('*')[1]}"]`;
    }
  });
  return attributesSelector;
}

function _filterExtraAttributes(attributes) {
  return _.filter(attributes, (attribute) => {
    return _.indexOf(['__name', '__exactly'], attribute.name) === -1;
  });
}

function getReturnAttributes(elements, attributes) {
  if (_.isEmpty(elements) || _.isEmpty(attributes)) {
    return undefined;
  }
  const attributesToReturn = _.filter(attributes, (attribute) => {
      return attribute.toReturn === true;
    }),
    attributesValues = {};
  _.forEach(attributesToReturn, (attribute) => {
    attributeCounter++;
    const retField = `$${attributeCounter}`;
    attributesValues[retField] = [];
    _.forEach(elements, (elem) => {
      const returnedValue = elem.attribs[attribute.name];
      if (returnedValue) {
        attributesValues[retField].push(returnedValue);
      }
    });
  });
  return attributesValues;
}

/**
 * Escape names that use any of JQuery meta-characters as a literal part of a name.
 * @param str a String that may use any of the meta-characters
 * @returns {String} The escaped string with two backslashes replacing the
 * JQuery's special meta-characters
 * @private
 */
function escapeSpecialCharacters(str) {
  const r = str.replace(/([;&,\.\+\*\~':"\!\^#$%@\[\]\(\)=>\|])/g, '\$1');
  return r.replace(/(:|\.)/g, '\\$1');
}

module.exports = {
  init,
  getElementName,
  escapeSpecialCharacters,
  getReturnAttributes,
  getChildName,
  getAttributeSelectors
};
<commit_msg>refactor<commit_after>'use strict';
const _ = require('lodash');

let attributeCounter = 0;

function init() {
  attributeCounter = 0;
}

function getElementName(element) {
  let selector = element.name;
  if (selector === '_') {
    selector = '*';
  }
  if ('attributes' in element) {
    const actualAttributes = _filterExtraAttributes(element.attributes);
    selector += getAttributeSelectors(actualAttributes);
  }
  return escapeSpecialCharacters(selector);
}

function getChildName(child) {
  let childName = child.name;
  if (childName === '_') {
    childName = '*';
  }
  if ('attributes' in child) {
    const actualAttributes = _filterExtraAttributes(child.attributes);
    childName += getAttributeSelectors(actualAttributes);
  }
  if (childName !== '*') {
    childName = escapeSpecialCharacters(childName);
  }
  return childName;
}

function getAttributeSelectors(attributes) {
  let attributesSelector = '';
  _.forEach(attributes, (attribute) => {
    const idx = attribute.value.indexOf('*');
    // Attribute value equals to a value
    if (idx === -1) {
      attributesSelector += `[${attribute.name}="${attribute.value}"]`;
    }
    // Attribute value starts with a value
    else if (idx === attribute.value.length - 1) {
      attributesSelector += `[${attribute.name}^="${attribute.value.split('*')[0]}"]`;
    }
    // Attribute value ends with a value
    else if (idx === 0) {
      attributesSelector += `[${attribute.name}$="${attribute.value.split('*')[1]}"]`;
    }
  });
  return attributesSelector;
}

function _filterExtraAttributes(attributes) {
  return _.filter(attributes, (attribute) => {
    return _.indexOf(['__name', '__exactly'], attribute.name) === -1;
  });
}

function getReturnAttributes(elements, attributes) {
  if (_.isEmpty(elements) || _.isEmpty(attributes)) {
    return undefined;
  }
  const attributesToReturn = _.filter(attributes, (attribute) => {
      return attribute.toReturn === true;
    }),
    attributesValues = {};
  _.forEach(attributesToReturn, (attribute) => {
    attributeCounter++;
    const retField = `$${attributeCounter}`;
    attributesValues[retField] = [];
    _.forEach(elements, (elem) => {
      const returnedValue = elem.attribs[attribute.name];
      if (returnedValue) {
        attributesValues[retField].push(returnedValue);
      }
    });
  });
  return attributesValues;
}

/**
 * Escape names that use any of JQuery meta-characters as a literal part of a name.
 * @param str a String that may use any of the meta-characters
 * @returns {String} The escaped string with two backslashes replacing the
 * JQuery's special meta-characters
 * @private
 */
function escapeSpecialCharacters(str) {
  const r = str.replace(/([;&,\.\+\*\~':"\!\^#$%@\[\]\(\)=>\|])/g, '\$1');
  return r.replace(/(:|\.)/g, '\\$1');
}

module.exports = {
  init,
  getElementName,
  escapeSpecialCharacters,
  getReturnAttributes,
  getChildName,
  getAttributeSelectors
};
<|endoftext|>


<commit_before>// Copyright (c) 2012 Romain Vallet <romain.vallet@gmail.com>
// Licensed under the MIT license, read license.txt

// Load options from local storage
// Return default values if none exist
function loadOptions() {
	var options;
	if (localStorage.options == null) {
		localStorage.options = '{}';
	}
	options = JSON.parse(localStorage.options);

	options.extensionEnabled = 	options.hasOwnProperty('extensionEnabled') ? options.extensionEnabled : true;
	options.pageActionEnabled = options.hasOwnProperty('pageActionEnabled') ? options.pageActionEnabled : true;
	options.showCaptions = 		options.hasOwnProperty('showCaptions') ? options.showCaptions : true;
	options.showHighRes = 		options.hasOwnProperty('showHighRes') ? options.showHighRes : false;
	options.addToHistory = 		options.hasOwnProperty('addToHistory') ? options.addToHistory : false;
	options.alwaysPreload = 	options.hasOwnProperty('alwaysPreload') ? options.alwaysPreload : false;
	options.displayDelay = 		options.hasOwnProperty('displayDelay') ? options.displayDelay : 100;
	options.fadeDuration = 		options.hasOwnProperty('fadeDuration') ? options.fadeDuration : 200;
	options.excludedSites = 	options.hasOwnProperty('excludedSites') ? options.excludedSites : [];
	options.whiteListMode = 	options.hasOwnProperty('whiteListMode') ? options.whiteListMode : false;
	options.picturesOpacity = 	options.hasOwnProperty('picturesOpacity') ? options.picturesOpacity : 1;
	options.showWhileLoading = 	options.hasOwnProperty('showWhileLoading') ? options.showWhileLoading : true;
	//options.expAlwaysFullZoom = options.hasOwnProperty('expAlwaysFullZoom') ? options.expAlwaysFullZoom : false;
	options.mouseUnderlap = 	options.hasOwnProperty('mouseUnderlap') ? options.mouseUnderlap : true;
	options.updateNotifications = 	options.hasOwnProperty('updateNotifications') ? options.updateNotifications : true;
	options.enableAds = 		options.hasOwnProperty('enableAds') ? options.enableAds : 0;
	options.filterNSFW = 		options.hasOwnProperty('filterNSFW') ? options.filterNSFW : false;

	// Action keys
	options.actionKey = 			options.hasOwnProperty('actionKey') ? options.actionKey : 0;
	options.fullZoomKey = 			options.hasOwnProperty('fullZoomKey') ? options.fullZoomKey : 90;
	options.hideKey = 				options.hasOwnProperty('hideKey') ? options.hideKey : 88;
	options.openImageInWindowKey =	options.hasOwnProperty('openImageInWindowKey') ? options.openImageInWindowKey : 87;
	options.openImageInTabKey =		options.hasOwnProperty('openImageInTabKey') ? options.openImageInTabKey : 84;
	options.saveImageKey =			options.hasOwnProperty('saveImageKey') ? options.saveImageKey : 83;

	localStorage.options = JSON.stringify(options);

	return options;
}

// Send options to all tabs and extension pages
function sendOptions(options) {
	var request = {action: 'optionsChanged', 'options': options};

	// Send options to all tabs
	chrome.windows.getAll(null, function (windows) {
		for (var i=0; i<windows.length; i++) {
			chrome.tabs.getAllInWindow(windows[i].id, function(tabs) {
				for (var j=0; j<tabs.length; j++) {
					chrome.tabs.sendRequest(tabs[j].id, request);
				}
			});
		}
	});

	// Send options to other extension pages
	chrome.extension.sendRequest(request);
}

// Return true is the url is part of an excluded site
function isExcludedSite(url) {
	var excluded = !options.whiteListMode;
	var siteAddress = url.substr(url.indexOf('://') + 3);
	if (siteAddress.substr(0, 4) == 'www.') {
		siteAddress = siteAddress.substr(4);
	}
	for (var i = 0; i < options.excludedSites.length; i++) {
		var es = options.excludedSites[i];
		if (es.substr(0, 4) == 'www.') {
			es = es.substr(4);
		}
		if (es && es.length <= siteAddress.length) {
			if (siteAddress.substr(0, es.length) == es) {
				return excluded;
			}
		}
	}
	return !excluded;
}

function compareVersionNumbers(v1, v2) {
	var aV1 = v1.split('.'),
		aV2 = v2.split('.'),
		l = Math.min(aV1.length, aV2.length),
		i, cmp;
	for (i = 0; i < l; i++) {
		cmp = parseInt(aV1[i]) < parseInt(aV2[i]);
		if (cmp !== 0) {
			return cmp;
		}
	}
	return aV1.length - aV2.length;
}

// Return true if the version of Chrome is superior or equal to minVersion
function hasMinChromeVersion(minVersion) {
	var matches = navigator.appVersion.match(/Chrome\/([^\s]+)/);
	if (!matches || matches.length < 2) { return; }
	var currentVersion = matches[1];
	return compareVersionNumbers(currentVersion, minVersion) >= 0;
}

function keyCodeToKeyName(keyCode) {
	if (keyCode == 16) {
		return 'Shift';
	} else if (keyCode == 17) {
		return 'Ctrl';
	} else if (keyCode == 17) {
		return 'Command';
	} else if (keyCode >= 65 && keyCode <= 90) {
		return String.fromCharCode(keyCode);
	} else {
		return 'None';
	}
}

function showUpdateNotification() {
	webkitNotifications.createHTMLNotification(chrome.extension.getURL('html/update-notif.html')).show();
}
<commit_msg>Made 'Add to history' active by default.<commit_after>// Copyright (c) 2012 Romain Vallet <romain.vallet@gmail.com>
// Licensed under the MIT license, read license.txt

// Load options from local storage
// Return default values if none exist
function loadOptions() {
	var options;
	if (localStorage.options == null) {
		localStorage.options = '{}';
	}
	options = JSON.parse(localStorage.options);

	options.extensionEnabled = 	options.hasOwnProperty('extensionEnabled') ? options.extensionEnabled : true;
	options.pageActionEnabled = options.hasOwnProperty('pageActionEnabled') ? options.pageActionEnabled : true;
	options.showCaptions = 		options.hasOwnProperty('showCaptions') ? options.showCaptions : true;
	options.showHighRes = 		options.hasOwnProperty('showHighRes') ? options.showHighRes : false;
	options.addToHistory = 		options.hasOwnProperty('addToHistory') ? options.addToHistory : true;
	options.alwaysPreload = 	options.hasOwnProperty('alwaysPreload') ? options.alwaysPreload : false;
	options.displayDelay = 		options.hasOwnProperty('displayDelay') ? options.displayDelay : 100;
	options.fadeDuration = 		options.hasOwnProperty('fadeDuration') ? options.fadeDuration : 200;
	options.excludedSites = 	options.hasOwnProperty('excludedSites') ? options.excludedSites : [];
	options.whiteListMode = 	options.hasOwnProperty('whiteListMode') ? options.whiteListMode : false;
	options.picturesOpacity = 	options.hasOwnProperty('picturesOpacity') ? options.picturesOpacity : 1;
	options.showWhileLoading = 	options.hasOwnProperty('showWhileLoading') ? options.showWhileLoading : true;
	//options.expAlwaysFullZoom = options.hasOwnProperty('expAlwaysFullZoom') ? options.expAlwaysFullZoom : false;
	options.mouseUnderlap = 	options.hasOwnProperty('mouseUnderlap') ? options.mouseUnderlap : true;
	options.updateNotifications = 	options.hasOwnProperty('updateNotifications') ? options.updateNotifications : true;
	options.enableAds = 		options.hasOwnProperty('enableAds') ? options.enableAds : 0;
	options.filterNSFW = 		options.hasOwnProperty('filterNSFW') ? options.filterNSFW : false;

	// Action keys
	options.actionKey = 			options.hasOwnProperty('actionKey') ? options.actionKey : 0;
	options.fullZoomKey = 			options.hasOwnProperty('fullZoomKey') ? options.fullZoomKey : 90;
	options.hideKey = 				options.hasOwnProperty('hideKey') ? options.hideKey : 88;
	options.openImageInWindowKey =	options.hasOwnProperty('openImageInWindowKey') ? options.openImageInWindowKey : 87;
	options.openImageInTabKey =		options.hasOwnProperty('openImageInTabKey') ? options.openImageInTabKey : 84;
	options.saveImageKey =			options.hasOwnProperty('saveImageKey') ? options.saveImageKey : 83;

	localStorage.options = JSON.stringify(options);

	return options;
}

// Send options to all tabs and extension pages
function sendOptions(options) {
	var request = {action: 'optionsChanged', 'options': options};

	// Send options to all tabs
	chrome.windows.getAll(null, function (windows) {
		for (var i=0; i<windows.length; i++) {
			chrome.tabs.getAllInWindow(windows[i].id, function(tabs) {
				for (var j=0; j<tabs.length; j++) {
					chrome.tabs.sendRequest(tabs[j].id, request);
				}
			});
		}
	});

	// Send options to other extension pages
	chrome.extension.sendRequest(request);
}

// Return true is the url is part of an excluded site
function isExcludedSite(url) {
	var excluded = !options.whiteListMode;
	var siteAddress = url.substr(url.indexOf('://') + 3);
	if (siteAddress.substr(0, 4) == 'www.') {
		siteAddress = siteAddress.substr(4);
	}
	for (var i = 0; i < options.excludedSites.length; i++) {
		var es = options.excludedSites[i];
		if (es.substr(0, 4) == 'www.') {
			es = es.substr(4);
		}
		if (es && es.length <= siteAddress.length) {
			if (siteAddress.substr(0, es.length) == es) {
				return excluded;
			}
		}
	}
	return !excluded;
}

function compareVersionNumbers(v1, v2) {
	var aV1 = v1.split('.'),
		aV2 = v2.split('.'),
		l = Math.min(aV1.length, aV2.length),
		i, cmp;
	for (i = 0; i < l; i++) {
		cmp = parseInt(aV1[i]) < parseInt(aV2[i]);
		if (cmp !== 0) {
			return cmp;
		}
	}
	return aV1.length - aV2.length;
}

// Return true if the version of Chrome is superior or equal to minVersion
function hasMinChromeVersion(minVersion) {
	var matches = navigator.appVersion.match(/Chrome\/([^\s]+)/);
	if (!matches || matches.length < 2) { return; }
	var currentVersion = matches[1];
	return compareVersionNumbers(currentVersion, minVersion) >= 0;
}

function keyCodeToKeyName(keyCode) {
	if (keyCode == 16) {
		return 'Shift';
	} else if (keyCode == 17) {
		return 'Ctrl';
	} else if (keyCode == 17) {
		return 'Command';
	} else if (keyCode >= 65 && keyCode <= 90) {
		return String.fromCharCode(keyCode);
	} else {
		return 'None';
	}
}

function showUpdateNotification() {
	webkitNotifications.createHTMLNotification(chrome.extension.getURL('html/update-notif.html')).show();
}
<|endoftext|>


<commit_before>module.exports = function(conn) {
  return {
    list: function(businessId, callback) {
      conn.get('/businesses/'+businessId+'/audits', callback);
    },

    create: function(businessId, audit, callback) {
      conn.post('/businesses/'+businessId+'/audits', audit, callback);
    },

    edit: function(businessId, auditId, audit, callback) {
      conn.put('/businesses/'+businessId+'/audits/'+auditId, audit, callback);
    },

    find: function(businessId, auditId, callback) {
      conn.get('/businesses/'+businessId+'/audits/'+auditId, callback);
    },

    delete: function(businessId, auditId, callback){
      conn.delete('/businesses/'+businessId+'/audits/'+auditId, callback);
    },

    addFailure: function(businessId, auditId, failure, callback) {
      conn.post(
        '/businesses/' + businessId + '/audits/' + auditId + '/failures',
        failure,
        callback
      );
    },

    listShared: function(businessId, callback) {
      conn.get('/businesses/' + businessId + '/audits/shared', callback);
    },

    share: function(businessId, shareData, callback){
      conn.post('/businesses/' + businessId + '/audits/', shareData, callback);
    }
  };
};
<commit_msg>this adds functions for sharing & removing sharing for a specific audit<commit_after>module.exports = function(conn) {
  return {
    list: function(businessId, callback) {
      conn.get('/businesses/'+businessId+'/audits', callback);
    },

    create: function(businessId, audit, callback) {
      conn.post('/businesses/'+businessId+'/audits', audit, callback);
    },

    edit: function(businessId, auditId, audit, callback) {
      conn.put('/businesses/'+businessId+'/audits/'+auditId, audit, callback);
    },

    find: function(businessId, auditId, callback) {
      conn.get('/businesses/'+businessId+'/audits/'+auditId, callback);
    },

    delete: function(businessId, auditId, callback){
      conn.delete('/businesses/'+businessId+'/audits/'+auditId, callback);
    },

    addFailure: function(businessId, auditId, failure, callback) {
      conn.post(
        '/businesses/' + businessId + '/audits/' + auditId + '/failures',
        failure,
        callback
      );
    },

    listShared: function(businessId, callback) {
      conn.get('/businesses/' + businessId + '/audits/shared', callback);
    },

    share: function(customerId, shareData, callback){
      conn.post('/businesses/' + customerId + '/audits/', shareData, callback);
    },
    removeShare: function(customerId, shareData, callback){
      conn.delete('/businesses/'+customerId+'/audits/shared/', callback);
    }
  };
};
<|endoftext|>


<commit_before>ig.module(
	'game.entities.demonfang'
)
.requires(
	'impact.entity'
)

.defines(function(){
	EntityDemonFang = ig.Entity.extend({
		/* Set up projectile properties */
		size: {x: 20, y: 20},
		offset: {x: 5, y: 6},
		animSheet: new ig.AnimationSheet('media/demonfang.png', 28, 28),
		maxVel: {x:100, y: 0},
		speed: 100,

		/* Set up collision properties */
		type: ig.Entity.TYPE.NONE,
		checkAgainst: ig.Entity.TYPE.B,
		collides: ig.Entity.COLLIDES.PASSIVE,

		/* init method */
		init: function( x, y, settings ) {
			this.addAnim('idle', 0.1, [0, 1, 2]);
        	this.parent( x , y, settings );
            this.vel.x = settings.flip ? -1*this.speed : 1*this.speed;
            this.currentAnim.flip.x = settings.flip;
        },

        /* check method for collisions */
        check: function( other ) {
            other.receiveDamage( 5, this );
            this.kill();
        },

        handleMovementTrace: function(res){
            this.parent(res);
            if(res.collision.x){
            	this.kill();
            }
        },

	});
});<commit_msg>Commenting demon fang<commit_after>ig.module(
	'game.entities.demonfang'
)
.requires(
	'impact.entity'
)

.defines(function(){
	EntityDemonFang = ig.Entity.extend({
		/* Set up projectile properties */
		size: {x: 20, y: 20},
		offset: {x: 5, y: 6},
		animSheet: new ig.AnimationSheet('media/demonfang.png', 28, 28),
		maxVel: {x:100, y: 0},
		speed: 100,

		/* Set up collision properties */
		type: ig.Entity.TYPE.NONE,
		checkAgainst: ig.Entity.TYPE.B,
		collides: ig.Entity.COLLIDES.PASSIVE,

		/* init method */
		init: function( x, y, settings ) {
			// Define animation frames
			this.addAnim('idle', 0.1, [0, 1, 2]);
			// Read settings from parent object (player.js)
        	this.parent( x , y, settings );
        	// Assign velocity based on flip property of player (stored in settings)
            this.vel.x = settings.flip ? -1*this.speed : 1*this.speed;
            // Flip projectile based on player's flip value
            this.currentAnim.flip.x = settings.flip;
        },

        /* check method for collisions */
        check: function( other ) {
            other.receiveDamage( 5, this );
            this.kill();
        },

        /* Kill projectile on collision on the x-axis */
        handleMovementTrace: function(res){
            this.parent(res);
            if(res.collision.x){
            	this.kill();
            }
        },

	});
});<|endoftext|>


<commit_before>//加载一个包含单词以及模板的全局config对象
//日语
//资源根路径 http://ecator.github.io/anki-theme-hjbasic/
var config={
	tpl:{
		front:"
{{word}}
",
		back:"

{{word}}

{{phonetic}}

{{trans}}
"
	},
	baseUrl:"http://ecator.github.io/anki-theme-basic-baidu-jp-en/",
	//语言设置
	//日语
	jp:{
		words:new Array("暗記","日本語","こんにちは"),
		phonetic:new Array("あんき","にほんご","こんにちは"),
		trans:new Array("背诵","日语","你好")
	},
	//德语
	de:{
		words:new Array("Deutsch","Hallo"),
		phonetics:new Array("",""),
		trans:new Array("德语","你好")
	},
	//英语
	en:{
		words:new Array("english","hello"),
		phonetics:new Array("ɪŋɡlɪʃ","hə'ləʊ"),
		trans:new Array("英语","你好")
	},
	//法语
	fra:{
		words:new Array("française","Bonjour"),
		phonetics:new Array("frɑ̃sɛ","bɔ̃ʒu:r"),
		trans:new Array("法语","你好")
	},
	//韩语
	kor:{
		words:new Array("한국어","오빠"),
		phonetics:new Array("",""),
		trans:new Array("德语","你好")
	},
	//西班牙语
	spa:{
		words:new Array("España","testigo"),
		phonetics:new Array("",""),
		trans:new Array("西班牙语","你好")
	},
	//阿拉伯语
	ara:{
		words:new Array("عربي","مرحبا"),
		phonetics:new Array("",""),
		trans:new Array("阿拉伯语","你好")
	},
	//俄语
	ru:{
		words:new Array("русский","Привет"),
		phonetics:new Array("",""),
		trans:new Array("俄语","你好")
	},
	//葡萄牙语
	pt:{
		words:new Array("Português","Olá"),
		phonetics:new Array("",""),
		trans:new Array("葡萄牙语","你好")
	},
	//泰语
	th:{
		words:new Array("ภาษาไทย","สวัสดี"),
		phonetics:new Array("",""),
		trans:new Array("泰语","你好")
	},
	//粤语
	cte:{
		words:new Array("广东话","你好"),
		phonetics:new Array("",""),
		trans:new Array("粤语","你好")
	}
}<commit_msg>修复日语config中phonetic字段错误<commit_after>//加载一个包含单词以及模板的全局config对象
//日语
//资源根路径 http://ecator.github.io/anki-theme-hjbasic/
var config={
	tpl:{
		front:"
{{word}}
",
		back:"

{{word}}

{{phonetic}}

{{trans}}
"
	},
	baseUrl:"http://ecator.github.io/anki-theme-basic-baidu-jp-en/",
	//语言设置
	//日语
	jp:{
		words:new Array("暗記","日本語","こんにちは"),
		phonetics:new Array("あんき","にほんご","こんにちは"),
		trans:new Array("背诵","日语","你好")
	},
	//德语
	de:{
		words:new Array("Deutsch","Hallo"),
		phonetics:new Array("",""),
		trans:new Array("德语","你好")
	},
	//英语
	en:{
		words:new Array("english","hello"),
		phonetics:new Array("ɪŋɡlɪʃ","hə'ləʊ"),
		trans:new Array("英语","你好")
	},
	//法语
	fra:{
		words:new Array("française","Bonjour"),
		phonetics:new Array("frɑ̃sɛ","bɔ̃ʒu:r"),
		trans:new Array("法语","你好")
	},
	//韩语
	kor:{
		words:new Array("한국어","오빠"),
		phonetics:new Array("",""),
		trans:new Array("德语","你好")
	},
	//西班牙语
	spa:{
		words:new Array("España","testigo"),
		phonetics:new Array("",""),
		trans:new Array("西班牙语","你好")
	},
	//阿拉伯语
	ara:{
		words:new Array("عربي","مرحبا"),
		phonetics:new Array("",""),
		trans:new Array("阿拉伯语","你好")
	},
	//俄语
	ru:{
		words:new Array("русский","Привет"),
		phonetics:new Array("",""),
		trans:new Array("俄语","你好")
	},
	//葡萄牙语
	pt:{
		words:new Array("Português","Olá"),
		phonetics:new Array("",""),
		trans:new Array("葡萄牙语","你好")
	},
	//泰语
	th:{
		words:new Array("ภาษาไทย","สวัสดี"),
		phonetics:new Array("",""),
		trans:new Array("泰语","你好")
	},
	//粤语
	cte:{
		words:new Array("广东话","你好"),
		phonetics:new Array("",""),
		trans:new Array("粤语","你好")
	}
}<|endoftext|>


<commit_before>/* Facebook like page*/

(function(d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s); js.id = id;
    js.src = "//connect.facebook.net/fr_FR/sdk.js#xfbml=1&version=v2.4&appId=1534300023482847";
    fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

/* Google analytics */

(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
        (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-67287154-1', 'auto');
ga('send', 'pageview');

/* Navigation bar */

document.getElementById("nav").innerHTML =
    '
'+
    ''+
    '
'+
    '<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">'+
    'Toggle navigation'+
    ''+
    ''+
    ''+
    '</button>'+
    ''+
    'Feed Southern Africa'+
    '
'+
    ''+
    '
'+
    '
'+
    '
HOME
'+
    '
ABOUT
'+
    '
PROGRAMS
'+
    '
JOIN
'+
    '
RATES
'+
    '
CONTACT
'+
    '
Gallery
'+
    '
'+
    '
'+
    '
'+
    '
'
;
/* Footer */

document.getElementById("footer").innerHTML = '
'+
    '
'+
    '
'+
    '
' +
    '
' +
    '
' +
    'Feed Southern Africa' +
    '' +
    '
' +
    '
' +
    '
' +
    '
'+
    '
'+
    '
 ' +
    '©  ' + new Date().getFullYear() + ' Feed Southern Africa. All rights reserved.' +
    '
'+
    '
'+
    '
'+
    '
';
<commit_msg>trying stuff<commit_after>/* Facebook like page*/

(function(d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s); js.id = id;
    js.src = "//connect.facebook.net/fr_FR/sdk.js#xfbml=1&version=v2.4&appId=1534300023482847";
    fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

/* Google analytics */

(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
        (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-67287154-1', 'auto');
ga('send', 'pageview');

/* iframe loading function*/
function IFrameScroll(link){
    window.galleryIframe.location=link;
    window.location.hash='galleryIframe';
}

/* Navigation bar */

document.getElementById("nav").innerHTML =
    '
'+
    ''+
    '
'+
    '<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">'+
    'Toggle navigation'+
    ''+
    ''+
    ''+
    '</button>'+
    ''+
    'Feed Southern Africa'+
    '
'+
    ''+
    '
'+
    '
'+
    '
HOME
'+
    '
ABOUT
'+
    '
PROGRAMS
'+
    '
JOIN
'+
    '
RATES
'+
    '
CONTACT
'+
    '
Gallery
'+
    '
'+
    '
'+
    '
'+
    '
'
;
/* Footer */

document.getElementById("footer").innerHTML = '
'+
    '
'+
    '
'+
    '
' +
    '
' +
    '
' +
    'Feed Southern Africa' +
    '' +
    '
' +
    '
' +
    '
' +
    '
'+
    '
'+
    '
 ' +
    '©  ' + new Date().getFullYear() + ' Feed Southern Africa. All rights reserved.' +
    '
'+
    '
'+
    '
'+
    '
';
<|endoftext|>


<commit_before>/*
 *** CUSTOM JS ***
*/

// Setup three.js WebGL renderer. Note: Antialiasing is a big performance hit.
// Only enable it if you actually need to.
var renderer = new THREE.WebGLRenderer({antialias: true});
renderer.setPixelRatio(window.devicePixelRatio);

// Append the canvas element created by the renderer to document body element.
document.body.appendChild(renderer.domElement);

// Create a three.js scene.
var scene = new THREE.Scene();

// Create a three.js camera.
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 10000);

var controls = new THREE.VRControls(camera);
controls.standing = true; //raise user above ground

/*** VR Controls ***/
// https://github.com/brianpeiris/three-firstperson-vr-controls
// https://brian.peiris.io/three-firstperson-vr-controls/demo/
// Create VRControls in addition to FirstPersonVRControls.
var vrControls = new THREE.VRControls(camera);
//vrControls.standing = true;
var fpVrControls = new THREE.FirstPersonVRControls(camera, scene);
// Optionally enable vertical movement.
fpVrControls.verticalMovement = true;
fpVrControls.movementSpeed = 5; //normal
fpVrControls.movementSpeed = 10;

// Apply VR stereo rendering to renderer.
var effect = new THREE.VREffect(renderer);
effect.setSize(window.innerWidth, window.innerHeight);

// Add a repeating grid as a skybox.
var boxSize = 40;
//var boxSize = 20;
var loader = new THREE.TextureLoader();
loader.load('img/box.png', onTextureLoaded);
//loader.load('assets/textures/crate.gif', onTextureLoaded);
//loader.load('assets/mc-textures/leaves_big_oak_opaque.png', onTextureLoaded);
var dirt_texture = new THREE.TextureLoader().load( "assets/textures/dirt.png" );

/* see: https://threejs.org/docs/api/textures/Texture.html */
function onTextureLoaded(texture) {
  //texture.wrapS = THREE.RepeatWrapping;
  //texture.wrapT = THREE.RepeatWrapping;
  //texture.repeat.set(boxSize, boxSize);
  //texture.repeat.set( 5, 5 ); //how many times the texture is repeated across the surface, in each direction U and V

  var geometry = new THREE.BoxGeometry(boxSize, boxSize, boxSize);
  var material = new THREE.MeshBasicMaterial({
    map: dirt_texture,
    //map: texture,
    color: 0x01BE00,
    //side: THREE.BackSide //inside
    //side: THREE.FrontSide //outsiWde (nothing / default)
    side: THREE.DoubleSide //both
  });

  // Align the skybox to the floor (which is at y=0).
  skybox = new THREE.Mesh(geometry, material);
  //skybox.position.y = boxSize/2;
  skybox.position.y = 2.5; //grid box way above
  //scene.add(skybox);

  // For high end VR devices like Vive and Oculus, take into account the stage parameters provided.
  setupStage();
}

///////////
// FLOOR //
///////////
// note: 4x4 checkboard pattern scaled so that each square is 25 by 25 pixels.
//var floorTexture = new THREE.ImageUtils.loadTexture( 'assets/textures/checkerboard.jpg' );
var floorTexture = new THREE.ImageUtils.loadTexture( 'assets/textures/ground.png' );
//floorTexture.wrapS = floorTexture.wrapT = THREE.RepeatWrapping;
floorTexture.wrapS = floorTexture.wrapT = THREE.RepeatWrapping;
floorTexture.repeat.set( 1, 1 );
// DoubleSide: render texture on both sides of mesh
var floorMaterial = new THREE.MeshBasicMaterial( { map: floorTexture, side: THREE.DoubleSide } );
var floorGeometry = new THREE.PlaneGeometry(60, 40, 1, 1); // e/w, n/s
var floor = new THREE.Mesh(floorGeometry, floorMaterial);
//floor.position.y = -0.5;
floor.position.y = -4.8; //lower = floor lowers
floor.rotation.x = Math.PI / 2; // 1.57
scene.add(floor);

///////////
// WALL //
///////////
var wall_y_pos = -2.3;
//var wallTexture = new THREE.ImageUtils.loadTexture( 'assets/textures/checkerboard.jpg' );
var wallTexture = new THREE.ImageUtils.loadTexture( 'assets/textures/wall.png' );
wallTexture.wrapS = floorTexture.wrapT = THREE.RepeatWrapping;
wallTexture.repeat.set( 1, 1 );
// DoubleSide: render texture on both sides of mesh
var wallMaterial = new THREE.MeshBasicMaterial( { map: wallTexture, side: THREE.DoubleSide } );
var wallGeometry = new THREE.PlaneGeometry(60, 40, 1, 1); // e/w, n/s
//var wallGeometry = new THREE.PlaneGeometry(600, 40, 1, 1); // extended
var wall1 = new THREE.Mesh(wallGeometry, wallMaterial);
var wall2 = new THREE.Mesh(wallGeometry, wallMaterial);
var wall3 = new THREE.Mesh(wallGeometry, wallMaterial);
var wall4 = new THREE.Mesh(wallGeometry, wallMaterial);
//floor.position.y = -0.5;
/* Front Wall */
wall1.position.x = 0;
wall1.position.y = wall_y_pos;
wall1.position.z = -15; //further away
var wall_rotation = 0.01;
console.log(wall_rotation);
//wall1.rotation.x = wall_rotation;
scene.add(wall1);
/* Back Wall */
wall2.position.x = 0;
wall2.position.y = wall_y_pos;
wall2.position.z = 15; //further away
//wall2.rotation.x = wall_rotation;
scene.add(wall2);
/* Left Side Wall */
wall3.position.x = -15;
wall3.position.y = wall_y_pos;
wall3.position.z = 0; //further away
//wall3.rotation.x = wall_rotation;
//wall3.rotation.y = 2;
wall3.rotation.y = Math.PI / 2;
scene.add(wall3);
/* Right Side Wall */
wall4.position.x = 15;
wall4.position.y = wall_y_pos;
wall4.position.z = 0; //further away
wall4.rotation.y = Math.PI / 2;
scene.add(wall4);

// Create a VR manager helper to enter and exit VR mode.
var params = {
  hideButton: false, // Default: false.
  isUndistorted: false // Default: false.
};
var manager = new WebVRManager(renderer, effect, params);

/////////////
// OBJECTS //
/////////////
// Create 3D objects.
var geometry = new THREE.BoxGeometry(0.5, 0.5, 0.5);
var material = new THREE.MeshNormalMaterial();
var cube = new THREE.Mesh(geometry, material);
var sign = new THREE.Mesh(geometry, material);
//cube.position.set(0, controls.userHeight, -1);
cube.position.set(0, 3.5, -1); //move cube higher
scene.add(cube);
//sign.position.set(-2.25, 0.25, -2.5); //left-right, top-down, forward-back
sign.position.set(-4.75, 0.25, -4.75); //left-right, top-down, forward-back
scene.add(sign);

///////////
// SOUND //
///////////
var listener = new THREE.AudioListener();
camera.add( listener );

// sound spheres
//var sphere = new THREE.SphereGeometry( 5, 8, 4 );
var sphere = new THREE.SphereGeometry( 2.5, 4, 2 );
material_sphere1 = new THREE.MeshPhongMaterial( { color: 0xffaa00, shading: THREE.FlatShading, shininess: 0 } );
material_sphere2 = new THREE.MeshPhongMaterial( { color: 0xff2200, shading: THREE.FlatShading, shininess: 0 } );
material_sphere3 = new THREE.MeshPhongMaterial( { color: 0x6622aa, shading: THREE.FlatShading, shininess: 0 } );

var audioLoader = new THREE.AudioLoader();

var mesh1 = new THREE.Mesh( sphere, material_sphere1 );
mesh1.position.set(0, 2.5, -20);
scene.add( mesh1 );
var sound1 = new THREE.PositionalAudio( listener );
audioLoader.load( 'assets/sounds/lost-woods.mp3', function( buffer ) {
  sound1.setBuffer( buffer );
  sound1.setRefDistance( 2 );
  sound1.setVolume(0.5);
  sound1.setLoop(true);
  sound1.play();
});
mesh1.add( sound1 );

//

var mesh2 = new THREE.Mesh( sphere, material_sphere2 );
mesh2.position.set(0, 2.5, 20);
scene.add( mesh2 );

var sound2 = new THREE.PositionalAudio( listener );
audioLoader.load( 'assets/sounds/bolero-of-fire.mp3', function( buffer ) {
  sound2.setBuffer( buffer );
  sound2.setRefDistance( 2 );
  sound2.setVolume(0.5);
  sound2.setLoop(true);
  sound2.play();
});
mesh2.add( sound2 );

//

var mesh3 = new THREE.Mesh( sphere, material_sphere3 );
mesh3.position.set(20, 2.5, 0);
scene.add( mesh3 );

var sound3 = new THREE.PositionalAudio( listener );
audioLoader.load( 'assets/sounds/ice-cavern.mp3', function( buffer ) {
  sound3.setBuffer( buffer );
  sound3.setRefDistance( 2 );
  sound3.setVolume(0.1);
  sound3.setLoop(true);
  sound3.play();
});
mesh3.add( sound3 );

///////////////////
// LIGHT / MODEL //
///////////////////
var ambient = new THREE.AmbientLight( 0x444444 );
//var ambient = new THREE.AmbientLight( 0x101030 );
scene.add( ambient );

var directionalLight = new THREE.DirectionalLight( 0xffeedd );
directionalLight.position.set( 0, 0, 1 ).normalize();
scene.add( directionalLight );

var onProgress = function ( xhr ) {
  if ( xhr.lengthComputable ) {
    var percentComplete = xhr.loaded / xhr.total * 100;
    console.log( Math.round(percentComplete, 2) + '% downloaded' );
  }
};

var onError = function ( xhr ) { };

THREE.Loader.Handlers.add( /\.dds$/i, new THREE.DDSLoader() );

var mtlLoader = new THREE.MTLLoader();
mtlLoader.setPath( 'assets/models/ganondorf/' );
mtlLoader.load( 'model.mtl', function( materials ) {

  materials.preload();

  var objLoader = new THREE.OBJLoader();
  objLoader.setMaterials( materials );
  objLoader.setPath( 'assets/models/ganondorf/' );
  objLoader.load( 'model.obj', function ( object ) {

    //object.scale.set(0.4, 0.4, 0.4);
    object.scale.set(0.5, 0.5, 0.5);
    //object.position.y = - 95;
    //object.position.set(0, 0, -5);
    object.position.set(0, -4.5, -5); //ganondorf on ground

    //object.material.emissive = new THREE.Color( 0.2, 0.2, 0.2 );

    scene.add( object );

  }, onProgress, onError );

});

window.addEventListener('resize', onResize, true);
window.addEventListener('vrdisplaypresentchange', onResize, true);

// Request animation frame loop function
var lastRender = 0;
function animate(timestamp) {
  var delta = Math.min(timestamp - lastRender, 500);
  lastRender = timestamp;

  // Apply rotation to cube mesh
  cube.rotation.y += delta * 0.0006;

  controls.update();
  // Render the scene through the manager.

  // Update FirstPersonControls after VRControls.
  // FirstPersonControls requires a timestamp.
  vrControls.update();
  fpVrControls.update(timestamp);

  manager.render(scene, camera, timestamp);
  effect.render(scene, camera);

  vrDisplay.requestAnimationFrame(animate);
}

function onResize(e) {
  effect.setSize(window.innerWidth, window.innerHeight);
  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();
}

var vrDisplay;

// Get the HMD, and if we're dealing with something that specifies stageParameters, rearrange the scene.
function setupStage() {
  navigator.getVRDisplays().then(function(displays) {
    if (displays.length > 0) {
      vrDisplay = displays[0];
      if (vrDisplay.stageParameters) {
        setStageDimensions(vrDisplay.stageParameters);
      }
      vrDisplay.requestAnimationFrame(animate);
    }
  });
}

function setStageDimensions(stage) {
  /* not sure what this does... */
  // Make the skybox fit the stage.
  var material = skybox.material;
  scene.remove(skybox);

  // Size the skybox according to the size of the actual stage.
  var geometry = new THREE.BoxGeometry(stage.sizeX, boxSize, stage.sizeZ);
  skybox = new THREE.Mesh(geometry, material);

  // Place it on the floor.
  skybox.position.y = boxSize/2;
  scene.add(skybox);

  // Place the cube in the middle of the scene, at user height.
  cube.position.set(0, controls.userHeight, 0);
}<commit_msg>hide cubes<commit_after>/*
 *** CUSTOM JS ***
*/

// Setup three.js WebGL renderer. Note: Antialiasing is a big performance hit.
// Only enable it if you actually need to.
var renderer = new THREE.WebGLRenderer({antialias: true});
renderer.setPixelRatio(window.devicePixelRatio);

// Append the canvas element created by the renderer to document body element.
document.body.appendChild(renderer.domElement);

// Create a three.js scene.
var scene = new THREE.Scene();

// Create a three.js camera.
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 10000);

var controls = new THREE.VRControls(camera);
controls.standing = true; //raise user above ground

/*** VR Controls ***/
// https://github.com/brianpeiris/three-firstperson-vr-controls
// https://brian.peiris.io/three-firstperson-vr-controls/demo/
// Create VRControls in addition to FirstPersonVRControls.
var vrControls = new THREE.VRControls(camera);
//vrControls.standing = true;
var fpVrControls = new THREE.FirstPersonVRControls(camera, scene);
// Optionally enable vertical movement.
fpVrControls.verticalMovement = true;
fpVrControls.movementSpeed = 5; //normal
fpVrControls.movementSpeed = 10;

// Apply VR stereo rendering to renderer.
var effect = new THREE.VREffect(renderer);
effect.setSize(window.innerWidth, window.innerHeight);

// Add a repeating grid as a skybox.
var boxSize = 40;
//var boxSize = 20;
var loader = new THREE.TextureLoader();
loader.load('img/box.png', onTextureLoaded);
//loader.load('assets/textures/crate.gif', onTextureLoaded);
//loader.load('assets/mc-textures/leaves_big_oak_opaque.png', onTextureLoaded);
var dirt_texture = new THREE.TextureLoader().load( "assets/textures/dirt.png" );

/* see: https://threejs.org/docs/api/textures/Texture.html */
function onTextureLoaded(texture) {
  //texture.wrapS = THREE.RepeatWrapping;
  //texture.wrapT = THREE.RepeatWrapping;
  //texture.repeat.set(boxSize, boxSize);
  //texture.repeat.set( 5, 5 ); //how many times the texture is repeated across the surface, in each direction U and V

  var geometry = new THREE.BoxGeometry(boxSize, boxSize, boxSize);
  var material = new THREE.MeshBasicMaterial({
    map: dirt_texture,
    //map: texture,
    color: 0x01BE00,
    //side: THREE.BackSide //inside
    //side: THREE.FrontSide //outside
    side: THREE.DoubleSide //both
  });

  // Align the skybox to the floor (which is at y=0).
  skybox = new THREE.Mesh(geometry, material);
  //skybox.position.y = boxSize/2;
  skybox.position.y = 2.5; //grid box way above
  //scene.add(skybox);

  // For high end VR devices like Vive and Oculus, take into account the stage parameters provided.
  setupStage();
}

///////////
// FLOOR //
///////////
// note: 4x4 checkboard pattern scaled so that each square is 25 by 25 pixels.
//var floorTexture = new THREE.ImageUtils.loadTexture( 'assets/textures/checkerboard.jpg' );
var floorTexture = new THREE.ImageUtils.loadTexture( 'assets/textures/ground.png' );
//floorTexture.wrapS = floorTexture.wrapT = THREE.RepeatWrapping;
floorTexture.wrapS = floorTexture.wrapT = THREE.RepeatWrapping;
floorTexture.repeat.set( 1, 1 );
// DoubleSide: render texture on both sides of mesh
var floorMaterial = new THREE.MeshBasicMaterial( { map: floorTexture, side: THREE.DoubleSide } );
var floorGeometry = new THREE.PlaneGeometry(60, 40, 1, 1); // e/w, n/s
var floor = new THREE.Mesh(floorGeometry, floorMaterial);
//floor.position.y = -0.5;
floor.position.y = -4.8; //lower = floor lowers
floor.rotation.x = Math.PI / 2; // 1.57
scene.add(floor);

///////////
// WALL //
///////////
var wall_y_pos = -2.3;
//var wallTexture = new THREE.ImageUtils.loadTexture( 'assets/textures/checkerboard.jpg' );
var wallTexture = new THREE.ImageUtils.loadTexture( 'assets/textures/wall.png' );
wallTexture.wrapS = floorTexture.wrapT = THREE.RepeatWrapping;
wallTexture.repeat.set( 1, 1 );
// DoubleSide: render texture on both sides of mesh
var wallMaterial = new THREE.MeshBasicMaterial( { map: wallTexture, side: THREE.DoubleSide } );
var wallGeometry = new THREE.PlaneGeometry(60, 40, 1, 1); // e/w, n/s
//var wallGeometry = new THREE.PlaneGeometry(600, 40, 1, 1); // extended
var wall1 = new THREE.Mesh(wallGeometry, wallMaterial);
var wall2 = new THREE.Mesh(wallGeometry, wallMaterial);
var wall3 = new THREE.Mesh(wallGeometry, wallMaterial);
var wall4 = new THREE.Mesh(wallGeometry, wallMaterial);
//floor.position.y = -0.5;
/* Front Wall */
wall1.position.x = 0;
wall1.position.y = wall_y_pos;
wall1.position.z = -15; //further away
var wall_rotation = 0.01;
console.log(wall_rotation);
//wall1.rotation.x = wall_rotation;
scene.add(wall1);
/* Back Wall */
wall2.position.x = 0;
wall2.position.y = wall_y_pos;
wall2.position.z = 15; //further away
//wall2.rotation.x = wall_rotation;
scene.add(wall2);
/* Left Side Wall */
wall3.position.x = -15;
wall3.position.y = wall_y_pos;
wall3.position.z = 0; //further away
//wall3.rotation.x = wall_rotation;
//wall3.rotation.y = 2;
wall3.rotation.y = Math.PI / 2;
scene.add(wall3);
/* Right Side Wall */
wall4.position.x = 15;
wall4.position.y = wall_y_pos;
wall4.position.z = 0; //further away
wall4.rotation.y = Math.PI / 2;
scene.add(wall4);

// Create a VR manager helper to enter and exit VR mode.
var params = {
  hideButton: false, // Default: false.
  isUndistorted: false // Default: false.
};
var manager = new WebVRManager(renderer, effect, params);

/////////////
// OBJECTS //
/////////////
// Create 3D objects.
var geometry = new THREE.BoxGeometry(0.5, 0.5, 0.5);
var material = new THREE.MeshNormalMaterial();
var cube = new THREE.Mesh(geometry, material);
var sign = new THREE.Mesh(geometry, material);
//cube.position.set(0, controls.userHeight, -1);
cube.position.set(0, 3.5, -1); //move cube higher
sign.position.set(-4.75, 0.25, -4.75); //left-right, top-down, forward-back

//scene.add(cube);
//scene.add(sign);

///////////
// SOUND //
///////////
var listener = new THREE.AudioListener();
camera.add( listener );

// sound spheres
//var sphere = new THREE.SphereGeometry( 5, 8, 4 );
var sphere = new THREE.SphereGeometry( 2.5, 4, 2 );
material_sphere1 = new THREE.MeshPhongMaterial( { color: 0xffaa00, shading: THREE.FlatShading, shininess: 0 } );
material_sphere2 = new THREE.MeshPhongMaterial( { color: 0xff2200, shading: THREE.FlatShading, shininess: 0 } );
material_sphere3 = new THREE.MeshPhongMaterial( { color: 0x6622aa, shading: THREE.FlatShading, shininess: 0 } );

var audioLoader = new THREE.AudioLoader();

var mesh1 = new THREE.Mesh( sphere, material_sphere1 );
mesh1.position.set(0, 2.5, -20);
scene.add( mesh1 );
var sound1 = new THREE.PositionalAudio( listener );
audioLoader.load( 'assets/sounds/lost-woods.mp3', function( buffer ) {
  sound1.setBuffer( buffer );
  sound1.setRefDistance( 2 );
  sound1.setVolume(0.5);
  sound1.setLoop(true);
  sound1.play();
});
mesh1.add( sound1 );

//

var mesh2 = new THREE.Mesh( sphere, material_sphere2 );
mesh2.position.set(0, 2.5, 20);
scene.add( mesh2 );

var sound2 = new THREE.PositionalAudio( listener );
audioLoader.load( 'assets/sounds/bolero-of-fire.mp3', function( buffer ) {
  sound2.setBuffer( buffer );
  sound2.setRefDistance( 2 );
  sound2.setVolume(0.5);
  sound2.setLoop(true);
  sound2.play();
});
mesh2.add( sound2 );

//

var mesh3 = new THREE.Mesh( sphere, material_sphere3 );
mesh3.position.set(20, 2.5, 0);
scene.add( mesh3 );

var sound3 = new THREE.PositionalAudio( listener );
audioLoader.load( 'assets/sounds/ice-cavern.mp3', function( buffer ) {
  sound3.setBuffer( buffer );
  sound3.setRefDistance( 2 );
  sound3.setVolume(0.1);
  sound3.setLoop(true);
  sound3.play();
});
mesh3.add( sound3 );

///////////////////
// LIGHT / MODEL //
///////////////////
var ambient = new THREE.AmbientLight( 0x444444 );
//var ambient = new THREE.AmbientLight( 0x101030 );
scene.add( ambient );

var directionalLight = new THREE.DirectionalLight( 0xffeedd );
directionalLight.position.set( 0, 0, 1 ).normalize();
scene.add( directionalLight );

var onProgress = function ( xhr ) {
  if ( xhr.lengthComputable ) {
    var percentComplete = xhr.loaded / xhr.total * 100;
    console.log( Math.round(percentComplete, 2) + '% downloaded' );
  }
};

var onError = function ( xhr ) { };

THREE.Loader.Handlers.add( /\.dds$/i, new THREE.DDSLoader() );

var mtlLoader = new THREE.MTLLoader();
mtlLoader.setPath( 'assets/models/ganondorf/' );
mtlLoader.load( 'model.mtl', function( materials ) {

  materials.preload();

  var objLoader = new THREE.OBJLoader();
  objLoader.setMaterials( materials );
  objLoader.setPath( 'assets/models/ganondorf/' );
  objLoader.load( 'model.obj', function ( object ) {

    //object.scale.set(0.4, 0.4, 0.4);
    object.scale.set(0.5, 0.5, 0.5);
    //object.position.y = - 95;
    //object.position.set(0, 0, -5);
    object.position.set(0, -4.5, -5); //ganondorf on ground

    //object.material.emissive = new THREE.Color( 0.2, 0.2, 0.2 );

    scene.add( object );

  }, onProgress, onError );

});

window.addEventListener('resize', onResize, true);
window.addEventListener('vrdisplaypresentchange', onResize, true);

// Request animation frame loop function
var lastRender = 0;
function animate(timestamp) {
  var delta = Math.min(timestamp - lastRender, 500);
  lastRender = timestamp;

  // Apply rotation to cube mesh
  cube.rotation.y += delta * 0.0006;

  controls.update();
  // Render the scene through the manager.

  // Update FirstPersonControls after VRControls.
  // FirstPersonControls requires a timestamp.
  vrControls.update();
  fpVrControls.update(timestamp);

  manager.render(scene, camera, timestamp);
  effect.render(scene, camera);

  vrDisplay.requestAnimationFrame(animate);
}

function onResize(e) {
  effect.setSize(window.innerWidth, window.innerHeight);
  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();
}

var vrDisplay;

// Get the HMD, and if we're dealing with something that specifies stageParameters, rearrange the scene.
function setupStage() {
  navigator.getVRDisplays().then(function(displays) {
    if (displays.length > 0) {
      vrDisplay = displays[0];
      if (vrDisplay.stageParameters) {
        setStageDimensions(vrDisplay.stageParameters);
      }
      vrDisplay.requestAnimationFrame(animate);
    }
  });
}

function setStageDimensions(stage) {
  /* not sure what this does... */
  // Make the skybox fit the stage.
  var material = skybox.material;
  scene.remove(skybox);

  // Size the skybox according to the size of the actual stage.
  var geometry = new THREE.BoxGeometry(stage.sizeX, boxSize, stage.sizeZ);
  skybox = new THREE.Mesh(geometry, material);

  // Place it on the floor.
  skybox.position.y = boxSize/2;
  scene.add(skybox);

  // Place the cube in the middle of the scene, at user height.
  cube.position.set(0, controls.userHeight, 0);
}<|endoftext|>


<commit_before>// Closes the sidebar menu
$("#menu-close").click(function(e) {
  e.preventDefault();
  $("#sidebar-wrapper").toggleClass("active");
});

// Opens the sidebar menu
$("#menu-toggle").click(function(e) {
  e.preventDefault();
  $("#sidebar-wrapper").toggleClass("active");
});

// Scrolls to the selected menu item on the page
$(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') || location.hostname == this.hostname) {

      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top
        }, 1000);
        return false;
      }
    }
  });
});

// Map scrolling behaviour
$(document).ready(function() {
  $('#map_iframe').addClass('scrolloff');
  $('#map').on('click', function () {
    $('#map_iframe').removeClass('scrolloff');
  });

  $('#map_iframe').mouseleave(function  () {
    $('#map_iframe').addClass('scrolloff');
  });
});
<commit_msg>timeline<commit_after>// Closes the sidebar menu
$("#menu-close").click(function(e) {
  e.preventDefault();
  $("#sidebar-wrapper").toggleClass("active");
});

// Opens the sidebar menu
$("#menu-toggle").click(function(e) {
  e.preventDefault();
  $("#sidebar-wrapper").toggleClass("active");
});

// Scrolls to the selected menu item on the page
$(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') || location.hostname == this.hostname) {

      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top
        }, 1000);
        return false;
      }
    }
  });
});

// Map scrolling behaviour
$(document).ready(function() {
  $('#map_iframe').addClass('scrolloff');
  $('#map').on('click', function () {
    $('#map_iframe').removeClass('scrolloff');
  });

  $('#map_iframe').mouseleave(function  () {
    $('#map_iframe').addClass('scrolloff');
  });
});

// Timeline behaviour
jQuery(document).ready(function($){
	var $timeline_block = $('.cd-timeline-block');

	//hide timeline blocks which are outside the viewport
	$timeline_block.each(function(){
		if($(this).offset().top > $(window).scrollTop()+$(window).height()*0.75) {
			$(this).find('.cd-timeline-img, .cd-timeline-content').addClass('is-hidden');
		}
	});

	//on scolling, show/animate timeline blocks when enter the viewport
	$(window).on('scroll', function(){
		$timeline_block.each(function(){
			if( $(this).offset().top <= $(window).scrollTop()+$(window).height()*0.75 && $(this).find('.cd-timeline-img').hasClass('is-hidden') ) {
				$(this).find('.cd-timeline-img, .cd-timeline-content').removeClass('is-hidden').addClass('bounce-in');
			}
		});
	});
});
<|endoftext|>


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

    /* Hide menu after click
    ----------------------------------------------*/
    $('.navbar-nav li a').click(function(event) {
        $('.in').collapse('hide');
    });

    /* Smooth scroll to section
    ----------------------------------------------*/
    $('a.scroll[href*=#]:not([href=#])').click(function() {
        if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') || location.hostname == this.hostname) {

            var target = $(this.hash);
            target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
            if (target.length) {
                $('html,body').animate({
                    scrollTop: target.offset().top-70
                }, 2000);
                return false;
            }
        }
    });

    /* Team slideshow
    ----------------------------------------------*/
    $("#team-carousel").owlCarousel({

        autoPlay: 5000, //Set AutoPlay to 5 seconds

        items : 4,
        itemsDesktopSmall : [979,3],
        stopOnHover: true

    });

    /* Testimonials slideshow
    ----------------------------------------------*/
    $("#testimonial-carousel").owlCarousel({

        autoPlay: 6000, //Set AutoPlay to 6 seconds

        singleItem: true,
        pagination : false

    });

    /* Tooltip
    ----------------------------------------------*/
    $('[data-toggle="tooltip"]').tooltip();

    /* Lightbox
    ----------------------------------------------*/
    $('.image-link').magnificPopup({
        type:'image'
    });

    /* Google map
    ----------------------------------------------*/
    $(".map").each(function(){

        var data_zoom = 17;

        if ($(this).attr("data-zoom") !== undefined) {
            data_zoom = parseInt($(this).attr("data-zoom"),10);
        }

        $(this).gmap3({
            marker: {
                values: [{
                    address: $(this).attr("data-address"),
                    data: $(this).attr("data-address-details")
                }],
                options:{
                    draggable: false
                },
                events:{
                    click: function(marker, event, context){
                        var map = $(this).gmap3("get"),
                        infowindow = $(this).gmap3({get:{name:"infowindow"}});
                        if (infowindow){
                            infowindow.open(map, marker);
                            infowindow.setContent(context.data);
                        } else {
                            $(this).gmap3({
                                infowindow:{
                                    anchor:marker,
                                    options:{content: context.data}
                                }
                            });
                        }
                    }
                }
            },
            map: {
                options: {
                    mapTypeId: google.maps.MapTypeId.ROADMAP,
                    zoom: data_zoom,
                    scrollwheel: false
                }
            }
        });

    });

})(jQuery);

<commit_msg>2 team<commit_after>(function($) {
    'use strict';

    /* Hide menu after click
    ----------------------------------------------*/
    $('.navbar-nav li a').click(function(event) {
        $('.in').collapse('hide');
    });

    /* Smooth scroll to section
    ----------------------------------------------*/
    $('a.scroll[href*=#]:not([href=#])').click(function() {
        if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') || location.hostname == this.hostname) {

            var target = $(this.hash);
            target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
            if (target.length) {
                $('html,body').animate({
                    scrollTop: target.offset().top-70
                }, 2000);
                return false;
            }
        }
    });

    /* Team slideshow
    ----------------------------------------------*/
    $("#team-carousel").owlCarousel({

        autoPlay: 5000, //Set AutoPlay to 5 seconds

        items : 2,
        itemsDesktopSmall : [979,2],
        stopOnHover: true,

    });

    /* Testimonials slideshow
    ----------------------------------------------*/
    $("#testimonial-carousel").owlCarousel({

        autoPlay: 6000, //Set AutoPlay to 6 seconds

        singleItem: true,
        pagination : false

    });

    /* Tooltip
    ----------------------------------------------*/
    $('[data-toggle="tooltip"]').tooltip();

    /* Lightbox
    ----------------------------------------------*/
    $('.image-link').magnificPopup({
        type:'image'
    });

    /* Google map
    ----------------------------------------------*/
    $(".map").each(function(){

        var data_zoom = 17;

        if ($(this).attr("data-zoom") !== undefined) {
            data_zoom = parseInt($(this).attr("data-zoom"),10);
        }

        $(this).gmap3({
            marker: {
                values: [{
                    address: $(this).attr("data-address"),
                    data: $(this).attr("data-address-details")
                }],
                options:{
                    draggable: false
                },
                events:{
                    click: function(marker, event, context){
                        var map = $(this).gmap3("get"),
                        infowindow = $(this).gmap3({get:{name:"infowindow"}});
                        if (infowindow){
                            infowindow.open(map, marker);
                            infowindow.setContent(context.data);
                        } else {
                            $(this).gmap3({
                                infowindow:{
                                    anchor:marker,
                                    options:{content: context.data}
                                }
                            });
                        }
                    }
                }
            },
            map: {
                options: {
                    mapTypeId: google.maps.MapTypeId.ROADMAP,
                    zoom: data_zoom,
                    scrollwheel: false
                }
            }
        });

    });

})(jQuery);

<|endoftext|>


<commit_before>import Exception from "../exception";

var AST = {
  Program: function(statements, blockParams, strip, locInfo) {
    this.loc = locInfo;
    this.type = 'Program';
    this.body = statements;

    this.blockParams = blockParams;
    this.strip = strip;
  },

  MustacheStatement: function(rawParams, open, strip, locInfo) {
    this.loc = locInfo;
    this.type = 'MustacheStatement';

    this.sexpr = rawParams;

    // Open may be a string parsed from the parser or a passed boolean flag
    if (open != null && open.charAt) {
      // Must use charAt to support IE pre-10
      var escapeFlag = open.charAt(3) || open.charAt(2);
      this.escaped = escapeFlag !== '{' && escapeFlag !== '&';
    } else {
      this.escaped = !!open;
    }

    this.strip = strip;
  },

  BlockStatement: function(sexpr, program, inverse, strip, locInfo) {
    this.loc = locInfo;

    this.type = 'BlockStatement';
    this.sexpr = sexpr;
    this.program  = program;
    this.inverse  = inverse;
    this.strip = strip;
  },

  PartialStatement: function(sexpr, strip, locInfo) {
    this.loc = locInfo;
    this.type = 'PartialStatement';
    this.sexpr = sexpr;
    this.indent = '';

    this.strip = strip;
    this.strip.inlineStandalone = true;
  },

  ContentStatement: function(string, locInfo) {
    this.loc = locInfo;
    this.type = 'ContentStatement';
    this.original = this.value = string;
  },

  CommentStatement: function(comment, strip, locInfo) {
    this.loc = locInfo;
    this.type = 'CommentStatement';
    this.value = comment;

    this.strip = strip;
    strip.inlineStandalone = true;
  },

  SubExpression: function(rawParams, hash, locInfo) {
    this.loc = locInfo;

    this.type = 'SubExpression';
    this.path = rawParams[0];
    this.params = rawParams.slice(1);
    this.hash = hash;
  },

  PathExpression: function(data, parts, locInfo) {
    this.loc = locInfo;
    this.type = 'PathExpression';

    var original = '',
        dig = [],
        depth = 0,
        depthString = '';

    for(var i=0,l=parts.length; i<l; i++) {
      var part = parts[i].part;
      original += (parts[i].separator || '') + part;

      if (part === '..' || part === '.' || part === 'this') {
        if (dig.length > 0) {
          throw new Exception('Invalid path: ' + original, this);
        } else if (part === '..') {
          depth++;
          depthString += '../';
        }
      } else {
        dig.push(part);
      }
    }

    this.data = data;
    this.original = (data ? '@' : '') + original;
    this.parts    = dig;
    this.depth    = depth;
  },

  StringLiteral: function(string, locInfo) {
    this.loc = locInfo;
    this.type = 'StringLiteral';
    this.original =
      this.value = string;
  },

  NumberLiteral: function(number, locInfo) {
    this.loc = locInfo;
    this.type = 'NumberLiteral';
    this.original =
      this.value = Number(number);
  },

  BooleanLiteral: function(bool, locInfo) {
    this.loc = locInfo;
    this.type = 'BooleanLiteral';
    this.value = bool === 'true';
  },

  Hash: function(pairs, locInfo) {
    this.loc = locInfo;
    this.type = 'Hash';
    this.pairs = pairs;
  },
  HashPair: function(key, value, locInfo) {
    this.loc = locInfo;
    this.type = 'HashPair';
    this.key = key;
    this.value = value;
  }
};

// Must be exported as an object rather than the root of the module as the jison lexer
// most modify the object to operate properly.
export default AST;
<commit_msg>Add original to BooleanLiteral<commit_after>import Exception from "../exception";

var AST = {
  Program: function(statements, blockParams, strip, locInfo) {
    this.loc = locInfo;
    this.type = 'Program';
    this.body = statements;

    this.blockParams = blockParams;
    this.strip = strip;
  },

  MustacheStatement: function(rawParams, open, strip, locInfo) {
    this.loc = locInfo;
    this.type = 'MustacheStatement';

    this.sexpr = rawParams;

    // Open may be a string parsed from the parser or a passed boolean flag
    if (open != null && open.charAt) {
      // Must use charAt to support IE pre-10
      var escapeFlag = open.charAt(3) || open.charAt(2);
      this.escaped = escapeFlag !== '{' && escapeFlag !== '&';
    } else {
      this.escaped = !!open;
    }

    this.strip = strip;
  },

  BlockStatement: function(sexpr, program, inverse, strip, locInfo) {
    this.loc = locInfo;

    this.type = 'BlockStatement';
    this.sexpr = sexpr;
    this.program  = program;
    this.inverse  = inverse;
    this.strip = strip;
  },

  PartialStatement: function(sexpr, strip, locInfo) {
    this.loc = locInfo;
    this.type = 'PartialStatement';
    this.sexpr = sexpr;
    this.indent = '';

    this.strip = strip;
    this.strip.inlineStandalone = true;
  },

  ContentStatement: function(string, locInfo) {
    this.loc = locInfo;
    this.type = 'ContentStatement';
    this.original = this.value = string;
  },

  CommentStatement: function(comment, strip, locInfo) {
    this.loc = locInfo;
    this.type = 'CommentStatement';
    this.value = comment;

    this.strip = strip;
    strip.inlineStandalone = true;
  },

  SubExpression: function(rawParams, hash, locInfo) {
    this.loc = locInfo;

    this.type = 'SubExpression';
    this.path = rawParams[0];
    this.params = rawParams.slice(1);
    this.hash = hash;
  },

  PathExpression: function(data, parts, locInfo) {
    this.loc = locInfo;
    this.type = 'PathExpression';

    var original = '',
        dig = [],
        depth = 0,
        depthString = '';

    for(var i=0,l=parts.length; i<l; i++) {
      var part = parts[i].part;
      original += (parts[i].separator || '') + part;

      if (part === '..' || part === '.' || part === 'this') {
        if (dig.length > 0) {
          throw new Exception('Invalid path: ' + original, this);
        } else if (part === '..') {
          depth++;
          depthString += '../';
        }
      } else {
        dig.push(part);
      }
    }

    this.data = data;
    this.original = (data ? '@' : '') + original;
    this.parts    = dig;
    this.depth    = depth;
  },

  StringLiteral: function(string, locInfo) {
    this.loc = locInfo;
    this.type = 'StringLiteral';
    this.original =
      this.value = string;
  },

  NumberLiteral: function(number, locInfo) {
    this.loc = locInfo;
    this.type = 'NumberLiteral';
    this.original =
      this.value = Number(number);
  },

  BooleanLiteral: function(bool, locInfo) {
    this.loc = locInfo;
    this.type = 'BooleanLiteral';
    this.original =
      this.value = bool === 'true';
  },

  Hash: function(pairs, locInfo) {
    this.loc = locInfo;
    this.type = 'Hash';
    this.pairs = pairs;
  },
  HashPair: function(key, value, locInfo) {
    this.loc = locInfo;
    this.type = 'HashPair';
    this.key = key;
    this.value = value;
  }
};

// Must be exported as an object rather than the root of the module as the jison lexer
// most modify the object to operate properly.
export default AST;
<|endoftext|>


<commit_before>/**
 * Module dependencies.
 */

var _ = require('lodash');
var toLoadAndRegisterControllers = require('./to-load-and-register-controllers');
var toInterpretRouteSyntax = require('./to-interpret-route-syntax');

/**
 * `controllers` (Core Hook)
 */
module.exports = function(sails) {

  return {

    /**
     * Implicit defaults which will be merged into sails.config before this hook is loaded...
     * @type {Dictionary}
     */
    defaults: {},

    /**
     * Before any hooks have begun loading...
     * (called automatically by Sails core)
     */
    configure: function() {
      // This initial setup of `sails.controllers` was included here as an experimental
      // feature so that these modules would be accessible for other hooks.  This will be
      // deprecated in Sails v1.0 in favor of the ability for hook authors to register or unregister
      // controllers programatically.  In addition, controllers will no longer be exposed
      // on the `sails` app instance.
      sails.controllers = {};
    },

    /**
     * When the hook is loaded...
     * (called automatically by Sails core)
     */
    initialize: function(cb) {

      // In future versions of Sails, the empty registry of controllers can be initialized here:
      // sails.controllers = {};

      // Register route syntax for binding controllers.
      var interpretRouteSyntax = toInterpretRouteSyntax(sails);
      sails.on('route:typeUnknown', interpretRouteSyntax);

      // Load controllers from app and register their actions as middleware.
      var loadAndRegisterControllers = toLoadAndRegisterControllers(sails, this);
      loadAndRegisterControllers(cb);
    },

    /**
     * explicitActions
     *
     * This is used to hold a reference to explicit actions and controllers.
     * << This will be removed in a future release of Sails. >>
     *
     * @type {Dictionary}
     * @api private
     */
    explicitActions: {},

  };
};
<commit_msg>Expose the `loadAndRegisterControllers` method for now.<commit_after>/**
 * Module dependencies.
 */

var _ = require('lodash');
var toLoadAndRegisterControllers = require('./to-load-and-register-controllers');
var toInterpretRouteSyntax = require('./to-interpret-route-syntax');

/**
 * `controllers` (Core Hook)
 */
module.exports = function(sails) {

  return {

    /**
     * Implicit defaults which will be merged into sails.config before this hook is loaded...
     * @type {Dictionary}
     */
    defaults: {},

    /**
     * Before any hooks have begun loading...
     * (called automatically by Sails core)
     */
    configure: function() {
      // This initial setup of `sails.controllers` was included here as an experimental
      // feature so that these modules would be accessible for other hooks.  This will be
      // deprecated in Sails v1.0 in favor of the ability for hook authors to register or unregister
      // controllers programatically.  In addition, controllers will no longer be exposed
      // on the `sails` app instance.
      sails.controllers = {};
    },

    /**
     * When the hook is loaded...
     * (called automatically by Sails core)
     */
    initialize: function(cb) {

      // In future versions of Sails, the empty registry of controllers can be initialized here:
      // sails.controllers = {};

      // Register route syntax for binding controllers.
      var interpretRouteSyntax = toInterpretRouteSyntax(sails);
      sails.on('route:typeUnknown', interpretRouteSyntax);

      // Load controllers from app and register their actions as middleware.
      // TODO -- make a public .reload() hook method, rather than exposing
      // this private method on the hook object.  Doing this for now because
      // certain apps in the wild are relying on it.
      this.loadAndRegisterControllers = toLoadAndRegisterControllers(sails, this);
      this.loadAndRegisterControllers(cb);
    },

    /**
     * explicitActions
     *
     * This is used to hold a reference to explicit actions and controllers.
     * << This will be removed in a future release of Sails. >>
     *
     * @type {Dictionary}
     * @api private
     */
    explicitActions: {},

  };
};
<|endoftext|>