<commit_before>(function(document, location, history) { /* jshint maxdepth:8, boss:true */
    "use strict";

    // do not enable the plugin for old browsers BUT keep for jasmine
    if (!history.pushState || !("timeout" in XMLHttpRequest.prototype || window.jasmine)) return;

    const identity = (s) => s;
    const reTitle = /<title>(.*?)<\/title>/;
    const states = []; // in-memory storage for states
    var lastState = {}, lastFormData;

    function attachNonPreventedListener(eventType, callback) {
        document.addEventListener(eventType, function(e) {
            if (!e.defaultPrevented) {
                callback(e);
            }
        }, false);
    }

    function attachCapturingListener(eventType, callback) {
        document.addEventListener("ajaxify:update", callback, true);
    }

    function dispatchAjaxifyEvent(el, eventType, eventDetail) {
        const e = document.createEvent("CustomEvent");

        e.initCustomEvent("ajaxify:" + eventType, true, true, eventDetail || null);

        return el.dispatchEvent(e);
    }

    function updateState(state, detail) {
        const body = document.body;

        if (dispatchAjaxifyEvent(body, "update", detail)) {
            // by default just swap body elements
            body.parentNode.replaceChild(state.body, body);
        }

        if (states.indexOf(lastState) < 0) {
            // if state does not exist - store it in memory
            states.push(lastState);
        }

        document.title = state.title;
    }

    attachNonPreventedListener("click", (e) => {
        const body = document.body;

        for (var el = e.target; el !== body; el = el.parentNode) {
            if (el.nodeName.toLowerCase() === "a") {
                if (!el.target) {
                    if (el.getAttribute("aria-disabled") === "true") {
                        e.preventDefault();
                    } else if (el.protocol.slice(0, 4) === "http") {
                        // handle only http(s) links
                        var targetUrl = el.href;
                        var currentUrl = location.href;

                        if (targetUrl === currentUrl || targetUrl.split("#")[0] !== currentUrl.split("#")[0]) {
                            if (dispatchAjaxifyEvent(el, "fetch")) {
                                // override default bahavior for links
                                e.preventDefault();
                            }
                        } else {
                            location.hash = el.hash;
                            // override default bahavior for anchors
                            e.preventDefault();
                        }
                    }
                }

                break;
            }
        }
    });

    attachNonPreventedListener("submit", (e) => {
        const el = e.target;

        if (!el.target) {
            if (el.getAttribute("aria-disabled") === "true") {
                e.preventDefault();
            } else {
                const formEnctype = el.getAttribute("enctype");

                var data;

                if (formEnctype === "multipart/form-data") {
                    data = new FormData(el);
                } else {
                    data = {};

                    for (var i = 0, field; field = el.elements[i]; ++i) {
                        const fieldType = field.type;

                        if (fieldType && field.name && !field.disabled) {
                            const fieldName = field.name;

                            if (fieldType === "select-multiple") {
                                for (var j = 0, option; option = field.options[j]; ++j) {
                                    if (option.selected) {
                                        (data[fieldName] = data[fieldName] || []).push(option.value);
                                    }
                                }
                            } else if ((fieldType !== "checkbox" && fieldType !== "radio") || field.checked) {
                                data[fieldName] = field.value;
                            }
                        }
                    }
                }

                if (!dispatchAjaxifyEvent(el, "serialize", data)) {
                    e.preventDefault();
                } else {
                    if (data instanceof FormData) {
                        lastFormData = data;
                    } else {
                        const encode = formEnctype === "text/plain" ? identity : encodeURIComponent;
                        const reSpace = encode === identity ? / /g : /%20/g;

                        lastFormData = Object.keys(data).map((key) => {
                            const name = encode(key);
                            var value = data[key];

                            if (Array.isArray(value)) {
                                value = value.map(encode).join("&" + name + "=");
                            }

                            return name + "=" + encode(value);
                        }).join("&").replace(reSpace, "+");
                    }

                    if (dispatchAjaxifyEvent(el, "fetch")) {
                        e.preventDefault();
                    }

                    lastFormData = null; // cleanup internal reference
                }
            }
        }
    });

    attachNonPreventedListener("ajaxify:fetch", (e) => {
        const el = e.target;
        const xhr = new XMLHttpRequest();
        const method = (el.method || "GET").toUpperCase();
        const nodeName = el.nodeName.toLowerCase();
        const nodeType = el.nodeType;

        var url = e.detail;

        if (nodeName === "a") {
            url = url || el.href;
        } else if (nodeName === "form") {
            url = url || el.action;

            if (method === "GET" && lastFormData) {
                url += (~url.indexOf("?") ? "&" : "?") + lastFormData;
                // for get forms append all data to url
                lastFormData = null;
            }
        }

        ["abort", "error", "load", "timeout"].forEach((type) => {
            xhr["on" + type] = () => {
                if (nodeType === 1) {
                    el.removeAttribute("aria-disabled");
                }

                dispatchAjaxifyEvent(el, type, xhr);
            };
        });

        xhr.open(method, url, true);

        if (dispatchAjaxifyEvent(el, "send", xhr)) {
            xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");

            if (method !== "GET") {
                xhr.setRequestHeader("Content-Type", el.getAttribute("enctype") || el.enctype);
            }

            xhr.send(lastFormData);

            if (nodeType === 1) {
                el.setAttribute("aria-disabled", "true");
            }
        }
    });

    attachCapturingListener("ajaxify:load", (e) => {
        const xhr = e.detail;
        const res = xhr.response;

        var url = xhr.responseURL;
        // polyfill xhr.responseURL value
        if (!url && res && res.URL) {
            url = xhr.getResponseHeader("Location");

            if (url) {
                url = location.origin + url;

                Object.defineProperty(xhr, "responseURL", {get: () => url});
            }
        }
    });

    attachNonPreventedListener("ajaxify:load", (e) => {
        const xhr = e.detail;
        const status = xhr.status;
        const state = {body: xhr.responseText};

        if (status < 200 || status > 300 && status !== 304) {
            state.title = xhr.status + " " + xhr.statusText;
        }

        updateState(state, xhr.response);

        lastState = {}; // create a new state object

        var url = xhr.responseURL;

        if (url !== location.href) {
            history.pushState(states.length, state.title, url);
        }
    });

    attachCapturingListener("ajaxify:update", (e) => {
        const detail = e.detail;
        // override string e.detail
        if (typeof detail === "string") {
            const titleMatch = reTitle.exec(detail);
            const doc = document.implementation.createHTMLDocument(titleMatch && titleMatch[1] || "");

            doc.body.innerHTML = detail.trim().replace(titleMatch && titleMatch[0], "");

            Object.defineProperty(e, "detail", {get: () => doc});
        }

        lastState.body = e.target;
        lastState.title = document.title;
    });

    window.addEventListener("popstate", (e) => {
        // numeric value indicates better-ajaxify state
        if (!e.defaultPrevented && e.state >= 0) {
            const state = states[e.state];

            if (state) {
                updateState(state, state.body);

                lastState = state;
            }
        }
    });

    // update initial state address url
    history.replaceState(0, document.title);

}(window.document, window.location, window.history));
<commit_msg>fix e.detail, extract createDocument<commit_after>(function(document, location, history) { /* jshint maxdepth:8, boss:true */
    "use strict";

    // do not enable the plugin for old browsers BUT keep for jasmine
    if (!history.pushState || !("timeout" in XMLHttpRequest.prototype || window.jasmine)) return;

    const identity = (s) => s;
    const reTitle = /<title>(.*?)<\/title>/;
    const states = []; // in-memory storage for states
    var lastState = {}, lastFormData;

    function attachNonPreventedListener(eventType, callback) {
        document.addEventListener(eventType, function(e) {
            if (!e.defaultPrevented) {
                callback(e);
            }
        }, false);
    }

    function attachCapturingListener(eventType, callback) {
        document.addEventListener("ajaxify:update", callback, true);
    }

    function dispatchAjaxifyEvent(el, eventType, eventDetail) {
        const e = document.createEvent("CustomEvent");

        e.initCustomEvent("ajaxify:" + eventType, true, true, eventDetail || null);

        return el.dispatchEvent(e);
    }

    function updateState(state, detail) {
        const body = document.body;

        if (dispatchAjaxifyEvent(body, "update", detail)) {
            // by default just swap body elements
            body.parentNode.replaceChild(state.body, body);
        }

        if (states.indexOf(lastState) < 0) {
            // if state does not exist - store it in memory
            states.push(lastState);
        }

        document.title = state.title;
    }

    function createDocument(htmlText) {
        const titleMatch = reTitle.exec(htmlText);
        const doc = document.implementation.createHTMLDocument(titleMatch && titleMatch[1] || "");

        doc.body.innerHTML = htmlText.trim().replace(titleMatch && titleMatch[0], "");

        return doc;
    }

    attachNonPreventedListener("click", (e) => {
        const body = document.body;

        for (var el = e.target; el !== body; el = el.parentNode) {
            if (el.nodeName.toLowerCase() === "a") {
                if (!el.target) {
                    if (el.getAttribute("aria-disabled") === "true") {
                        e.preventDefault();
                    } else if (el.protocol.slice(0, 4) === "http") {
                        // handle only http(s) links
                        var targetUrl = el.href;
                        var currentUrl = location.href;

                        if (targetUrl === currentUrl || targetUrl.split("#")[0] !== currentUrl.split("#")[0]) {
                            if (dispatchAjaxifyEvent(el, "fetch")) {
                                // override default bahavior for links
                                e.preventDefault();
                            }
                        } else {
                            location.hash = el.hash;
                            // override default bahavior for anchors
                            e.preventDefault();
                        }
                    }
                }

                break;
            }
        }
    });

    attachNonPreventedListener("submit", (e) => {
        const el = e.target;

        if (!el.target) {
            if (el.getAttribute("aria-disabled") === "true") {
                e.preventDefault();
            } else {
                const formEnctype = el.getAttribute("enctype");

                var data;

                if (formEnctype === "multipart/form-data") {
                    data = new FormData(el);
                } else {
                    data = {};

                    for (var i = 0, field; field = el.elements[i]; ++i) {
                        const fieldType = field.type;

                        if (fieldType && field.name && !field.disabled) {
                            const fieldName = field.name;

                            if (fieldType === "select-multiple") {
                                for (var j = 0, option; option = field.options[j]; ++j) {
                                    if (option.selected) {
                                        (data[fieldName] = data[fieldName] || []).push(option.value);
                                    }
                                }
                            } else if ((fieldType !== "checkbox" && fieldType !== "radio") || field.checked) {
                                data[fieldName] = field.value;
                            }
                        }
                    }
                }

                if (!dispatchAjaxifyEvent(el, "serialize", data)) {
                    e.preventDefault();
                } else {
                    if (data instanceof FormData) {
                        lastFormData = data;
                    } else {
                        const encode = formEnctype === "text/plain" ? identity : encodeURIComponent;
                        const reSpace = encode === identity ? / /g : /%20/g;

                        lastFormData = Object.keys(data).map((key) => {
                            const name = encode(key);
                            var value = data[key];

                            if (Array.isArray(value)) {
                                value = value.map(encode).join("&" + name + "=");
                            }

                            return name + "=" + encode(value);
                        }).join("&").replace(reSpace, "+");
                    }

                    if (dispatchAjaxifyEvent(el, "fetch")) {
                        e.preventDefault();
                    }

                    lastFormData = null; // cleanup internal reference
                }
            }
        }
    });

    attachNonPreventedListener("ajaxify:fetch", (e) => {
        const el = e.target;
        const xhr = new XMLHttpRequest();
        const method = (el.method || "GET").toUpperCase();
        const nodeName = el.nodeName.toLowerCase();
        const nodeType = el.nodeType;

        var url = e.detail;

        if (nodeName === "a") {
            url = url || el.href;
        } else if (nodeName === "form") {
            url = url || el.action;

            if (method === "GET" && lastFormData) {
                url += (~url.indexOf("?") ? "&" : "?") + lastFormData;
                // for get forms append all data to url
                lastFormData = null;
            }
        }

        ["abort", "error", "load", "timeout"].forEach((type) => {
            xhr["on" + type] = () => {
                if (nodeType === 1) {
                    el.removeAttribute("aria-disabled");
                }

                dispatchAjaxifyEvent(el, type, xhr);
            };
        });

        xhr.open(method, url, true);

        if (dispatchAjaxifyEvent(el, "send", xhr)) {
            xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");

            if (method !== "GET") {
                xhr.setRequestHeader("Content-Type", el.getAttribute("enctype") || el.enctype);
            }

            xhr.send(lastFormData);

            if (nodeType === 1) {
                el.setAttribute("aria-disabled", "true");
            }
        }
    });

    attachCapturingListener("ajaxify:load", (e) => {
        const xhr = e.detail;
        const res = xhr.response;

        var url = xhr.responseURL;
        // polyfill xhr.responseURL value
        if (!url && res && res.URL) {
            url = xhr.getResponseHeader("Location");

            if (url) {
                url = location.origin + url;

                Object.defineProperty(xhr, "responseURL", {get: () => url});
            }
        }
    });

    attachNonPreventedListener("ajaxify:load", (e) => {
        const xhr = e.detail;
        const detail = createDocument(xhr.responseText);
        const state = {body: detail.body};

        if (detail.title) {
            state.title = detail.title;
        } else {
            state.title = xhr.status + " " + xhr.statusText;
        }

        updateState(state, detail);

        lastState = {}; // create a new state object

        var url = xhr.responseURL;

        if (url !== location.href) {
            history.pushState(states.length, state.title, url);
        }
    });

    attachCapturingListener("ajaxify:update", (e) => {
        var detail = e.detail;

        if (typeof detail === "string") {
            detail = createDocument(detail);
            // override property e.detail
            Object.defineProperty(e, "detail", {get: () => detail});
        }

        lastState.body = e.target;
        lastState.title = document.title;
    });

    window.addEventListener("popstate", (e) => {
        // numeric value indicates better-ajaxify state
        if (!e.defaultPrevented && e.state >= 0) {
            const state = states[e.state];

            if (state) {
                updateState(state, state.body);

                lastState = state;
            }
        }
    });

    // update initial state address url
    history.replaceState(0, document.title);

}(window.document, window.location, window.history));
<|endoftext|>


