<commit_before>const electron = require('electron');
const AutoLaunch = require('auto-launch');
const contribution = require('contribution');

const log = require('./logger');
const icon = require('./icon');
const pjson = require('../package.json');
const store = require('./store');

const { app, BrowserWindow, Tray, Menu, shell, ipcMain } = electron;

app.on('ready', () => {
  const streakerAutoLauncher = new AutoLaunch({
    name: pjson.name
  });

  const tray = new Tray(icon.done);
  let usernameWindow = null;

  function createUsernameWindow() {
    if (usernameWindow) {
      usernameWindow.focus();
      return;
    }
    usernameWindow = new BrowserWindow({
      title: `${pjson.name} - Set GitHub Username`,
      frame: false,
      width: 270,
      height: 60,
      resizable: false,
      maximizable: false,
      show: false
    });
    usernameWindow.loadURL(`file://${__dirname}/username.html`);
    usernameWindow.once('ready-to-show', () => {
      const screen = electron.screen.getDisplayNearestPoint(
        electron.screen.getCursorScreenPoint()
      );
      usernameWindow.setPosition(
        Math.floor(
          screen.bounds.x +
            screen.size.width / 2 -
            usernameWindow.getSize()[0] / 2
        ),
        Math.floor(
          screen.bounds.y +
            screen.size.height / 2 -
            usernameWindow.getSize()[1] / 2
        )
      );
      usernameWindow.show();
    });
    usernameWindow.on('closed', () => {
      usernameWindow = null;
    });
    usernameWindow.on('blur', () => {
      usernameWindow.close();
    });
  }

  function createTrayMenu(contributionCount, currentStreak, bestStreak) {
    const username = store.get('username') || 'username not set';
    const githubProfileUrl = `https://github.com/${username}`;
    const menuTemplate = [
      { label: username, enabled: false },
      { type: 'separator' },
      { label: `Current Streak: ${currentStreak}`, enabled: false },
      { label: `Best Streak: ${bestStreak}`, enabled: false },
      { label: `Contributions: ${contributionCount}`, enabled: false },
      { type: 'separator' },
      { label: 'Reload', accelerator: 'Cmd+R', click: requestContributionData },
      {
        label: 'Open GitHub Profile...',
        accelerator: 'Cmd+O',
        click: () => shell.openExternal(githubProfileUrl)
      },
      { type: 'separator' },
      {
        label: 'Set GitHub Username...',
        accelerator: 'Cmd+S',
        click: createUsernameWindow
      },
      {
        label: 'Preferences',
        submenu: [
          {
            label: `Launch ${pjson.name} at login`,
            type: 'checkbox',
            checked: store.get('autoLaunch'),
            click: checkbox => {
              store.set('autoLaunch', checkbox.checked);
              if (checkbox.checked) {
                streakerAutoLauncher.enable();
              } else {
                streakerAutoLauncher.disable();
              }
              log.info(`Store updated - autoLaunch=${checkbox.checked}`);
            }
          }
        ]
      },
      { type: 'separator' },
      {
        label: `About ${pjson.name}...`,
        click: () => shell.openExternal(pjson.homepage)
      },
      {
        label: 'Feedback && Support...',
        click: () => shell.openExternal(pjson.bugs.url)
      },
      { type: 'separator' },
      {
        label: `Quit ${pjson.name}`,
        accelerator: 'Cmd+Q',
        click: () => app.quit()
      }
    ];
    return Menu.buildFromTemplate(menuTemplate);
  }

  function requestContributionData() {
    tray.setImage(icon.load);
    tray.setContextMenu(
      createTrayMenu('Loading...', 'Loading...', 'Loading...')
    );

    const username = store.get('username');

    if (username === '') {
      tray.setImage(icon.fail);
      createUsernameWindow();
      return;
    }

    contribution(username)
      .then(data => {
        tray.setContextMenu(
          createTrayMenu(
            data.contributions,
            data.currentStreak,
            data.bestStreak
          )
        );
        tray.setImage(data.currentStreak > 0 ? icon.done : icon.todo);
        log.info(
          `Request successful - username=${username} streak=${
            data.currentStreak
          } today=${data.contributions > 0}`
        );
      })
      .catch(error => {
        tray.setContextMenu(createTrayMenu('Error', 'Error', 'Error'));
        tray.setImage(icon.fail);
        log.error(
          `Request failed - username=${username}) statusCode=${
            error.statusCode
          }`
        );
      });
  }

  function setUsername(event, username) {
    usernameWindow.close();
    if (username && username !== store.get('username')) {
      store.set('username', username);
      requestContributionData();
      log.info(`Store updated - username=${username}`);
    }
  }

  process.on('uncaughtException', (error) => {
      tray.setContextMenu(createTrayMenu('Error', 'Error', 'Error'));
      tray.setImage(icon.fail);
      log.error(error);
  })

  if (process.platform === 'darwin') {
    app.dock.hide();
  }

  app.on('window-all-closed', () => {});
  tray.on('right-click', requestContributionData);
  ipcMain.on('setUsername', setUsername);

  requestContributionData();
  setInterval(requestContributionData, 1000 * 60 * 15); // 15 Minutes
});
<commit_msg>Move check before 'Loading...'<commit_after>const electron = require('electron');
const AutoLaunch = require('auto-launch');
const contribution = require('contribution');

const log = require('./logger');
const icon = require('./icon');
const pjson = require('../package.json');
const store = require('./store');

const { app, BrowserWindow, Tray, Menu, shell, ipcMain } = electron;

app.on('ready', () => {
  const streakerAutoLauncher = new AutoLaunch({
    name: pjson.name
  });

  const tray = new Tray(icon.done);
  let usernameWindow = null;

  function createUsernameWindow() {
    if (usernameWindow) {
      usernameWindow.focus();
      return;
    }
    usernameWindow = new BrowserWindow({
      title: `${pjson.name} - Set GitHub Username`,
      frame: false,
      width: 270,
      height: 60,
      resizable: false,
      maximizable: false,
      show: false
    });
    usernameWindow.loadURL(`file://${__dirname}/username.html`);
    usernameWindow.once('ready-to-show', () => {
      const screen = electron.screen.getDisplayNearestPoint(
        electron.screen.getCursorScreenPoint()
      );
      usernameWindow.setPosition(
        Math.floor(
          screen.bounds.x +
            screen.size.width / 2 -
            usernameWindow.getSize()[0] / 2
        ),
        Math.floor(
          screen.bounds.y +
            screen.size.height / 2 -
            usernameWindow.getSize()[1] / 2
        )
      );
      usernameWindow.show();
    });
    usernameWindow.on('closed', () => {
      usernameWindow = null;
    });
    usernameWindow.on('blur', () => {
      usernameWindow.close();
    });
  }

  function createTrayMenu(contributionCount, currentStreak, bestStreak) {
    const username = store.get('username') || 'username not set';
    const githubProfileUrl = `https://github.com/${username}`;
    const menuTemplate = [
      { label: username, enabled: false },
      { type: 'separator' },
      { label: `Current Streak: ${currentStreak}`, enabled: false },
      { label: `Best Streak: ${bestStreak}`, enabled: false },
      { label: `Contributions: ${contributionCount}`, enabled: false },
      { type: 'separator' },
      { label: 'Reload', accelerator: 'Cmd+R', click: requestContributionData },
      {
        label: 'Open GitHub Profile...',
        accelerator: 'Cmd+O',
        click: () => shell.openExternal(githubProfileUrl)
      },
      { type: 'separator' },
      {
        label: 'Set GitHub Username...',
        accelerator: 'Cmd+S',
        click: createUsernameWindow
      },
      {
        label: 'Preferences',
        submenu: [
          {
            label: `Launch ${pjson.name} at login`,
            type: 'checkbox',
            checked: store.get('autoLaunch'),
            click: checkbox => {
              store.set('autoLaunch', checkbox.checked);
              if (checkbox.checked) {
                streakerAutoLauncher.enable();
              } else {
                streakerAutoLauncher.disable();
              }
              log.info(`Store updated - autoLaunch=${checkbox.checked}`);
            }
          }
        ]
      },
      { type: 'separator' },
      {
        label: `About ${pjson.name}...`,
        click: () => shell.openExternal(pjson.homepage)
      },
      {
        label: 'Feedback && Support...',
        click: () => shell.openExternal(pjson.bugs.url)
      },
      { type: 'separator' },
      {
        label: `Quit ${pjson.name}`,
        accelerator: 'Cmd+Q',
        click: () => app.quit()
      }
    ];
    return Menu.buildFromTemplate(menuTemplate);
  }

  function requestContributionData() {

    const username = store.get('username');

    if (username === '') {
      tray.setImage(icon.fail);
      createUsernameWindow();
      return;
    }

    tray.setImage(icon.load);
    tray.setContextMenu(
      createTrayMenu('Loading...', 'Loading...', 'Loading...')
    );

    contribution(username)
      .then(data => {
        tray.setContextMenu(
          createTrayMenu(
            data.contributions,
            data.currentStreak,
            data.bestStreak
          )
        );
        tray.setImage(data.currentStreak > 0 ? icon.done : icon.todo);
        log.info(
          `Request successful - username=${username} streak=${
            data.currentStreak
          } today=${data.contributions > 0}`
        );
      })
      .catch(error => {
        tray.setContextMenu(createTrayMenu('Error', 'Error', 'Error'));
        tray.setImage(icon.fail);
        log.error(
          `Request failed - username=${username}) statusCode=${
            error.statusCode
          }`
        );
      });
  }

  function setUsername(event, username) {
    usernameWindow.close();
    if (username && username !== store.get('username')) {
      store.set('username', username);
      requestContributionData();
      log.info(`Store updated - username=${username}`);
    }
  }

  process.on('uncaughtException', (error) => {
      tray.setContextMenu(createTrayMenu('Error', 'Error', 'Error'));
      tray.setImage(icon.fail);
      log.error(error);
  })

  if (process.platform === 'darwin') {
    app.dock.hide();
  }

  app.on('window-all-closed', () => {});
  tray.on('right-click', requestContributionData);
  ipcMain.on('setUsername', setUsername);

  requestContributionData();
  setInterval(requestContributionData, 1000 * 60 * 15); // 15 Minutes
});
<|endoftext|>


<commit_before>thermostat = new Thermostat();

TemperatureColour = function() {
  temperature.style.color = thermostat.colorChange();
};

DisplayTemp = function() {
  temperature.innerHTML = thermostat.temperature();
}

var temperature = document.getElementById('temperature'); {
  temperature.innerHTML = thermostat.temperature();
};

var upButton = document.getElementById('upButton');
upButton.onclick = function() {thermostat.increaseTemperature();
                                DisplayTemp();
                                TemperatureColour();
                               };

var downButton = document.getElementById('downButton');
downButton.onclick = function() {thermostat.decreaseTemperature();
                                  DisplayTemp();
                                 TemperatureColour();
                                 };

