<commit_before>// @flow
import { omit, isNil } from 'lodash'
import { NOTIFICATION_TYPES, NOTIFICATION_POSITIONS, DEFAULT_NOTIFICATION_TIMEOUT } from '../core/constants'

let notificationTimeoutId

type NotificationArgsType = {
  message: string,
  title?: string,
  position?: $Values<typeof NOTIFICATION_POSITIONS>,
  width?: string,
  dismissible?: boolean,
  dismissAfter?: number,
  html?: boolean,
  noAnimation?: boolean,
  onClick?: ?Function
}

type HideNotificationType = {
  noAnimate?: boolean,
}

type ShowNotificationType = NotificationArgsType & {
  type: $Values<typeof NOTIFICATION_TYPES>,
}

type NotificationFactoryArgsType = ShowNotificationType & {
  dispatch: DispatchType,
}

const notificationFactory = (args: NotificationFactoryArgsType) => {
  const {
    dispatch,
    dismissible,
    dismissAfter
  } = args

  if (notificationTimeoutId) {
    clearTimeout(notificationTimeoutId)
  }
  const argsToRemove = ['dispatch', 'isShown', 'dismissible', 'dismissAfter']
  dispatch(showNotification(omit(args, argsToRemove)))
  if (dismissible) {
    notificationTimeoutId = setTimeout(() => dispatch(hideNotification()), dismissAfter)
  }
}

// Constants
export const SHOW_NOTIFICATION = 'SHOW_NOTIFICATION'
export const HIDE_NOTIFICATION = 'HIDE_NOTIFICATION'

// Actions
export function showNotification (args: ShowNotificationType) {
  return {
    type: SHOW_NOTIFICATION,
    payload: args
  }
}

export function hideNotification (args?: HideNotificationType) {
  return {
    type: HIDE_NOTIFICATION,
    payload: args
  }
}

const getDefaultNotificationArgs = ({ dismissAfter, dismissible }: NotificationArgsType, dispatch: DispatchType, getState: GetStateType) => ({
  dismissAfter: isNil(dismissAfter) ? DEFAULT_NOTIFICATION_TIMEOUT : dismissAfter,
  dismissible: isNil(dismissible) ? true : dismissible,
  dispatch
})

export const showSuccessNotification = (args: NotificationArgsType) => (dispatch: DispatchType, getState: GetStateType) => {
  notificationFactory({
    ...args,
    ...getDefaultNotificationArgs(args, dispatch, getState),
    type: NOTIFICATION_TYPES.SUCCESS
  })
}

export const showStickySuccessNotification = (args: NotificationArgsType) => (dispatch: DispatchType, getState: GetStateType) => {
  dispatch(showSuccessNotification({ ...args, dismissible: false }))
}

export const showErrorNotification = (args: NotificationArgsType) => (dispatch: DispatchType, getState: GetStateType) => {
  notificationFactory({
    ...args,
    ...getDefaultNotificationArgs(args, dispatch, getState),
    type: NOTIFICATION_TYPES.ERROR
  })
}

export const showStickyErrorNotification = (args: NotificationArgsType) => (dispatch: DispatchType, getState: GetStateType) => {
  dispatch(showErrorNotification({ ...args, dismissible: false }))
}

export const showWarningNotification = (args: NotificationArgsType) => (dispatch: DispatchType, getState: GetStateType) => {
  notificationFactory({
    ...args,
    ...getDefaultNotificationArgs(args, dispatch, getState),
    type: NOTIFICATION_TYPES.WARNING
  })
}

export const showStickyWarningNotification = (args: NotificationArgsType) => (dispatch: DispatchType, getState: GetStateType) => {
  dispatch(showErrorNotification({ ...args, dismissible: false }))
}

export const showInfoNotification = (args: NotificationArgsType) => (dispatch: DispatchType, getState: GetStateType) => {
  notificationFactory({
    ...args,
    ...getDefaultNotificationArgs(args, dispatch, getState),
    type: NOTIFICATION_TYPES.INFO
  })
}

export const showStickyInfoNotification = (args: NotificationArgsType) => (dispatch: DispatchType, getState: GetStateType) => {
  dispatch(showInfoNotification({ ...args, dismissible: false }))
}

const initialState = {
  title: '',
  message: '',
  type: NOTIFICATION_TYPES.INFO,
  position: NOTIFICATION_POSITIONS.TOP,
  isShown: false,
  width: '100%',
  html: false,
  onClick: null,
  noAnimation: false
}

export default (state: Object = initialState, action: Object) => {
  switch (action.type) {
    case SHOW_NOTIFICATION:
      return {
        ...initialState,
        ...action.payload,
        isShown: true
      }
    case HIDE_NOTIFICATION:
      return {
        ...state,
        ...action.payload,
        isShown: false
      }
    default:
      return state
  }
}
<commit_msg>Fix typo<commit_after>// @flow
import { omit, isNil } from 'lodash'
import { NOTIFICATION_TYPES, NOTIFICATION_POSITIONS, DEFAULT_NOTIFICATION_TIMEOUT } from '../core/constants'

let notificationTimeoutId

type NotificationArgsType = {
  message: string,
  title?: string,
  position?: $Values<typeof NOTIFICATION_POSITIONS>,
  width?: string,
  dismissible?: boolean,
  dismissAfter?: number,
  html?: boolean,
  noAnimation?: boolean,
  onClick?: ?Function
}

type HideNotificationType = {
  noAnimation?: boolean,
}

type ShowNotificationType = NotificationArgsType & {
  type: $Values<typeof NOTIFICATION_TYPES>,
}

type NotificationFactoryArgsType = ShowNotificationType & {
  dispatch: DispatchType,
}

const notificationFactory = (args: NotificationFactoryArgsType) => {
  const {
    dispatch,
    dismissible,
    dismissAfter
  } = args

  if (notificationTimeoutId) {
    clearTimeout(notificationTimeoutId)
  }
  const argsToRemove = ['dispatch', 'isShown', 'dismissible', 'dismissAfter']
  dispatch(showNotification(omit(args, argsToRemove)))
  if (dismissible) {
    notificationTimeoutId = setTimeout(() => dispatch(hideNotification()), dismissAfter)
  }
}

// Constants
export const SHOW_NOTIFICATION = 'SHOW_NOTIFICATION'
export const HIDE_NOTIFICATION = 'HIDE_NOTIFICATION'

// Actions
export function showNotification (args: ShowNotificationType) {
  return {
    type: SHOW_NOTIFICATION,
    payload: args
  }
}

export function hideNotification (args?: HideNotificationType) {
  return {
    type: HIDE_NOTIFICATION,
    payload: args
  }
}

const getDefaultNotificationArgs = ({ dismissAfter, dismissible }: NotificationArgsType, dispatch: DispatchType, getState: GetStateType) => ({
  dismissAfter: isNil(dismissAfter) ? DEFAULT_NOTIFICATION_TIMEOUT : dismissAfter,
  dismissible: isNil(dismissible) ? true : dismissible,
  dispatch
})

export const showSuccessNotification = (args: NotificationArgsType) => (dispatch: DispatchType, getState: GetStateType) => {
  notificationFactory({
    ...args,
    ...getDefaultNotificationArgs(args, dispatch, getState),
    type: NOTIFICATION_TYPES.SUCCESS
  })
}

export const showStickySuccessNotification = (args: NotificationArgsType) => (dispatch: DispatchType, getState: GetStateType) => {
  dispatch(showSuccessNotification({ ...args, dismissible: false }))
}

export const showErrorNotification = (args: NotificationArgsType) => (dispatch: DispatchType, getState: GetStateType) => {
  notificationFactory({
    ...args,
    ...getDefaultNotificationArgs(args, dispatch, getState),
    type: NOTIFICATION_TYPES.ERROR
  })
}

export const showStickyErrorNotification = (args: NotificationArgsType) => (dispatch: DispatchType, getState: GetStateType) => {
  dispatch(showErrorNotification({ ...args, dismissible: false }))
}

export const showWarningNotification = (args: NotificationArgsType) => (dispatch: DispatchType, getState: GetStateType) => {
  notificationFactory({
    ...args,
    ...getDefaultNotificationArgs(args, dispatch, getState),
    type: NOTIFICATION_TYPES.WARNING
  })
}

export const showStickyWarningNotification = (args: NotificationArgsType) => (dispatch: DispatchType, getState: GetStateType) => {
  dispatch(showErrorNotification({ ...args, dismissible: false }))
}

export const showInfoNotification = (args: NotificationArgsType) => (dispatch: DispatchType, getState: GetStateType) => {
  notificationFactory({
    ...args,
    ...getDefaultNotificationArgs(args, dispatch, getState),
    type: NOTIFICATION_TYPES.INFO
  })
}