<commit_before>const {app, shell, dialog, ipcMain, BrowserWindow, Menu} = require('electron')
const {resolve} = require('path')
const i18n = require('./i18n')
const setting = require('./setting')
const updater = require('./updater')

let windows = []
let openfile = null
let isReady = false

function newWindow(path) {
  let window = new BrowserWindow({
    icon:
      process.platform === 'linux' ? resolve(__dirname, '../logo.png') : null,
    title: app.name,
    useContentSize: true,
    width: setting.get('window.width'),
    height: setting.get('window.height'),
    minWidth: setting.get('window.minwidth'),
    minHeight: setting.get('window.minheight'),
    autoHideMenuBar: !setting.get('view.show_menubar'),
    backgroundColor: '#111111',
    show: false,
    webPreferences: {
      nodeIntegration: true,
      zoomFactor: setting.get('app.zoom_factor')
    }
  })

  windows.push(window)
  buildMenu()

  window.once('ready-to-show', () => {
    window.show()
  })

  window.on('closed', () => {
    window = null
  })

  window.webContents.audioMuted = !setting.get('sound.enable')

  window.webContents.on('did-finish-load', () => {
    if (path) window.webContents.send('load-file', path)
  })

  window.webContents.on('new-window', evt => {
    evt.preventDefault()
  })

  window.loadURL(`file://${resolve(__dirname, '../index.html')}`)

  return window
}

function buildMenu(props = {}) {
  let template = require('./menu').get(props)

  // Process menu items

  let processMenu = items => {
    return items.map(item => {
      if ('click' in item) {
        item.click = () => {
          let window = BrowserWindow.getFocusedWindow()
          if (!window) return

          window.webContents.send(`menu-click-${item.id}`)
        }
      }

      if ('clickMain' in item) {
        let key = item.clickMain

        item.click = () =>
          ({
            newWindow,
            checkForUpdates: () => checkForUpdates({showFailDialogs: true})
          }[key]())

        delete item.clickMain
      }

      if ('submenu' in item) {
        processMenu(item.submenu)
      }

      return item
    })
  }

  Menu.setApplicationMenu(Menu.buildFromTemplate(processMenu(template)))

  // Create dock menu

  let dockMenu = Menu.buildFromTemplate([
    {
      label: i18n.t('menu.file', 'New &Window'),
      click: () => newWindow()
    }
  ])

  if (process.platform === 'darwin') {
    app.dock.setMenu(dockMenu)
  }
}

async function checkForUpdates({showFailDialogs = false} = {}) {
  try {
    let t = i18n.context('updater')
    let info = await updater.check(`SabakiHQ/${app.name}`)

    if (info.hasUpdates) {
      dialog.showMessageBox(
        {
          type: 'info',
          buttons: [t('Download Update'), t('View Changelog'), t('Not Now')],
          title: app.name,
          message: t(p => `${p.appName} v${p.version} is available now.`, {
            appName: app.name,
            version: info.latestVersion
          }),
          noLink: true,
          cancelId: 2
        },
        response => {
          if (response === 2) return

          shell.openExternal(
            response === 0 ? info.downloadUrl || info.url : info.url
          )
        }
      )
    } else if (showFailDialogs) {
      dialog.showMessageBox(
        {
          type: 'info',
          buttons: [t('OK')],
          title: t('No updates available'),
          message: t(p => `Sabaki v${p.version} is the latest version.`, {
            version: app.getVersion()
          })
        },
        () => {}
      )
    }
  } catch (err) {
    if (showFailDialogs) {
      dialog.showMessageBox({
        type: 'warning',
        buttons: [t('OK')],
        title: app.name,
        message: t('An error occurred while checking for updates.')
      })
    }
  }
}

function main() {
  app.allowRendererProcessReuse = true

  if (!setting.get('app.enable_hardware_acceleration')) {
    app.disableHardwareAcceleration()
  }

  app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
      app.quit()
    } else {
      buildMenu({disableAll: true})
    }
  })

  app.on('ready', () => {
    isReady = true

    if (!openfile && process.argv.length >= 2) {
      if (
        !process.argv[0].endsWith('electron.exe') &&
        !process.argv[0].endsWith('electron')
      ) {
        openfile = process.argv[1]
      } else if (process.argv.length >= 3) {
        openfile = process.argv[2]
      }
    }

    newWindow(openfile)

    if (setting.get('app.startup_check_updates')) {
      setTimeout(
        () => checkForUpdates(),
        setting.get('app.startup_check_updates_delay')
      )
    }

    ipcMain.on('new-window', (evt, ...args) => newWindow(...args))
    ipcMain.on('build-menu', (evt, ...args) => buildMenu(...args))
    ipcMain.on('check-for-updates', (evt, ...args) => checkForUpdates(...args))
  })

  app.on('activate', (evt, hasVisibleWindows) => {
    if (!hasVisibleWindows) newWindow()
  })

  app.on('open-file', (evt, path) => {
    evt.preventDefault()

    if (!isReady) {
      openfile = path
    } else {
      newWindow(path)
    }
  })

  process.on('uncaughtException', err => {
    let t = i18n.context('exception')

    dialog.showErrorBox(
      t(p => `${p.appName} v${p.version}`, {
        appName: app.name,
        version: app.getVersion()
      }),
      t(
        p =>
          [
            `Something weird happened. ${p.appName} will shut itself down.`,
            `If possible, please report this on ${p.appName}’s repository on GitHub.`
          ].join(' '),
        {
          appName: app.name
        }
      ) +
        '\n\n' +
        err.stack
    )

    process.exit(1)
  })
}

main()
<commit_msg>Fix #617, fix #392<commit_after>const {app, shell, dialog, ipcMain, BrowserWindow, Menu} = require('electron')
const {resolve} = require('path')
const i18n = require('./i18n')
const setting = require('./setting')
const updater = require('./updater')

let windows = []
let openfile = null
let isReady = false

function newWindow(path) {
  let window = new BrowserWindow({
    icon:
      process.platform === 'linux' ? resolve(__dirname, '../logo.png') : null,
    title: app.name,
    useContentSize: true,
    width: setting.get('window.width'),
    height: setting.get('window.height'),
    minWidth: setting.get('window.minwidth'),
    minHeight: setting.get('window.minheight'),
    autoHideMenuBar: !setting.get('view.show_menubar'),
    backgroundColor: '#111111',
    show: false,
    webPreferences: {
      nodeIntegration: true,
      zoomFactor: setting.get('app.zoom_factor')
    }
  })

  windows.push(window)
  buildMenu()

  window.once('ready-to-show', () => {
    window.show()
  })

  window.on('closed', () => {
    window = null
  })

  window.webContents.audioMuted = !setting.get('sound.enable')

  window.webContents.on('did-finish-load', () => {
    if (path) window.webContents.send('load-file', path)
  })

  window.webContents.on('new-window', evt => {
    evt.preventDefault()
  })

  window.loadURL(`file://${resolve(__dirname, '../index.html')}`)

  return window
}

function buildMenu(props = {}) {
  let template = require('./menu').get(props)

  // Process menu items

  let processMenu = items => {
    return items.map(item => {
      if ('click' in item) {
        item.click = () => {
          let window = BrowserWindow.getFocusedWindow()
          if (!window) return

          window.webContents.send(`menu-click-${item.id}`)
        }
      }

      if ('clickMain' in item) {
        let key = item.clickMain

        item.click = () =>
          ({
            newWindow,
            checkForUpdates: () => checkForUpdates({showFailDialogs: true})
          }[key]())

        delete item.clickMain
      }

      if ('submenu' in item) {
        processMenu(item.submenu)
      }

      return item
    })
  }

  Menu.setApplicationMenu(Menu.buildFromTemplate(processMenu(template)))

  // Create dock menu

  let dockMenu = Menu.buildFromTemplate([
    {
      label: i18n.t('menu.file', 'New &Window'),
      click: () => newWindow()
    }
  ])

  if (process.platform === 'darwin') {
    app.dock.setMenu(dockMenu)
  }
}