var resetButton = document.getElementById('resetButton');
resetButton.onclick = function() {thermostat.resetTemperature();
                                    DisplayTemp();
                                   TemperatureColour();
                                     };

var saveButton = document.getElementById('saveButton');
saveButton.checked = function() {
                                   if(this.checked) {
                                     thermostat.switchMode();
                                     TemperatureColour();
                                       DisplayTemp();
                                   } else {
                                     thermostat.switchMode();
                                     TemperatureColour();
                                       DisplayTemp();
                                   };
                                 };
<commit_msg>tidied up<commit_after>thermostat = new Thermostat();

TemperatureColour = function() {
  temperature.style.color = thermostat.colorChange();
};

DisplayTemp = function() {
  temperature.innerHTML = thermostat.temperature();
}

var temperature = document.getElementById('temperature'); {
  temperature.innerHTML = thermostat.temperature();
};

var upButton = document.getElementById('upButton');
upButton.onclick = function() {
                                thermostat.increaseTemperature();
                                DisplayTemp();
                                TemperatureColour();
                              };

var downButton = document.getElementById('downButton');
downButton.onclick = function() {
                                  thermostat.decreaseTemperature();
                                  DisplayTemp();
                                  TemperatureColour();
                                };

var resetButton = document.getElementById('resetButton');
resetButton.onclick = function() {
                                    thermostat.resetTemperature();
                                    DisplayTemp();
                                    TemperatureColour();
                                  };

var saveButton = document.getElementById('saveButton');
saveButton.checked = function() {
                                   if (this.checked) {
                                     thermostat.switchMode();
                                     TemperatureColour();
                                     DisplayTemp();
                                   } else {
                                     thermostat.switchMode();
                                     TemperatureColour();
                                     DisplayTemp();
                                   };
                                 };
<|endoftext|>


<commit_before>var Spot = require('spot-framework');
var app = require('ampersand-app');
var Router = require('./router');
var MainView = require('./pages/main');
var domReady = require('domready');
var widgetFactory = require('./widgets/widget-factory');
var viewFactory = require('./widgets/view-factory');

// NOTE: material-design-light does not work properly with require()
// workaround via browserify-shim (configured in package.json)
require('mdl');

// attach our app to `window` so we can
// easily access it from the console.
window.app = app;

// Extends our main app singleton
app.extend({
  fullscreenMode: false,
  me: new Spot(),
  widgetFactory: widgetFactory,
  viewFactory: viewFactory,
  router: new Router(),

  // CSV parsing options
  CSVSeparator: ',',
  CSVHeaders: true,
  CSVQuote: '"',
  CSVComment: '#',

  // This is where it all starts
  init: function () {
    // Create and attach our main view
    this.mainView = new MainView({
      model: this.me,
      el: document.body
    });

    // this kicks off our backbutton tracking (browser history)
    // and will cause the first matching handler in the router
    // to fire.
    this.router.history.start({
      root: 'spot',
      pushState: true
    });
  },
  // This is a helper for navigating around the app.
  // this gets called by a global click handler that handles
  // all the <a> tags in the app.
  // it expects a url pathname for example: "/costello/settings"
  navigate: function (page) {
    var url = (page.charAt(0) === '/') ? page.slice(1) : page;
    this.router.history.navigate(url, {
      trigger: true
    });
  },
  progress: function (percentage) {
    var progressBar = document.getElementById('progress-bar');
    progressBar.MaterialProgress.setProgress(percentage);

    progressBar.style.display = 'inherit';
  },
  message: function (options) {
    var snackbarContainer = document.getElementById('snack-bar');
    var snackData = { message: options.text };

    // BUGFIX: during app initialization, the snackbar is not always ready yet
    if (!snackbarContainer) {
      return;
    }

    var progressBar = document.getElementById('progress-bar');
    progressBar.style.display = 'none';

    if (options.type === 'error') {
      console.warn(options.text, options.error);
      snackData.timeout = 10000; // show error for 10 seconds
    } else {
      console.log(options.text);
      snackData.timeout = 2750;
    }
    snackbarContainer.MaterialSnackbar.showSnackbar(snackData);
  }
});

// run it on domReady
domReady(function () {
  app.init();

  // un-comment to start locked down and connected to database
  // app.me.isLockedDown = true;
  // app.me.connectToServer(window.location.hostname);
  // app.me.socket.emit('getDatasets');
});
<commit_msg>BUGFIX: error on loading page<commit_after>var Spot = require('spot-framework');
var app = require('ampersand-app');
var Router = require('./router');
var MainView = require('./pages/main');
var domReady = require('domready');
var widgetFactory = require('./widgets/widget-factory');
var viewFactory = require('./widgets/view-factory');

// NOTE: material-design-light does not work properly with require()
// workaround via browserify-shim (configured in package.json)
require('mdl');

// attach our app to `window` so we can
// easily access it from the console.
window.app = app;

// Extends our main app singleton
app.extend({
  fullscreenMode: false,
  me: new Spot(),
  widgetFactory: widgetFactory,
  viewFactory: viewFactory,
  router: new Router(),

  // CSV parsing options
  CSVSeparator: ',',
  CSVHeaders: true,
  CSVQuote: '"',
  CSVComment: '#',

  // This is where it all starts
  init: function () {
    // Create and attach our main view
    this.mainView = new MainView({
      model: this.me,
      el: document.body
    });

    // this kicks off our backbutton tracking (browser history)
    // and will cause the first matching handler in the router
    // to fire.
    this.router.history.start({
      root: 'spot',
      pushState: true
    });
  },
  // This is a helper for navigating around the app.
  // this gets called by a global click handler that handles
  // all the <a> tags in the app.
  // it expects a url pathname for example: "/costello/settings"
  navigate: function (page) {
    var url = (page.charAt(0) === '/') ? page.slice(1) : page;
    this.router.history.navigate(url, {
      trigger: true
    });
  },
  progress: function (percentage) {
    var progressBar = document.getElementById('progress-bar');
    progressBar.MaterialProgress.setProgress(percentage);

    progressBar.style.display = 'inherit';
  },
  message: function (options) {
    var snackbarContainer = document.getElementById('snack-bar');
    var snackData = { message: options.text };

    // BUGFIX: during app initialization, the snackbar is not always ready yet
    if (!snackbarContainer.MaterialSnackbar) {
      return;
    }

    var progressBar = document.getElementById('progress-bar');
    progressBar.style.display = 'none';

    if (options.type === 'error') {
      console.warn(options.text, options.error);
      snackData.timeout = 10000; // show error for 10 seconds
    } else {
      console.log(options.text);
      snackData.timeout = 2750;
    }
    snackbarContainer.MaterialSnackbar.showSnackbar(snackData);
  }
});

// run it on domReady
domReady(function () {
  app.init();

  // un-comment to start locked down and connected to database
  // app.me.isLockedDown = true;
  // app.me.connectToServer(window.location.hostname);
  // app.me.socket.emit('getDatasets');
});
<|endoftext|>


<commit_before>import {inject} from 'aurelia-framework';
import {I18N} from 'aurelia-i18n';
import {EventAggregator} from 'aurelia-event-aggregator';
import {parseJSON} from './resources/jsonparser';
import {Field} from './resources/elements/abstract/field';
import {schema, fieldsToShow} from './schemas/index';
import YAML from 'yamljs';
import $ from 'jquery';

@inject(I18N, EventAggregator)
export class App {
  constructor(i18n, ea) {
    Field.internationalizer = i18n;
    Field.eventAggregator = ea;
    // Allow access from browser console
    window.$oai = this;

    try {
      const pointerlessSchema = $.extend(true, {}, schema);
      this.forms = parseJSON('form', pointerlessSchema);
      if (window.localStorage['openapi-v2-design']) {
        const savedData = JSON.parse(window.localStorage['openapi-v2-design']);
        this.forms.setValue(savedData);
      }
    } catch (exception) {
      console.log(exception);
      this.exception = exception;
      return;
    }

    this.activeForm = 'about';

    window.onhashchange = () => {
      const formID = window.location.hash.substr(2) || 'about';
      if (typeof this.activeForm === 'object') {
        this.activeForm.show = false;
      }
      if (formID === 'about') {
        this.activeForm = 'about';
      } else if (this.forms.hasChild(formID)) {
        this.activeForm = this.forms.getChild(formID);
        this.activeForm.show = true;
      } else {
        return;
      }
      $('.nav > .nav-link.open').removeClass('open');
      $(`#nav-${formID}`).addClass('open');
    };

    this.forms.addChangeListener(() => this.saveFormLocal());
  }

  attached() {
    if (window.onhashchange) {
      window.onhashchange();
    }
  }

  import(type) {
    if (type === 'paste') {
      alert('Paste imports have not yet been implemented.');
    } else if (type === 'file') {
      const fileInput = $('<input/>');
      fileInput.attr('type', 'file');
      fileInput.css({display: 'none'});
      fileInput.appendTo($('body'));
      fileInput.trigger('click');

      fileInput.change(() => {
        const file = fileInput[0].files[0];
        const reader = new FileReader();
        reader.addEventListener('load', () => {
          const data = JSON.parse(reader.result);
          this.forms.setValue(data);
        }, false);
        reader.readAsText(file);
      });
    }
  }

  download(type) {
    let data;
    if (type === 'json') {
      data = this.json;
    } else if (type === 'yaml') {
      data = this.yaml;
    } else {
      return;
    }

    // Add an anchor element that has the data as the href attribute, then click
    // the element to download the data.
    const blob = new Blob([data], {type: 'text/json'});
    if (window.navigator.msSaveOrOpenBlob) {
      window.navigator.msSaveBlob(blob, `swagger.${type}`);
    } else {
      const downloadLink = document.createElement('a');
      downloadLink.href = window.URL.createObjectURL(blob);
      downloadLink.download = `swagger.${type}`;
      document.body.appendChild(downloadLink);
      downloadLink.click();
      document.body.removeChild(downloadLink);
    }
  }

  delete() {
    let userInput = confirm('Do you want to delete locally cached form data? \nThis action can not be undone.');
    if (userInput === true) {
      delete localStorage['openapi-v2-design'];
      location.reload();
    }
  }

  openInfo() {
    $(this.infoModal).removeClass('hidden');
  }

  closeInfo() {
    $(this.infoModal).addClass('hidden');
  }

  dontCloseInfo(evt) {
    evt.stopPropagation();
  }

  getFormData() {
    const data = this.forms.getValue();
    data.swagger = '2.0';
    return data;
  }

  get yaml() {
    return YAML.stringify(this.getFormData(), 10, 2);
  }

  get json() {
    const data = JSON.stringify(this.getFormData(), '', '  ');
    return data;
  }

  saveFormLocal() {
    window.localStorage['openapi-v2-design'] = JSON.stringify(this.getFormData());
  }