export const showStickyInfoNotification = (args: NotificationArgsType) => (dispatch: DispatchType, getState: GetStateType) => {
  dispatch(showInfoNotification({ ...args, dismissible: false }))
}

const initialState = {
  title: '',
  message: '',
  type: NOTIFICATION_TYPES.INFO,
  position: NOTIFICATION_POSITIONS.TOP,
  isShown: false,
  width: '100%',
  html: false,
  onClick: null,
  noAnimation: false
}

export default (state: Object = initialState, action: Object) => {
  switch (action.type) {
    case SHOW_NOTIFICATION:
      return {
        ...initialState,
        ...action.payload,
        isShown: true
      }
    case HIDE_NOTIFICATION:
      return {
        ...state,
        ...action.payload,
        isShown: false
      }
    default:
      return state
  }
}
<|endoftext|>


<commit_before>// Generated by CoffeeScript 1.6.1
(function () {

    this.JavascriptLoader = (function () {

        function JavascriptLoader() {
        }

        JavascriptLoader.executeModuleScripts = function (el, callback) {
            var callbackCalled, completed, completionHandlerGenerator, completionHandlerGeneratorIE, i, loaded, placeholders,
                _this = this;
            if (callback == null) {
                callback = null;
            }
            placeholders = el.find(".script_placeholder");
            if (placeholders.length === 0) {
                if (callback != null) {
                    callback();
                }
                return;
            }
            completed = (function () {
                var _i, _ref, _results;
                _results = [];
                for (i = _i = 1, _ref = placeholders.length; 1 <= _ref ? _i <= _ref : _i >= _ref; i = 1 <= _ref ? ++_i : --_i) {
                    _results.push(false);
                }
                return _results;
            })();
            callbackCalled = false;
            completionHandlerGeneratorIE = function (index) {
                return function () {
                    if (this.readyState === 'complete' || this.readyState === 'loaded') {
                        return completionHandlerGenerator(index)();
                    }
                };
            };
            completionHandlerGenerator = function (index) {
                return function () {
                    var allComplete, flag, _i, _len;
                    allComplete = true;
                    completed[index] = true;
                    for (_i = 0, _len = completed.length; _i < _len; _i++) {
                        flag = completed[_i];
                        if (!flag) {
                            allComplete = false;
                            break;
                        }
                    }
                    if (allComplete && !callbackCalled) {
                        callbackCalled = true;
                        if (callback != null) {
                            return callback();
                        }
                    }
                };
            };
            loaded = {};
            return placeholders.each(function (index, placeholder) {
                var s, src;
                src = $(placeholder).attr("data-src");
                if (!(src in loaded)) {
                    loaded[src] = true;
                    s = document.createElement('script');
                    s.setAttribute('src', src);
                    s.setAttribute('type', "text/javascript");
                    s.onload = completionHandlerGenerator(index);
                    s.onreadystatechange = completionHandlerGeneratorIE(index);
                    $('head')[0].appendChild(s);
                } else {
                    completionHandlerGenerator(index)();
                }
                return $(placeholder).remove();
            });
        };

        return JavascriptLoader;

    })();

}).call(this);
<commit_msg>Fix eslint violations.<commit_after>(function() {
    'use strict';
    this.JavascriptLoader = (function() {
        function JavascriptLoader() {
        }

        /**
         * Set of library functions that provide common interface for javascript loading
         * for all module types. All functionality provided by JavascriptLoader should take
         * place at module scope, i.e. don't run jQuery over entire page.
         *
         * executeModuleScripts:
         *     Scan the module ('el') for "script_placeholder"s, then:
         *
         *     1) Fetch each script from server
         *     2) Explicitly attach the script to the <head> of document
         *     3) Explicitly wait for each script to be loaded
         *     4) Return to callback function when all scripts loaded
         */
        JavascriptLoader.executeModuleScripts = function(el, callback) {
            var callbackCalled, completed, completionHandlerGenerator, loaded, placeholders;
            if (!callback) {
                callback = null; // eslint-disable-line no-param-reassign
            }
            placeholders = el.find('.script_placeholder');
            if (placeholders.length === 0) {
                if (callback !== null) {
                    callback();
                }
                return [];
            }
            // TODO: Verify the execution order of multiple placeholders
            completed = (function() {
                var i, ref, results;
                results = [];
                for (i = 1, ref = placeholders.length; ref >= 1 ? i <= ref : i >= ref; ref >= 1 ? ++i : --i) {
                    results.push(false);
                }
                return results;
            }());
            callbackCalled = false;
            completionHandlerGenerator = function(index) {
                return function() {
                    var allComplete, flag, i, len;
                    allComplete = true;
                    completed[index] = true;
                    for (i = 0, len = completed.length; i < len; i++) {
                        flag = completed[i];
                        if (!flag) {
                            allComplete = false;
                            break;
                        }
                    }
                    if (allComplete && !callbackCalled) {
                        callbackCalled = true;
                        if (callback !== null) {
                            return callback();
                        }
                    }
                    return undefined;
                };
            };
            // Keep a map of what sources we're loaded from, and don't do it twice.
            loaded = {};
            return placeholders.each(function(index, placeholder) {
                var s, src;
                // TODO: Check if the script already exists in DOM. If so, (1) copy it
                // into memory; (2) delete the DOM script element; (3) reappend it.
                // This would prevent memory bloat and save a network request.
                src = $(placeholder).attr('data-src');
                if (!(src in loaded)) {
                    loaded[src] = true;
                    s = document.createElement('script');
                    s.setAttribute('src', src);
                    s.setAttribute('type', 'text/javascript');
                    s.onload = completionHandlerGenerator(index);
                    // Need to use the DOM elements directly or the scripts won't execute properly.
                    $('head')[0].appendChild(s);
                } else {
                    // just call the completion callback directly, without reloading the file
                    completionHandlerGenerator(index)();
                }
                return $(placeholder).remove();
            });
        };

        return JavascriptLoader;
    }());
}).call(this);
<|endoftext|>


<commit_before>Template.PopupToggle.events({
    'click >': function(e) {
        e.preventDefault();
        var globalTpl = Template.instance();
        var el = globalTpl.$('>');
        var thisDataId = Template.currentData().id;
        console.log(thisDataId);
        var popover = $('[data-popup=' + thisDataId + ']');

        var top = el.position().top - 70;
        var left = el.position().left;
        left = left - (popover.width() / 2) + (el.width() / 2) - 2;

        popover.css('opacity', 1).css('left', left).css('top', top).toggle('slow');
        popover.find('input').focus();
        //$('[data-popup=' + thisDataId + ']').toggle('slow');

    }
});
<commit_msg>removed some debug info<commit_after>Template.PopupToggle.events({
    'click >': function(e) {
        e.preventDefault();
        var globalTpl = Template.instance();
        var el = globalTpl.$('>');
        var thisDataId = Template.currentData().id;
        var popover = $('[data-popup=' + thisDataId + ']');

        var top = el.position().top - 70;
        var left = el.position().left;
        left = left - (popover.width() / 2) + (el.width() / 2) - 2;

        popover.css('opacity', 1).css('left', left).css('top', top).toggle('slow');
        popover.find('input').focus();
        //$('[data-popup=' + thisDataId + ']').toggle('slow');

    }
});
<|endoftext|>


<commit_before>// Copyright 2015 Senorsen <sen@senorsen.com>
//

var logger = require('./setlogger.js');
var dns = require('native-dns');
var util = require('util');
var express = require('express');
var config = require('./config.json');

var app = express();
app.set('trust proxy', 'loopback, 127.0.0.1');
app.get('/', function(req, res) {
    var name = req.query.name;
    var ip = req.ip;
    logger.log('info', 'client ' + ip + ' query: ' + name);
    if (typeof name == 'undefined') {
        return res.json({
            err: 2,
            msg: 'parameter error'
        });
    }
    var question = dns.Question({
        name: name,
        type: 'A'
    });
    var dnsreq = dns.Request({
        question: question,
        server: { address: '8.8.8.8', port: 53, type: 'udp' },
        timeout: 2000
    });
    dnsreq.on('timeout', function () {
        logger.log('warn', 'name: ' + name + ' lookup timeout');
        res.json({
            err: 1,
            msg: 'timeout'
        });
    });
    dnsreq.on('message', function (err, answer) {
        logger.log('info', 'name: ' + name + ', query reached.');
        res.json({
            err: err ? 1 : 0,
            msg: err ? 'error' : 'success',
            obj: answer.answer
        });
    });
    try {
        dnsreq.send();
    } catch (e) {
        logger.log('error', 'resolv error', e);
        res.json({
            err: 2,
            msg: 'error'
        });
    }
});

app.listen(config.vps_port);
logger.log('info', 'http server listen at ' + config.vps_port);