async function checkForUpdates({showFailDialogs = false} = {}) {
  try {
    let t = i18n.context('updater')
    let info = await updater.check(`SabakiHQ/${app.name}`)

    if (info.hasUpdates) {
      dialog.showMessageBox(
        {
          type: 'info',
          buttons: [t('Download Update'), t('View Changelog'), t('Not Now')],
          title: app.name,
          message: t(p => `${p.appName} v${p.version} is available now.`, {
            appName: app.name,
            version: info.latestVersion
          }),
          noLink: true,
          cancelId: 2
        },
        response => {
          if (response === 2) return

          shell.openExternal(
            response === 0 ? info.downloadUrl || info.url : info.url
          )
        }
      )
    } else if (showFailDialogs) {
      dialog.showMessageBox(
        {
          type: 'info',
          buttons: [t('OK')],
          title: t('No updates available'),
          message: t(p => `Sabaki v${p.version} is the latest version.`, {
            version: app.getVersion()
          })
        },
        () => {}
      )
    }
  } catch (err) {
    if (showFailDialogs) {
      dialog.showMessageBox({
        type: 'warning',
        buttons: [t('OK')],
        title: app.name,
        message: t('An error occurred while checking for updates.')
      })
    }
  }
}

function main() {
  app.allowRendererProcessReuse = true

  if (!setting.get('app.enable_hardware_acceleration')) {
    app.disableHardwareAcceleration()
  }

  app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
      app.quit()
    } else {
      buildMenu({disableAll: true})
    }
  })

  app.on('ready', () => {
    isReady = true

    if (!openfile && process.argv.length >= 2) {
      if (
        !process.argv[0].endsWith('electron.exe') &&
        !process.argv[0].endsWith('electron')
      ) {
        openfile = process.argv[1]
      } else if (process.argv.length >= 3) {
        openfile = process.argv[2]
      }
    }

    newWindow(openfile)

    if (setting.get('app.startup_check_updates')) {
      setTimeout(
        () => checkForUpdates(),
        setting.get('app.startup_check_updates_delay')
      )
    }

    ipcMain.on('new-window', (evt, ...args) => newWindow(...args))
    ipcMain.on('build-menu', (evt, ...args) => buildMenu(...args))
    ipcMain.on('check-for-updates', (evt, ...args) => checkForUpdates(...args))
  })

  app.on('activate', (evt, hasVisibleWindows) => {
    if (isReady && !hasVisibleWindows) newWindow()
  })

  app.on('open-file', (evt, path) => {
    evt.preventDefault()

    if (!isReady) {
      openfile = path
    } else {
      newWindow(path)
    }
  })

  process.on('uncaughtException', err => {
    let t = i18n.context('exception')

    dialog.showErrorBox(
      t(p => `${p.appName} v${p.version}`, {
        appName: app.name,
        version: app.getVersion()
      }),
      t(
        p =>
          [
            `Something weird happened. ${p.appName} will shut itself down.`,
            `If possible, please report this on ${p.appName}’s repository on GitHub.`
          ].join(' '),
        {
          appName: app.name
        }
      ) +
        '\n\n' +
        err.stack
    )

    process.exit(1)
  })
}

main()
<|endoftext|>


<commit_before>/* jshint -W040 */

angular.module('nemo')

    .provider('nemoInputDirectiveCreator', ['$compileProvider', 'nemoUtilsProvider',
        function ($compileProvider, utilsProvider) {

            'use strict';

            function getTemplateWithAttributes(template) {
                var parentTemplateElement, templateElement;
                parentTemplateElement = document.createElement('div');
                parentTemplateElement.innerHTML = template;
                templateElement = parentTemplateElement.firstChild;
                templateElement.setAttribute('ng-model', 'model.value');
                templateElement.setAttribute('ng-focus', 'setActiveField()');
                templateElement.setAttribute('name', '{{model.name}}');
                templateElement.setAttribute('id', 'nemo-{{model.name}}');
                return parentTemplateElement.innerHTML;
            }

            function manageDefaultValue(scope, formHandlerCtrl, defaultValue) {
                var fieldName = scope.model.name,
                    unregisterFn = scope.$watch(function () {
                        return formHandlerCtrl.getFieldValue(fieldName);
                    }, function (fieldValue) {
                        if (defaultValue !== undefined && (fieldValue === null || fieldValue === undefined)) {
                            formHandlerCtrl.setFieldValue(fieldName, defaultValue);
                        }
                        unregisterFn();
                    });
            }

            function manageCustomLinkFn(scope, element, attrs, controllers, $compile, $http, linkFn) {
                (linkFn || angular.noop)(scope, element, attrs, controllers, $compile, $http);
            }

            function validateFormOnFieldChange(scope, ngModelCtrl, formHandlerCtrl) {
                scope.$watch(function () {
                    return ngModelCtrl.$viewValue;
                }, function (newVal, oldVal) {
                    scope.$evalAsync(function () {
                        //noinspection JSValidateTypes
                        if (newVal === oldVal) {
                            return;
                        }
                        ngModelCtrl.forcedValidityValue = undefined;
                        formHandlerCtrl.validateForm();
                    });
                });
            }

            function getLinkFn(options, $compile, $http, nemoMessages) {
                return function (scope, element, attrs, controllers) {
                    var ngModelCtrl = controllers[0],
                        formHandlerCtrl = controllers[1],
                        parentNgModelCtrl = controllers[2];
                    validateFormOnFieldChange(scope, ngModelCtrl, formHandlerCtrl);

                    var interfaceFuns = registerField(scope, element, ngModelCtrl, formHandlerCtrl, nemoMessages, options.fieldInterfaceFns);
                    interfaceFuns.setupBusinessRules();

                    manageCustomLinkFn(scope, element, attrs, controllers, $compile, $http, options.linkFn);
                    manageDefaultValue(scope, formHandlerCtrl, options.defaultValue);
                    handleActivationState(scope, formHandlerCtrl, parentNgModelCtrl);
                };
            }

            function handleActivationState(scope, formHandlerCtrl, parentNgModelCtrl) {
                var newActiveField = (parentNgModelCtrl) ? [parentNgModelCtrl.$name, scope.model.name] : scope.model.name;
                scope.setActiveField = function () {
                    formHandlerCtrl.setActiveField(newActiveField);
                };
            }

            function registerField(scope, element, ngModelCtrl, formHandlerCtrl, nemoMessages, customFieldInterfaceFns) {
                var fieldInterfaceFns = getFieldInterfaceFns(scope, element, ngModelCtrl, formHandlerCtrl, nemoMessages),
                    customerFieldInterface = customFieldInterfaceFns ? customFieldInterfaceFns(scope, element, ngModelCtrl, formHandlerCtrl) : {};
                angular.extend(fieldInterfaceFns, customerFieldInterface);
                formHandlerCtrl.registerField(scope.model.name, fieldInterfaceFns);
                return fieldInterfaceFns;
            }

            function getFieldInterfaceFns(scope, element, ngModelCtrl, formHandlerCtrl, nemoMessages) {
                return {
                    activeFieldChange: function (activeField) {
                        activeFieldChange(scope, ngModelCtrl, activeField);
                    },
                    releaseActive: function () {
                        ngModelCtrl.isActive = false;
                    },
                    isActive: function () {
                        return ngModelCtrl.isActive;
                    },
                    isValid: function () {
                        return ngModelCtrl.$valid;
                    },
                    isTouched: function () {
                        return ngModelCtrl.$touched;
                    },
                    hasHelp: function () {
                        return scope.model.properties.help && scope.model.properties.help.message;
                    },
                    setFocus: function () {
                        element[0].focus();
                        formHandlerCtrl.setActiveField(scope.model.name);
                    },
                    getValue: function () {
                        return ngModelCtrl.$viewValue;
                    },
                    setValue: function (value) {
                        ngModelCtrl.$setViewValue(value);
                        ngModelCtrl.$render();
                    },
                    getNgModelCtrl: function () {
                        return ngModelCtrl;
                    },
                    setFilthy: function () {
                        ngModelCtrl.$setDirty();
                        ngModelCtrl.$setTouched();
                    },
                    setupBusinessRules: function () {
                        if (scope.model.properties && scope.model.properties.businessrules) {
                            if (utilsProvider.contains(scope.model.properties.businessrules, 'noAutocomplete')) {
                                element.attr('autocomplete', 'off');
                            }
                            if (utilsProvider.contains(scope.model.properties.businessrules, 'noPaste')) {
                                element.attr('onPaste', 'return false;');
                            }
                        }
                    },
                    forceServerInvalid: function (errorMessage, errorIndex) {
                        utilsProvider.forceServerInvalid(errorMessage,errorIndex, scope, ngModelCtrl);
                    }
                };
            }

            function activeFieldChange(scope, ngModelCtrl, activeField) {
                ngModelCtrl.isActive = isFieldNowActive(scope.model.name, activeField);
            }

            function isFieldNowActive(fieldName, activeField) {
                if (typeof activeField === 'string') {
                    return isFieldTheOnlyActiveOne(fieldName, activeField);
                } else if (typeof activeField === 'object') {
                    return isFieldPartOfActiveList(fieldName, activeField);
                }
            }

            function isFieldTheOnlyActiveOne(fieldName, activeField) {
                return activeField === fieldName;
            }

            function isFieldPartOfActiveList(fieldName, activeFieldList) {
                var isFieldNowActive = false;
                for (var i = 0; i < activeFieldList.length; i++) {
                    if (activeFieldList[i] === fieldName) {
                        isFieldNowActive = true;
                        break;
                    }
                }
                return isFieldNowActive;
            }

            function getDirectiveDefinitionObject(options, $compile, $http, nemoMessages) {
                return {
                    require: ['ngModel', '^nemoFormHandler', '?^^ngModel'],
                    template: getTemplateWithAttributes(options.template),
                    replace: true,
                    restrict: 'A',
                    link: getLinkFn(options, $compile, $http, nemoMessages),
                    controller: options.controller
                };
            }

            function input(type, options) {
                $compileProvider.directive
                    .apply(null, [
                        'input' + utilsProvider.capitalise(type),
                        ['$compile', '$http', 'nemoMessages', function ($compile, $http, nemoMessages) {
                            return getDirectiveDefinitionObject(options, $compile, $http, nemoMessages);
                        }]]);
                return this;
            }

            return {
                input: input,
                $get: angular.noop
            };
        }
    ]);