  get currentFormJSON() {
    if (fieldsToShow.hasOwnProperty(this.activeForm.id)) {
      const rawData = this.getFormData();
      let output = '';
      for (const field of fieldsToShow[this.activeForm.id]) {
        if (rawData[field]) {
          output += `"${field}": ${JSON.stringify(rawData[field], '', '  ')}\n`;
        }
      }
      return output;
    }
    const data = this.activeForm.getValue();
    if (!data || (typeof data === 'object' && Object.entries(data).length === 0)) {
      return '';
    }
    const stringData = JSON.stringify(data, '', '  ');
    return `"${this.activeForm.id}": ${stringData}`;
  }
}
<commit_msg>Add YAML import support<commit_after>import {inject} from 'aurelia-framework';
import {I18N} from 'aurelia-i18n';
import {EventAggregator} from 'aurelia-event-aggregator';
import {parseJSON} from './resources/jsonparser';
import {Field} from './resources/elements/abstract/field';
import {schema, fieldsToShow} from './schemas/index';
import YAML from 'yamljs';
import $ from 'jquery';

@inject(I18N, EventAggregator)
export class App {
  constructor(i18n, ea) {
    Field.internationalizer = i18n;
    Field.eventAggregator = ea;
    // Allow access from browser console
    window.$oai = this;

    try {
      const pointerlessSchema = $.extend(true, {}, schema);
      this.forms = parseJSON('form', pointerlessSchema);
      if (window.localStorage['openapi-v2-design']) {
        const savedData = JSON.parse(window.localStorage['openapi-v2-design']);
        this.forms.setValue(savedData);
      }
    } catch (exception) {
      console.log(exception);
      this.exception = exception;
      return;
    }

    this.activeForm = 'about';

    window.onhashchange = () => {
      const formID = window.location.hash.substr(2) || 'about';
      if (typeof this.activeForm === 'object') {
        this.activeForm.show = false;
      }
      if (formID === 'about') {
        this.activeForm = 'about';
      } else if (this.forms.hasChild(formID)) {
        this.activeForm = this.forms.getChild(formID);
        this.activeForm.show = true;
      } else {
        return;
      }
      $('.nav > .nav-link.open').removeClass('open');
      $(`#nav-${formID}`).addClass('open');
    };

    this.forms.addChangeListener(() => this.saveFormLocal());
  }

  attached() {
    if (window.onhashchange) {
      window.onhashchange();
    }
  }

  import(type) {
    if (type === 'paste') {
      alert('Paste imports have not yet been implemented.');
    } else if (type === 'file') {
      const fileInput = $('<input/>');
      fileInput.attr('type', 'file');
      fileInput.css({display: 'none'});
      fileInput.appendTo($('body'));
      fileInput.trigger('click');

      fileInput.change(() => {
        const file = fileInput[0].files[0];
        const reader = new FileReader();
        reader.addEventListener('load', () => {
          let data;
          if (file.name.endsWith('.yaml') || file.name.endsWith('.yml')) {
            data = YAML.parse(reader.result);
          } else {
            data = JSON.parse(reader.result);
          }
          this.forms.setValue(data);
        }, false);
        reader.readAsText(file);
      });
    }
  }

  download(type) {
    let data;
    if (type === 'json') {
      data = this.json;
    } else if (type === 'yaml') {
      data = this.yaml;
    } else {
      return;
    }

    // Add an anchor element that has the data as the href attribute, then click
    // the element to download the data.
    const blob = new Blob([data], {type: 'text/json'});
    if (window.navigator.msSaveOrOpenBlob) {
      window.navigator.msSaveBlob(blob, `swagger.${type}`);
    } else {
      const downloadLink = document.createElement('a');
      downloadLink.href = window.URL.createObjectURL(blob);
      downloadLink.download = `swagger.${type}`;
      document.body.appendChild(downloadLink);
      downloadLink.click();
      document.body.removeChild(downloadLink);
    }
  }

  delete() {
    let userInput = confirm('Do you want to delete locally cached form data? \nThis action can not be undone.');
    if (userInput === true) {
      delete localStorage['openapi-v2-design'];
      location.reload();
    }
  }

  openInfo() {
    $(this.infoModal).removeClass('hidden');
  }

  closeInfo() {
    $(this.infoModal).addClass('hidden');
  }

  dontCloseInfo(evt) {
    evt.stopPropagation();
  }

  getFormData() {
    const data = this.forms.getValue();
    data.swagger = '2.0';
    return data;
  }

  get yaml() {
    return YAML.stringify(this.getFormData(), 10, 2);
  }

  get json() {
    const data = JSON.stringify(this.getFormData(), '', '  ');
    return data;
  }

  saveFormLocal() {
    window.localStorage['openapi-v2-design'] = JSON.stringify(this.getFormData());
  }

  get currentFormJSON() {
    if (fieldsToShow.hasOwnProperty(this.activeForm.id)) {
      const rawData = this.getFormData();
      let output = '';
      for (const field of fieldsToShow[this.activeForm.id]) {
        if (rawData[field]) {
          output += `"${field}": ${JSON.stringify(rawData[field], '', '  ')}\n`;
        }
      }
      return output;
    }
    const data = this.activeForm.getValue();
    if (!data || (typeof data === 'object' && Object.entries(data).length === 0)) {
      return '';
    }
    const stringData = JSON.stringify(data, '', '  ');
    return `"${this.activeForm.id}": ${stringData}`;
  }
}
<|endoftext|>


<commit_before>(function(window, undefined) {
    var oLastTagDiv;
    var oTimer;

    $(function() {
        fWindowLoad();
    });

    function fWindowLoad() {
        $('a.tag').mouseenter(fTagMouseEnter)
            .mouseleave(fTagMouseLeave);
        fSuggest();
    }

    function fTagMouseEnter() {
        fHideTipDiv($('a[data-toggle=feedback]'), '007');

        var oTagDiv = $(this);
        var sDescrition = oTagDiv.data('des');
        var sId = oTagDiv.data('index');
        var nHeight = oTagDiv.height();
        var nTop = oTagDiv.position().top;

        clearTimeout(oTimer);
        if(oLastTagDiv && oLastTagDiv.get(0) != oTagDiv.get(0)) {
            fHideTipDiv(oLastTagDiv, sId);
        }
        oLastTagDiv = oTagDiv;

        var sPos = (nTop - $(document.body).scrollTop()) * 2 > $(window).height() ? 'top' : 'bottom';

        oTagDiv.popover({
            placement: sPos,
            title: '详情',
            html: true,
            container: document.body,
            content: '
' + sDescrition + '

loading...
',
            trigger: 'manual'
        });

        var oTipDiv = oTagDiv.data('popover').tip();
        oTipDiv.one('mouseenter', function() {
            clearTimeout(oTimer);
        }).one('mouseleave', function() {
            fHideTipDiv(oTagDiv, sId);
        });

        oTagDiv.popover('show');
        $('#temp' + sId).replaceWith(fBuildCommentBox(sId));
    }

    function fTagMouseLeave() {
        var oTagDiv = $(this);
        oTimer = setTimeout(function() {
            var sId = oTagDiv.data('index');
            fHideTipDiv(oTagDiv, sId);
        }, 250);
    }

    function fHideTipDiv(oTagDiv, sId) {
        // 移动后还是会重新加载啊啊啊
        try {
            var oTipDiv = oTagDiv.data('popover').tip();
            var oIframe = $('iframe', oTipDiv);
            $(document.body).append(oIframe);
            oIframe.hide();
            oTagDiv.popover('hide');
        } catch(e) {};
    }

    function fSuggest() {
        var oTagDiv = $('a[data-toggle=feedback]');
        oTagDiv.popover({
            placement: 'bottom',
            title: '反馈',
            html: true,
            content: '
loading...
',
            trigger: 'click'
        });

        var bShow = true;
        oTagDiv.on('click', function() {
            if(bShow) {
                $('#temp007').replaceWith(fBuildCommentBox('007'));
            } else {
                fHideTipDiv(oTagDiv, '007');
            }
            bShow = !bShow;
        });
    }

    function fBuildCommentBox(sId) {
        var oIframe = $('#iframe' + sId);
        if(oIframe.length != 0) {
            oIframe.show();
            return oIframe.get(0);
        }

        oIframe = document.createElement('IFRAME');
        var sTmpl = [
                '',
                '',
                '',
                '

',
                '',
                ''
        ].join('');
        oIframe.id = 'iframe' + sId;
        oIframe.style.display = 'none';
        oIframe.frameborder = 0;
        oIframe.marginwidth = 0;
        oIframe.allowTransparency = true;
        oIframe.marginheight = 0;
        oIframe.style.border = 0;
        oIframe.style.width = '400px';
        oIframe.style.height = '400px';
        document.body.appendChild(oIframe);

        $(oIframe).on('load', function() {
            var oIframeDoc = oIframe.contentDocument || oIframe.contentWindow.document;
            oIframeDoc.write(sTmpl.replace(/\{id\}/g, sId));
            $(this).show();
        });

        return oIframe;
    }

})(window);<commit_msg>修改了一些，还是有bug<commit_after>(function(window, undefined) {
    var bSuggestShow = true;
    var TIPHEIGHT = 450; // 弹窗高度
    var oLastTagDiv; // 上一个弹窗
    var oTimer; // 全局计时对象

    $(function() {
        fWindowLoad();
    });

    function fWindowLoad() {
        $('a.tag').mouseenter(fTagMouseEnter)
            .mouseleave(fTagMouseLeave);

        // 意见反馈弹窗
        fSuggest();

        //百度统计自定义事件数据
        window._hmt = window._hmt || [];
    }

    function fTagMouseEnter() {
        // 隐藏意见反馈
        fHideTipDiv($('a[data-toggle=feedback]'), '007');
        bSuggestShow = true;

        var oTagDiv = $(this);
        var sDescrition = oTagDiv.data('des');
        var sId = oTagDiv.data('index');
        var nHeight = oTagDiv.height();
        var nTop = oTagDiv.position().top;

        // 隐藏上一个弹窗
        clearTimeout(oTimer);
        if(oLastTagDiv && oLastTagDiv.get(0) != oTagDiv.get(0)) {
            fHideTipDiv(oLastTagDiv, sId);
        }
        oLastTagDiv = oTagDiv;

        // 上方有完整展示空间才向上展示
        var sPos = (nTop - $(document.body).scrollTop()) - TIPHEIGHT > 0 ? 'top' : 'bottom'
        console.log(sPos);
        oTagDiv.popover({
            placement: sPos,
            title: '详情',
            html: true,
            container: document.body,
            content: '
' + sDescrition + '

loading...
',
            trigger: 'manual'
        });

        var oTipDiv = oTagDiv.data('popover').tip();
        oTipDiv.one('mouseenter', function() {
            clearTimeout(oTimer);
        }).one('mouseleave', function() {
            fHideTipDiv(oTagDiv, sId);
        });

        oTagDiv.popover('show');
        $('#temp' + sId).replaceWith(fBuildCommentBox(sId));
    }

    function fTagMouseLeave() {
        var oTagDiv = $(this);
        clearTimeout(oTimer);
        oTimer = setTimeout(function() {
            var sId = oTagDiv.data('index');
            fHideTipDiv(oTagDiv, sId);
        }, 250);
    }

    function fHideTipDiv(oTagDiv, sId) {
        clearTimeout(oTimer);
        // DOM位置变换后，iframe还是会重新加载，缓存不了啊啊啊
        // TODO:fixed it
        try {
            var oTipDiv = oTagDiv.data('popover').tip();
            var oIframe = $('iframe', oTipDiv);
            $(document.body).append(oIframe);
            oIframe.hide();
            oTagDiv.popover('hide');
        } catch(e) {};
    }

    function fSuggest() {
        var oTagDiv = $('a[data-toggle=feedback]');
        oTagDiv.popover({
            placement: 'bottom',
            title: '反馈',
            html: true,
            content: '
loading...
',
            trigger: 'click'
        });

        oTagDiv.on('click', function() {
            if(bSuggestShow) {
                $('#temp007').replaceWith(fBuildCommentBox('007'));
            } else {
                fHideTipDiv(oTagDiv, '007');
            }
            bSuggestShow = !bSuggestShow;
        });
    }

    function fBuildCommentBox(sId) {
        var oIframe = $('#iframe' + sId);
        if(oIframe.length != 0) {
            oIframe.show();
            return oIframe.get(0);
        }

        oIframe = document.createElement('IFRAME');
        var sTmpl = [
                '',
                '',
                '',
                '

',
                '',
                ''
        ].join('');
        oIframe.id = 'iframe' + sId;
        oIframe.style.display = 'none';
        oIframe.frameborder = 0;
        oIframe.marginwidth = 0;
        oIframe.allowTransparency = true;
        oIframe.marginheight = 0;
        oIframe.style.border = 0;
        oIframe.style.width = '400px';
        oIframe.style.height = '400px';
        document.body.appendChild(oIframe);

        $(oIframe).on('load', function() {
            var oIframeDoc = oIframe.contentDocument || oIframe.contentWindow.document;
            oIframeDoc.write(sTmpl.replace(/\{id\}/g, sId));
            $(this).show();
        });

        return oIframe;
    }

})(window);<|endoftext|>