<commit_msg>GC again<commit_after>// Copyright 2015 Senorsen <sen@senorsen.com>
//

var logger = require('./setlogger.js');
var dns = require('native-dns');
var util = require('util');
var express = require('express');
var config = require('./config.json');

var app = express();
app.set('trust proxy', 'loopback, 127.0.0.1');
app.get('/', function(req, res) {
    var name = req.query.name;
    var ip = req.ip;
    logger.log('info', 'client ' + ip + ' query: ' + name);
    if (typeof name == 'undefined') {
        return res.json({
            err: 2,
            msg: 'parameter error'
        });
    }
    var question = dns.Question({
        name: name,
        type: 'A'
    });
    var dnsreq = dns.Request({
        question: question,
        server: { address: '8.8.8.8', port: 53, type: 'udp' },
        timeout: 2000
    });
    dnsreq.on('timeout', function () {
        logger.log('warn', 'name: ' + name + ' lookup timeout');
        res.json({
            err: 1,
            msg: 'timeout'
        });
    });
    dnsreq.on('message', function (err, answer) {
        logger.log('info', 'name: ' + name + ', query reached.');
        res.json({
            err: err ? 1 : 0,
            msg: err ? 'error' : 'success',
            obj: answer.answer
        });
    });
    dnsreq.on('end', function() {
        delete dnsreq;
    });
    try {
        dnsreq.send();
    } catch (e) {
        logger.log('error', 'resolv error', e);
        res.json({
            err: 2,
            msg: 'error'
        });
    }
});

app.listen(config.vps_port);
logger.log('info', 'http server listen at ' + config.vps_port);

<|endoftext|>


<commit_before>/*globals _,window,exports*/
/*exported createBrowser*/

var BrowserInstance;

function createBrowser() {
  'use strict';

  if (BrowserInstance) {
    return BrowserInstance;
  }

  var homeUrl;
  var webviewDomainLimit;
  var webview;
  var webviewLoaded = false;

  function BrowserControls() {
    this._callbacks = [];

    this.isHome = false;
    this.isBack = false;
    this.isForward = false;
    this.isTop = false;
    this.isReload = false;

    this.scrollTopCan = false;
    window.addEventListener('message', function onMessage() {
      if (event && event.data && event.data.command && event.data.command === 'scroll') {
        if (event.data.value > 100) {
          this.scrollTopCan = true;
        } else {
          this.scrollTopCan = false;
        }

        if (this._callbacks.length > 0) {
          _.each(this._callbacks, function (v) {
            v('scroll', this);
          }, this);
        }
      }
    }.bind(this));
  }

  BrowserControls.prototype.addChangeCallback = function addChangeCallback(callback) {
    if (typeof callback === 'function') {
      this._callbacks.push(callback);
    }
  };

  BrowserControls.prototype.canBack = function canGoBack() {
    if (webview) {
      this.isBack = webview.canGoBack();
    } else {
      this.isBack = false;
    }

    return this.isBack;
  };

  BrowserControls.prototype.back = function goBack() {
    if (!this.canBack()) {
      return;
    }
    webview.back();
  };

  BrowserControls.prototype.canForward = function canGoForward() {
    if (webview) {
      this.isForward = webview.canGoForward();
    } else {
      this.isForward = false;
    }

    return this.isForward;
  };

  BrowserControls.prototype.forward = function goForward() {
    if (!this.canForward()) {
      return;
    }
    webview.forward();
  };

  BrowserControls.prototype.canReload = function canReloadPage() {
    if (webview) {
      this.isReload = true;
    } else {
      this.isReload = false;
    }
    return this.isReload;
  };

  BrowserControls.prototype.reload = function reloadPage() {
    if (!this.canReload()) {
      return;
    }
    webview.reload();
  };

  BrowserControls.prototype.canHome = function canGoHome() {
    if (webview) {
      this.isHome = webview.src !== homeUrl;
    } else {
      this.isHome = false;
    }
    return this.isHome;
  };

  BrowserControls.prototype.home = function goHome() {
    if (!webview) {
      return;
    }
    webview.src = homeUrl;
  };

  BrowserControls.prototype.go = function goToPage(page) {
    if (!webview) {
      return;
    }
    webview.src = page;
  };

  BrowserControls.prototype.clearData = function clearData(callback) {
    if (!webview) {
      if (callback) {
        callback(false);
      }
      return;
    }
    webview.clearData({}, {
      'appcache': true,
      'cookies': true
    }, function clearDataDone() {
      this.home();
      if (callback) {
        callback(true);
      }
    }.bind(this));
  };

  BrowserControls.prototype.canTop = function canGoTop() {
    if (webview) {
      this.isTop = webviewLoaded && this.scrollTopCan;
    } else {
      this.isTop = false;
    }
    return this.isTop;
  };

  BrowserControls.prototype.top = function goTop() {
    if (!webview) {
      return;
    }
    if (!webviewLoaded) {
      return;
    }
    webview.contentWindow.postMessage({
      command: 'scrollTop'
    }, '*');
  };

  BrowserControls.prototype.check = function () {
    this.canReload();
    this.canHome();
    this.canTop();
    this.canBack();
    this.canForward();
  };

  function Browser() {
    this._callbacks = [];
    this._downloadFrom = '';
    this._allowNewWindows = false;
    this.controls = new BrowserControls();
  }

  Browser.prototype.exec = function exec(v) {
    if (!webview) {
      return;
    }
    if (!webviewLoaded) {
      return;
    }
    webview.focus();
    webview.contentWindow.postMessage({
      command: 'execute',
      value: v
    }, '*');
  };

  Browser.prototype.getControls = function getControls() {
    return this.controls;
  };

  Browser.prototype.allowNewWindows = function allowNewWindows(b) {
    this._allowNewWindows = b;
  };

  Browser.prototype.allowDownloadFrom = function allowDownloadFrom(d) {
    this._downloadFrom = d;
  };

  Browser.prototype.bindWebview = function bindWebview(selecter, partition, userAgent) {
    if (webview) {
      throw new Error('Browser is already bound to Webview!');
    }
    webview = window.document.querySelector(selecter);
    if (!webview) {
      throw new Error('Invalid selector or webview not found!');
    }

    //set where to save cookie and other data
    if (partition) {
      webview.partition = partition;
    }

    //useragent
    if (userAgent) {
      webview.setUserAgentOverride(webview.getUserAgent() + ' ' + userAgent);
    }

    //disable zoom
    webview.setZoomMode('disabled');

    //inject
    webview.addContentScripts([{
      name: 'rule',
      matches: ['http://*/*', 'https://*/*'],
      js: {
        files: ['scripts/inject.js']
      },
      css: {
        files: ['styles/inject.css']
      },
      'run_at': 'document_start'
    }]);

    //on close
    webview.addEventListener('close', function onCloseWebview(e) {
      webview.src = 'about:blank';
      if (this._callbacks.length > 0) {
        _.each(this._callbacks, function (v) {
          v('close', null, e, this);
        }, this);
      }
    }.bind(this));

    webview.addEventListener('loadstart', function onStartWebview(e) {
      if (e.isTopLevel && webviewDomainLimit && (e.url.search(webviewDomainLimit) === -1 && e.url !== 'about:blank' && e.url !== 'data:text/html,chromewebdata')) {
        webview.stop();
        if (this._callbacks.length > 0) {
          _.each(this._callbacks, function (v) {
            v('loadstart', new Error(e.url), e, this);
          }, this);
        }
        return;
      }

      webviewLoaded = false;
      if (this._callbacks.length > 0) {
        _.each(this._callbacks, function (v) {
          v('loadstart', null, e, this);
        }, this);
      }
    }.bind(this));

    webview.addEventListener('loadstop', function onStopWebview(e) {
      webviewLoaded = true;
      if (this._callbacks.length > 0) {
        _.each(this._callbacks, function (v) {
          v('loadstop', null, e, this);
        }, this);
      }
    }.bind(this));

    webview.addEventListener('contentload', function onLoadWebview(e) {
      //shake hands to send this app id to web
      var handshake = function handshake(event) {
        if (event && event.data && event.data.command && event.data.command === 'handshakereply') {
          if (event.data.url) {
            if (this._callbacks.length > 0) {
              _.each(this._callbacks, function (v) {
                v('handshake', null, event, this);
              }, this);
            }
          }
          window.removeEventListener('message', handshake);
        }
      }.bind(this);
      window.addEventListener('message', handshake);
      webview.contentWindow.postMessage({
        command: 'handshake'
      }, '*');

      if (this._callbacks.length > 0) {
        _.each(this._callbacks, function (v) {
          v('contentload', null, e, this);
        }, this);
      }
    }.bind(this));

    webview.addEventListener('newwindow', function onNewWindowWebview(e) {
      if (this._allowNewWindows) {
        e.preventDefault();
        window.open(e.targetUrl); //open in chrome
        if (this._callbacks.length > 0) {
          _.each(this._callbacks, function (v) {
            v('newwindow', null, e, this);
          }, this);
        }
      } else {
        e.window.discard();
        if (this._callbacks.length > 0) {
          _.each(this._callbacks, function (v) {
            v('newwindow', new Error(e.targetUrl), e, this);
          }, this);
        }
      }
    }.bind(this));

    webview.addEventListener('permissionrequest', function onPermissionWebview(e) {
      if (e.permission === 'download' && this._downloadFrom && e.request.url.search(this._downloadFrom) !== -1) {
        e.request.allow();
      }
      if (this._callbacks.length > 0) {
        _.each(this._callbacks, function (v) {
          v('permissionrequest', null, e, this);
        }, this);
      }
    }.bind(this));

    webview.addEventListener('dialog', function onDialogWebview(e) {
      if (this._callbacks.length > 0) {
        _.each(this._callbacks, function (v) {
          v('dialog', null, e, this);
        }, this);
      }
    }.bind(this));

    // force webview focus from app body
    setInterval(function keepWebviewFocus() {
      if (webview && webviewLoaded) {
        if (window.document.activeElement !== webview && window.document.activeElement.tagName !== 'INPUT' && window.document.activeElement.tagName !== 'TEXTAREA') {
          webview.focus();
        }
      }
    }, 1000);
  };

  Browser.prototype.setHome = function setHome(url) {
    homeUrl = url;
  };
  Browser.prototype.setDomainLimit = function setDomainLimit(reg) {
    webviewDomainLimit = reg;
  };

  Browser.prototype.getUrl = function getUrl() {
    return webview.src;
  };

  Browser.prototype.addChangeCallback = function addChangeCallback(callback) {
    if (typeof callback === 'function') {
      this._callbacks.push(callback);
    }
  };

  Browser.prototype.start = function startBrowser(callback) {
    if (!webview) {
      throw new Error('Use \'bindWebview\' to set webview selector first!');
    }
    if (!homeUrl) {
      throw new Error('Use \'setHome\' to set home page first!');
    }

    var done = function done() {
      if (webview.src === 'about:blank' || webview.src === '') {
        webview.src = homeUrl;
      }
    };

    if (callback) {
      callback(webview, done);
    } else {
      done();
    }
  };

  BrowserInstance = new Browser();
  return BrowserInstance;
}