<commit_msg>@Josh @Ricardo Improving the defensive strategy against non defined properties (help messages).<commit_after>/* jshint -W040 */

angular.module('nemo')

    .provider('nemoInputDirectiveCreator', ['$compileProvider', 'nemoUtilsProvider',
        function ($compileProvider, utilsProvider) {

            'use strict';

            function getTemplateWithAttributes(template) {
                var parentTemplateElement, templateElement;
                parentTemplateElement = document.createElement('div');
                parentTemplateElement.innerHTML = template;
                templateElement = parentTemplateElement.firstChild;
                templateElement.setAttribute('ng-model', 'model.value');
                templateElement.setAttribute('ng-focus', 'setActiveField()');
                templateElement.setAttribute('name', '{{model.name}}');
                templateElement.setAttribute('id', 'nemo-{{model.name}}');
                return parentTemplateElement.innerHTML;
            }

            function manageDefaultValue(scope, formHandlerCtrl, defaultValue) {
                var fieldName = scope.model.name,
                    unregisterFn = scope.$watch(function () {
                        return formHandlerCtrl.getFieldValue(fieldName);
                    }, function (fieldValue) {
                        if (defaultValue !== undefined && (fieldValue === null || fieldValue === undefined)) {
                            formHandlerCtrl.setFieldValue(fieldName, defaultValue);
                        }
                        unregisterFn();
                    });
            }

            function manageCustomLinkFn(scope, element, attrs, controllers, $compile, $http, linkFn) {
                (linkFn || angular.noop)(scope, element, attrs, controllers, $compile, $http);
            }

            function validateFormOnFieldChange(scope, ngModelCtrl, formHandlerCtrl) {
                scope.$watch(function () {
                    return ngModelCtrl.$viewValue;
                }, function (newVal, oldVal) {
                    scope.$evalAsync(function () {
                        //noinspection JSValidateTypes
                        if (newVal === oldVal) {
                            return;
                        }
                        ngModelCtrl.forcedValidityValue = undefined;
                        formHandlerCtrl.validateForm();
                    });
                });
            }

            function getLinkFn(options, $compile, $http, nemoMessages) {
                return function (scope, element, attrs, controllers) {
                    var ngModelCtrl = controllers[0],
                        formHandlerCtrl = controllers[1],
                        parentNgModelCtrl = controllers[2];
                    validateFormOnFieldChange(scope, ngModelCtrl, formHandlerCtrl);

                    var interfaceFuns = registerField(scope, element, ngModelCtrl, formHandlerCtrl, nemoMessages, options.fieldInterfaceFns);
                    interfaceFuns.setupBusinessRules();

                    manageCustomLinkFn(scope, element, attrs, controllers, $compile, $http, options.linkFn);
                    manageDefaultValue(scope, formHandlerCtrl, options.defaultValue);
                    handleActivationState(scope, formHandlerCtrl, parentNgModelCtrl);
                };
            }

            function handleActivationState(scope, formHandlerCtrl, parentNgModelCtrl) {
                var newActiveField = (parentNgModelCtrl) ? [parentNgModelCtrl.$name, scope.model.name] : scope.model.name;
                scope.setActiveField = function () {
                    formHandlerCtrl.setActiveField(newActiveField);
                };
            }

            function registerField(scope, element, ngModelCtrl, formHandlerCtrl, nemoMessages, customFieldInterfaceFns) {
                var fieldInterfaceFns = getFieldInterfaceFns(scope, element, ngModelCtrl, formHandlerCtrl, nemoMessages),
                    customerFieldInterface = customFieldInterfaceFns ? customFieldInterfaceFns(scope, element, ngModelCtrl, formHandlerCtrl) : {};
                angular.extend(fieldInterfaceFns, customerFieldInterface);
                formHandlerCtrl.registerField(scope.model.name, fieldInterfaceFns);
                return fieldInterfaceFns;
            }

            function getFieldInterfaceFns(scope, element, ngModelCtrl, formHandlerCtrl, nemoMessages) {
                return {
                    activeFieldChange: function (activeField) {
                        activeFieldChange(scope, ngModelCtrl, activeField);
                    },
                    releaseActive: function () {
                        ngModelCtrl.isActive = false;
                    },
                    isActive: function () {
                        return ngModelCtrl.isActive;
                    },
                    isValid: function () {
                        return ngModelCtrl.$valid;
                    },
                    isTouched: function () {
                        return ngModelCtrl.$touched;
                    },
                    hasHelp: function () {
                        return scope.model.properties && scope.model.properties.help && scope.model.properties.help.message;
                    },
                    setFocus: function () {
                        element[0].focus();
                        formHandlerCtrl.setActiveField(scope.model.name);
                    },
                    getValue: function () {
                        return ngModelCtrl.$viewValue;
                    },
                    setValue: function (value) {
                        ngModelCtrl.$setViewValue(value);
                        ngModelCtrl.$render();
                    },
                    getNgModelCtrl: function () {
                        return ngModelCtrl;
                    },
                    setFilthy: function () {
                        ngModelCtrl.$setDirty();
                        ngModelCtrl.$setTouched();
                    },
                    setupBusinessRules: function () {
                        if (scope.model.properties && scope.model.properties.businessrules) {
                            if (utilsProvider.contains(scope.model.properties.businessrules, 'noAutocomplete')) {
                                element.attr('autocomplete', 'off');
                            }
                            if (utilsProvider.contains(scope.model.properties.businessrules, 'noPaste')) {
                                element.attr('onPaste', 'return false;');
                            }
                        }
                    },
                    forceServerInvalid: function (errorMessage, errorIndex) {
                        utilsProvider.forceServerInvalid(errorMessage,errorIndex, scope, ngModelCtrl);
                    }
                };
            }

            function activeFieldChange(scope, ngModelCtrl, activeField) {
                ngModelCtrl.isActive = isFieldNowActive(scope.model.name, activeField);
            }

            function isFieldNowActive(fieldName, activeField) {
                if (typeof activeField === 'string') {
                    return isFieldTheOnlyActiveOne(fieldName, activeField);
                } else if (typeof activeField === 'object') {
                    return isFieldPartOfActiveList(fieldName, activeField);
                }
            }

            function isFieldTheOnlyActiveOne(fieldName, activeField) {
                return activeField === fieldName;
            }

            function isFieldPartOfActiveList(fieldName, activeFieldList) {
                var isFieldNowActive = false;
                for (var i = 0; i < activeFieldList.length; i++) {
                    if (activeFieldList[i] === fieldName) {
                        isFieldNowActive = true;
                        break;
                    }
                }
                return isFieldNowActive;
            }

            function getDirectiveDefinitionObject(options, $compile, $http, nemoMessages) {
                return {
                    require: ['ngModel', '^nemoFormHandler', '?^^ngModel'],
                    template: getTemplateWithAttributes(options.template),
                    replace: true,
                    restrict: 'A',
                    link: getLinkFn(options, $compile, $http, nemoMessages),
                    controller: options.controller
                };
            }

            function input(type, options) {
                $compileProvider.directive
                    .apply(null, [
                        'input' + utilsProvider.capitalise(type),
                        ['$compile', '$http', 'nemoMessages', function ($compile, $http, nemoMessages) {
                            return getDirectiveDefinitionObject(options, $compile, $http, nemoMessages);
                        }]]);
                return this;
            }

            return {
                input: input,
                $get: angular.noop
            };
        }
    ]);
<|endoftext|>


<commit_before>var req = require('./lib/request.js');
var handle = require('./handle.js');
var events = require('./events.js');
var util = require('./util.js');
var type_of = require('./type-of.js');
var captcha = require('./captcha.js');
var version = require('./version.js');
var request = require('./request.js');

var _global = (window || global);

if(!_global){
	console.log('Not in support');
}

var YHSD = {};
YHSD.events = events;
YHSD.util = util;
YHSD.request = request;
YHSD.captcha = captcha;

_global.yhsd = {
	_$interceptors: {
		request: {
			_$callback: function (oRequest, fnNext) {
				fnNext(oRequest);
			},
			use: function (_fn) {
				this._$callback = _fn;
			},
			run: function (oRequest, fnNext) {
				this._$callback(oRequest, fnNext);
			}
		},
		response: {
			_$callback: function (oResponse, fnNext) {
				fnNext(oResponse);
			},
			use: function (_fn) {
				this._$callback = _fn;
			},
			run: function (oResponse, fnNext) {
				this._$callback(oResponse, fnNext);
			}
		}
   }
};

_global.yhsd.version = function(){
	return version.get();
};

var aFunctionReady = [];
var bHasInit = false;

var runWhenReady = function(fn){
	if(type_of(fn) === 'function'){
		if(bHasInit){
			fn(YHSD);
		}else{
			aFunctionReady.push(fn);
		}
	}
};

_global.yhsd.ready = runWhenReady;
_global.yhsd.sdk = YHSD;

if(typeof _global.yhsdDebug === 'undefined'){
	_global.yhsdDebug = false;
}

var aInitModule = ['account', 'area', 'address', 'blog', 'cart', 'shop', 'order', 'page', 'payment_method', 'product', 'type', 'vendor', 'discount', 'coupon', 'reward_point', 'page_block', 'post', 'favorite', 'service', 'trade_invoice', 'weapp'];

function checkModule(moduleName){
	return (util.inArray(moduleName, aInitModule) > -1);
}

YHSD.account = checkModule('account') ? require('./account.js') : {};
YHSD.area = checkModule('area') ? require('./area.js') : {};
YHSD.address = checkModule('address') ? require('./address.js') : {};
YHSD.blog = checkModule('blog') ? require('./blog.js') : {};
YHSD.cart = checkModule('cart') ? require('./cart.js') : {};
YHSD.discount = checkModule('discount') ? require('./discount.js') : {};
YHSD.shop = checkModule('shop') ? require('./shop.js') : {};
YHSD.order = checkModule('order') ? require('./order.js') : {};
YHSD.page = checkModule('page') ? require('./page.js') : {};
YHSD.payment_method = checkModule('payment_method') ? require('./payment_method.js') : {};
YHSD.product = checkModule('product') ? require('./product.js') : {};
YHSD.type = checkModule('type') ? require('./type.js') : {};
YHSD.vendor = checkModule('vendor') ? require('./vendor.js') : {};
YHSD.coupon = checkModule('coupon') ? require('./coupon.js') : {};
YHSD.reward_point = checkModule('reward_point') ? require('./reward_point.js') : {};
YHSD.page_block = checkModule('page_block') ? require('./page_block.js') : {};
YHSD.post = checkModule('post') ? require('./post.js') : {};
YHSD.favorite = checkModule('favorite') ? require('./favorite.js') : {};
YHSD.service = checkModule('service') ? require('./service.js') : {};
YHSD.trade_invoice = checkModule('trade_invoice') ? require('./trade_invoice.js') : {};
YHSD.weapp = checkModule('weapp') ? require('./weapp.js') : {};