<commit_before>/*
 * Notes :
 * need to figure out if there is a way to continously check if
 * the alarms sets off.
 */

/**
 * Welcome to Pebble.js!
 * Test
 * This is where you write your app.
 */

// Calls in required stuff
var UI = require('ui');
var Vibe = require('ui/vibe');
var Settings = require('settings');
var Accel = require('ui/accel');
var date = new Date();

//var time = require('time.js');
//var Vector2 = require('vector2');

// initialize
Accel.init();

/*
var hours = [];
for (var i = 0; i < 24; i++) {
    hours.push(i + 1);
}
var minutes = [];
for (var i = 0; i < 60; i++) {
    minutes.push(i + 1);
}
*/

var alarms = Settings.data('alarms') || [];
var createAlarmItems = function(alarms) {
    var items = [];
    items.push({
        title: "Add New Alarm"
    });
    console.log("alarm length : " + alarms.length);
    if (alarms.length > 0) {
        for (var i = 0; i < alarms.length; i++) {
            items.push({
                title: alarms[i].time,
                subtitle: alarms[i].enabled ? "Enabled" : "Disabled"
            });
            console.log(i);
        }
    }
    console.log("created item list");
    Settings.data('alarms', alarms);
    console.log('saved item list');
    return items;
};

/*
var createTimeItems = function(time) {
    var items = [];
    for (var i = 0; i < time.length; i++) {
        items.push({
            title : time[i]
        });
    }
    return items;
};
*/

var detectTimeLoop = function() {
    date = new Date();
	for (var i = 0; i < alarms.length; i++) {
		//console.log("alarm " + alarms[i].hour + "h " + alarms[i].minute + "m");
		//console.log("actual " + date.getHours() + "h  " + date.getMinutes() + "m");

		// break if no longer valid alarm(s)
		if ( !alarms[i].hour || !alarms[i].minute ) { break; }

		if ( alarms[i].enabled && alarms[i].allowVib && alarms[i].hour == date.getHours() && alarms[i].minute == date.getMinutes() ) {

			Vibe.vibrate('long');
			console.log(i + ": I vibrated");

            if ( date.getSeconds() === 0 ) {

				var card = new UI.Card();
				card.title('Alarm');
				card.subtitle('Is going off!');
				card.body('Press \'select\' to turn it off.');
                main.hide();
				card.show();

				var index = i;
				var count = 0;

				/*
					Increments the count, disables alarm if 4 combinations detected
				*/

				var checkDisable = function() {

					count++;

					if ( count >= 4 ) {
                        console.log("alarm has stopped");
						alarms[index].allowVib = false;
						card.hide();
						main.show();
					}
                    console.log("count : " + count);
				}

				card.on('click', 'select', function(e) {
					checkDisable();
				});

				card.on('click', 'up', function(e) {
					checkDisable();
				});

				card.on('click', 'down', function(e) {
					checkDisable();
				});

				card.on('accelTap', function(e) {
					checkDisable();
                    console.log("tap tap");
				});
            }
		} else if ( alarms[i].hour !== date.getHours() && alarms[i].minute !== date.getMinutes()
					|| ( alarms[i].hour === date.getHours() && alarms[i].minute !== date.getMinutes() )
					|| ( alarms[i].minute === date.getMinutes() && alarms[i].hour !== date.getHours() ) ) {
			// make sure to allow vibrations after alarm minute has passed..
			if ( !alarms[i].allowVib ) {
				alarms[i].allowVib = true;
			}
		}
    }

	setTimeout(function() {
		detectTimeLoop();
	}, 1000);
};

detectTimeLoop();

/*
	Formats time from the 24-hour clock to 12-hour
*/
var formatTime = function( h, m ) {
	var hour = ( h % 12 !== 0 ? h % 12 : 12 );
    var minute = m < 10 ? "0" + m : m;
	return hour + ":" + minute + " " + ( ( h < 12 ) ? "AM" : "PM" );
};

// Sets up the alarms
var alarmItems = createAlarmItems(alarms);

/*
// Creates a loop to make an array of hours
var createHourItems = function() {
  var items = [];
  for (var i = 0; i hideurs.length; i++) {
    items.push({
      title: hours[i]
    });
  }
  return items;
};
*/

/*
var main = new UI.Menu({
   sections:[{
     items: createItems()
  }]
});

main.show();
*/

// The Splashscreen
var splashScreen = new UI.Card({
    title: 'Alarm',
    icon: 'images/menu_icon.png',
    subtitle: 'Welcome to Our App',
    body: 'This is the splash page'
    //banner (future plans)
});

// Makes a menu with New Alarms
var main = new UI.Menu({
    sections: [{
        items: alarmItems
        /*
            [{
            title: 'Add New Alarm',
            subtitle: 'New Alarm'
        }, {
            // Dr. Seuss
            title: 'One Alarm'
        }, {
            title: 'Two Alarm'
        }, {
            title: 'Red Alarm'
        }, {
            title: 'Blue Alarm'
        }]
        */
        //, createAlarmItems(alarms)
    }]
});

// Shows the spashscreen and goes to the menu after 400 ms
splashScreen.show();
setTimeout(function() {
    splashScreen.hide();
    main.show();
}, 800);

var createAlarm = function(callback) {

	date = new Date();

    alarms.push({
        time: formatTime( date.getHours(), date.getMinutes() + 1 ),
        hour: date.getHours(),
        minute: date.getMinutes() + 1,
        enabled: true,
		allowVib: true
    });
    console.log("hour : " + date.getHours());
    console.log("minute : " + date.getMinutes());
    console.log("time : " + formatTime( date.getHours(), date.getMinutes() ));
    callback();
};

main.on('select', function(e) {
    console.log(e.sectionIndex);
    // If it is on the "New Alarm Option"
    if (e.itemIndex === 0) {
        // Has a random card as a placeholder
        //var wind = new UI.Wind();

        var card = new UI.Card();
        card.title('A Card');
        card.subtitle('Is a Window');
        card.body('The simplest window type in Pebble.js.');
        card.show();
        //wind.show();

        // When click the middle button it makes an alarm
        card.on('click', 'select', function() {
            createAlarm(function() {
                alarmItems = createAlarmItems(alarms);
                console.log('Items done');
                console.log(alarmItems);
                card.hide();
                main.section(0, section = {
                    items: alarmItems
                });
                console.log("success");
                //hourChange = new time.hourChange();
                //time.hourChange.show();
            });
        });
    } else {
        // Otherwise the user selects an alarm
        // Creates the Menu for Alarm Options
        var alarmOptions = new UI.Menu({
            sections : [{
                items: [{
                    title: alarms[e.itemIndex - 1].enabled ? 'Disable' : 'Enable'
                }, {
                    title: 'Edit'
                }, {
                    title: 'Delete'
                }]
            }]
        });
        alarmOptions.show();

        alarmOptions.on('select', function(f) {
            switch(f.itemIndex) {
                case 0:
                    // Disable or Enable the Alarm
                    for (var i = 0; i < alarms.length; i++) {
                        console.log(i + " : " + alarms[i].enabled);
                        console.log(f.itemIndex + 1 + " : " + alarms[f.itemIndex + 1].enabled);
                    }
                    alarms[f.itemIndex - 0].enabled = !alarms[f.itemIndex - 0].enabled;
                    break;
                case 1:
                    // Edit the time of the alarm
                    break;
                case 2:
                    // Deletes the alarm
                    alarms.splice(f.itemIndex - 2, 1);
                    console.log("deleted at : " + f.itemIndex - 2);
                    break;
                default:
                    console.log("error");
                    break;
            }
            // Update the alarms and gets rid of the option menu
            alarmOptions.hide();
            alarmItems = createAlarmItems(alarms);
            main.section(0, section = {
                items: alarmItems
            });
            //console.log('updated alarms');
        });
    }
    // Choose an option to chnage alarm
});
<commit_msg>indexOfAlarm<commit_after>/*
 * Notes :
 * need to figure out if there is a way to continously check if
 * the alarms sets off.
 */

/**
 * Welcome to Pebble.js!
 * Test
 * This is where you write your app.
 */

// Calls in required stuff
var UI = require('ui');
var Vibe = require('ui/vibe');
var Settings = require('settings');
var Accel = require('ui/accel');
var date = new Date();

//var time = require('time.js');
//var Vector2 = require('vector2');

// initialize
Accel.init();

/*
var hours = [];
for (var i = 0; i < 24; i++) {
    hours.push(i + 1);
}
var minutes = [];
for (var i = 0; i < 60; i++) {
    minutes.push(i + 1);
}
*/