if (typeof exports !== 'undefined') {
  exports.browser = createBrowser();
}
<commit_msg>browser add loadabort event for future use<commit_after>/*globals _,window,exports*/
/*exported createBrowser*/

var BrowserInstance;

function createBrowser() {
  'use strict';

  if (BrowserInstance) {
    return BrowserInstance;
  }

  var homeUrl;
  var webviewDomainLimit;
  var webview;
  var webviewLoaded = false;

  function BrowserControls() {
    this._callbacks = [];

    this.isHome = false;
    this.isBack = false;
    this.isForward = false;
    this.isTop = false;
    this.isReload = false;

    this.scrollTopCan = false;
    window.addEventListener('message', function onMessage() {
      if (event && event.data && event.data.command && event.data.command === 'scroll') {
        if (event.data.value > 100) {
          this.scrollTopCan = true;
        } else {
          this.scrollTopCan = false;
        }

        if (this._callbacks.length > 0) {
          _.each(this._callbacks, function (v) {
            v('scroll', this);
          }, this);
        }
      }
    }.bind(this));
  }

  BrowserControls.prototype.addChangeCallback = function addChangeCallback(callback) {
    if (typeof callback === 'function') {
      this._callbacks.push(callback);
    }
  };

  BrowserControls.prototype.canBack = function canGoBack() {
    if (webview) {
      this.isBack = webview.canGoBack();
    } else {
      this.isBack = false;
    }

    return this.isBack;
  };

  BrowserControls.prototype.back = function goBack() {
    if (!this.canBack()) {
      return;
    }
    webview.back();
  };

  BrowserControls.prototype.canForward = function canGoForward() {
    if (webview) {
      this.isForward = webview.canGoForward();
    } else {
      this.isForward = false;
    }

    return this.isForward;
  };

  BrowserControls.prototype.forward = function goForward() {
    if (!this.canForward()) {
      return;
    }
    webview.forward();
  };

  BrowserControls.prototype.canReload = function canReloadPage() {
    if (webview) {
      this.isReload = true;
    } else {
      this.isReload = false;
    }
    return this.isReload;
  };

  BrowserControls.prototype.reload = function reloadPage() {
    if (!this.canReload()) {
      return;
    }
    webview.reload();
  };

  BrowserControls.prototype.canHome = function canGoHome() {
    if (webview) {
      this.isHome = webview.src !== homeUrl;
    } else {
      this.isHome = false;
    }
    return this.isHome;
  };

  BrowserControls.prototype.home = function goHome() {
    if (!webview) {
      return;
    }
    webview.src = homeUrl;
  };

  BrowserControls.prototype.go = function goToPage(page) {
    if (!webview) {
      return;
    }
    webview.src = page;
  };

  BrowserControls.prototype.clearData = function clearData(callback) {
    if (!webview) {
      if (callback) {
        callback(false);
      }
      return;
    }
    webview.clearData({}, {
      'appcache': true,
      'cookies': true
    }, function clearDataDone() {
      this.home();
      if (callback) {
        callback(true);
      }
    }.bind(this));
  };

  BrowserControls.prototype.canTop = function canGoTop() {
    if (webview) {
      this.isTop = webviewLoaded && this.scrollTopCan;
    } else {
      this.isTop = false;
    }
    return this.isTop;
  };

  BrowserControls.prototype.top = function goTop() {
    if (!webview) {
      return;
    }
    if (!webviewLoaded) {
      return;
    }
    webview.contentWindow.postMessage({
      command: 'scrollTop'
    }, '*');
  };

  BrowserControls.prototype.check = function () {
    this.canReload();
    this.canHome();
    this.canTop();
    this.canBack();
    this.canForward();
  };

  function Browser() {
    this._callbacks = [];
    this._downloadFrom = '';
    this._allowNewWindows = false;
    this.controls = new BrowserControls();
  }

  Browser.prototype.exec = function exec(v) {
    if (!webview) {
      return;
    }
    if (!webviewLoaded) {
      return;
    }
    webview.focus();
    webview.contentWindow.postMessage({
      command: 'execute',
      value: v
    }, '*');
  };

  Browser.prototype.getControls = function getControls() {
    return this.controls;
  };

  Browser.prototype.allowNewWindows = function allowNewWindows(b) {
    this._allowNewWindows = b;
  };

  Browser.prototype.allowDownloadFrom = function allowDownloadFrom(d) {
    this._downloadFrom = d;
  };

  Browser.prototype.bindWebview = function bindWebview(selecter, partition, userAgent) {
    if (webview) {
      throw new Error('Browser is already bound to Webview!');
    }
    webview = window.document.querySelector(selecter);
    if (!webview) {
      throw new Error('Invalid selector or webview not found!');
    }

    //set where to save cookie and other data
    if (partition) {
      webview.partition = partition;
    }

    //useragent
    if (userAgent) {
      webview.setUserAgentOverride(webview.getUserAgent() + ' ' + userAgent);
    }

    //disable zoom
    webview.setZoomMode('disabled');

    //inject
    webview.addContentScripts([{
      name: 'rule',
      matches: ['http://*/*', 'https://*/*'],
      js: {
        files: ['scripts/inject.js']
      },
      css: {
        files: ['styles/inject.css']
      },
      'run_at': 'document_start'
    }]);

    //on close
    webview.addEventListener('close', function onCloseWebview(e) {
      webview.src = 'about:blank';
      if (this._callbacks.length > 0) {
        _.each(this._callbacks, function (v) {
          v('close', null, e, this);
        }, this);
      }
    }.bind(this));

    webview.addEventListener('loadstart', function onStartWebview(e) {
      if (e.isTopLevel && webviewDomainLimit && (e.url.search(webviewDomainLimit) === -1 && e.url !== 'about:blank' && e.url !== 'data:text/html,chromewebdata')) {
        webview.stop();
        if (this._callbacks.length > 0) {
          _.each(this._callbacks, function (v) {
            v('loadstart', new Error(e.url), e, this);
          }, this);
        }
        return;
      }

      webviewLoaded = false;
      if (this._callbacks.length > 0) {
        _.each(this._callbacks, function (v) {
          v('loadstart', null, e, this);
        }, this);
      }
    }.bind(this));

    webview.addEventListener('loadstop', function onStopWebview(e) {
      webviewLoaded = true;
      if (this._callbacks.length > 0) {
        _.each(this._callbacks, function (v) {
          v('loadstop', null, e, this);
        }, this);
      }
    }.bind(this));

    webview.addEventListener('loadabort', function onAbortWebview(e) {
      if (this._callbacks.length > 0) {
        _.each(this._callbacks, function (v) {
          v('loadabort', null, e, this);
        }, this);
      }
    }.bind(this));

    webview.addEventListener('contentload', function onLoadWebview(e) {
      //shake hands to send this app id to web
      var handshake = function handshake(event) {
        if (event && event.data && event.data.command && event.data.command === 'handshakereply') {
          if (event.data.url) {
            if (this._callbacks.length > 0) {
              _.each(this._callbacks, function (v) {
                v('handshake', null, event, this);
              }, this);
            }
          }
          window.removeEventListener('message', handshake);
        }
      }.bind(this);
      window.addEventListener('message', handshake);
      webview.contentWindow.postMessage({
        command: 'handshake'
      }, '*');

      if (this._callbacks.length > 0) {
        _.each(this._callbacks, function (v) {
          v('contentload', null, e, this);
        }, this);
      }
    }.bind(this));

    webview.addEventListener('newwindow', function onNewWindowWebview(e) {
      if (this._allowNewWindows) {
        e.preventDefault();
        window.open(e.targetUrl); //open in chrome
        if (this._callbacks.length > 0) {
          _.each(this._callbacks, function (v) {
            v('newwindow', null, e, this);
          }, this);
        }
      } else {
        e.window.discard();
        if (this._callbacks.length > 0) {
          _.each(this._callbacks, function (v) {
            v('newwindow', new Error(e.targetUrl), e, this);
          }, this);
        }
      }
    }.bind(this));

    webview.addEventListener('permissionrequest', function onPermissionWebview(e) {
      if (e.permission === 'download' && this._downloadFrom && e.request.url.search(this._downloadFrom) !== -1) {
        e.request.allow();
      }
      if (this._callbacks.length > 0) {
        _.each(this._callbacks, function (v) {
          v('permissionrequest', null, e, this);
        }, this);
      }
    }.bind(this));

    webview.addEventListener('dialog', function onDialogWebview(e) {
      if (this._callbacks.length > 0) {
        _.each(this._callbacks, function (v) {
          v('dialog', null, e, this);
        }, this);
      }
    }.bind(this));

    // force webview focus from app body
    setInterval(function keepWebviewFocus() {
      if (webview && webviewLoaded) {
        if (window.document.activeElement !== webview && window.document.activeElement.tagName !== 'INPUT' && window.document.activeElement.tagName !== 'TEXTAREA') {
          webview.focus();
        }
      }
    }, 1000);
  };

  Browser.prototype.setHome = function setHome(url) {
    homeUrl = url;
  };
  Browser.prototype.setDomainLimit = function setDomainLimit(reg) {
    webviewDomainLimit = reg;
  };

  Browser.prototype.getUrl = function getUrl() {
    return webview.src;
  };

  Browser.prototype.addChangeCallback = function addChangeCallback(callback) {
    if (typeof callback === 'function') {
      this._callbacks.push(callback);
    }
  };

  Browser.prototype.start = function startBrowser(callback) {
    if (!webview) {
      throw new Error('Use \'bindWebview\' to set webview selector first!');
    }
    if (!homeUrl) {
      throw new Error('Use \'setHome\' to set home page first!');
    }

    var done = function done() {
      if (webview.src === 'about:blank' || webview.src === '') {
        webview.src = homeUrl;
      }
    };

    if (callback) {
      callback(webview, done);
    } else {
      done();
    }
  };

  BrowserInstance = new Browser();
  return BrowserInstance;
}