function jssdkInit(){
	if(aFunctionReady.length === 0){
		bHasInit = true;
	}else{
		(aFunctionReady.shift())(YHSD);
		jssdkInit();
	}
}

(function(){
	var ajaxToken = null;
	if('ajaxToken' in _global) {
		jssdkInit();
	} else {
		Object.defineProperty(_global, 'ajaxToken', {
			set: function(token){
				if(!ajaxToken) {
					ajaxToken = token;
					jssdkInit();
				} else {
					ajaxToken = token;
				}
			},
			get: function(){
				return ajaxToken;
			}
		});
	}
})();<commit_msg>feat: global.yhsd<commit_after>var req = require('./lib/request.js');
var handle = require('./handle.js');
var events = require('./events.js');
var util = require('./util.js');
var type_of = require('./type-of.js');
var captcha = require('./captcha.js');
var version = require('./version.js');
var request = require('./request.js');

var _global = (window || global);

if(!_global){
	console.log('Not in support');
}

var YHSD = {};
YHSD.events = events;
YHSD.util = util;
YHSD.request = request;
YHSD.captcha = captcha;

_global.yhsd = _global.yhsd || {};

_global.yhsd._$interceptors = {
	request: {
		_$callback: function (oRequest, fnNext) {
			fnNext(oRequest);
		},
		use: function (_fn) {
			this._$callback = _fn;
		},
		run: function (oRequest, fnNext) {
			this._$callback(oRequest, fnNext);
		}
	},
	response: {
		_$callback: function (oResponse, fnNext) {
			fnNext(oResponse);
		},
		use: function (_fn) {
			this._$callback = _fn;
		},
		run: function (oResponse, fnNext) {
			this._$callback(oResponse, fnNext);
		}
	}
};

_global.yhsd.version = function(){
	return version.get();
};

var aFunctionReady = [];
var bHasInit = false;

var runWhenReady = function(fn){
	if(type_of(fn) === 'function'){
		if(bHasInit){
			fn(YHSD);
		}else{
			aFunctionReady.push(fn);
		}
	}
};

_global.yhsd.ready = runWhenReady;
_global.yhsd.sdk = YHSD;

if(typeof _global.yhsdDebug === 'undefined'){
	_global.yhsdDebug = false;
}

var aInitModule = ['account', 'area', 'address', 'blog', 'cart', 'shop', 'order', 'page', 'payment_method', 'product', 'type', 'vendor', 'discount', 'coupon', 'reward_point', 'page_block', 'post', 'favorite', 'service', 'trade_invoice', 'weapp'];

function checkModule(moduleName){
	return (util.inArray(moduleName, aInitModule) > -1);
}

YHSD.account = checkModule('account') ? require('./account.js') : {};
YHSD.area = checkModule('area') ? require('./area.js') : {};
YHSD.address = checkModule('address') ? require('./address.js') : {};
YHSD.blog = checkModule('blog') ? require('./blog.js') : {};
YHSD.cart = checkModule('cart') ? require('./cart.js') : {};
YHSD.discount = checkModule('discount') ? require('./discount.js') : {};
YHSD.shop = checkModule('shop') ? require('./shop.js') : {};
YHSD.order = checkModule('order') ? require('./order.js') : {};
YHSD.page = checkModule('page') ? require('./page.js') : {};
YHSD.payment_method = checkModule('payment_method') ? require('./payment_method.js') : {};
YHSD.product = checkModule('product') ? require('./product.js') : {};
YHSD.type = checkModule('type') ? require('./type.js') : {};
YHSD.vendor = checkModule('vendor') ? require('./vendor.js') : {};
YHSD.coupon = checkModule('coupon') ? require('./coupon.js') : {};
YHSD.reward_point = checkModule('reward_point') ? require('./reward_point.js') : {};
YHSD.page_block = checkModule('page_block') ? require('./page_block.js') : {};
YHSD.post = checkModule('post') ? require('./post.js') : {};
YHSD.favorite = checkModule('favorite') ? require('./favorite.js') : {};
YHSD.service = checkModule('service') ? require('./service.js') : {};
YHSD.trade_invoice = checkModule('trade_invoice') ? require('./trade_invoice.js') : {};
YHSD.weapp = checkModule('weapp') ? require('./weapp.js') : {};

function jssdkInit(){
	if(aFunctionReady.length === 0){
		bHasInit = true;
	}else{
		(aFunctionReady.shift())(YHSD);
		jssdkInit();
	}
}

(function(){
	var ajaxToken = null;
	if('ajaxToken' in _global) {
		jssdkInit();
	} else {
		Object.defineProperty(_global, 'ajaxToken', {
			set: function(token){
				if(!ajaxToken) {
					ajaxToken = token;
					jssdkInit();
				} else {
					ajaxToken = token;
				}
			},
			get: function(){
				return ajaxToken;
			}
		});
	}
})();<|endoftext|>


<commit_before>require('dotenv').load();

const craftai = require('craft-ai').createClient;
const fs = require('fs');
const path = require('path');
const process = require('process');

const ROOM = 'BEDROOM_1';
// const ROOM = 'LIVING_ROOM';
// const ROOM = 'RESTROOM';

const LOCAL_FILE_PATH = path.join(__dirname, `../data/twor_${ROOM}.json`);

// 0 - Create the craft client
const CRAFT_CLIENT = craftai(process.env.CRAFT_TOKEN);

// 1 - Retrieve the prepared data
new Promise((resolve, reject) => fs.readFile(LOCAL_FILE_PATH, (err, data) => {
  if (err) reject(err);
  resolve(data);
}))
.then(data => JSON.parse(data))
.then(context => {
  const agentName = ROOM;
  // 2 - Cleanup the mess (agent's name can't be duplicate)
  return CRAFT_CLIENT.deleteAgent(agentName)
  // 3 - Create the agent
  .then(() => {
    console.log(`Creating agent ${agentName}.`);
    return CRAFT_CLIENT.createAgent({
      context: {
        movement: {
          type: 'continuous'
        },
        light: {
          type: 'enum'
        },
        tz: {
          type: 'timezone'
        },
        time: {
          type: 'time_of_day'
        }
      },
      output: ['light'],
      time_quantum: 15 * 60 // 15 min
    }, agentName);
  })
  // 4 - Send the dataset's operations
  .then(() => {
    console.log(`Adding context operations for agent ${agentName}...`);
    return CRAFT_CLIENT.addAgentContextOperations(agentName, context);
  })
  .then(() => {
    console.log(`Computing the decision model for agent ${agentName} (this may take a little while)...`);
    // 5 - Compute decision from the decision tree in order to automate the light
    // Download the tree
    return CRAFT_CLIENT.getAgentDecisionTree(agentName, context[context.length - 1].timestamp);
  })
  .then(tree => {
    console.log('Decision tree computed!');
    // 6 - Get decisions
    {
      const d = craftai.decide(
        tree,
        {
          movement: 0
        },
        new craftai.Time('2010-01-04T01:30:00+09:00')
      );
      console.log(`Decision taken:\n- The light is ${d.output.light.predicted_value} when there is no movement at 1:30AM.`);
    }
    {
      const d = craftai.decide(
        tree,
        {
          movement: 0
        },
        new craftai.Time('2010-01-04T08:58:00+09:00')
      );
      console.log(`- The light is ${d.output.light.predicted_value} when there is no movement at 8:58AM.`);
    }
    {
      const d = craftai.decide(
        tree,
        {
          movement: 0
        },
        new craftai.Time('2010-01-04T09:42:00+09:00')
      );
      console.log(`- The light is ${d.output.light.predicted_value} when there is no movement at 9:42AM.`);
    }
    {
      const d = craftai.decide(
        tree,
        {
          movement: 2
        },
        new craftai.Time('2010-01-04T09:42:00+09:00')
      );
      console.log(`- The light is ${d.output.light.predicted_value} when there is some movement at 9:42AM.`);
    }
    {
      const d = craftai.decide(
        tree,
        {
          movement: 2
        },
        new craftai.Time('2010-01-04T17:03:00+09:00')
      );
      console.log(`- The light is ${d.output.light.predicted_value} when there is some movement at 5:03PM.`);
    }
    {
      const d = craftai.decide(
        tree,
        {
          movement: 2
        },
        new craftai.Time('2010-01-04T20:55:00+09:00')
      );
      console.log(`- The light is ${d.output.light.predicted_value} when there is some movement at 8:55PM.`);
    }
    {
      const d = craftai.decide(
        tree,
        {
          movement: 2
        },
        new craftai.Time('2010-01-04T22:07:00+09:00')
      );
      console.log(`- The light is ${d.output.light.predicted_value} when there is some movement at 10:07PM.`);
    }
    {
      const d = craftai.decide(
        tree,
        {
          movement: 10
        },
        new craftai.Time('2010-01-04T09:42:00+09:00')
      );
      console.log(`- The light is ${d.output.light.predicted_value} when there is a lot of movement at 9:42AM.`);
    }
    {
      const d = craftai.decide(
        tree,
        {
          movement: 10
        },
        new craftai.Time('2010-01-04T02:17:00+09:00')
      );
      console.log(`- The light is ${d.output.light.predicted_value} when there is a lot of movement at 2:17AM.`);
    }
    process.exit(0);
  });
})
.catch(error => {
  console.log('Error!', error);
  process.exit(1);
});
<commit_msg>Removing unneeded `process.exit(0)`<commit_after>require('dotenv').load();

const craftai = require('craft-ai').createClient;
const fs = require('fs');
const path = require('path');
const process = require('process');

const ROOM = 'BEDROOM_1';
// const ROOM = 'LIVING_ROOM';
// const ROOM = 'RESTROOM';

const LOCAL_FILE_PATH = path.join(__dirname, `../data/twor_${ROOM}.json`);

// 0 - Create the craft client
const CRAFT_CLIENT = craftai(process.env.CRAFT_TOKEN);