var alarms = Settings.data('alarms') || [];
var createAlarmItems = function(alarms) {
    var items = [];
    items.push({
        title: "Add New Alarm"
    });
    console.log("alarm length : " + alarms.length);
    if (alarms.length > 0) {
        for (var i = 0; i < alarms.length; i++) {
            items.push({
                title: alarms[i].time,
                subtitle: alarms[i].enabled ? "Enabled" : "Disabled"
            });
            console.log(i);
        }
    }
    console.log("created item list");
    Settings.data('alarms', alarms);
    console.log('saved item list');
    return items;
};

/*
var createTimeItems = function(time) {
    var items = [];
    for (var i = 0; i < time.length; i++) {
        items.push({
            title : time[i]
        });
    }
    return items;
};
*/

var detectTimeLoop = function() {
    date = new Date();
	for (var i = 0; i < alarms.length; i++) {
		//console.log("alarm " + alarms[i].hour + "h " + alarms[i].minute + "m");
		//console.log("actual " + date.getHours() + "h  " + date.getMinutes() + "m");

		// break if no longer valid alarm(s)
		if ( !alarms[i].hour || !alarms[i].minute ) { break; }

		if ( alarms[i].enabled && alarms[i].allowVib && alarms[i].hour == date.getHours() && alarms[i].minute == date.getMinutes() ) {

			Vibe.vibrate('long');
			console.log(i + ": I vibrated");

            if ( date.getSeconds() === 0 ) {

				var card = new UI.Card();
				card.title('Alarm');
				card.subtitle('Is going off!');
				card.body('Press \'select\' to turn it off.');
                main.hide();
				card.show();

				var index = i;
				var count = 0;

				/*
					Increments the count, disables alarm if 4 combinations detected
				*/

				var checkDisable = function() {

					count++;

					if ( count >= 4 ) {
                        console.log("alarm has stopped");
						alarms[index].allowVib = false;
						card.hide();
						main.show();
					}
                    console.log("count : " + count);
				}

				card.on('click', 'select', function(e) {
					checkDisable();
				});

				card.on('click', 'up', function(e) {
					checkDisable();
				});

				card.on('click', 'down', function(e) {
					checkDisable();
				});

				card.on('accelTap', function(e) {
					checkDisable();
                    console.log("tap tap");
				});
            }
		} else if ( alarms[i].hour !== date.getHours() && alarms[i].minute !== date.getMinutes()
					|| ( alarms[i].hour === date.getHours() && alarms[i].minute !== date.getMinutes() )
					|| ( alarms[i].minute === date.getMinutes() && alarms[i].hour !== date.getHours() ) ) {
			// make sure to allow vibrations after alarm minute has passed..
			if ( !alarms[i].allowVib ) {
				alarms[i].allowVib = true;
			}
		}
    }

	setTimeout(function() {
		detectTimeLoop();
	}, 1000);
};

detectTimeLoop();

/*
	Formats time from the 24-hour clock to 12-hour
*/
var formatTime = function( h, m ) {
	var hour = ( h % 12 !== 0 ? h % 12 : 12 );
    var minute = m < 10 ? "0" + m : m;
	return hour + ":" + minute + " " + ( ( h < 12 ) ? "AM" : "PM" );
};

// Sets up the alarms
var alarmItems = createAlarmItems(alarms);

/*
// Creates a loop to make an array of hours
var createHourItems = function() {
  var items = [];
  for (var i = 0; i hideurs.length; i++) {
    items.push({
      title: hours[i]
    });
  }
  return items;
};
*/

/*
var main = new UI.Menu({
   sections:[{
     items: createItems()
  }]
});

main.show();
*/

// The Splashscreen
var splashScreen = new UI.Card({
    title: 'Alarm',
    icon: 'images/menu_icon.png',
    subtitle: 'Welcome to Our App',
    body: 'This is the splash page'
    //banner (future plans)
});

// Makes a menu with New Alarms
var main = new UI.Menu({
    sections: [{
        items: alarmItems
        /*
            [{
            title: 'Add New Alarm',
            subtitle: 'New Alarm'
        }, {
            // Dr. Seuss
            title: 'One Alarm'
        }, {
            title: 'Two Alarm'
        }, {
            title: 'Red Alarm'
        }, {
            title: 'Blue Alarm'
        }]
        */
        //, createAlarmItems(alarms)
    }]
});

// Shows the spashscreen and goes to the menu after 400 ms
splashScreen.show();
setTimeout(function() {
    splashScreen.hide();
    main.show();
}, 800);

var createAlarm = function(callback) {

	date = new Date();

    alarms.push({
        time: formatTime( date.getHours(), date.getMinutes() + 1 ),
        hour: date.getHours(),
        minute: date.getMinutes() + 1,
        enabled: true,
		allowVib: true
    });
    console.log("hour : " + date.getHours());
    console.log("minute : " + date.getMinutes());
    console.log("time : " + formatTime( date.getHours(), date.getMinutes() ));
    callback();
};

main.on('select', function(e) {
    console.log(e.sectionIndex);
    // If it is on the "New Alarm Option"
    if (e.itemIndex === 0) {
        // Has a random card as a placeholder
        //var wind = new UI.Wind();

        var card = new UI.Card();
        card.title('A Card');
        card.subtitle('Is a Window');
        card.body('The simplest window type in Pebble.js.');
        card.show();
        //wind.show();

        // When click the middle button it makes an alarm
        card.on('click', 'select', function() {
            createAlarm(function() {
                alarmItems = createAlarmItems(alarms);
                console.log('Items done');
                console.log(alarmItems);
                card.hide();
                main.section(0, section = {
                    items: alarmItems
                });
                console.log("success");
                //hourChange = new time.hourChange();
                //time.hourChange.show();
            });
        });
    } else {
        // Otherwise the user selects an alarm
        // Creates the Menu for Alarm Options
        var alarmOptions = new UI.Menu({
            sections : [{
                items: [{
                    title: alarms[e.itemIndex - 1].enabled ? 'Disable' : 'Enable'
                }, {
                    title: 'Edit'
                }, {
                    title: 'Delete'
                }]
            }]
        });
        alarmOptions.show();

        alarmOptions.on('select', function(f) {
            var indexOfAlarm = f.itemIndex;
            console.log(indexOfAlarm);
            switch(f.itemIndex) {
                case 0:
                    // Disable or Enable the Alarm
                    for (var i = 0; i < alarms.length; i++) {
                        console.log(i + " : " + alarms[i].enabled);
                        console.log(f.itemIndex + 1 + " : " + alarms[f.itemIndex + 1].enabled);
                    }
                    alarms[f.itemIndex - 0].enabled = !alarms[f.itemIndex - 0].enabled;
                    break;
                case 1:
                    // Edit the time of the alarm
                    break;
                case 2:
                    // Deletes the alarm
                    alarms.splice(f.itemIndex - 2, 1);
                    console.log("deleted at : " + f.itemIndex - 2);
                    break;
                default:
                    console.log("error");
                    break;
            }
            // Update the alarms and gets rid of the option menu
            alarmOptions.hide();
            alarmItems = createAlarmItems(alarms);
            main.section(0, section = {
                items: alarmItems
            });
            //console.log('updated alarms');
        });
    }
    // Choose an option to chnage alarm
});
<|endoftext|>


<commit_before>'use strict';

const apiai = require('apiai');
const express = require('express');
const bodyParser = require('body-parser');
const uuid = require('node-uuid');
const request = require('request');
const JSONbig = require('json-bigint');
const async = require('async');

const REST_PORT = (process.env.PORT || 5000);
const APIAI_ACCESS_TOKEN = process.env.APIAI_ACCESS_TOKEN;
const APIAI_LANG = process.env.APIAI_LANG || 'nl';
const FB_VERIFY_TOKEN = process.env.FB_VERIFY_TOKEN;
const FB_PAGE_ACCESS_TOKEN = process.env.FB_PAGE_ACCESS_TOKEN;

const apiAiService = apiai(APIAI_ACCESS_TOKEN, {language: APIAI_LANG, requestSource: "fb"});
const sessionIds = new Map();

function processEvent(event) {
    var sender = event.sender.id.toString();

    if ((event.message && event.message.text) || (event.postback && event.postback.payload)) {
        var text = event.message ? event.message.text : event.postback.payload;
        // Handle a text message from this sender

        if (!sessionIds.has(sender)) {
            sessionIds.set(sender, uuid.v1());
        }

        console.log("proces event: ", text);
        //send message to api.ai
        let apiaiRequest = apiAiService.textRequest(text,
            {
                sessionId: sessionIds.get(sender)
            });
        //receive message from api.ai
        apiaiRequest.on('response', (response) => {
            if (isDefined(response.result)) {
                let responseText = response.result.fulfillment.speech;
                let responseData = response.result.fulfillment.data;
                let action = response.result.action; //actie in intent
                let action = response.result.metadata.
                console.log(response.result);

                getFBName(sender, (name) => {
                        console.log(sender, name);
                    });

                if (isDefined(responseData) && isDefined(responseData.facebook)) {

                    if (!Array.isArray(responseData.facebook)) {
                        try {
                            console.log('Response as formatted message');
                            sendFBMessage(sender, responseData.facebook + ' geformatteerd bericht');
                        } catch (err) {
                            sendFBMessage(sender, {text: err.message});
                        }
                    } else {
                        responseData.facebook.forEach((facebookMessage) => {
                            try {
                                if (facebookMessage.sender_action) {
                                    console.log('Response as sender action');
                                    //sendFBMessage(sender, ' debug fb action: ' + sender_action);
                                    sendFBSenderAction(sender, facebookMessage.sender_action);
                                }
                                else {
                                    console.log('Response as formatted message');
                                    sendFBMessage(sender, facebookMessage + ' geformatteerd bericht 2');
                                }
                            } catch (err) {
                                sendFBMessage(sender, {text: err.message});
                            }
                        });
                    }
                //hier komen de standaard tekst antwoorden van api.ai terecht
                } else if (isDefined(responseText)) {
                    console.log('Response as text message');
                    //achterhaal of er intelligentie nodig is
                    var speech ="";
                        switch(action) {
                        case "who_are_you": //check if user is known
                            speech += action;
                        break;
                        case "pam_sum": //calculate PAM score
                            speech += response.result.parameters.pam_score;
                            //hoe geef je waarde aan api.ai variabele?
                            //apiaiRequest.contexts.pam_sum.paramaters.pam_total += response.result.parameters.pam_score
                        break;
                        default:
                        speech += 'Sorry, de actie is niet bekend.';
                        }

                    // facebook API limit for text length is 320,
                    // so we must split message if needed
                    var splittedText = splitResponse(responseText);

                    async.eachSeries(splittedText, (textPart, callback) => {
                        //sendFBMessage(sender, {text: textPart + ' debug callback: ' + speech}, callback);
                        sendFBMessage(sender, {text: textPart}, callback);
                    });
                }

            }
        });
        apiaiRequest.on('error', (error) => console.error(error));
        apiaiRequest.end();
    }
}

function splitResponse(str) {
    if (str.length <= 320) {
        return [str];
    }

    return chunkString(str, 300);
}