if (typeof exports !== 'undefined') {
  exports.browser = createBrowser();
}
<|endoftext|>


<commit_before>

var allowed_file_types = ["image/png","image/jpeg","application/pdf","application/msword","application/vnd.ms-excel","application/vnd.oasis.opendocument.text","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.oasis.opendocument.spreadsheet"];
var file_max_size = 15000000; // 15MB

var file_form_template = $("#file-form-template");
var file_count = 0;

$(document).ready(function() {
    /**********************************************************/
    /* Attach a onchange listener to the file input field.    */
    /* This listener will verify the validity of the filesize */
    /**********************************************************/
    $(document.body).delegate(":file", "change", fileSelected);
    $("#file-upload").click(function (evt) {
        evt.preventDefault();
        file_form_template.find(":file").click();
    });
});

/********************************************************************************************/
/* This function checks the size of the current selected file in the file form input field. */
/********************************************************************************************/
    function fileSelected(evt) {
        var inputFile = evt.currentTarget;
        var file;

        var form_copy = file_form_template.clone();
        file_form_template.attr('id', '');
        file_form_template.find(":input").each(function(index, input) {
            input.id = input.id.replace(/__prefix__/g, file_count);
            input.name = input.name.replace(/__prefix__/g, file_count);
        })
        file_form_template.find("label").each(function(index, label) {
            $(label).attr('for', $(label).attr('for').replace(/__prefix__/g, file_count));
        })
        $('#form-files').append(file_form_template);
        $('#form-files').append(form_copy);

        file_form_template = form_copy;

        file_count++;
        $("#id_files-TOTAL_FORMS").val(file_count);

        if (inputFile.files != 'undefined' && inputFile.files.length) {
            file = inputFile.files[0];
            if(file.size == 0) {
                alert('Filesize must be greater than 0');
                $("#fileForm #id_file").val("");
                return;
            }
            //TODO determine max file size
            else if(file.size > file_max_size) {
                alert('File to large');
                $("#fileForm #id_file").val("");
                return;
            }
            else if(allowed_file_types.indexOf(file.type)==-1 ){
                alert('The type of the file is not correct. You can only upload files of type: jpg, png, pdf, doc and xls.');
                $("#fileForm #id_file").val("");
                return;
            }
            else {
                var title = $("#fileForm #id_title").val();
                if (title == "") {
                    $("#fileForm #id_title").val(file.name);
                }
            }

            if(file.lastModifiedDate) {
                // Append file creation date
                var fileDate = new Date(file.lastModifiedDate);
                day = fileDate.getDate();
                month = fileDate.getMonth()+1;
                year = fileDate.getFullYear();
                hour = fileDate.getHours();
                minute = fileDate.getMinutes();

                file_form_template.find("#id_files-"+file_count+"-file_creation_date").val(year+"-"+month+"-"+day+" "+hour+":"+minute);
            }

            AddFileToView(file_form_template, file);
        }
    }

/************************************************************************************/
/* Add the submitted file to the view and save it in the session and on the server. */
/************************************************************************************/
function AddFileToView(elem, file){
    //Determine the type of the submited file
    var type = file.type.split("/")[1];
    //Structured Data of the file to add
    var title = elem.find(":file").val();
    if (title == ""){
        title = file.name;
    }

    var thumbnails = "", img = elem.find("img");
    if (type == "pdf"){
        thumbnails = "/static/images/icon-pdf.png";
    }
    else if (type == "msword"){
        thumbnails = "/static/images/icon-word.jpg";
    }
    else if(type == "vnd.ms-excel"){
        thumbnails = "/static/images/icon-excel.png";
    }
    else if (type == "vnd.openxmlformats-officedocument.wordprocessingml.document"){
        thumbnails = "/static/images/icon-word.jpg";
    } else {
        thumbnails = "/static/images/icon-file.png";
    }

    if (FileReader && (type == "jpeg" || type == "png")) {
        img[0].file = file;

        var reader = new FileReader();
        reader.onload = function(e) {
            img.attr("src", e.target.result);
        };
        reader.readAsDataURL(file);
    } else {
        img.attr("src", thumbnails);
    }
}
<commit_msg>fix image preview bug<commit_after>

var allowed_file_types = [
        "image/png","image/jpeg","application/pdf","application/msword","application/vnd.ms-excel",
        "application/vnd.oasis.opendocument.text",
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        "application/vnd.oasis.opendocument.spreadsheet"
    ];
var file_max_size = 15000000; // 15MB

var file_form_template = $("#file-form-template");
var file_count = 0;

$(document).ready(function() {
    /**********************************************************/
    /* Attach a onchange listener to the file input field.    */
    /* This listener will verify the validity of the filesize */
    /**********************************************************/
    $(document.body).delegate(":file", "change", fileSelected);
    $("#file-upload").click(function (evt) {
        evt.preventDefault();
        file_form_template.find(":file").click();
    });
});