// 1 - Retrieve the prepared data
new Promise((resolve, reject) => fs.readFile(LOCAL_FILE_PATH, (err, data) => {
  if (err) reject(err);
  resolve(data);
}))
.then(data => JSON.parse(data))
.then(context => {
  const agentName = ROOM;
  // 2 - Cleanup the mess (agent's name can't be duplicate)
  return CRAFT_CLIENT.deleteAgent(agentName)
  // 3 - Create the agent
  .then(() => {
    console.log(`Creating agent ${agentName}.`);
    return CRAFT_CLIENT.createAgent({
      context: {
        movement: {
          type: 'continuous'
        },
        light: {
          type: 'enum'
        },
        tz: {
          type: 'timezone'
        },
        time: {
          type: 'time_of_day'
        }
      },
      output: ['light'],
      time_quantum: 15 * 60 // 15 min
    }, agentName);
  })
  // 4 - Send the dataset's operations
  .then(() => {
    console.log(`Adding context operations for agent ${agentName}...`);
    return CRAFT_CLIENT.addAgentContextOperations(agentName, context);
  })
  .then(() => {
    console.log(`Computing the decision model for agent ${agentName} (this may take a little while)...`);
    // 5 - Compute decision from the decision tree in order to automate the light
    // Download the tree
    return CRAFT_CLIENT.getAgentDecisionTree(agentName, context[context.length - 1].timestamp);
  })
  .then(tree => {
    console.log('Decision tree computed!');
    // 6 - Get decisions
    {
      const d = craftai.decide(
        tree,
        {
          movement: 0
        },
        new craftai.Time('2010-01-04T01:30:00+09:00')
      );
      console.log(`Decision taken:\n- The light is ${d.output.light.predicted_value} when there is no movement at 1:30AM.`);
    }
    {
      const d = craftai.decide(
        tree,
        {
          movement: 0
        },
        new craftai.Time('2010-01-04T08:58:00+09:00')
      );
      console.log(`- The light is ${d.output.light.predicted_value} when there is no movement at 8:58AM.`);
    }
    {
      const d = craftai.decide(
        tree,
        {
          movement: 0
        },
        new craftai.Time('2010-01-04T09:42:00+09:00')
      );
      console.log(`- The light is ${d.output.light.predicted_value} when there is no movement at 9:42AM.`);
    }
    {
      const d = craftai.decide(
        tree,
        {
          movement: 2
        },
        new craftai.Time('2010-01-04T09:42:00+09:00')
      );
      console.log(`- The light is ${d.output.light.predicted_value} when there is some movement at 9:42AM.`);
    }
    {
      const d = craftai.decide(
        tree,
        {
          movement: 2
        },
        new craftai.Time('2010-01-04T17:03:00+09:00')
      );
      console.log(`- The light is ${d.output.light.predicted_value} when there is some movement at 5:03PM.`);
    }
    {
      const d = craftai.decide(
        tree,
        {
          movement: 2
        },
        new craftai.Time('2010-01-04T20:55:00+09:00')
      );
      console.log(`- The light is ${d.output.light.predicted_value} when there is some movement at 8:55PM.`);
    }
    {
      const d = craftai.decide(
        tree,
        {
          movement: 2
        },
        new craftai.Time('2010-01-04T22:07:00+09:00')
      );
      console.log(`- The light is ${d.output.light.predicted_value} when there is some movement at 10:07PM.`);
    }
    {
      const d = craftai.decide(
        tree,
        {
          movement: 10
        },
        new craftai.Time('2010-01-04T09:42:00+09:00')
      );
      console.log(`- The light is ${d.output.light.predicted_value} when there is a lot of movement at 9:42AM.`);
    }
    {
      const d = craftai.decide(
        tree,
        {
          movement: 10
        },
        new craftai.Time('2010-01-04T02:17:00+09:00')
      );
      console.log(`- The light is ${d.output.light.predicted_value} when there is a lot of movement at 2:17AM.`);
    }
  });
})
.catch(error => {
  console.log('Error!', error);
  process.exit(1);
});
<|endoftext|>


<commit_before>module.exports = {
  Reporter: require("./reporter/reporter")
};<commit_msg>Fix custom reporters -- bad path<commit_after>module.exports = {
  Reporter: require("./reporters/reporter")
};<|endoftext|>


<commit_before>import express from 'express'
import compress from 'compression'
import david from 'david'
import npm from 'npm'
import Helmet from 'react-helmet'
import { match } from 'react-router'
import { createStore, applyMiddleware } from 'redux'
import thunkMiddleware from 'redux-thunk'
import Boom from 'boom'
import pkg from '../package.json'
import reducers from './ui/reducers'
import { layoutTpl, bodyTpl } from './ui/server.jsx'

import config from './config'
import createNspApiClient from 'nsp-advisories-api'
import createDb from './lib/db'
import createNsp from './lib/nsp'
import createRegistry from './lib/registry'
import createGithub from './lib/github'
import createAuth from './lib/auth'
import createManifest from './lib/manifest'
import createBrains from './lib/brains'
import createGraph from './lib/graph'
import createChangelog from './lib/changelog'
import createProfile from './lib/profile'
import createFeed from './lib/feed'
import createStats from './lib/stats'

const nspApiClient = createNspApiClient()
const db = createDb({ dbConfig: config.db })
const nsp = createNsp({ nspApiClient, db })
const registry = createRegistry({ npmConfig: config.npm })
const github = createGithub({ githubConfig: config.github })
const auth = createAuth({ github, githubConfig: config.github })
const manifest = createManifest({ db, registry, github, githubConfig: config.github })
const brains = createBrains({ david, db, registry, nsp, brainsConfig: config.brains, npmConfig: config.npm })
const graph = createGraph({ db, npmConfig: config.npm })
const changelog = createChangelog({ github, githubConfig: config.github, npmConfig: config.npm })
// TODO: Reinstate paginated
const profile = createProfile({ manifest, brains, github }) // eslint-disable-line
const feed = createFeed({ npm, npmConfig: config.npm, siteConfig: config.site })
const stats = createStats({ registry, manifest })

const app = express()

app.use(compress())

import statics from './statics'

statics({ app, version: pkg.version })

import middleware from './middleware'

middleware.session({ app, db })
middleware.user({ app })
middleware.cors({ app })
middleware.errorHandler({ app })

import routes from './routes'

routes.session.oauthCallback(app, auth)
routes.rss.news(app)
routes.api.csrfToken(app, auth)
routes.api.dependencyCounts(app, stats)
routes.api.stats(app, stats)
routes.api.changelog(app, changelog)
routes.api.info(app, manifest, brains)
routes.api.graph(app, graph, manifest)
routes.api.news(app)
routes.api.project(app, manifest)
routes.api.user(app)
routes.rss.feed(app, feed, manifest)
routes.badge(app, manifest, brains)

import uiRoutes from './ui/routes.jsx'

app.get('*', (req, res, next) => {
  match({ routes: uiRoutes(), location: req.url }, (err, redirectLocation, renderProps) => {
    if (err) return next(err)

    if (redirectLocation) {
      return res.redirect(302, redirectLocation.pathname + redirectLocation.search)
    }

    if (!renderProps) {
      return next(Boom.notFound())
    }

    const components = renderProps.components

    if (components.some((c) => c && c.displayName === 'error-404')) {
      res.status(404)
    }

    const initialState = { config: config.public, version: pkg.version }
    const store = createStore(reducers, initialState, applyMiddleware(thunkMiddleware))
    const { location, params, history } = renderProps

    Promise
      .all(
        components
          .filter((c) => c && c.requestData)
          .map((c) => c.requestData({ store, location, params, history }))
      )
      .then(() => {
        const head = Helmet.rewind()
        const body = bodyTpl({ store, props: renderProps })
        const state = store.getState()

        res.send(layoutTpl({ head, body, state, version: pkg.version }))
      })
      .catch((err) => next(err))
  })
})

nsp.syncAdvisories()
nsp.syncAdvisoriesPeriodically(config.nsp && config.nsp.syncAdvisoriesInterval)

const port = parseInt(process.env.PORT || 1337, 10)
const server = app.listen(port, () => console.log('David started', server.address()))
<commit_msg>Fix server side rendered head<commit_after>import express from 'express'
import compress from 'compression'
import david from 'david'
import npm from 'npm'
import Helmet from 'react-helmet'
import { match } from 'react-router'
import { createStore, applyMiddleware } from 'redux'
import thunkMiddleware from 'redux-thunk'
import Boom from 'boom'
import pkg from '../package.json'
import reducers from './ui/reducers'
import { layoutTpl, bodyTpl } from './ui/server.jsx'

import config from './config'
import createNspApiClient from 'nsp-advisories-api'
import createDb from './lib/db'
import createNsp from './lib/nsp'
import createRegistry from './lib/registry'
import createGithub from './lib/github'
import createAuth from './lib/auth'
import createManifest from './lib/manifest'
import createBrains from './lib/brains'
import createGraph from './lib/graph'
import createChangelog from './lib/changelog'
import createProfile from './lib/profile'
import createFeed from './lib/feed'
import createStats from './lib/stats'

const nspApiClient = createNspApiClient()
const db = createDb({ dbConfig: config.db })
const nsp = createNsp({ nspApiClient, db })
const registry = createRegistry({ npmConfig: config.npm })
const github = createGithub({ githubConfig: config.github })
const auth = createAuth({ github, githubConfig: config.github })
const manifest = createManifest({ db, registry, github, githubConfig: config.github })
const brains = createBrains({ david, db, registry, nsp, brainsConfig: config.brains, npmConfig: config.npm })
const graph = createGraph({ db, npmConfig: config.npm })
const changelog = createChangelog({ github, githubConfig: config.github, npmConfig: config.npm })
// TODO: Reinstate paginated
const profile = createProfile({ manifest, brains, github }) // eslint-disable-line
const feed = createFeed({ npm, npmConfig: config.npm, siteConfig: config.site })
const stats = createStats({ registry, manifest })

const app = express()

app.use(compress())

import statics from './statics'

statics({ app, version: pkg.version })

import middleware from './middleware'

middleware.session({ app, db })
middleware.user({ app })
middleware.cors({ app })
middleware.errorHandler({ app })

import routes from './routes'

routes.session.oauthCallback(app, auth)
routes.rss.news(app)
routes.api.csrfToken(app, auth)
routes.api.dependencyCounts(app, stats)
routes.api.stats(app, stats)
routes.api.changelog(app, changelog)
routes.api.info(app, manifest, brains)
routes.api.graph(app, graph, manifest)
routes.api.news(app)
routes.api.project(app, manifest)
routes.api.user(app)
routes.rss.feed(app, feed, manifest)
routes.badge(app, manifest, brains)

import uiRoutes from './ui/routes.jsx'

app.get('*', (req, res, next) => {
  match({ routes: uiRoutes(), location: req.url }, (err, redirectLocation, renderProps) => {
    if (err) return next(err)

    if (redirectLocation) {
      return res.redirect(302, redirectLocation.pathname + redirectLocation.search)
    }

    if (!renderProps) {
      return next(Boom.notFound())
    }

    const components = renderProps.components

    if (components.some((c) => c && c.displayName === 'error-404')) {
      res.status(404)
    }

    const initialState = { config: config.public, version: pkg.version }
    const store = createStore(reducers, initialState, applyMiddleware(thunkMiddleware))
    const { location, params, history } = renderProps

    Promise
      .all(
        components
          .filter((c) => c && c.requestData)
          .map((c) => c.requestData({ store, location, params, history }))
      )
      .then(() => {
        const body = bodyTpl({ store, props: renderProps })
        const state = store.getState()
        const head = Helmet.rewind()

        res.send(layoutTpl({ head, body, state, version: pkg.version }))
      })
      .catch((err) => next(err))
  })
})

nsp.syncAdvisories()
nsp.syncAdvisoriesPeriodically(config.nsp && config.nsp.syncAdvisoriesInterval)