function chunkString(s, len) {
    var curr = len, prev = 0;

    var output = [];

    while (s[curr]) {
        if (s[curr++] == ' ') {
            output.push(s.substring(prev, curr));
            prev = curr;
            curr += len;
        }
        else {
            var currReverse = curr;
            do {
                if (s.substring(currReverse - 1, currReverse) == ' ') {
                    output.push(s.substring(prev, currReverse));
                    prev = currReverse;
                    curr = currReverse + len;
                    break;
                }
                currReverse--;
            } while (currReverse > prev)
        }
    }
    output.push(s.substr(prev));
    return output;
}

function getFBName(id, callback){
    console.log('id:', id);
    request({
        url: 'https://graph.facebook.com/v2.6/' + id + '?fields=name',
        qs: {access_token: FB_PAGE_ACCESS_TOKEN},
        method: 'GET'
    }, (error, response, body) => {
        console.log(error, body);
        if(callback){
            callback(body.name)
        }
    });
}

function sendFBMessage(sender, messageData, callback) {
    request({
        url: 'https://graph.facebook.com/v2.6/me/messages',
        qs: {access_token: FB_PAGE_ACCESS_TOKEN},
        method: 'POST',
        json: {
            recipient: {id: sender},
            message: messageData
        }
    }, (error, response, body) => {
        if (error) {
            console.log('Error sending message: ', error);
        } else if (response.body.error) {
            console.log('Error: ', response.body.error);
        }

        if (callback) {
            callback();
        }
    });
}

function sendFBSenderAction(sender, action, callback) {
    setTimeout(() => {
        request({
            url: 'https://graph.facebook.com/v2.6/me/messages',
            qs: {access_token: FB_PAGE_ACCESS_TOKEN},
            method: 'POST',
            json: {
                recipient: {id: sender},
                sender_action: action
            }
        }, (error, response, body) => {
            if (error) {
                console.log('Error sending action: ', error);
            } else if (response.body.error) {
                console.log('Error: ', response.body.error);
            }
            if (callback) {
                callback();
            }
        });
    }, 1000);
}

function doSubscribeRequest() {
    request({
            method: 'POST',
            uri: "https://graph.facebook.com/v2.6/me/subscribed_apps?access_token=" + FB_PAGE_ACCESS_TOKEN
        },
        (error, response, body) => {
            if (error) {
                console.error('Error while subscription: ', error);
            } else {
                console.log('Subscription result: ', response.body);
            }
        });
}

function isDefined(obj) {
    if (typeof obj == 'undefined') {
        return false;
    }

    if (!obj) {
        return false;
    }

    return obj != null;
}

const app = express();
const frontofficeid = 1533050426761050;
app.use(bodyParser.text({type: 'application/json'})); //geen response als deze weggelaten wordt
app.use(bodyParser.urlencoded({extended: false})); //toegevoegd: heeft invloed verwerking event
app.use(bodyParser.json()); //toegevoegd: corrigeert de werking weer

var debugtekst = "";

// Server frontpage
app.get('/', function (req, res) {
        res.send('This is Paula');
        });

app.get('/webhook/', (req, res) => {
    if (req.query['hub.verify_token'] == FB_VERIFY_TOKEN) {
        res.send(req.query['hub.challenge']);

        setTimeout(() => {
            doSubscribeRequest();
        }, 5000);
    } else {
        res.send('Error, wrong validation token');
    }
});

//ontvangen van FB bericht
app.post('/webhook/', (req, res) => {
    try {
        var data = JSONbig.parse(req.body);

        if (data.entry) {
            let entries = data.entry;
            entries.forEach((entry) => {
                let messaging_events = entry.messaging;
                if (messaging_events) {
                    messaging_events.forEach((event) => {
                        if (event.message && !event.message.is_echo ||
                            event.postback && event.postback.payload) {
                            //sendFBMessage(event.sender.id, {text: "Debugtekst fb: " + debugtekst});
                            processEvent(event);
                            //sendFBMessage(event.sender.id, {text: "Jij bent: " + event.sender.id});
                        }
                    });
                }
            });
        }

        return res.status(200).json({
            status: "ok"
        });
    } catch (err) {
        return res.status(400).json({
            status: "error",
            error: err
        });
    }

});

//bewerking van api.ai vanuit webhook alvorens terug te sturen
//app.post('/herokuai', function (req1, res1) {
//         try {
//         var requestBody = req1.action;
//         debugtekst = "herokuai webhook: " + requestBody.action;
//            } catch (err) {
//                console.error("Can't process request", err);
//                debugtekst = "herokuai webhook err: " + err;
//         }
//});

app.listen(REST_PORT, () => {
    console.log('Rest service ready on port ' + REST_PORT);
});

doSubscribeRequest();
<commit_msg>Facebook name test<commit_after>'use strict';

const apiai = require('apiai');
const express = require('express');
const bodyParser = require('body-parser');
const uuid = require('node-uuid');
const request = require('request');
const JSONbig = require('json-bigint');
const async = require('async');

const REST_PORT = (process.env.PORT || 5000);
const APIAI_ACCESS_TOKEN = process.env.APIAI_ACCESS_TOKEN;
const APIAI_LANG = process.env.APIAI_LANG || 'nl';
const FB_VERIFY_TOKEN = process.env.FB_VERIFY_TOKEN;
const FB_PAGE_ACCESS_TOKEN = process.env.FB_PAGE_ACCESS_TOKEN;

const apiAiService = apiai(APIAI_ACCESS_TOKEN, {language: APIAI_LANG, requestSource: "fb"});
const sessionIds = new Map();

function processEvent(event) {
    var sender = event.sender.id.toString();

    if ((event.message && event.message.text) || (event.postback && event.postback.payload)) {
        var text = event.message ? event.message.text : event.postback.payload;
        // Handle a text message from this sender

        if (!sessionIds.has(sender)) {
            sessionIds.set(sender, uuid.v1());
        }

        console.log("proces event: ", text);
        //send message to api.ai
        let apiaiRequest = apiAiService.textRequest(text,
            {
                sessionId: sessionIds.get(sender)
            });
        //receive message from api.ai
        apiaiRequest.on('response', (response) => {
            if (isDefined(response.result)) {
                let responseText = response.result.fulfillment.speech;
                let responseData = response.result.fulfillment.data;
                let action = response.result.action; //actie in intent
                let intent = response.result.metadata.intentId;
                console.log(response.result);

                getFBName(sender, (name) => {
                        console.log(sender, name);
                    });

                if (isDefined(responseData) && isDefined(responseData.facebook)) {

                    if (!Array.isArray(responseData.facebook)) {
                        try {
                            console.log('Response as formatted message');
                            sendFBMessage(sender, responseData.facebook + ' geformatteerd bericht');
                        } catch (err) {
                            sendFBMessage(sender, {text: err.message});
                        }
                    } else {
                        responseData.facebook.forEach((facebookMessage) => {
                            try {
                                if (facebookMessage.sender_action) {
                                    console.log('Response as sender action');
                                    //sendFBMessage(sender, ' debug fb action: ' + sender_action);
                                    sendFBSenderAction(sender, facebookMessage.sender_action);
                                }
                                else {
                                    console.log('Response as formatted message');
                                    sendFBMessage(sender, facebookMessage + ' geformatteerd bericht 2');
                                }
                            } catch (err) {
                                sendFBMessage(sender, {text: err.message});
                            }
                        });
                    }
                //hier komen de standaard tekst antwoorden van api.ai terecht
                } else if (isDefined(responseText)) {
                    console.log('Response as text message');
                    //achterhaal of er intelligentie nodig is
                    var speech ="";
                        switch(action) {
                        case "who_are_you": //check if user is known
                            speech += action;
                        break;
                        case "pam_sum": //calculate PAM score
                            speech += response.result.parameters.pam_score;
                            //hoe geef je waarde aan api.ai variabele?
                            //apiaiRequest.contexts.pam_sum.paramaters.pam_total += response.result.parameters.pam_score
                        break;
                        default:
                        speech += 'Sorry, de actie is niet bekend.';
                        }

                    // facebook API limit for text length is 320,
                    // so we must split message if needed
                    var splittedText = splitResponse(responseText);

                    async.eachSeries(splittedText, (textPart, callback) => {
                        //sendFBMessage(sender, {text: textPart + ' debug callback: ' + speech}, callback);
                        sendFBMessage(sender, {text: textPart}, callback);
                    });
                }

            }
        });
        apiaiRequest.on('error', (error) => console.error(error));
        apiaiRequest.end();
    }
}

function splitResponse(str) {
    if (str.length <= 320) {
        return [str];
    }

    return chunkString(str, 300);
}

function chunkString(s, len) {
    var curr = len, prev = 0;

    var output = [];

    while (s[curr]) {
        if (s[curr++] == ' ') {
            output.push(s.substring(prev, curr));
            prev = curr;
            curr += len;
        }
        else {
            var currReverse = curr;
            do {
                if (s.substring(currReverse - 1, currReverse) == ' ') {
                    output.push(s.substring(prev, currReverse));
                    prev = currReverse;
                    curr = currReverse + len;
                    break;
                }
                currReverse--;
            } while (currReverse > prev)
        }
    }
    output.push(s.substr(prev));
    return output;
}

function getFBName(id, callback){
    console.log('id:', id);
    request({
        url: 'https://graph.facebook.com/v2.6/' + id + '?fields=name',
        qs: {access_token: FB_PAGE_ACCESS_TOKEN},
        method: 'GET'
    }, (error, response, body) => {
        console.log(error, body);
        if(callback){
            callback(body.name)
        }
    });
}

function sendFBMessage(sender, messageData, callback) {
    request({
        url: 'https://graph.facebook.com/v2.6/me/messages',
        qs: {access_token: FB_PAGE_ACCESS_TOKEN},
        method: 'POST',
        json: {
            recipient: {id: sender},
            message: messageData
        }
    }, (error, response, body) => {
        if (error) {
            console.log('Error sending message: ', error);
        } else if (response.body.error) {
            console.log('Error: ', response.body.error);
        }

        if (callback) {
            callback();
        }
    });
}

function sendFBSenderAction(sender, action, callback) {
    setTimeout(() => {
        request({
            url: 'https://graph.facebook.com/v2.6/me/messages',
            qs: {access_token: FB_PAGE_ACCESS_TOKEN},
            method: 'POST',
            json: {
                recipient: {id: sender},
                sender_action: action
            }
        }, (error, response, body) => {
            if (error) {
                console.log('Error sending action: ', error);
            } else if (response.body.error) {
                console.log('Error: ', response.body.error);
            }
            if (callback) {
                callback();
            }
        });
    }, 1000);
}

function doSubscribeRequest() {
    request({
            method: 'POST',
            uri: "https://graph.facebook.com/v2.6/me/subscribed_apps?access_token=" + FB_PAGE_ACCESS_TOKEN
        },
        (error, response, body) => {
            if (error) {
                console.error('Error while subscription: ', error);
            } else {
                console.log('Subscription result: ', response.body);
            }
        });
}