/********************************************************************************************/
/* This function checks the size of the current selected file in the file form input field. */
/********************************************************************************************/
    function fileSelected(evt) {
        var inputFile = evt.currentTarget;
        var file;

        var form_copy = file_form_template.clone();
        var form_new = file_form_template;
        file_form_template = form_copy;

        form_new.attr('id', '');
        form_new.find(":input").each(function(index, input) {
            input.id = input.id.replace(/__prefix__/g, file_count);
            input.name = input.name.replace(/__prefix__/g, file_count);
        })
        form_new.find("label").each(function(index, label) {
            $(label).attr('for', $(label).attr('for').replace(/__prefix__/g, file_count));
        })
        $('#form-files').append(form_new);
        $('#form-files').append(file_form_template);

        file_count++;
        $("#id_files-TOTAL_FORMS").val(file_count);

        if (inputFile.files != 'undefined' && inputFile.files.length) {
            file = inputFile.files[0];
            if(file.size == 0) {
                alert('Filesize must be greater than 0');
                $("#fileForm #id_file").val("");
                return;
            }
            //TODO determine max file size
            else if(file.size > file_max_size) {
                alert('File to large');
                $("#fileForm #id_file").val("");
                return;
            }
            else if(allowed_file_types.indexOf(file.type)==-1 ){
                alert('The type of the file is not correct. You can only upload files of type: jpg, png, pdf, doc and xls.');
                $("#fileForm #id_file").val("");
                return;
            }
            else {
                var title = $("#fileForm #id_title").val();
                if (title == "") {
                    $("#fileForm #id_title").val(file.name);
                }
            }

            if(file.lastModifiedDate) {
                // Append file creation date
                var fileDate = new Date(file.lastModifiedDate);
                day = fileDate.getDate();
                month = fileDate.getMonth()+1;
                year = fileDate.getFullYear();
                hour = fileDate.getHours();
                minute = fileDate.getMinutes();

                form_new.find("#id_files-"+file_count+"-file_creation_date").val(year+"-"+month+"-"+day+" "+hour+":"+minute);
            }

            AddFileToView(form_new, file);
        }
    }

/************************************************************************************/
/* Add the submitted file to the view and save it in the session and on the server. */
/************************************************************************************/
function AddFileToView(elem, file){
    //Determine the type of the submited file
    var type = file.type.split("/")[1];
    //Structured Data of the file to add
    var title = elem.find(":file").val();
    if (title == ""){
        title = file.name;
    }

    var thumbnails = "", img = elem.find("img");
    console.log(file.name);
    console.log('ello',img);
    if (type == "pdf"){
        thumbnails = "/static/images/icon-pdf.png";
    }
    else if (type == "msword"){
        thumbnails = "/static/images/icon-word.jpg";
    }
    else if(type == "vnd.ms-excel"){
        thumbnails = "/static/images/icon-excel.png";
    }
    else if (type == "vnd.openxmlformats-officedocument.wordprocessingml.document"){
        thumbnails = "/static/images/icon-word.jpg";
    } else {
        thumbnails = "/static/images/icon-file.png";
    }

    if (FileReader && (type == "jpeg" || type == "png")) {
        img[0].file = file;

        var reader = new FileReader();
        reader.onload = function(e) {
            img.attr("src", e.target.result);
        };
        reader.readAsDataURL(file);
    } else {
        img.attr("src", thumbnails);
    }
}
<|endoftext|>


<commit_before>app
.factory('gridService', function() {
    var gridsterOptions = {
        margins: [20, 20],
        columns: 8,
        draggable: {
            enabled: true,
            handle: '.box-header'
        }
    };

    var widgetDefinitions = [
    {
        sizeY: 3,
        sizeX: 3,
        name: "Ground Track",
        directive: "groundtrack",
		directiveSettings: "samplesettings",
        id: "addGround",
        icon: {
            id: "g-track",
            type: "fa-globe"
        },
        main: true,
		settings: false,
		saveLoad: false,
		delete: false
    },
    {
        sizeY: 3,
        sizeX: 3,
        name: "Telemetry Table",
        directive: "tabletext",
		directiveSettings: "samplesettings",
        id: "addtablewidget",
        icon: {
            id: "t-table",
            type: "fa-table"
        },
        main: true,
		settings: false,
		saveLoad: false,
		delete: false
    },
    {
        sizeY: 3,
        sizeX: 3,
        name: "Search By Id",
        directive: "searchtable",
		directiveSettings: "samplesettings",
        id: "searchId",
        icon: {
            id: "s-table",
            type: "fa-search"
        },
        main: true,
		settings: false,
		saveLoad: false,
		delete: false
    },
    {
        sizeY: 3,
        sizeX: 4,
        name: "Line Plot",
        directive: "lineplot",
		directiveSettings: "linesettings",
        id: "addLine",
        icon: {
            id: "l-plot",
            type: "fa-line-chart"
        },
        main: true,
		settings: false,
		saveLoad: false,
		delete: false
    },
    {
        sizeY: 2,
        sizeX: 6,
        name: "Data Table",
        directive: "datatable",
		directiveSettings: "datatablesettings",
        id: "datatable",
        icon: {
            id: "d-table",
            type: "fa-table"
        },
        main: true,
		settings: false,
		saveLoad: false,
		delete: false

    }];

    var dashboards = {
        '1': {
            id: '1',
            name: 'Home',
            widgets: [{
                col: 0,
                row: 0,
                sizeY: 2,
                sizeX: 6,
                name: "Data Table",
                directive: "datatable",
				directiveSettings: "datatablesettings",
                id: "datatable",
                icon: {
                    id: "d-table",
                    type: "fa-table"
                },
                main: true,
				settings: false,
				saveLoad: false,
				delete: false,
            },
			{
				col: 0,
                row: 3,
				sizeY: 3,
				sizeX: 4,
				name: "Line Plot",
				directive: "lineplot",
				directiveSettings: "linesettings",
				id: "addLine",
				icon: {
					id: "l-plot",
					type: "fa-line-chart"
				},
				main: true,
				settings: false,
				saveLoad: false,
				delete: false
			}]
        }
    };

    var dashboard = dashboards[1];

    var selectedDashboardId = '1';

    function getDashboard() {
        return dashboard;
    }

    function setDashboard(d1) {
        dashboard = d1;
    }

    function getDashboardId() {
        return selectedDashboardId;
    }

    function setDashboardId(id1) {
        selectedDashboardId = id1;
    }

    function clear() {
        dashboards[selectedDashboardId].widgets = [];
    };

    function addWidget() {
        dashboards[selectedDashboardId].widgets.push({
            name: "New Widget",
            sizeX: 1,
            sizeY: 1
        });
    };

    function addWidgets(widget) {
        dashboards[selectedDashboardId].widgets.push({
            name: widget.name,
            sizeX: widget.sizeX,
            sizeY: widget.sizeY,
            directive: widget.directive,
			directiveSettings: widget.directiveSettings,
            id: widget.id,
            icon: {
                id: widget.icon.id,
                type: widget.icon.type
            },
			main: widget.main,
			settings: widget.settings,
			saveLoad: widget.saveLoad,
			delete: widget.delete
        });
    }

    function remove(widget) {
        dashboard.widgets.splice(dashboard.widgets.indexOf(widget), 1);
    }

	return {
        gridsterOptions : gridsterOptions,
        dashboards : dashboards,
        clear : clear,
        addWidget : addWidget,
        getDashboard : getDashboard,
        getDashboardId : getDashboardId,
        setDashboard : setDashboard,
        setDashboardId : setDashboardId,
        addWidgets : addWidgets,
        widgetDefinitions : widgetDefinitions,
        remove : remove
	}
});<commit_msg>lineplot not default<commit_after>app
.factory('gridService', function() {
    var gridsterOptions = {
        margins: [20, 20],
        columns: 8,
        draggable: {
            enabled: true,
            handle: '.box-header'
        }
    };

    var widgetDefinitions = [
    {
        sizeY: 3,
        sizeX: 3,
        name: "Ground Track",
        directive: "groundtrack",
		directiveSettings: "samplesettings",
        id: "addGround",
        icon: {
            id: "g-track",
            type: "fa-globe"
        },
        main: true,
		settings: false,
		saveLoad: false,
		delete: false
    },
    {
        sizeY: 3,
        sizeX: 3,
        name: "Telemetry Table",
        directive: "tabletext",
		directiveSettings: "samplesettings",
        id: "addtablewidget",
        icon: {
            id: "t-table",
            type: "fa-table"
        },
        main: true,
		settings: false,
		saveLoad: false,
		delete: false
    },
    {
        sizeY: 3,
        sizeX: 3,
        name: "Search By Id",
        directive: "searchtable",
		directiveSettings: "samplesettings",
        id: "searchId",
        icon: {
            id: "s-table",
            type: "fa-search"
        },
        main: true,
		settings: false,
		saveLoad: false,
		delete: false
    },
    {
        sizeY: 3,
        sizeX: 4,
        name: "Line Plot",
        directive: "lineplot",
		directiveSettings: "linesettings",
        id: "addLine",
        icon: {
            id: "l-plot",
            type: "fa-line-chart"
        },
        main: true,
		settings: false,
		saveLoad: false,
		delete: false
    },
    {
        sizeY: 2,
        sizeX: 6,
        name: "Data Table",
        directive: "datatable",
		directiveSettings: "datatablesettings",
        id: "datatable",
        icon: {
            id: "d-table",
            type: "fa-table"
        },
        main: true,
		settings: false,
		saveLoad: false,
		delete: false

    }];

    var dashboards = {
        '1': {
            id: '1',
            name: 'Home',
            widgets: [{
                col: 0,
                row: 0,
                sizeY: 2,
                sizeX: 6,
                name: "Data Table",
                directive: "datatable",
				directiveSettings: "datatablesettings",
                id: "datatable",
                icon: {
                    id: "d-table",
                    type: "fa-table"
                },
                main: true,
				settings: false,
				saveLoad: false,
				delete: false,
            }]
        }
    };

    var dashboard = dashboards[1];

    var selectedDashboardId = '1';

    function getDashboard() {
        return dashboard;
    }

    function setDashboard(d1) {
        dashboard = d1;
    }

    function getDashboardId() {
        return selectedDashboardId;
    }

    function setDashboardId(id1) {
        selectedDashboardId = id1;
    }

    function clear() {
        dashboards[selectedDashboardId].widgets = [];
    };

    function addWidget() {
        dashboards[selectedDashboardId].widgets.push({
            name: "New Widget",
            sizeX: 1,
            sizeY: 1
        });
    };

    function addWidgets(widget) {
        dashboards[selectedDashboardId].widgets.push({
            name: widget.name,
            sizeX: widget.sizeX,
            sizeY: widget.sizeY,
            directive: widget.directive,
			directiveSettings: widget.directiveSettings,
            id: widget.id,
            icon: {
                id: widget.icon.id,
                type: widget.icon.type
            },
			main: widget.main,
			settings: widget.settings,
			saveLoad: widget.saveLoad,
			delete: widget.delete
        });
    }

    function remove(widget) {
        dashboard.widgets.splice(dashboard.widgets.indexOf(widget), 1);
    }

	return {
        gridsterOptions : gridsterOptions,
        dashboards : dashboards,
        clear : clear,
        addWidget : addWidget,
        getDashboard : getDashboard,
        getDashboardId : getDashboardId,
        setDashboard : setDashboard,
        setDashboardId : setDashboardId,
        addWidgets : addWidgets,
        widgetDefinitions : widgetDefinitions,
        remove : remove
	}
});<|endoftext|>