const port = parseInt(process.env.PORT || 1337, 10)
const server = app.listen(port, () => console.log('David started', server.address()))
<|endoftext|>


<commit_before>YAHOO.util.Event.onDOMReady(function() {

    // initialize Konami Code
    if (typeof(Konami) != "undefined")
    {
        var konami = new Konami();
        konami.pattern = "384069696783495651";
        konami.code = function() {
            alert("You have unlimited submits!");
        };
        konami.load();
    }

});

$(document).ready(function() {

	this.spinner = new Spinner({radius: 30, length: 30}).spin($("#spinner")[0]);

	function updateForm() {
		if ($('#code-input').val() != undefined && $('#code-input').val() != '') {
			$('#upload-file-btn').removeAttr("disabled");
		} else {
			$('#upload-file-btn').attr("disabled", '');
		}

	}

	$('.code-submission').click(function(){
		closeFeedback();
	});

	showSpinner = function() {
        $("#spinner").removeClass();
    };

    hideSpinner = function() {
        $("#spinner").addClass("hide");
    };

	function closeFeedback() {
		var ul = document.getElementById("errorlist2");
		var items = ul.getElementsByTagName("li");
		var itemLength = items.length;
		// clearFileInput();

		while(items.length) {
			items[0].remove();
		}
	}

	function clearFileInput() {
		$control = $('#code-input');
		$control.replaceWith($control = $control.clone(true));
		$('#upload-file-btn').attr("disabled", "disabled");
		$('#code-input').parent().find('span')[0].innerHTML = "Select files";

	}

	$('input[type=file]').bootstrapFileInput();

	// hide navigation if not logged in
	if (window.location.href.indexOf('login') > -1) {
		$('.navigation').hide();
	}

	$('.closeBtn').on("click", function() {
		$debugButton = $(".debugButton");
		$debugButton.css('outline', 0);
		closeFeedback();

	});

	$('#code-input').on("change", function(){
		updateForm();
	});

	$('#code-input').val('');
	updateForm();

    $('#upload-file-btn').click(function() {
        var form_data = new FormData($('#upload-file')[0]);
        showSpinner();
        $.ajax({
            type: 'POST',
            url: '/uploadajax',
            data: form_data,
            contentType: false,
            cache: false,
            processData: false,
            async: false,
            error: function() {
            	console.log('Failure!');
            },
            success: function(data) {
                console.log('Success!');

                for(var i = 0; i < data.errors.length; ++i) {
					if(data.errors[i + 1] && !data.errors[i].search("Grading ") && !data.errors[i + 1].search("Grading ") ) {
						$("#errorlist2").append("

" + data.errors[i] + "

");
						$("#errorlist2").append("
No errors have been found! :)
");
					} else if(!data.errors[i + 1] && !data.errors[i].search("Grading ")) {
						$("#errorlist2").append("

" + data.errors[i] + "

");
						$("#errorlist2").append("
No errors have been found! :)
");
					} else if(!data.errors[i].search("Grading ")) {
						$("#errorlist2").append("

" + data.errors[i] + "

");
					} else {
						$("#errorlist2").append("
" + data.errors[i] + "
");
					}
				}

				$('pre').show();
				hideSpinner();
			},
		});
	});
});

<commit_msg>Fixed an issue where you could click the 'Submit' button again without selecting new files<commit_after>YAHOO.util.Event.onDOMReady(function() {

    // initialize Konami Code
    if (typeof(Konami) != "undefined")
    {
        var konami = new Konami();
        konami.pattern = "384069696783495651";
        konami.code = function() {
            alert("You have unlimited submits!");
        };
        konami.load();
    }

});

$(document).ready(function() {

	this.spinner = new Spinner({radius: 30, length: 30}).spin($("#spinner")[0]);

	function updateForm() {
		if ($('#code-input').val() != undefined && $('#code-input').val() != '') {
			$('#upload-file-btn').removeAttr("disabled");
		} else {
			$('#upload-file-btn').attr("disabled", '');
		}

	}

	$('.code-submission').click(function(){
		closeFeedback();
	});

	showSpinner = function() {
        $("#spinner").removeClass();
    };

    hideSpinner = function() {
        $("#spinner").addClass("hide");
    };

	function closeFeedback() {
		var ul = document.getElementById("errorlist2");
		var items = ul.getElementsByTagName("li");
		var itemLength = items.length;
		// clearFileInput();

		while(items.length) {
			items[0].remove();
		}
	}

	function clearFileInput() {
		$control = $('#code-input');
		$control.replaceWith($control = $control.clone(true));
		$('#upload-file-btn').attr("disabled", "disabled");
		$('#code-input').parent().find('span')[0].innerHTML = "Select files";

	}

	$('input[type=file]').bootstrapFileInput();

	// hide navigation if not logged in
	if (window.location.href.indexOf('login') > -1) {
		$('.navigation').hide();
	}

	$('.closeBtn').on("click", function() {
		$debugButton = $(".debugButton");
		$debugButton.css('outline', 0);
		closeFeedback();

	});

	$('#code-input').on("change", function(){
		updateForm();
	});

	$('#code-input').val('');
	updateForm();

    $('#upload-file-btn').click(function() {
        var form_data = new FormData($('#upload-file')[0]);
        showSpinner();
        $.ajax({
            type: 'POST',
            url: '/uploadajax',
            data: form_data,
            contentType: false,
            cache: false,
            processData: false,
            async: false,
            error: function() {
            	console.log('Failure!');
            },
            success: function(data) {
                console.log('Success!');

                for(var i = 0; i < data.errors.length; ++i) {
					if(data.errors[i + 1] && !data.errors[i].search("Grading ") && !data.errors[i + 1].search("Grading ") ) {
						$("#errorlist2").append("

" + data.errors[i] + "

");
						$("#errorlist2").append("
No errors have been found! :)
");
					} else if(!data.errors[i + 1] && !data.errors[i].search("Grading ")) {
						$("#errorlist2").append("

" + data.errors[i] + "

");
						$("#errorlist2").append("
No errors have been found! :)
");
					} else if(!data.errors[i].search("Grading ")) {
						$("#errorlist2").append("

" + data.errors[i] + "

");
					} else {
						$("#errorlist2").append("
" + data.errors[i] + "
");
					}
				}

				$('pre').show();
				hideSpinner();
			},
		});
		clearFileInput();
	});
});

<|endoftext|>


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

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global require, define, window, brackets, navigator */

/**
 * The boostrapping module for brackets. This module sets up the require
 * configuration and loads the brackets module.
 */
require.config({
    paths: {
        "text"              : "thirdparty/text/text",
        "i18n"              : "thirdparty/i18n/i18n",

        // The file system implementation. Change this value to use different
        // implementations (e.g. cloud-based storage).
        "fileSystemImpl"    : "filesystem/impls/appshell/AppshellFileSystem"
    }
});

if (window.location.search.indexOf("testEnvironment") > -1) {
    require.config({
        paths: {
            "preferences/PreferencesImpl": "../test/TestPreferencesImpl"
        }
    });
}

/**
 * hack for r.js optimization, move locale to another config call
 *
 * Use custom brackets property until CEF sets the correct navigator.language
 * NOTE: When we change to navigator.language here, we also should change to
 * navigator.language in ExtensionLoader (when making require contexts for each
 * extension).
 */
require.config({
    locale: window.localStorage.getItem("locale") || (typeof (brackets) !== "undefined" ? brackets.app.language : navigator.language)
});

define(function (require) {
    "use strict";

    // Load compatibility shims--these need to load early, be careful moving this
    require(["utils/Compatibility"], function () {
        // Load the brackets module. This is a self-running module that loads and runs the entire application.
        require(["brackets"]);
    });
});
<commit_msg>corrected typo in 'bootstrapping'<commit_after>/*
 * Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 */

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global require, define, window, brackets, navigator */

/**
 * The bootstrapping module for brackets. This module sets up the require
 * configuration and loads the brackets module.
 */
require.config({
    paths: {
        "text"              : "thirdparty/text/text",
        "i18n"              : "thirdparty/i18n/i18n",

        // The file system implementation. Change this value to use different
        // implementations (e.g. cloud-based storage).
        "fileSystemImpl"    : "filesystem/impls/appshell/AppshellFileSystem"
    }
});

if (window.location.search.indexOf("testEnvironment") > -1) {
    require.config({
        paths: {
            "preferences/PreferencesImpl": "../test/TestPreferencesImpl"
        }
    });
}

/**
 * hack for r.js optimization, move locale to another config call
 *
 * Use custom brackets property until CEF sets the correct navigator.language
 * NOTE: When we change to navigator.language here, we also should change to
 * navigator.language in ExtensionLoader (when making require contexts for each
 * extension).
 */
require.config({
    locale: window.localStorage.getItem("locale") || (typeof (brackets) !== "undefined" ? brackets.app.language : navigator.language)
});

define(function (require) {
    "use strict";

    // Load compatibility shims--these need to load early, be careful moving this
    require(["utils/Compatibility"], function () {
        // Load the brackets module. This is a self-running module that loads and runs the entire application.
        require(["brackets"]);
    });
});
<|endoftext|>


<commit_before>#!/usr/bin/env node

const fs = require("fs");
const program = require("commander");
const azure = require("./azure").default;
const diagram = require("./seqDiagram").default;
const { exec } = require("child_process");

program
  .option("-g, --group [group]", "set resource group [REQUIRED]")
  .parse(process.argv);

program.on("--help", function() {
  console.log("");
  console.log("Use above params to point to a resource group");
  console.log("that contains a VNet that has subnets, public");
  console.log("IPs, load balancers, and NSGs");
  console.log("");
  console.log("Set environment variables for:");
  console.log("  ARM_SUBSCRIPTION_ID");
  console.log("  ARM_CLIENT_ID");
  console.log("  ARM_CLIENT_SECRET");
  console.log("  ARM_TENANT_ID");
  console.log("  ");
});

if (
  !program.group ||
  !process.env.ARM_SUBSCRIPTION_ID ||
  !process.env.ARM_CLIENT_ID ||
  !process.env.ARM_CLIENT_SECRET ||
  !process.env.ARM_TENANT_ID
) {
  program.help();
}

azure(program.group)
  .then(result => {
    const d = diagram(result);
    fs.mkdir("out", () => {
      fs.writeFile(`out/seq-${program.group}.uml`, d, function(err) {
        if (err) throw new Error(err);
        exec(
          `./bin/plantuml out/seq-${program.group}.uml`,
          (err, stdout, stderr) => {
            if (err) throw new Error(err);
          }
        );
      });
    });
  })
  .catch(err => {
    console.dir(err, { depth: null, colors: true });
  });
<commit_msg>works for me<commit_after>#!/usr/bin/env node

const fs = require("fs");
const program = require("commander");
const azure = require("./azure").default;
const diagram = require("./seqDiagram").default;
const { exec } = require("child_process");

program
  .option("-g, --group [group]", "set resource group [REQUIRED]")
  .parse(process.argv);

program.on("--help", function() {
  console.log("");
  console.log("Use above params to point to a resource group");
  console.log("that contains a VNet that has subnets, public");
  console.log("IPs, load balancers, and NSGs");
  console.log("");
  console.log("Set environment variables for:");
  console.log("  ARM_SUBSCRIPTION_ID");
  console.log("  ARM_CLIENT_ID");
  console.log("  ARM_CLIENT_SECRET");
  console.log("  ARM_TENANT_ID");
  console.log("  ");
});

if (
  !program.group ||
  !process.env.ARM_SUBSCRIPTION_ID ||
  !process.env.ARM_CLIENT_ID ||
  !process.env.ARM_CLIENT_SECRET ||
  !process.env.ARM_TENANT_ID
) {
  program.help();
}

azure(program.group)
  .then(result => {
    const d = diagram(result);
    fs.mkdir("out", () => {
      fs.writeFile(`out/seq-${program.group}.uml`, d, function(err) {
        if (err) throw new Error(err);
        exec(
          `./bin/plantuml out/seq-${program.group}.uml`,
          (err, stdout, stderr) => {
            if (err) throw new Error(err);
          }
        );
      });
    });
  })
  .catch(err => {
    console.dir(err, { depth: null, colors: true });
  });
<|endoftext|>


<commit_before>// Copyright © 2014 Intel Corporation. All rights reserved.
// Use  of this  source  code is  governed by  an Apache v2
// license that can be found in the LICENSE-APACHE-V2 file.

var ShellJS = require("shelljs");

var CommandParser = require("./CommandParser");
var Config = require("./Config");
var Console = require("./Console");
var Downloader = require("./Downloader");
var ProjectBackends = require("./ProjectBackends");

/**
 * Main script.
 * @namespace main
 */

function workingDirectoryIsProject() {

    if (ShellJS.test("-f", "AndroidManifest.xml") &&
        ShellJS.test("-d", "xwalk_core_library")) {

        return true;
    }

    return false;
}

function instantiateProject() {

    var Backend = ProjectBackends.loadDefault();
    if (!Backend) {
        Console.error("Failed to load project backend");
        return null;
    }

    var project;

    try {
        project = new Backend(Config, Console, Downloader);
    } catch (e) {
        Console.error("The Android SDK could not be found. " +
                      "Make sure the directory containing the 'android' " +
                      "executable is mentioned in the PATH environment variable.");
        return null;
    }

    return project;
}

/**
 * Create skeleton project.
 * @param {String} packageId Identifier in the form of com.example.Foo
 * @param {Function} [callback] Callback returning true/false.
 * @memberOf main
 * @private
 */
function create(packageId, callback) {

    // Handle callback not passed.
    if (!callback)
        callback = function() {};

    var project = instantiateProject();
    if (!project) {
        callback(false);
        return;
    }

    project.generate(packageId, function(errormsg) {

        if (errormsg) {
            Console.error(errormsg);
            callback(false);
            return;
        } else {
            callback(true);
            return;
        }
    });
}

/**
 * Build application package.
 * @param {String} type "debug" or "release".
 * @param {Function} [callback] Callback returning true/false.
 * @memberOf main
 * @private
 */
function build(type, callback) {

    // Handle callback not passed.
    if (!callback)
        callback = function() {};

    // Check we're inside a project
    /* TODO move this inside the AndroidProject
    if (!workingDirectoryIsProject()) {
        Console.error("This does not appear to be a Crosswalk project.");
        callback(false);
        return;
    }
    */

    var project = instantiateProject();
    if (!project) {
        callback(false);
        return;
    }

    // Build
    var abis = ["armeabi-v7a", "x86"];
    var release = type === "release" ? true : false;
    project.build(abis, release, function(errormsg) {

        if (errormsg) {
            Console.error(errormsg);
            callback(false);
            return;
        } else {
            callback(true);
            return;
        }
    });
}

/**
 * Display usage information.
 * @param {CommandParser} parser.
 * @memberOf main
 * @private
 */
function printHelp(parser) {

    var buf = parser.help();
    console.log(buf);
}

/**
 * Display version information.
 * @memberOf main
 * @private
 */
function printVersion() {

    var Package = require("../package.json");

    console.log(Package.version);
}

function main() {

    var parser = new CommandParser(process.argv);
    var cmd = parser.getCommand();
    if (cmd) {

        switch (cmd) {
        case "create":
            var packageId = parser.createGetPackageId();
            create(packageId);
            break;
        case "update":
            var version = parser.updateGetVersion();
            console.log("TODO implement");
            break;
        case "build":
            var type = parser.buildGetType();
            build(type);
            break;
        case "help":
            printHelp(parser);
            break;
        case "version":
            printVersion();
            break;
        default:
            // TODO
        }

    } else {

        printHelp(parser);
    }
}

module.exports = {

    main: main,

    test: {
        create: create,
        build: build,
        printHelp: printHelp,
        printVersion: printVersion
    }
};
<commit_msg>main: Actually instantiate and pass application object to backends<commit_after>// Copyright © 2014 Intel Corporation. All rights reserved.
// Use  of this  source  code is  governed by  an Apache v2
// license that can be found in the LICENSE-APACHE-V2 file.

var ShellJS = require("shelljs");

var CommandParser = require("./CommandParser");
var Config = require("./Config");
var Console = require("./Console");
var Downloader = require("./Downloader");
var ProjectBackends = require("./ProjectBackends");

var _application = require("./Application");

/**
 * Main script.
 * @namespace main
 */

function workingDirectoryIsProject() {

    if (ShellJS.test("-f", "AndroidManifest.xml") &&
        ShellJS.test("-d", "xwalk_core_library")) {

        return true;
    }

    return false;
}

function instantiateProject() {

    var Backend = ProjectBackends.loadDefault();
    if (!Backend) {
        Console.error("Failed to load project backend");
        return null;
    }

    var project;

    try {
        project = new Backend(_application);
    } catch (e) {
        Console.error("The Android SDK could not be found. " +
                      "Make sure the directory containing the 'android' " +
                      "executable is mentioned in the PATH environment variable.");
        return null;
    }

    return project;
}

/**
 * Create skeleton project.
 * @param {String} packageId Identifier in the form of com.example.Foo
 * @param {Function} [callback] Callback returning true/false.
 * @memberOf main
 * @private
 */
function create(packageId, callback) {

    // Handle callback not passed.
    if (!callback)
        callback = function() {};

    var project = instantiateProject();
    if (!project) {
        callback(false);
        return;
    }

    project.generate(packageId, function(errormsg) {

        if (errormsg) {
            Console.error(errormsg);
            callback(false);
            return;
        } else {
            callback(true);
            return;
        }
    });
}

/**
 * Build application package.
 * @param {String} type "debug" or "release".
 * @param {Function} [callback] Callback returning true/false.
 * @memberOf main
 * @private
 */
function build(type, callback) {

    // Handle callback not passed.
    if (!callback)
        callback = function() {};

    // Check we're inside a project
    /* TODO move this inside the AndroidProject
    if (!workingDirectoryIsProject()) {
        Console.error("This does not appear to be a Crosswalk project.");
        callback(false);
        return;
    }
    */

    var project = instantiateProject();
    if (!project) {
        callback(false);
        return;
    }

    // Build
    var abis = ["armeabi-v7a", "x86"];
    var release = type === "release" ? true : false;
    project.build(abis, release, function(errormsg) {

        if (errormsg) {
            Console.error(errormsg);
            callback(false);
            return;
        } else {
            callback(true);
            return;
        }
    });
}

/**
 * Display usage information.
 * @param {CommandParser} parser.
 * @memberOf main
 * @private
 */
function printHelp(parser) {

    var buf = parser.help();
    console.log(buf);
}

/**
 * Display version information.
 * @memberOf main
 * @private
 */
function printVersion() {

    var Package = require("../package.json");

    console.log(Package.version);
}

function main() {

    var parser = new CommandParser(process.argv);
    var cmd = parser.getCommand();
    if (cmd) {

        switch (cmd) {
        case "create":
            var packageId = parser.createGetPackageId();
            create(packageId);
            break;
        case "update":
            var version = parser.updateGetVersion();
            console.log("TODO implement");
            break;
        case "build":
            var type = parser.buildGetType();
            build(type);
            break;
        case "help":
            printHelp(parser);
            break;
        case "version":
            printVersion();
            break;
        default:
            // TODO
        }

    } else {

        printHelp(parser);
    }
}

module.exports = {

    main: main,

    test: {
        create: create,
        build: build,
        printHelp: printHelp,
        printVersion: printVersion
    }
};
<|endoftext|>


<commit_before>import _ from 'lodash';
import Vue from 'vue';

import App from 'src/components/App';
import StartupError from 'src/components/StartupError';
import Logger from 'src/libs/Logger';
import ConfigLoader from 'src/libs/ConfigLoader';
import state from 'src/libs/state';

// A handy debugging var..
window.state = state;

let configLoader = new ConfigLoader();
configLoader.loadFromUrl('static/config.json')
    .then(applyConfig)
	.then(startApp)
	.catch(showError);

function applyConfig(config) {
    _.each(config, (val, key) => {
        state.settings[key] = val;
    });
}

function startApp() {
    /* eslint-disable no-new */
    new Vue({
        el: '#app',
        render: h => h(App),
    });
}

function showError(err) {
    if (err) {
        Logger.error('Error starting Kiwi IRC:', err);
    } else {
        Logger.error('Unknown error starting Kiwi IRC');
    }

    /* eslint-disable no-new */
    new Vue({
        el: '#app',
        render: h => h(StartupError),
    });
}
<commit_msg>Setting the window title from config.js<commit_after>import _ from 'lodash';
import Vue from 'vue';

import App from 'src/components/App';
import StartupError from 'src/components/StartupError';
import Logger from 'src/libs/Logger';
import ConfigLoader from 'src/libs/ConfigLoader';
import state from 'src/libs/state';

// A handy debugging var..
window.state = state;

let configLoader = new ConfigLoader();
configLoader.loadFromUrl('static/config.json')
    .then(applyConfig)
	.then(startApp)
	.catch(showError);

function applyConfig(config) {
    _.each(config, (val, key) => {
        state.settings[key] = val;
    });

    // Update the window title if we have one
    if (state.settings.windowTitle) {
        window.document.title = state.settings.windowTitle;
    }
    state.$watch('settings.windowTitle', newVal => {
        window.document.title = newVal;
    });
}

function startApp() {
    /* eslint-disable no-new */
    new Vue({
        el: '#app',
        render: h => h(App),
    });
}

function showError(err) {
    if (err) {
        Logger.error('Error starting Kiwi IRC:', err);
    } else {
        Logger.error('Unknown error starting Kiwi IRC');
    }

    /* eslint-disable no-new */
    new Vue({
        el: '#app',
        render: h => h(StartupError),
    });
}
<|endoftext|>