function isDefined(obj) {
    if (typeof obj == 'undefined') {
        return false;
    }

    if (!obj) {
        return false;
    }

    return obj != null;
}

const app = express();
const frontofficeid = 1533050426761050;
app.use(bodyParser.text({type: 'application/json'})); //geen response als deze weggelaten wordt
app.use(bodyParser.urlencoded({extended: false})); //toegevoegd: heeft invloed verwerking event
app.use(bodyParser.json()); //toegevoegd: corrigeert de werking weer

var debugtekst = "";

// Server frontpage
app.get('/', function (req, res) {
        res.send('This is Paula');
        });

app.get('/webhook/', (req, res) => {
    if (req.query['hub.verify_token'] == FB_VERIFY_TOKEN) {
        res.send(req.query['hub.challenge']);

        setTimeout(() => {
            doSubscribeRequest();
        }, 5000);
    } else {
        res.send('Error, wrong validation token');
    }
});

//ontvangen van FB bericht
app.post('/webhook/', (req, res) => {
    try {
        var data = JSONbig.parse(req.body);

        if (data.entry) {
            let entries = data.entry;
            entries.forEach((entry) => {
                let messaging_events = entry.messaging;
                if (messaging_events) {
                    messaging_events.forEach((event) => {
                        if (event.message && !event.message.is_echo ||
                            event.postback && event.postback.payload) {
                            //sendFBMessage(event.sender.id, {text: "Debugtekst fb: " + debugtekst});
                            processEvent(event);
                            //sendFBMessage(event.sender.id, {text: "Jij bent: " + event.sender.id});
                        }
                    });
                }
            });
        }

        return res.status(200).json({
            status: "ok"
        });
    } catch (err) {
        return res.status(400).json({
            status: "error",
            error: err
        });
    }

});

//bewerking van api.ai vanuit webhook alvorens terug te sturen
//app.post('/herokuai', function (req1, res1) {
//         try {
//         var requestBody = req1.action;
//         debugtekst = "herokuai webhook: " + requestBody.action;
//            } catch (err) {
//                console.error("Can't process request", err);
//                debugtekst = "herokuai webhook err: " + err;
//         }
//});

app.listen(REST_PORT, () => {
    console.log('Rest service ready on port ' + REST_PORT);
});

doSubscribeRequest();
<|endoftext|>


<commit_before>'use strict';

var npdcCommon = require('npdc-common');
var AutoConfig = npdcCommon.AutoConfig;

var angular = require('angular');
require('formula');
require('angular-route');
require('angular-npolar');

var npdcPersonApp = angular.module('npdcPersonApp', ['ngRoute', 'formula', 'npolarApi', 'npolarUi', 'npdcUi', 'templates']);

npdcPersonApp.controller('UserShowController', require('./show/UserShowController'));
npdcPersonApp.controller('UserListController', require('./list/UserListController'));
npdcPersonApp.controller('UserEditController', require('./edit/UserEditController'));
npdcPersonApp.controller('UserRegisterController', require('./register/UserRegisterController'));
npdcPersonApp.controller('UserResetController', require('./reset/UserResetController'));
npdcPersonApp.controller('UserUpdateController', require('./update/UserUpdateController'));

// Bootstrap ngResource models using NpolarApiResource
var resources = [
  {'path': '/user', 'resource': 'User'},
  {'path': '/person', 'resource': 'Person'}
];

resources.forEach(service => {
  // Expressive DI syntax is needed here
  npdcPersonApp.factory(service.resource, ['NpolarApiResource', function (NpolarApiResource) {
    return NpolarApiResource.resource(service);
  }]);
});

// API HTTP interceptor
npdcPersonApp.config($httpProvider => {
  $httpProvider.interceptors.push('npolarApiInterceptor');
});

// Routing
npdcPersonApp.config(require('./router'));

// Inject npolarApiConfig and run
npdcPersonApp.run(npolarApiConfig => {
  var environment = 'production';
  var autoconfig = new AutoConfig(environment);
  angular.extend(npolarApiConfig, autoconfig, { resources, formula : { template : 'material' } });
  console.log("npolarApiConfig", npolarApiConfig);
});
<commit_msg>Removed unnecessary dependencies and modules<commit_after>'use strict';

var npdcCommon = require('npdc-common');
var AutoConfig = npdcCommon.AutoConfig;

var angular = require('angular');

var npdcPersonApp = angular.module('npdcPersonApp', ['npdcUi']);

npdcPersonApp.controller('UserShowController', require('./show/UserShowController'));
npdcPersonApp.controller('UserListController', require('./list/UserListController'));
npdcPersonApp.controller('UserEditController', require('./edit/UserEditController'));
npdcPersonApp.controller('UserRegisterController', require('./register/UserRegisterController'));
npdcPersonApp.controller('UserResetController', require('./reset/UserResetController'));
npdcPersonApp.controller('UserUpdateController', require('./update/UserUpdateController'));

// Bootstrap ngResource models using NpolarApiResource
var resources = [
  {'path': '/user', 'resource': 'User'},
  {'path': '/person', 'resource': 'Person'}
];

resources.forEach(service => {
  // Expressive DI syntax is needed here
  npdcPersonApp.factory(service.resource, ['NpolarApiResource', function (NpolarApiResource) {
    return NpolarApiResource.resource(service);
  }]);
});

// API HTTP interceptor
npdcPersonApp.config($httpProvider => {
  $httpProvider.interceptors.push('npolarApiInterceptor');
});

// Routing
npdcPersonApp.config(require('./router'));

// Inject npolarApiConfig and run
npdcPersonApp.run(npolarApiConfig => {
  var environment = 'production';
  var autoconfig = new AutoConfig(environment);
  angular.extend(npolarApiConfig, autoconfig, { resources, formula : { template : 'material' } });
  console.log("npolarApiConfig", npolarApiConfig);
});
<|endoftext|>


<commit_before>/**
 * Main application module.
 * Project started: 16.03.2014 - 00:21
 * @module app
 * @author Sören Gade
 *
 * @requires config
 * @requires web/index
 * @requires io/rfidreader
 * */

require('./log-replace')();
var config = require('./config');
var web = require('./web/');
var RFIDReader = require('./io/rfidreader');
var Relais = require('./io/relais');

console.log("Hello World!");
console.log("This is going to be a full featured door lock system.");
/* ==========
 * Globals
 * ==========
 * */
var rfidReader = null;
var relais = null;

/* ==========
 * Init
 * ==========
 * */
/**
 * Starts the webserver.
 * */
function startWeb() {
  var port = config.web.port;

  web.init(port, web_RFIDRequest);
  web.start(function() {
    console.log("Web interface running on port " + web.getPort() + ".");
  });
}
function web_RFIDRequest(callback) {
  rfidReader.on('data', function(data) {
    callback(data);
  });
}

/**
 * Initializes the connection with the RFID reader.
 * */
function initRFIDReader() {
  var port = config.port.rfid;
  if ( !port ) {
    console.log("Please set the rfidreader port in the config.");
    return;
  }

  // create new instance
  rfidReader = new RFIDReader(port);

  // add event listeners
  rfidReader.on('data', function(data) {
    data = data.toString();
    console.log("Data by RFID reader:", data);
  });

  // open connection
  rfidReader.open(function() {
    console.log("Connection to RFID reader opened (" + port + ").");
  });
}
/**
 * Initializes the connection with the relais card.
 * */
function initRelais() {
  var port = config.port.relais;
  if ( !port ) {
    console.log("Please set the relais card port in the config.");
    return;
  }

  relais = new Relais(port);

  relais.open(function() {
    console.log("Connection to relais card opened (" + port + ").");

    relais.deactivateAll();
  });
}

/**
 * The main application entry point.
 * */
(function main() {
  initRFIDReader();
  initRelais();
  startWeb();
}());
<commit_msg>Added exit handler.<commit_after>/**
 * Main application module.
 * Project started: 16.03.2014 - 00:21
 * @module app
 * @author Sören Gade
 *
 * @requires config
 * @requires web/index
 * @requires io/rfidreader
 * */

require('./log-replace')();
var config = require('./config');
var web = require('./web/');
var RFIDReader = require('./io/rfidreader');
var Relais = require('./io/relais');

console.log("Hello World!");
console.log("This is going to be a full featured door lock system.");
/* ==========
 * Globals
 * ==========
 * */
var rfidReader = null;
var relais = null;

/* ==========
 * Init
 * ==========
 * */
/**
 * Starts the webserver.
 * */
function startWeb() {
  var port = config.web.port;

  web.init(port, web_RFIDRequest);
  web.start(function() {
    console.log("Web interface running on port " + web.getPort() + ".");
  });
}
function web_RFIDRequest(callback) {
  rfidReader.on('data', function(data) {
    callback(data);
  });
}

/**
 * Initializes the connection with the RFID reader.
 * */
function initRFIDReader() {
  var port = config.port.rfid;
  if ( !port ) {
    console.log("Please set the rfidreader port in the config.");
    return;
  }

  // create new instance
  rfidReader = new RFIDReader(port);

  // add event listeners
  rfidReader.on('data', function(data) {
    data = data.toString();
    console.log("Data by RFID reader:", data);
  });

  // open connection
  rfidReader.open(function() {
    console.log("Connection to RFID reader opened (" + port + ").");
  });
}
/**
 * Initializes the connection with the relais card.
 * */
function initRelais() {
  var port = config.port.relais;
  if ( !port ) {
    console.log("Please set the relais card port in the config.");
    return;
  }

  relais = new Relais(port);

  relais.open(function() {
    console.log("Connection to relais card opened (" + port + ").");

    relais.deactivateAll();
  });
}

/**
 * The main application entry point.
 * */
(function main() {
  initRFIDReader();
  initRelais();
  startWeb();
}());

function exit() {
  console.log("Exiting...");
  if ( rfidReader.isOpen ) {
    rfidReader.close();
  }
  if ( relais.isOpen ) {
    relais.close();
  }

  web.stop();

  // Done
  console.log("Bye!");
  // won't exit otherwise
  process.kill();
}
process.on('exit', exit);
process.on('SIGINT', exit);
process.on('uncaughtException', exit);
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import codePush from 'react-native-code-push'
import OneSignal from 'react-native-onesignal'

import { Router, Scene, Actions } from 'react-native-mobx'
import { Provider } from 'mobx-react/native'

import LoginScreen from './views/login_screen'
import HomeScreen from './views/home_screen'
import SettingScreen from './views/setting_screen'
import ChatScreen from './views/chat_screen'

import appStore from './store/AppStore'