<commit_before>define(['./module.js', 'underscore'], function(module, _) {
  return module.factory('lists', ['$http', '$locale', '$q',
    function($http, $locale, $q) {
      var lists = {};

      lists.getCountries = function(cb) {
        $http.get('langs/en/countries.json')
          .then(function(response) {
            cb(response.data);
          });
      };

      lists.getYears = function(rstart, rend, callback) {
        if (angular.isFunction(rstart)) {
          callback = rstart;
          rstart = null;
        }
        var end = rend || (new Date()).getFullYear() + 1,
          start = rstart || end - 25 - 1;
        return callback(_.range(start, end).reverse());
      };

      lists.getEbsas = function(regionName) {
        var deferred = $q.defer();
        $http.get('ebsaData/' + regionName + '.json')
          .then(function(response) {
            deferred.resolve(response.data);
          });
        return deferred.promise;
      };

      return lists;
    }
  ]);
});<commit_msg>change getCountries to return a promise for API consistency, change generateCountryList to cache the results of the getCountries call for performance<commit_after>define(['./module.js', 'underscore'], function(module, _) {
  return module.factory('lists', ['$http', '$locale', '$q',
    function($http, $locale, $q) {
      var lists = {};

      lists.getCountries = function() {
        var deferred = $q.defer();
        $http.get('langs/en/countries.json')
          .then(function(response) {
            deferred.resolve(response.data);
          });
        return deferred.promise;
      };

      lists.getYears = function(rstart, rend, callback) {
        if (angular.isFunction(rstart)) {
          callback = rstart;
          rstart = null;
        }
        var end = rend || (new Date()).getFullYear() + 1,
          start = rstart || end - 25 - 1;
        return callback(_.range(start, end).reverse());
      };

      lists.getEbsas = function(regionName) {
        var deferred = $q.defer();
        $http.get('ebsaData/' + regionName + '.json')
          .then(function(response) {
            deferred.resolve(response.data);
          });
        return deferred.promise;
      };

      return lists;
    }
  ]);
});<|endoftext|>


<commit_before>/**
    Access to use global App Modals
**/
'use strict';

var $ = require('jquery');

/**
    Generates a text message, with newlines if needed, describing the error
    object passed.
    @param err:any As a string, is returned 'as is'; as falsy, it return a generic
    message for 'unknow error'; as object, it investigate what type of error is to
    provide the more meaninful result, with fallback to JSON.stringify prefixed
    with 'Technical details:'.
    Objects recognized:
    - XHR/jQuery for JSON responses: just objects with responseJSON property, is
      used as the 'err' object and passed to the other object tests.
    - Object with 'errorMessage' (server-side formatted error).
    - Object with 'message' property, like the standard Error class and Exception objects.
    - Object with 'name' property, like the standard Exception objects. The name, if any,
      is set as prefix for the 'message' property value.
    - Object with 'errors' property. Each element in the array or object own keys
      is appended to the errorMessage or message separated by newline.
**/
exports.getErrorMessageFrom = function getErrorMessageFrom(err, defaultText) {
    /*jshint maxcomplexity:14, maxdepth:5*/

    defaultText = defaultText || 'Unknow error';

    if (!err) {
        return defaultText;
    }
    else if (typeof(err) === 'string') {
        return err || defaultText;
    }
    else {
        // If is a XHR object, use its response as the error.
        err = err.responseJSON || err;

        var msg = err.name && (err.name + ': ') || '';
        msg += err.errorMessage || err.message || '';

        if (err.errors) {
            msg += '\n' + exports.stringifyErrorsList(err.errors);
        }
        else {
            // Avoiding that en error converting the object (circular references)
            // breaks the error control!
            try {
                var jserr = JSON.stringify(err);
                // Avoiding that empty results (empty string or empty object when there
                // is no details to show) makes us to show an annoying 'technical details'
                var hasMoreInfo = jserr && jserr !== '{}';
                // Too if there is no more information than the one extracted to build the
                // message, since on that cases the 'technical details' will be just a
                // json formatted of the same displayed message
                if (hasMoreInfo) {
                    // Reset initially, re-enabled only if there are more properties
                    // than the ones from the list
                    hasMoreInfo = false;
                    var messagePropertiesList = ['name', 'errorMessage', 'message', 'errors'];
                    Object.keys(err).forEach(function(key) {
                        if (messagePropertiesList.indexOf(key) === -1)
                            hasMoreInfo = true;
                    });
                }

                if (hasMoreInfo)
                    msg += '\n\nTechnical details: ' + jserr;
            }
            catch (ex) {
                console.log('Impossible to stringify JSON error', err, ex);
            }
        }

        return msg || defaultText;
    }
};

exports.stringifyErrorsList = function (errors) {
    var msg = '';
    if (Array.isArray(errors)) {
        msg = errors.join('\n');
    }
    else {
        msg = Object.keys(errors).map(function(key) {
            return errors[key].join('\n');
        }).join('\n');
    }
    return msg;
};

/**
    Show an error modal to notify the user.
    @param options:Object {
        message:string DEPRECATED. Optional. Informative error message.
        error:string Optional. Error/Exception/XHR object, used to auto
            generate the error message. It takes precedence over 'message'
            option, discarding an error object/string is passed.
            It replaces 'message' since can do the same and more.
        title:string Optional. The text to show in the modal's header,
            with fallback to the Modal's default title.
    }
    @returns Promise. It resolves when the modal is dismissed/closed.
    No formal rejection happens.
**/
exports.showError = function showErrorModal(options) {

    var modal = $('#errorModal'),
        header = modal.find('#errorModal-label'),
        body = modal.find('#errorModal-body');

    options = options || {};

    // Fallback error message
    var msg = body.data('default-text');

    // Error message from given error object, with fallback to default one.
    // DEPRECATED temporarly using the 'message' option.
    msg = exports.getErrorMessageFrom(options.error || options.message, msg);

    body.multiline(msg);

    header.text(options.title || header.data('default-text'));

    return new Promise(function(resolve) {
        modal.modal('show');
        modal.on('hide.bs.modal', function() {
            resolve();
        });
    });
};