class App extends Component {
  componentDidMount() {
    console.log("-------xx------ App - componentDidMount ------xx-------")
    OneSignal.inFocusDisplaying(0)
    OneSignal.configure({
      onNotificationReceived: function(notification) {
        //console.log('NOTIFICATION RECEIVED: ', notification)
        if (notification.payload.additionalData.new_message && appStore.current_puid != notification.payload.additionalData.puid) {
          console.log("       appStore.new_messages + 1 : " + appStore.current_puid)
          appStore.new_messages = appStore.new_messages + 1
        }
      },
      onNotificationOpened: function(openResult) {
        console.log(openResult);
        console.log('MESSAGE: ', openResult.notification.payload.body)
        console.log('CURRENT PUID:' + appStore.current_pui)
        console.log('ISACTIVE: ', openResult.notification.isAppInFocus)
        console.log('DATA: ', openResult.notification.payload.additionalData)
        if (!openResult.notification.isAppInFocus) {
          if (openResult.notification.payload.additionalData) {
            if (appStore.current_puid != openResult.notification.payload.additionalData.puid) {
              Actions.login({ type: 'replace', postProps:openResult.notification.payload.additionalData })
            }
          }
          else {
            Actions.login({ type: 'replace', postProps:null })
          }
        }
      }
    })
  }
  render() {
    console.disableYellowBox = true
    return (
      <Provider appStore={appStore}>
        <Router>
          <Scene
            key="login"
            component={LoginScreen}
            duration={1}
            hideNavBar
            initial
          />
          <Scene
            key="home"
            component={HomeScreen}
            duration={1}
            hideNavBar
          />
          <Scene
            key="chat"
            component={ChatScreen}
            //direction="vertical"
            hideNavBar={false}
            panHandlers={null}
            duration={0}
          />
          <Scene
            key="setting"
            component={SettingScreen}
            hideNavBar={false}
            title="Edit your profile"
            panHandlers={null}
            duration={0}
          />
        </Router>
      </Provider>
    )
  }
}

//export default App
//export default App = codePush({ updateDialog: true, installMode: codePush.InstallMode.IMMEDIATE })(App)
export default App = codePush()(App)
<commit_msg>Revert "test commit"<commit_after>import React, { Component } from 'react'
import codePush from 'react-native-code-push'
import OneSignal from 'react-native-onesignal'

import { Router, Scene, Actions } from 'react-native-mobx'
import { Provider } from 'mobx-react/native'

import LoginScreen from './views/login_screen'
import HomeScreen from './views/home_screen'
import SettingScreen from './views/setting_screen'
import ChatScreen from './views/chat_screen'

import appStore from './store/AppStore'

class App extends Component {
  componentDidMount() {
    console.log("-------x------ App - componentDidMount ------x-------")
    OneSignal.inFocusDisplaying(0)
    OneSignal.configure({
      onNotificationReceived: function(notification) {
        //console.log('NOTIFICATION RECEIVED: ', notification)
        if (notification.payload.additionalData.new_message && appStore.current_puid != notification.payload.additionalData.puid) {
          console.log("       appStore.new_messages + 1 : " + appStore.current_puid)
          appStore.new_messages = appStore.new_messages + 1
        }
      },
      onNotificationOpened: function(openResult) {
        console.log(openResult);
        console.log('MESSAGE: ', openResult.notification.payload.body)
        console.log('CURRENT PUID:' + appStore.current_pui)
        console.log('ISACTIVE: ', openResult.notification.isAppInFocus)
        console.log('DATA: ', openResult.notification.payload.additionalData)
        if (!openResult.notification.isAppInFocus) {
          if (openResult.notification.payload.additionalData) {
            if (appStore.current_puid != openResult.notification.payload.additionalData.puid) {
              Actions.login({ type: 'replace', postProps:openResult.notification.payload.additionalData })
            }
          }
          else {
            Actions.login({ type: 'replace', postProps:null })
          }
        }
      }
    })
  }
  render() {
    console.disableYellowBox = true
    return (
      <Provider appStore={appStore}>
        <Router>
          <Scene
            key="login"
            component={LoginScreen}
            duration={1}
            hideNavBar
            initial
          />
          <Scene
            key="home"
            component={HomeScreen}
            duration={1}
            hideNavBar
          />
          <Scene
            key="chat"
            component={ChatScreen}
            //direction="vertical"
            hideNavBar={false}
            panHandlers={null}
            duration={0}
          />
          <Scene
            key="setting"
            component={SettingScreen}
            hideNavBar={false}
            title="Edit your profile"
            panHandlers={null}
            duration={0}
          />
        </Router>
      </Provider>
    )
  }
}

//export default App
//export default App = codePush({ updateDialog: true, installMode: codePush.InstallMode.IMMEDIATE })(App)
export default App = codePush()(App)
<|endoftext|>


<commit_before>// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE

(function(mod) {
  if (typeof exports == "object" && typeof module == "object") // CommonJS
    mod(require("../../lib/codemirror"));
  else if (typeof define == "function" && define.amd) // AMD
    define(["../../lib/codemirror"], mod);
  else // Plain browser env
    mod(CodeMirror);
})(function(CodeMirror) {
"use strict";

CodeMirror.defineMode("pascal", function() {
  function words(str) {
    var obj = {}, words = str.split(" ");
    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
    return obj;
  }
  var keywords = words("and array begin case const div do downto else end file for forward integer " +
                       "boolean char function goto if in label mod nil not of or packed procedure " +
                       "program record repeat set string then to type until var while with");
  var atoms = {"null": true};

  var isOperatorChar = /[+\-*&%=<>!?|\/]/;

  function tokenBase(stream, state) {
    var ch = stream.next();
    if (ch == "#" && state.startOfLine) {
      stream.skipToEnd();
      return "meta";
    }
    if (ch == '"' || ch == "'") {
      state.tokenize = tokenString(ch);
      return state.tokenize(stream, state);
    }
    if (ch == "(" && stream.eat("*")) {
      state.tokenize = tokenComment;
      return tokenComment(stream, state);
    }
    if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
      return null;
    }
    if (/\d/.test(ch)) {
      stream.eatWhile(/[\w\.]/);
      return "number";
    }
    if (ch == "/") {
      if (stream.eat("/")) {
        stream.skipToEnd();
        return "comment";
      }
    }
    if (isOperatorChar.test(ch)) {
      stream.eatWhile(isOperatorChar);
      return "operator";
    }
    stream.eatWhile(/[\w\$_]/);
    var cur = stream.current();
    if (keywords.propertyIsEnumerable(cur)) return "keyword";
    if (atoms.propertyIsEnumerable(cur)) return "atom";
    return "variable";
  }

  function tokenString(quote) {
    return function(stream, state) {
      var escaped = false, next, end = false;
      while ((next = stream.next()) != null) {
        if (next == quote && !escaped) {end = true; break;}
        escaped = !escaped && next == "\\";
      }
      if (end || !escaped) state.tokenize = null;
      return "string";
    };
  }

  function tokenComment(stream, state) {
    var maybeEnd = false, ch;
    while (ch = stream.next()) {
      if (ch == ")" && maybeEnd) {
        state.tokenize = null;
        break;
      }
      maybeEnd = (ch == "*");
    }
    return "comment";
  }

  // Interface

  return {
    startState: function() {
      return {tokenize: null};
    },

    token: function(stream, state) {
      if (stream.eatSpace()) return null;
      var style = (state.tokenize || tokenBase)(stream, state);
      if (style == "comment" || style == "meta") return style;
      return style;
    },

    electricChars: "{}"
  };
});

CodeMirror.defineMIME("text/x-pascal", "pascal");

});
<commit_msg>[pascal mode] Add more keywords<commit_after>// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: http://codemirror.net/LICENSE

(function(mod) {
  if (typeof exports == "object" && typeof module == "object") // CommonJS
    mod(require("../../lib/codemirror"));
  else if (typeof define == "function" && define.amd) // AMD
    define(["../../lib/codemirror"], mod);
  else // Plain browser env
    mod(CodeMirror);
})(function(CodeMirror) {
"use strict";

CodeMirror.defineMode("pascal", function() {
  function words(str) {
    var obj = {}, words = str.split(" ");
    for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
    return obj;
  }
  var keywords = words(
    "absolute and array asm begin case const constructor destructor div do " +
    "downto else end file for function goto if implementation in inherited " +
    "inline interface label mod nil not object of operator or packed procedure " +
    "program record reintroduce repeat self set shl shr string then to type " +
    "unit until uses var while with xor as class dispinterface except exports " +
    "finalization finally initialization inline is library on out packed " +
    "property raise resourcestring threadvar try absolute abstract alias " +
    "assembler bitpacked break cdecl continue cppdecl cvar default deprecated " +
    "dynamic enumerator experimental export external far far16 forward generic " +
    "helper implements index interrupt iocheck local message name near " +
    "nodefault noreturn nostackframe oldfpccall otherwise overload override " +
    "pascal platform private protected public published read register " +
    "reintroduce result safecall saveregisters softfloat specialize static " +
    "stdcall stored strict unaligned unimplemented varargs virtual write");
  var atoms = {"null": true};

  var isOperatorChar = /[+\-*&%=<>!?|\/]/;

  function tokenBase(stream, state) {
    var ch = stream.next();
    if (ch == "#" && state.startOfLine) {
      stream.skipToEnd();
      return "meta";
    }
    if (ch == '"' || ch == "'") {
      state.tokenize = tokenString(ch);
      return state.tokenize(stream, state);
    }
    if (ch == "(" && stream.eat("*")) {
      state.tokenize = tokenComment;
      return tokenComment(stream, state);
    }
    if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
      return null;
    }
    if (/\d/.test(ch)) {
      stream.eatWhile(/[\w\.]/);
      return "number";
    }
    if (ch == "/") {
      if (stream.eat("/")) {
        stream.skipToEnd();
        return "comment";
      }
    }
    if (isOperatorChar.test(ch)) {
      stream.eatWhile(isOperatorChar);
      return "operator";
    }
    stream.eatWhile(/[\w\$_]/);
    var cur = stream.current();
    if (keywords.propertyIsEnumerable(cur)) return "keyword";
    if (atoms.propertyIsEnumerable(cur)) return "atom";
    return "variable";
  }

  function tokenString(quote) {
    return function(stream, state) {
      var escaped = false, next, end = false;
      while ((next = stream.next()) != null) {
        if (next == quote && !escaped) {end = true; break;}
        escaped = !escaped && next == "\\";
      }
      if (end || !escaped) state.tokenize = null;
      return "string";
    };
  }

  function tokenComment(stream, state) {
    var maybeEnd = false, ch;
    while (ch = stream.next()) {
      if (ch == ")" && maybeEnd) {
        state.tokenize = null;
        break;
      }
      maybeEnd = (ch == "*");
    }
    return "comment";
  }

  // Interface

  return {
    startState: function() {
      return {tokenize: null};
    },

    token: function(stream, state) {
      if (stream.eatSpace()) return null;
      var style = (state.tokenize || tokenBase)(stream, state);
      if (style == "comment" || style == "meta") return style;
      return style;
    },

    electricChars: "{}"
  };
});

CodeMirror.defineMIME("text/x-pascal", "pascal");

});
<|endoftext|>