/**
    Show confirmation modal with two buttons.
    @param options:object {
        title:string Header title text
        message:string Message text
        yes:string Yes button label
        no:string No button label
    }
    @returns Promise. It resolves if button 'yes' pressed
    and reject on button 'no' pressed or modal dismissed/closed.
**/
exports.confirm = function confirm(options) {

    var modal = $('#confirmModal'),
        header = modal.find('#confirmModal-label'),
        body = modal.find('#confirmModal-body'),
        yesBtn = modal.find('#confirmModal-yesBtn'),
        noBtn = modal.find('#confirmModal-noBtn');

    options = options || {};

    // Fallback error message
    var title = header.data('default-text'),
        msg = body.data('default-text'),
        yes = yesBtn.data('default-text'),
        no = noBtn.data('default-text');

    body.multiline(options.message || msg);
    header.text(options.title || title);
    yesBtn.text(options.yes || yes);
    noBtn.text(options.no || no);

    return new Promise(function(resolve, reject) {
        modal.modal('show');
        yesBtn.on('click', function() {
            resolve();
        });
        noBtn.on('click', function() {
            reject();
        });
        modal.on('hide.bs.modal', function() {
            reject();
        });
    });
};

/**
    Show an information modal to notify the user about something.
    @param options:Object {
        message:string. Informative message.
        title:string Optional. The text to show in the modal's header,
            with fallback to the Modal's default title.
    }
    @returns Promise. It resolves when the modal is dismissed/closed.
    No formal rejection happens.
**/
exports.showNotification = function showNotification(options) {

    var modal = $('#notificationModal'),
        header = modal.find('#notificationModal-label'),
        button = modal.find('#notificationModal-button'),
        body = modal.find('#notificationModal-body');

    options = options || {};

    // Fallback message
    var msg = options.message || body.data('default-text');

    body.multiline(msg);

    header.text(options.title || header.data('default-text'));
    button.text(options.buttonText || button.data('default-text'));

    return new Promise(function(resolve) {
        modal.modal('show');
        modal.on('hide.bs.modal', function() {
            resolve();
        });
    });
};

exports.showTimePicker = require('./modals/timePicker').show;

exports.showTextEditor = require('./modals/textEditor').show;
<commit_msg>Fixed a general errors management bug that prevented some validation errors from being displayed, as in payment-account<commit_after>/**
    Access to use global App Modals
**/
'use strict';

var $ = require('jquery');

/**
    Generates a text message, with newlines if needed, describing the error
    object passed.
    @param err:any As a string, is returned 'as is'; as falsy, it return a generic
    message for 'unknow error'; as object, it investigate what type of error is to
    provide the more meaninful result, with fallback to JSON.stringify prefixed
    with 'Technical details:'.
    Objects recognized:
    - XHR/jQuery for JSON responses: just objects with responseJSON property, is
      used as the 'err' object and passed to the other object tests.
    - Object with 'errorMessage' (server-side formatted error).
    - Object with 'message' property, like the standard Error class and Exception objects.
    - Object with 'name' property, like the standard Exception objects. The name, if any,
      is set as prefix for the 'message' property value.
    - Object with 'errors' property. Each element in the array or object own keys
      is appended to the errorMessage or message separated by newline.
**/
exports.getErrorMessageFrom = function getErrorMessageFrom(err, defaultText) {
    /*jshint maxcomplexity:14, maxdepth:5*/

    defaultText = defaultText || 'Unknow error';

    if (!err) {
        return defaultText;
    }
    else if (typeof(err) === 'string') {
        return err || defaultText;
    }
    else {
        // If is a XHR object, use its response as the error.
        err = err.responseJSON || err;

        var msg = err.name && (err.name + ': ') || '';
        msg += err.errorMessage || err.message || '';

        if (err.errors) {
            msg += '\n' + exports.stringifyErrorsList(err.errors);
        }
        else {
            // Avoiding that en error converting the object (circular references)
            // breaks the error control!
            try {
                var jserr = JSON.stringify(err);
                // Avoiding that empty results (empty string or empty object when there
                // is no details to show) makes us to show an annoying 'technical details'
                var hasMoreInfo = jserr && jserr !== '{}';
                // Too if there is no more information than the one extracted to build the
                // message, since on that cases the 'technical details' will be just a
                // json formatted of the same displayed message
                if (hasMoreInfo) {
                    // Reset initially, re-enabled only if there are more properties
                    // than the ones from the list
                    hasMoreInfo = false;
                    var messagePropertiesList = ['name', 'errorMessage', 'message', 'errors'];
                    Object.keys(err).forEach(function(key) {
                        if (messagePropertiesList.indexOf(key) === -1)
                            hasMoreInfo = true;
                    });
                }

                if (hasMoreInfo)
                    msg += '\n\nTechnical details: ' + jserr;
            }
            catch (ex) {
                console.log('Impossible to stringify JSON error', err, ex);
            }
        }

        return msg || defaultText;
    }
};

exports.stringifyErrorsList = function (errors) {
    var msg = '';
    if (Array.isArray(errors)) {
        msg = errors.join('\n');
    }
    else {
        msg = Object.keys(errors).map(function(key) {
            var m = errors[key];
            if (m && m.join)
                return m.join('\n');
            else
                return m;
        }).join('\n');
    }
    return msg;
};

/**
    Show an error modal to notify the user.
    @param options:Object {
        message:string DEPRECATED. Optional. Informative error message.
        error:string Optional. Error/Exception/XHR object, used to auto
            generate the error message. It takes precedence over 'message'
            option, discarding an error object/string is passed.
            It replaces 'message' since can do the same and more.
        title:string Optional. The text to show in the modal's header,
            with fallback to the Modal's default title.
    }
    @returns Promise. It resolves when the modal is dismissed/closed.
    No formal rejection happens.
**/
exports.showError = function showErrorModal(options) {

    var modal = $('#errorModal'),
        header = modal.find('#errorModal-label'),
        body = modal.find('#errorModal-body');

    options = options || {};

    // Fallback error message
    var msg = body.data('default-text');

    // Error message from given error object, with fallback to default one.
    // DEPRECATED temporarly using the 'message' option.
    msg = exports.getErrorMessageFrom(options.error || options.message, msg);

    body.multiline(msg);

    header.text(options.title || header.data('default-text'));

    return new Promise(function(resolve) {
        modal.modal('show');
        modal.on('hide.bs.modal', function() {
            resolve();
        });
    });
};

/**
    Show confirmation modal with two buttons.
    @param options:object {
        title:string Header title text
        message:string Message text
        yes:string Yes button label
        no:string No button label
    }
    @returns Promise. It resolves if button 'yes' pressed
    and reject on button 'no' pressed or modal dismissed/closed.
**/
exports.confirm = function confirm(options) {

    var modal = $('#confirmModal'),
        header = modal.find('#confirmModal-label'),
        body = modal.find('#confirmModal-body'),
        yesBtn = modal.find('#confirmModal-yesBtn'),
        noBtn = modal.find('#confirmModal-noBtn');

    options = options || {};

    // Fallback error message
    var title = header.data('default-text'),
        msg = body.data('default-text'),
        yes = yesBtn.data('default-text'),
        no = noBtn.data('default-text');

    body.multiline(options.message || msg);
    header.text(options.title || title);
    yesBtn.text(options.yes || yes);
    noBtn.text(options.no || no);

    return new Promise(function(resolve, reject) {
        modal.modal('show');
        yesBtn.on('click', function() {
            resolve();
        });
        noBtn.on('click', function() {
            reject();
        });
        modal.on('hide.bs.modal', function() {
            reject();
        });
    });
};

/**
    Show an information modal to notify the user about something.
    @param options:Object {
        message:string. Informative message.
        title:string Optional. The text to show in the modal's header,
            with fallback to the Modal's default title.
    }
    @returns Promise. It resolves when the modal is dismissed/closed.
    No formal rejection happens.
**/
exports.showNotification = function showNotification(options) {

    var modal = $('#notificationModal'),
        header = modal.find('#notificationModal-label'),
        button = modal.find('#notificationModal-button'),
        body = modal.find('#notificationModal-body');

    options = options || {};

    // Fallback message
    var msg = options.message || body.data('default-text');

    body.multiline(msg);

    header.text(options.title || header.data('default-text'));
    button.text(options.buttonText || button.data('default-text'));

    return new Promise(function(resolve) {
        modal.modal('show');
        modal.on('hide.bs.modal', function() {
            resolve();
        });
    });
};

exports.showTimePicker = require('./modals/timePicker').show;

exports.showTextEditor = require('./modals/textEditor').show;
<|endoftext|>