<commit_before>/* Python 'iter' type */

var iter = __inherit(object);

iter.prototype.__init__ = function(obj) {
    this._index = 0;

    if (obj instanceof Array) {
        this._seq = obj;
    } else if (typeof(obj) === "string") {
        this._seq = obj.split("");
    } else if (obj.__class__ == iter) {
        this._seq = obj._seq;
    } else if (defined(obj.__iter__)) {
        this._seq = obj.__iter__()._seq;
    } else {
        throw new py_builtins.TypeError("object is not iterable");
    }
}

iter.__name__ = 'iter';
iter.prototype.__class__ = iter;

iter.prototype.__str__ = function () {
    return str.__call__("<iter of " + this._seq + " at " + this._index + ">");
};

iter.prototype.toString = function () {
    return js(this.__str__());
};

iter.prototype.next = function() {
    var value = this._seq[this._index++];

    if (defined(value)) {
        return value;
    } else {
        throw new py_builtins.StopIteration('no more items');
    }
};

<commit_msg> + Added debug .MARK to iter<commit_after>/* Python 'iter' type */

var iter = __inherit(object);

iter.prototype.MARK = "iter";

iter.prototype.__init__ = function(obj) {
    this._index = 0;

    if (obj instanceof Array) {
        this._seq = obj;
    } else if (typeof(obj) === "string") {
        this._seq = obj.split("");
    } else if (obj.__class__ == iter) {
        this._seq = obj._seq;
    } else if (defined(obj.__iter__)) {
        this._seq = obj.__iter__()._seq;
    } else {
        throw new py_builtins.TypeError("object is not iterable");
    }
}

iter.__name__ = 'iter';
iter.prototype.__class__ = iter;

iter.prototype.__str__ = function () {
    return str.__call__("<iter of " + this._seq + " at " + this._index + ">");
};

iter.prototype.toString = function () {
    return js(this.__str__());
};

iter.prototype.next = function() {
    var value = this._seq[this._index++];

    if (defined(value)) {
        return value;
    } else {
        throw new py_builtins.StopIteration('no more items');
    }
};

<|endoftext|>


<commit_before>(function () {

  // Borrowed from shared/js/settings_listener.js
  var SettingsListener = {
    /* lock stores here */
    _lock: null,

    /* keep record of observers in order to remove them in the future */
    _observers: [],

    /**
     * getSettingsLock: create a lock or retrieve one that we saved.
     * mozSettings.createLock() is expensive and lock should be reused
     * whenever possible.
     */
    getSettingsLock: function sl_getSettingsLock() {
      // If there is a lock present we return that
      if (this._lock && !this._lock.closed) {
        return this._lock;
      }

      // If there isn't we return one.
      var settings = window.navigator.mozSettings;

      return (this._lock = settings.createLock());
    },

    observe: function sl_observe(name, defaultValue, callback) {
      var settings = window.navigator.mozSettings;
      if (!settings) {
        window.setTimeout(function() { callback(defaultValue); });
        return;
      }

      var req;
      try {
        req = this.getSettingsLock().get(name);
      } catch (e) {
        // It is possible (but rare) for getSettingsLock() to return
        // a SettingsLock object that is no longer valid.
        // Until https://bugzilla.mozilla.org/show_bug.cgi?id=793239
        // is fixed, we just catch the resulting exception and try
        // again with a fresh lock
        console.warn('Stale lock in settings_listener.js.',
                     'See https://bugzilla.mozilla.org/show_bug.cgi?id=793239');
        this._lock = null;
        req = this.getSettingsLock().get(name);
      }

      req.addEventListener('success', (function onsuccess() {
        callback(typeof(req.result[name]) != 'undefined' ?
          req.result[name] : defaultValue);
      }));

      var settingChanged = function settingChanged(evt) {
        callback(evt.settingValue);
      };
      settings.addObserver(name, settingChanged);
      this._observers.push({
        name: name,
        callback: callback,
        observer: settingChanged
      });
    },

    unobserve: function sl_unobserve(name, callback) {
      var settings = window.navigator.mozSettings;
      var that = this;
      this._observers.forEach(function(value, index) {
        if (value.name === name && value.callback === callback) {
          settings.removeObserver(name, value.observer);
          that._observers.splice(index, 1);
        }
      });
    }
  };

  // If injecting into an app that was already running at the time
  // the app was enabled, simply initialize it.
  if (document.documentElement) {
    initialize();
  }

  // Otherwise, we need to wait for the DOM to be ready before
  // starting initialization since add-ons are usually (always?)
  // injected *before* `document.documentElement` is defined.
  else {
    window.addEventListener('DOMContentLoaded', initialize);
  }

  // var SettingsListener = window.wrappedJSObject.SettingsListener;

  function initialize() {
    // console.log('init quick settings');
    // console.log('SettingsListener', window.wrappedJSObject.SettingsListener);

    var quickSettingsContainer = document.querySelector('#quick-settings > ul');
    quickSettingsContainer.style.flexWrap = 'wrap';

    // Remove previously appended buttons if any
    var lastButton = document.querySelector('#quick-settings-full-app').parentNode;
    while (lastButton.nextSibling) {
      quickSettingsContainer.removeChild(lastButton.nextSibling);
    }

    // Template:
    //

    var settings = {
      volume: createButton('volume'),
      nfc: createButton('nfc'),
      flashlight: createButton('flashlight')
    };

    initVolumeButton(settings.volume.firstChild);
    initNfcButton(settings.nfc.firstChild);
    initFlashButton(settings.flashlight.firstChild);

    for (var prop in settings) {
      quickSettingsContainer.appendChild(settings[prop]);
    }

    // XXX: Add 2 additional li as placeholders to layout buttons correctly
    quickSettingsContainer.appendChild(document.createElement('li'));
    quickSettingsContainer.appendChild(document.createElement('li'));

    var allSettings = document.querySelectorAll('#quick-settings > ul > li');
    for (var i=0; i < allSettings.length; i++) {
      allSettings[i].style.flex = '1 1 20%';
    }

  }

  function createButton (name) {
    var li = document.createElement('li');
    var a = document.createElement('a');
    a.href = '#';
    a.id = 'quick-settings-' + name;
    a.classList.add('icon');
    a.classList.add('bb-button');
    a.setAttribute('role', 'button');
    li.appendChild(a);

    return li;
  }

  function initVolumeButton (button) {

    var originalVolume = 0;

    function onVolumeChanged (value) {
      if (value > 14) {
        button.dataset.icon = 'sound-max';
        button.dataset.l10nId = 'quick-settings-volumeButton-max';
      } else if (value < 1) {
        button.dataset.icon = 'mute';
        button.dataset.l10nId = 'quick-settings-volumeButton-mute';
      } else {
        button.dataset.icon = 'sound-min';
        button.dataset.l10nId = 'quick-settings-volumeButton-min';
      }

      originalVolume = value > 0 ? value : originalVolume;
    }

    function onClick () {
      if (button.dataset.icon === 'mute') {
        window.navigator.mozSettings.createLock().set({'audio.volume.notification': originalVolume});
      } else {
        window.navigator.mozSettings.createLock().set({'audio.volume.notification': 0});
      }
    }

    button.dataset.icon = 'sound-max';
    // button.dataset.enabled = false;
    button.dataset.l10nId = 'quick-settings-volumeButton-max';
    button.addEventListener('click', onClick);

    SettingsListener.observe('audio.volume.notification', '', onVolumeChanged);
  }

  function initNfcButton (button) {

    function onNfcStatusChanged (status) {
      if (status === 'enabling' || status === 'enabled') {
        button.style.color = '#008EAB';
        button.dataset.enabled = true;
        button.dataset.l10nId = 'quick-settings-nfcButton-on';
      } else if (status === 'disabling' || status === 'disabled') {
        button.style.color = '';
        button.dataset.enabled = false;
        button.dataset.l10nId = 'quick-settings-nfcButton-off';
      }
    }

    function onClick () {
      if (button.dataset.enabled === 'true') {
        window.navigator.mozSettings.createLock().set({'nfc.enabled': false});
      } else {
        window.navigator.mozSettings.createLock().set({'nfc.enabled': true});
      }
    }

    button.dataset.icon = 'nfc';
    button.dataset.enabled = false;
    button.dataset.l10nId = 'quick-settings-nfcButton-off';
    button.addEventListener('click', onClick);

    SettingsListener.observe('nfc.status', undefined, onNfcStatusChanged);
  }

  function initFlashButton (button) {

    var options = {
      mode: 'video'
    };

    var cameraId = window.navigator.mozCameras.getListOfCameras()[0];
    var mozCamera;

    // need to check if the current app uses camera or not, show an error toast if yes

    // need to release camera when the screen is on after it went black

    // before getCamera, need to check if any app other than the current app occupies the camera,
    // release the camera if yes

    function onClick () {
      console.log('onClick', button.dataset.enabled);
      if (button.dataset.enabled === 'true') {
        console.log('release camera');
        mozCamera.release();

        button.dataset.icon = 'flash-off';
        button.dataset.enabled = false;
        button.dataset.l10nId = 'quick-settings-flashlightButton-off';
      } else {
        console.log('get camera');
        window.navigator.mozCameras.getCamera(cameraId, options)
        .then(function (result) {
          console.log('set flash on');
          mozCamera = result.camera;
          mozCamera.flashMode = 'torch';
        }, function (error) {
          console.log(error);
        }).catch(function (e) {
          console.log('catch', e);
        });

        button.dataset.icon = 'flash-on';
        button.dataset.enabled = true;
        button.dataset.l10nId = 'quick-settings-flashlightButton-on';
      }
    }

    button.dataset.icon = 'flash-off';
    button.dataset.enabled = false;
    button.dataset.l10nId = 'quick-settings-flashlightButton-off';
    button.addEventListener('click', onClick);
  }

}());
<commit_msg>add basic hotspot support<commit_after>(function () {

  // Borrowed from shared/js/settings_listener.js
  var SettingsListener = {
    /* lock stores here */
    _lock: null,

    /* keep record of observers in order to remove them in the future */
    _observers: [],

    /**
     * getSettingsLock: create a lock or retrieve one that we saved.
     * mozSettings.createLock() is expensive and lock should be reused
     * whenever possible.
     */
    getSettingsLock: function sl_getSettingsLock() {
      // If there is a lock present we return that
      if (this._lock && !this._lock.closed) {
        return this._lock;
      }

      // If there isn't we return one.
      var settings = window.navigator.mozSettings;

      return (this._lock = settings.createLock());
    },

    observe: function sl_observe(name, defaultValue, callback) {
      var settings = window.navigator.mozSettings;
      if (!settings) {
        window.setTimeout(function() { callback(defaultValue); });
        return;
      }

      var req;
      try {
        req = this.getSettingsLock().get(name);
      } catch (e) {
        // It is possible (but rare) for getSettingsLock() to return
        // a SettingsLock object that is no longer valid.
        // Until https://bugzilla.mozilla.org/show_bug.cgi?id=793239
        // is fixed, we just catch the resulting exception and try
        // again with a fresh lock
        console.warn('Stale lock in settings_listener.js.',
                     'See https://bugzilla.mozilla.org/show_bug.cgi?id=793239');
        this._lock = null;
        req = this.getSettingsLock().get(name);
      }

      req.addEventListener('success', (function onsuccess() {
        callback(typeof(req.result[name]) != 'undefined' ?
          req.result[name] : defaultValue);
      }));

      var settingChanged = function settingChanged(evt) {
        callback(evt.settingValue);
      };
      settings.addObserver(name, settingChanged);
      this._observers.push({
        name: name,
        callback: callback,
        observer: settingChanged
      });
    },

    unobserve: function sl_unobserve(name, callback) {
      var settings = window.navigator.mozSettings;
      var that = this;
      this._observers.forEach(function(value, index) {
        if (value.name === name && value.callback === callback) {
          settings.removeObserver(name, value.observer);
          that._observers.splice(index, 1);
        }
      });
    }
  };

  // If injecting into an app that was already running at the time
  // the app was enabled, simply initialize it.
  if (document.documentElement) {
    initialize();
  }

  // Otherwise, we need to wait for the DOM to be ready before
  // starting initialization since add-ons are usually (always?)
  // injected *before* `document.documentElement` is defined.
  else {
    window.addEventListener('DOMContentLoaded', initialize);
  }

  // var SettingsListener = window.wrappedJSObject.SettingsListener;

  function initialize() {
    // console.log('init quick settings');
    // console.log('SettingsListener', window.wrappedJSObject.SettingsListener);

    var quickSettingsContainer = document.querySelector('#quick-settings > ul');
    quickSettingsContainer.style.flexWrap = 'wrap';

    // Remove previously appended buttons if any
    var lastButton = document.querySelector('#quick-settings-full-app').parentNode;
    while (lastButton.nextSibling) {
      quickSettingsContainer.removeChild(lastButton.nextSibling);
    }

    // Template:
    //

    var settings = {
      volume: createButton('volume'),
      nfc: createButton('nfc'),
      flashlight: createButton('flashlight'),
      hotspot: createButton('hotspot')
    };

    initVolumeButton(settings.volume.firstChild);
    initNfcButton(settings.nfc.firstChild);
    initFlashButton(settings.flashlight.firstChild);
    initHotSpotButton(settings.hotspot.firstChild);

    for (var prop in settings) {
      quickSettingsContainer.appendChild(settings[prop]);
    }

    // XXX: Add 2 additional li as placeholders to layout buttons correctly
    quickSettingsContainer.appendChild(document.createElement('li'));
    quickSettingsContainer.appendChild(document.createElement('li'));

    var allSettings = document.querySelectorAll('#quick-settings > ul > li');
    for (var i=0; i < allSettings.length; i++) {
      allSettings[i].style.flex = '1 1 20%';
    }
  }

  function createButton(name) {
    var li = document.createElement('li');
    var a = document.createElement('a');
    a.href = '#';
    a.id = 'quick-settings-' + name;
    a.classList.add('icon');
    a.classList.add('bb-button');
    a.setAttribute('role', 'button');
    li.appendChild(a);

    return li;
  }

  function initVolumeButton(button) {

    var originalVolume = 0;

    function onVolumeChanged(value) {
      if (value > 14) {
        button.dataset.icon = 'sound-max';
        button.dataset.l10nId = 'quick-settings-volumeButton-max';
      } else if (value < 1) {
        button.dataset.icon = 'mute';
        button.dataset.l10nId = 'quick-settings-volumeButton-mute';
      } else {
        button.dataset.icon = 'sound-min';
        button.dataset.l10nId = 'quick-settings-volumeButton-min';
      }

      originalVolume = value > 0 ? value : originalVolume;
    }

    function onClick() {
      if (button.dataset.icon === 'mute') {
        window.navigator.mozSettings.createLock().set({'audio.volume.notification': originalVolume});
      } else {
        window.navigator.mozSettings.createLock().set({'audio.volume.notification': 0});
      }
    }

    button.dataset.icon = 'sound-max';
    // button.dataset.enabled = false;
    button.dataset.l10nId = 'quick-settings-volumeButton-max';
    button.addEventListener('click', onClick);

    SettingsListener.observe('audio.volume.notification', '', onVolumeChanged);
  }

  function initNfcButton(button) {

    function onNfcStatusChanged(status) {
      if (status === 'enabling' || status === 'enabled') {
        button.style.color = '#008EAB';
        button.dataset.enabled = true;
        button.dataset.l10nId = 'quick-settings-nfcButton-on';
      } else if (status === 'disabling' || status === 'disabled') {
        button.style.color = '';
        button.dataset.enabled = false;
        button.dataset.l10nId = 'quick-settings-nfcButton-off';
      }
    }

    function onClick() {
      if (button.dataset.enabled === 'true') {
        window.navigator.mozSettings.createLock().set({'nfc.enabled': false});
      } else {
        window.navigator.mozSettings.createLock().set({'nfc.enabled': true});
      }
    }

    button.dataset.icon = 'nfc';
    button.dataset.enabled = false;
    button.dataset.l10nId = 'quick-settings-nfcButton-off';
    button.addEventListener('click', onClick);

    SettingsListener.observe('nfc.status', undefined, onNfcStatusChanged);
  }

  function initFlashButton(button) {

    var options = {
      mode: 'video'
    };

    var cameraId = window.navigator.mozCameras.getListOfCameras()[0];
    var mozCamera;

    // need to check if the current app uses camera or not, show an error toast if yes

    // need to release camera when the screen is on after it went black

    // before getCamera, need to check if any app other than the current app occupies the camera,
    // release the camera if yes

    function onClick () {
      console.log('onClick', button.dataset.enabled);
      if (button.dataset.enabled === 'true') {
        console.log('release camera');
        mozCamera.release();

        button.dataset.icon = 'flash-off';
        button.dataset.enabled = false;
        button.dataset.l10nId = 'quick-settings-flashlightButton-off';
      } else {
        console.log('get camera');
        window.navigator.mozCameras.getCamera(cameraId, options)
        .then(function (result) {
          console.log('set flash on');
          mozCamera = result.camera;
          mozCamera.flashMode = 'torch';
        }, function (error) {
          console.log(error);
        }).catch(function (e) {
          console.log('catch', e);
        });

        button.dataset.icon = 'flash-on';
        button.dataset.enabled = true;
        button.dataset.l10nId = 'quick-settings-flashlightButton-on';
      }
    }

    button.dataset.icon = 'flash-off';
    button.dataset.enabled = false;
    button.dataset.l10nId = 'quick-settings-flashlightButton-off';
    button.addEventListener('click', onClick);
  }

  function initHotSpotButton(button) {

    function onHotSpotStatusChanged(status) {
      if (status === 'enabling' || status === 'enabled') {
        button.style.color = '#008EAB';
        button.dataset.enabled = true;
        button.dataset.l10nId = 'quick-settings-hotSpotButton-on';
      } else if (status === 'disabling' || status === 'disabled') {
        button.style.color = '';
        button.dataset.enabled = false;
        button.dataset.l10nId = 'quick-settings-hotSpotButton-off';
      }
    }

    function onClick() {
      if (button.dataset.enabled === 'true') {
        window.navigator.mozSettings.createLock().set({'tethering.wifi.enabled': false});
      } else {
        window.navigator.mozSettings.createLock().set({'tethering.wifi.enabled': true});
      }
    }

    button.dataset.icon = 'tethering';
    button.dataset.enabled = false;
    button.dataset.l10nId = 'quick-settings-hotspotButton-off';
    button.addEventListener('click', onClick);

    SettingsListener.observe('tethering.wifi.enabled', undefined, onHotSpotStatusChanged);
  }

}());
<|endoftext|>


<commit_before>(function() {
	"use strict";

	var app = angular.module("kanbanApp", [
		"ui.bootstrap",
		"ui.router",
		"kanbanModule",
		"logginModule",
		"aboutModule",
		"stateInfoModule",
		"angular-loading-bar"
	]);

	app.config(function($stateProvider, $urlRouterProvider) {
		$urlRouterProvider.otherwise("/loggin");
	});

	app.run(function($state, $rootScope) {
		$rootScope.endPoint = "http://localhost:8000/api";
		$rootScope.state = $state;
	});
})();
<commit_msg>remove authorization from chain to create user<commit_after>(function() {
	"use strict";

	var app = angular.module("kanbanApp", [
		"ui.bootstrap",
		"ui.router",
		"kanbanModule",
		"logginModule",
		"aboutModule",
		"stateInfoModule",
		"angular-loading-bar"
	]);

	app.config(function($stateProvider, $urlRouterProvider) {
		$urlRouterProvider.otherwise("/loggin");
	});

	app.run(function($state, $rootScope) {
		$rootScope.endPoint = "http://bigbangkanban.herokuapp.com/api";
		$rootScope.state = $state;
	});
})();
<|endoftext|>


<commit_before>/**
 *
 * @return {Function}
 * @type function
 * @constructor
 */
module.exports = (function SecureJSONLogic() {

    var self = this;

    var logicMethods = {
        /**
         * '=='
         * @param {Array.<{name: String, name: String}>} params array with param-objects, length=2
         * @param {{}} allowedVars
         */
        "==": function (params, allowedVars) {
            if (params.length == 2 &&
                self._paramParse(params[0], allowedVars) &&
                self._paramParse(params[1], allowedVars)
            ) {
                return self._paramParse(params[0], allowedVars) + '===' + self._paramParse(params[1], allowedVars);
            } else {
                return 'false';
            }
        },
        /**
         * true if param[] starts with param[1]
         * @param {Array.<{name: String, name: String}>} params array with param-objects, length=2
         * @param {{}} allowedVars
         */
        startswith: function (params, allowedVars) {
            if (params.length == 2 &&
                self._paramParse(params[0], allowedVars) &&
                self._paramParse(params[1], allowedVars)
            ) {
                return self._paramParse(params[0], allowedVars) + '.indexOf(' + self._paramParse(params[1], allowedVars) + ') === 0';
            } else {
                return 'false';
            }
        },
        /**
         * true if param[] starts with param[1]
         * @param {Array.<{name: String, name: String}>} params array with param-objects, length=2
         * @param {{}} allowedVars
         */
        endswith: function (params, allowedVars) {
            if (params.length == 2 &&
                self._paramParse(params[0], allowedVars) &&
                self._paramParse(params[1], allowedVars)
            ) {
                return self._paramParse(params[0], allowedVars) + '' +
                    '.substring(' + self._paramParse(params[0], allowedVars) + '.length' +
                    '-' + self._paramParse(params[1], allowedVars) + '.length,' +
                    ' ' + self._paramParse(params[0], allowedVars) + '.length' + ') === ' + self._paramParse(params[1], allowedVars);
            } else {
                return 'false';
            }
        }
    };

    /**
     * return the string which should be added to the if-code
     * @param {{type: String, name: String}} param
     * @param {String[]} allowedVars only vars contained in this array are allowed
     * @return {string|boolean}
     */
    self._paramParse = function (param, allowedVars) {
        param.type = param.type.toLowerCase();
        var isType = typeof param.name;

        switch (param.type) {
            case 'string':
                if (isType === "string") {
                    param.name = param.name.replace(/["']/g, '');
                    return '"' + param.name + '"';
                }
                break;

            case 'var':
                if (isType === "string") {
                    if (allowedVars.indexOf(param.name) > -1) {
                        return 'i.' + param.name;
                    } else {
                        return false;
                    }
                }
                break;

            case 'number':
                if (isType === "number") {
                    return param.name;
                }
                break;
        }

        return false;
    };

    /**
     * creates the code-string for the given logikObject
     * @param {{params: {}, fkt: String}} logikObj
     * @param {String[]} allowedVars only vars contained in this array are allowed
     * @return {String|boolean} string with logic-code or false if not parseable
     */
    self._makeCode = function (logikObj, allowedVars) {
        var ret = '(';

        if (!logikObj || !logikObj.fkt) {
            return false;
        }

        switch (logikObj.fkt) {
            case "&&":
                var ands = [];
                logikObj.params.forEach(function (lobj) {
                    var add = self._makeCode(lobj, allowedVars);
                    if (add) {
                        ands.push(add);
                    }
                });
                ret += ands.join(' && ');
                break;
            case "||":
                var ors = [];
                logikObj.params.forEach(function (lobj) {
                    var add = self._makeCode(lobj, allowedVars);
                    if (add) {
                        ors.push(add);
                    }
                });
                ret += ors.join(' || ');
                break;
            default:

                if (logicMethods[logikObj.fkt]) {
                    ret += logicMethods[logikObj.fkt](logikObj.params, allowedVars);
                } else {
                    return 'false';
                }
                break;
        }
        ret += ')';
        return ret;
    };

    /**
     * get the function
     * @param {{}} logikObject
     * @param {String[]} allowedVars only vars contained in this array are allowed
     * @return {function({Object})} returns function which needs an input-object with the logic-vars
     */
    self.makeFunction = function makeFunction(logikObject, allowedVars) {
        var logikString = self._makeCode(logikObject, allowedVars);

        var returnFkt = new Function();
        var evalCode = 'returnFkt=' +
            'function(i){' +
            '   try{' +
            '       if(' + logikString + '){return true;}' +
            '   }catch(e){' +
            '       ' +
            '   }' +
            '   return false;'+
            '}';

        //make function-code smaller
        evalCode = evalCode.replace(/\s+/g, ' ');
        evalCode = evalCode.replace(/\{ /g, '{');
        evalCode = evalCode.replace(/\} /g, '}');
        evalCode = evalCode.replace(/ && /g, '&&');
        evalCode = evalCode.replace(/ \=\=\= /g, '===');
        evalCode = evalCode.replace(/ \|\| /g, '||');
        try {
            eval(evalCode);
        } catch (e) {
            console.error('cant build logic-function of given logic-object');
            console.dir(e);
            var stack = new Error().stack;
            console.log(stack);
            console.log('++++++++++++++++++++++++++++++');
            console.log(evalCode);
            process.exit(1);
        }
        return returnFkt;
    };
    return self.makeFunction;
})();
<commit_msg>replace this to not conflikt with no-scope calls<commit_after>/**
 *
 * @return {Function}
 * @type function
 * @constructor
 */
module.exports = (function SecureJSONLogic() {

    var self = {};

    var logicMethods = {
        /**
         * '=='
         * @param {Array.<{name: String, name: String}>} params array with param-objects, length=2
         * @param {{}} allowedVars
         */
        "==": function (params, allowedVars) {
            if (params.length == 2 &&
                self._paramParse(params[0], allowedVars) &&
                self._paramParse(params[1], allowedVars)
            ) {
                return self._paramParse(params[0], allowedVars) + '===' + self._paramParse(params[1], allowedVars);
            } else {
                return 'false';
            }
        },
        /**
         * true if param[] starts with param[1]
         * @param {Array.<{name: String, name: String}>} params array with param-objects, length=2
         * @param {{}} allowedVars
         */
        startswith: function (params, allowedVars) {
            if (params.length == 2 &&
                self._paramParse(params[0], allowedVars) &&
                self._paramParse(params[1], allowedVars)
            ) {
                return self._paramParse(params[0], allowedVars) + '.indexOf(' + self._paramParse(params[1], allowedVars) + ') === 0';
            } else {
                return 'false';
            }
        },
        /**
         * true if param[] starts with param[1]
         * @param {Array.<{name: String, name: String}>} params array with param-objects, length=2
         * @param {{}} allowedVars
         */
        endswith: function (params, allowedVars) {
            if (params.length == 2 &&
                self._paramParse(params[0], allowedVars) &&
                self._paramParse(params[1], allowedVars)
            ) {
                return self._paramParse(params[0], allowedVars) + '' +
                    '.substring(' + self._paramParse(params[0], allowedVars) + '.length' +
                    '-' + self._paramParse(params[1], allowedVars) + '.length,' +
                    ' ' + self._paramParse(params[0], allowedVars) + '.length' + ') === ' + self._paramParse(params[1], allowedVars);
            } else {
                return 'false';
            }
        }
    };

    /**
     * return the string which should be added to the if-code
     * @param {{type: String, name: String}} param
     * @param {String[]} allowedVars only vars contained in this array are allowed
     * @return {string|boolean}
     */
    self._paramParse = function (param, allowedVars) {
        param.type = param.type.toLowerCase();
        var isType = typeof param.name;

        switch (param.type) {
            case 'string':
                if (isType === "string") {
                    param.name = param.name.replace(/["']/g, '');
                    return '"' + param.name + '"';
                }
                break;

            case 'var':
                if (isType === "string") {
                    if (allowedVars.indexOf(param.name) > -1) {
                        return 'i.' + param.name;
                    } else {
                        return false;
                    }
                }
                break;

            case 'number':
                if (isType === "number") {
                    return param.name;
                }
                break;
        }

        return false;
    };

    /**
     * creates the code-string for the given logikObject
     * @param {{params: {}, fkt: String}} logikObj
     * @param {String[]} allowedVars only vars contained in this array are allowed
     * @return {String|boolean} string with logic-code or false if not parseable
     */
    self._makeCode = function (logikObj, allowedVars) {
        var ret = '(';

        if (!logikObj || !logikObj.fkt) {
            return false;
        }

        switch (logikObj.fkt) {
            case "&&":
                var ands = [];
                logikObj.params.forEach(function (lobj) {
                    var add = self._makeCode(lobj, allowedVars);
                    if (add) {
                        ands.push(add);
                    }
                });
                ret += ands.join(' && ');
                break;
            case "||":
                var ors = [];
                logikObj.params.forEach(function (lobj) {
                    var add = self._makeCode(lobj, allowedVars);
                    if (add) {
                        ors.push(add);
                    }
                });
                ret += ors.join(' || ');
                break;
            default:

                if (logicMethods[logikObj.fkt]) {
                    ret += logicMethods[logikObj.fkt](logikObj.params, allowedVars);
                } else {
                    return 'false';
                }
                break;
        }
        ret += ')';
        return ret;
    };

    /**
     * get the function
     * @param {{}} logikObject
     * @param {String[]} allowedVars only vars contained in this array are allowed
     * @return {function({Object})} returns function which needs an input-object with the logic-vars
     */
    self.makeFunction = function makeFunction(logikObject, allowedVars) {
        var logikString = self._makeCode(logikObject, allowedVars);

        var returnFkt = new Function();
        var evalCode = 'returnFkt=' +
            'function(i){' +
            '   try{' +
            '       if(' + logikString + '){return true;}' +
            '   }catch(e){' +
            '       ' +
            '   }' +
            '   return false;'+
            '}';

        //make function-code smaller
        evalCode = evalCode.replace(/\s+/g, ' ');
        evalCode = evalCode.replace(/\{ /g, '{');
        evalCode = evalCode.replace(/\} /g, '}');
        evalCode = evalCode.replace(/ && /g, '&&');
        evalCode = evalCode.replace(/ \=\=\= /g, '===');
        evalCode = evalCode.replace(/ \|\| /g, '||');
        try {
            eval(evalCode);
        } catch (e) {
            console.error('cant build logic-function of given logic-object');
            console.dir(e);
            var stack = new Error().stack;
            console.log(stack);
            console.log('++++++++++++++++++++++++++++++');
            console.log(evalCode);
            process.exit(1);
        }
        return returnFkt;
    };
    return self.makeFunction;
})();
<|endoftext|>


<commit_before>'use strict';

const path = require('path');

function createPattern(path) {
    return {
        pattern: path,
        included: true,
        served: true,
        watched: false
    };
}

function initLoud(files) {
    let resolvedPath = path.dirname(require.resolve('loud'));
    let distPath = path.join(resolvedPath, '../dist');

    files.unshift(createPattern(path.join(distPath, 'loud.js')));
}

initLoud.$inject = ['config.files'];

module.exports = {
    'framework:loud': ['factory', initLoud]
};
<commit_msg>Refactor code<commit_after>'use strict';

const path = require('path');

function createPattern(path) {
    return {
        pattern: path,
        included: true,
        served: true,
        watched: false
    };
}

function initLoud(files) {
    const resolvedPath = path.dirname(require.resolve('loud'));
    const distPath = path.join(resolvedPath, '../dist');

    files.unshift(createPattern(path.join(distPath, 'loud.js')));
}

initLoud.$inject = ['config.files'];

module.exports = {
    'framework:loud': ['factory', initLoud]
};
<|endoftext|>


<commit_before>/**
 * A very very small http server.
 */
var http = require('http');
var parseUrl = require('url').parse;
var domain = require('domain');

function default404(req, res) {
    res.writeHead(404);
    res.end('Oops, 404 not found.');
}

var exports = module.exports = function(routes) {
    routes = routes || {};
    var regexRoutes = [];
    process.nextTick(function(){
            // init routes and regexRoutes
            for(var key in routes) {
                addRegexRoute(key, routes[key]);
            }
    })

    for(var key in routes) {
        // if not "get:/foo/bar" but "/foo/bar"
        if(!/\w+:.*/.test(key)) {
            var fn = routes[key];
            delete routes[key];
            key = 'get:'+key;
            routes[key] = fn;
        }
    }

    function addRegexRoute(key, fn) {
        if(~key.indexOf('*') || ~key.indexOf('/:')) {
            // /foo/*
            // /foo/:bar
            var names = [];
            var regex = key.replace(/\/(?:([^:\/]+)|\:([^\/]+))/g, function(full, normal, name){
                    if(normal) return full;
                    names.push(name);
                    return '/(.+?)';
            }).replace(/\*/g, '(.*?)').replace(/\//g, '\\/');
            regexRoutes.push([new RegExp('^' + regex + '$'), names, fn]);
            delete routes[key];
        } else {
            // post:/foo/bar
            if(/\/$/.test(key)) {
                routes[key.replace(/\/$/, '')] = fn;
            } else {
                routes[key + '/'] = fn;
            }
        }
    }

    function defineRoute(method, path, fn) {
        var key = method + ':' + path;
        routes[key] = fn;
        addRegexRoute(key, fn);
    }

    function matchRegexRoutes(key, req){
        for (var i = 0, l = regexRoutes.length; i < l; i ++) {
            var v = regexRoutes[i];
            var match = key.match(v[0])
              , names = v[1]
              ;
            if(match) {
                req.params = {};
                for (var j = 1, l = match.length; j < l; j ++) {
                    var name = names[j - 1];
                    var str = match[j];
                    req.params[j] = str;
                    if(name) req.params[name] = str;
                }
                return v[2];
            }
        }
    }

    var beforeHandler, afterHandler;
    var server = http.createServer(function(req, res) {
        var d = domain.create();
        d.on('error', function(err) {
            server.emit('domainError', err, req, res);
        })
        d.add(req);
        d.add(res);
        d.run(function() {
            var method = req.method.toLowerCase();
            var urlinfo = parseUrl(req.url, true);
            req.urlinfo = urlinfo;
            beforeHandler && beforeHandler(req, res);
            afterHandler && res.on('finish', function(){
                afterHandler(req, res);
            });
            var key = method + ':' + urlinfo.pathname;
            var route = routes[key] || matchRegexRoutes(key, req) || routes['404'] || default404;
            route(req, res);
        })
    });

    server.before = function(_beforeHandler) {
        beforeHandler = _beforeHandler;
        return server;
    }

    server.after = function (_afterHandler) {
        afterHandler = _afterHandler;
        return server;
    }
    ;[
        'acl'
      , 'aseline-control'
      , 'checkin'
      , 'checkout'
      , 'connect'
      , 'copy'
      , 'delete'
      , 'get'
      , 'head'
      , 'label'
      , 'lock'
      , 'merge'
      , 'mkactivity'
      , 'mkcol'
      , 'mkworkspace'
      , 'move'
      , 'options'
      , 'orderpatch'
      , 'patch'
      , 'post'
      , 'propfind'
      , 'proppatch'
      , 'put'
      , 'report'
      , 'search'
      , 'trace'
      , 'uncheckout'
      , 'unlock'
      , 'update'
      , 'version-control'].forEach(function(verb) {
            server[verb] = function(path, fn) {
                defineRoute(verb, path, fn);
                return server;
            }
    });
    return server;
}
// req.urlinfo  see url.parse
// magic code
exports.req = http.IncomingMessage.prototype;
exports.res = http.ServerResponse.prototype;
exports.mock = function() {
    var mock = require('./mock');
    exports.req = mock.MockRequest.prototype;
    exports.res = mock.MockResponse.prototype;
    return mock;
}

<commit_msg>add req.query<commit_after>/**
 * A very very small http server.
 */
var http = require('http');
var parseUrl = require('url').parse;
var domain = require('domain');

function default404(req, res) {
    res.writeHead(404);
    res.end('Oops, 404 not found.');
}

var exports = module.exports = function(routes) {
    routes = routes || {};
    var regexRoutes = [];
    process.nextTick(function(){
            // init routes and regexRoutes
            for(var key in routes) {
                addRegexRoute(key, routes[key]);
            }
    })

    for(var key in routes) {
        // if not "get:/foo/bar" but "/foo/bar"
        if(!/\w+:.*/.test(key)) {
            var fn = routes[key];
            delete routes[key];
            key = 'get:'+key;
            routes[key] = fn;
        }
    }

    function addRegexRoute(key, fn) {
        if(~key.indexOf('*') || ~key.indexOf('/:')) {
            // /foo/*
            // /foo/:bar
            var names = [];
            var regex = key.replace(/\/(?:([^:\/]+)|\:([^\/]+))/g, function(full, normal, name){
                    if(normal) return full;
                    names.push(name);
                    return '/(.+?)';
            }).replace(/\*/g, '(.*?)').replace(/\//g, '\\/');
            regexRoutes.push([new RegExp('^' + regex + '$'), names, fn]);
            delete routes[key];
        } else {
            // post:/foo/bar
            if(/\/$/.test(key)) {
                routes[key.replace(/\/$/, '')] = fn;
            } else {
                routes[key + '/'] = fn;
            }
        }
    }

    function defineRoute(method, path, fn) {
        var key = method + ':' + path;
        routes[key] = fn;
        addRegexRoute(key, fn);
    }

    function matchRegexRoutes(key, req){
        for (var i = 0, l = regexRoutes.length; i < l; i ++) {
            var v = regexRoutes[i];
            var match = key.match(v[0])
              , names = v[1]
              ;
            if(match) {
                req.params = {};
                for (var j = 1, l = match.length; j < l; j ++) {
                    var name = names[j - 1];
                    var str = match[j];
                    req.params[j] = str;
                    if(name) req.params[name] = str;
                }
                return v[2];
            }
        }
    }

    var beforeHandler, afterHandler;
    var server = http.createServer(function(req, res) {
        var d = domain.create();
        d.on('error', function(err) {
            server.emit('domainError', err, req, res);
        })
        d.add(req);
        d.add(res);
        d.run(function() {
            var method = req.method.toLowerCase();
            var urlinfo = parseUrl(req.url, true);
            req.query = urlinfo.query;
            req.urlinfo = urlinfo;
            beforeHandler && beforeHandler(req, res);
            afterHandler && res.on('finish', function(){
                afterHandler(req, res);
            });
            var key = method + ':' + urlinfo.pathname;
            var route = routes[key] || matchRegexRoutes(key, req) || routes['404'] || default404;
            route(req, res);
        })
    });

    server.before = function(_beforeHandler) {
        beforeHandler = _beforeHandler;
        return server;
    }

    server.after = function (_afterHandler) {
        afterHandler = _afterHandler;
        return server;
    }
    ;[
        'acl'
      , 'aseline-control'
      , 'checkin'
      , 'checkout'
      , 'connect'
      , 'copy'
      , 'delete'
      , 'get'
      , 'head'
      , 'label'
      , 'lock'
      , 'merge'
      , 'mkactivity'
      , 'mkcol'
      , 'mkworkspace'
      , 'move'
      , 'options'
      , 'orderpatch'
      , 'patch'
      , 'post'
      , 'propfind'
      , 'proppatch'
      , 'put'
      , 'report'
      , 'search'
      , 'trace'
      , 'uncheckout'
      , 'unlock'
      , 'update'
      , 'version-control'].forEach(function(verb) {
            server[verb] = function(path, fn) {
                defineRoute(verb, path, fn);
                return server;
            }
    });
    return server;
}
// req.urlinfo  see url.parse
// magic code
exports.req = http.IncomingMessage.prototype;
exports.res = http.ServerResponse.prototype;
exports.mock = function() {
    var mock = require('./mock');
    exports.req = mock.MockRequest.prototype;
    exports.res = mock.MockResponse.prototype;
    return mock;
}

<|endoftext|>


<commit_before>/*
 * Copyright 2017 Nicolas Lochet Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and limitations under the License.
 */

module.exports = (function() {
  'use strict'
  var Store = require('wool-store')

  function Rule(r, s) {
    if (! (this instanceof Rule)) return new Rule(r, s)
    this.rules = r.reduce(function(p, c) {
      var x = p[c.n] = {}
      x.n = c.n
      x.p = c.p
      if ('c' in c) { x.c = c.c.bind(this) }
      x.o = c.o.bind(this)
      return p
    }.bind(this), {})
    this.store = s || Store()
  }
  Rule.prototype.push = function(cmd, cb) {
    var rule = this.rules[cmd.n]
    if ('c' in rule) {
      return rule.c(cmd.d, function(err) {
        if (err) return cb(err)
        else try {
          return this.execute(rule, cmd, cb)
        } catch (e) {
          return cb(e)
        }
      }.bind(this))
    } else {
      return this.execute(rule, cmd, cb)
    }
  }
  Rule.prototype.execute = function(rule, cmd, cb) {
    return rule.o(cmd.d, function(err, data) {
      if (err) return cb(err)
      else try {
        return cb(err, data)
      } catch (e) {
        return cb(e)
      }
    }.bind(this))
  }
  Rule.prototype.get = function(id) {
    return this.store.get(id)
  }
  Rule.prototype.create = function(f, data, cb) {
    try {
      var newId = Store.newId()
        , id = ((typeof f === 'function') ? f(newId) : ((typeof f === 'string') ? f+newId : newId))
      this.store.set(id, data)
      cb()
    } catch(e) {
      cb(e)
    }
  }
  Rule.prototype.update = function(id, data, cb) {
    try {
      this.store.set(id, data)
      cb()
    } catch(e) {
      cb(e)
    }
  }
  Rule.prototype.remove = function(id, cb) {
    try {
      this.store.del(id)
      cb()
    } catch(e) {
      cb(e)
    }
  }
  return Rule
}())
<commit_msg>add time to rules<commit_after>/*
 * Copyright 2017 Nicolas Lochet Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and limitations under the License.
 */

module.exports = (function() {
  'use strict'
  var Store = require('wool-store')

  function Rule(r, s) {
    if (! (this instanceof Rule)) return new Rule(r, s)
    this.rules = r.reduce(function(p, c) {
      var x = p[c.n] = {}
      x.n = c.n
      x.p = c.p
      if ('c' in c) { x.c = c.c.bind(this) }
      x.o = c.o.bind(this)
      return p
    }.bind(this), {})
    this.store = s || Store()
  }
  Rule.prototype.push = function(cmd, cb) {
    var rule = this.rules[cmd.n]
    if ('c' in rule) {
      return rule.c(cmd.t, cmd.d, function(err) {
        if (err) return cb(err)
        else try {
          return this.execute(rule, cmd, cb)
        } catch (e) {
          return cb(e)
        }
      }.bind(this))
    } else {
      return this.execute(rule, cmd, cb)
    }
  }
  Rule.prototype.execute = function(rule, cmd, cb) {
    return rule.o(cmd.t, cmd.d, function(err, data) {
      if (err) return cb(err)
      else try {
        return cb(err, data)
      } catch (e) {
        return cb(e)
      }
    }.bind(this))
  }
  Rule.prototype.get = function(id) {
    return this.store.get(id)
  }
  Rule.prototype.create = function(f, data, cb) {
    try {
      var newId = Store.newId()
        , id = ((typeof f === 'function') ? f(newId) : ((typeof f === 'string') ? f+newId : newId))
      this.store.set(id, data)
      cb()
    } catch(e) {
      cb(e)
    }
  }
  Rule.prototype.update = function(id, data, cb) {
    try {
      this.store.set(id, data)
      cb()
    } catch(e) {
      cb(e)
    }
  }
  Rule.prototype.remove = function(id, cb) {
    try {
      this.store.del(id)
      cb()
    } catch(e) {
      cb(e)
    }
  }
  return Rule
}())
<|endoftext|>


<commit_before>var Botkit = require('botkit')
var Witbot = require('witbot')
var dateFormat = require('dateformat');

var slackToken = process.env.SLACK_TOKEN
var witToken = process.env.WIT_TOKEN
var openWeatherApiKey = process.env.OPENWEATHER_KEY
var qpxApiKey = process.env.QPXKEY
var amazonApiId = process.env.AMAZONAPIID
var amazonSecret = process.env.AMAZONSECRET
var amazonTag = process.env.AMAZONTAG

var controller = Botkit.slackbot({
  debug: false
})

controller.spawn({
  token: slackToken
}).startRTM(function (err, bot, payload) {
  if (err) {
    throw new Error('Error connecting to slack: ', err)
  }
  console.log('Connected to slack')
})

var witbot = Witbot(witToken)
var wit;
var weather = require('./weather')(openWeatherApiKey)
var jokes = require('./jokes')()
var flights = require('./flights')(qpxApiKey)
var amazon = require('./amazon')(amazonApiId, amazonSecret, amazonTag)

controller.hears('.*', 'direct_message,direct_mention', function (bot, message) {
  var wit = witbot.process(message.text, bot, message)

  wit.hears('hello',0.5, function(bot, message, outcome) {
    bot.reply(message, '> Greetings human! \n> :robot_face: :wave:')
  })

  wit.hears('purpose',0.5, function(bot, message, outcome) {
    bot.reply(message, '> 42')
  })

  wit.hears('how_are_you',0.5, function(bot, message, outcome) {
    bot.reply(message, "> I\'m a bot. I\'m doing as well as could be expected. \n> ¯\\_(ツ)_/¯")
  })

  wit.hears('help',0.5, function(bot, message, outcome) {
    bot.reply(message, "> :partly_sunny_rain: I can give you the weather\n> :money_with_wings: I can help you buy things\n> :airplane: I can search for one-way flights\n> :face_with_rolling_eyes: Oh, and I can tell pretty terrible jokes")
  })

  wit.hears('thanks',0.5, function(bot, message, outcome) {
    bot.reply(message, "> Where's the blushing bot emoji when you need it...")
  })

  wit.hears('love',0.5, function(bot, message, outcome) {
    bot.reply(message, "> Right, right now... up the butt :point_right::ok_hand:")
  })

  wit.hears('humanity',0.5, function(bot, message, outcome) {
    bot.reply(message, "> What does it really mean to be human?")
  })

  wit.hears('name',0.5, function(bot, message, outcome) {
    bot.reply(message, "> My name is Reverend Dr. Raymond Arther James III, Esquire")
  })

  wit.hears('joke',0.5, function(bot, message, outcome) {
    jokes.get(function(error, msg) {
      bot.reply(message, msg)
    })
  })

  wit.hears('amazon',0.5, function(bot, message, outcome) {
    if (!outcome.entities.object[0].value) {
      bot.reply(message, "> :money_with_wings:Whachu tryna buy?")
      return
    }
    console.log(outcome.entities.object[0].value)
    var item = outcome.entities.object[0].value;

    bot.reply(message, '> :mag:*' + item + '* coming right up...')
    amazon.get(item, function(error, msg) {
      bot.reply(message, msg)
    })

  })

  wit.hears('flight',0.5, function(bot, message, outcome) {
    if (!outcome.entities.origin || !outcome.entities.destination || !outcome.entities.datetime) {
      bot.reply(message,"> I can't read your mind! I need an origin, a destination and a date!");
      return
    }
    console.log('getting flight info: ' + outcome.entities.origin[0].value + ' - ' + outcome.entities.destination[0].value + ' - ' + outcome.entities.datetime[0].value)
    var origin = outcome.entities.origin[0].value.toUpperCase()
    var destination = outcome.entities.destination[0].value.toUpperCase()
    var dateObj = new Date(outcome.entities.datetime[0].value)
    date = dateFormat(dateObj, "isoDate");

    if (origin.length !== 3 || destination.length !== 3) {
      bot.reply(message,"> I only work with 3 letter airport codes for now");
      return
    }

    flights.get(origin, destination, date, function(error, msg) {
      bot.reply(message, msg)
    })
  })

  wit.hears('weather',0.5, function(bot, message, outcome) {
    console.log('asking for weather from: ' + outcome.entities.location)
    if(!outcome.entities.location || outcome.entities.location.length == 0) {
      bot.reply(message,"> I'm a bot, not a psychic. I need your location first...");
      return
    }
    var location = outcome.entities.location[0].value
    weather.get(location, function(error, msg) {
      if (error) {
        console.log(error)
        bot.reply(message, "> Beep boop pssskt  :boom:")
        return
      }
      bot.reply(message, msg)
    })
  })

  wit.otherwise(function (outcome) {
    bot.reply(message, "> Beep boop pssskt  :boom: I am a weather, one-way flight and joke bot \n> But I learn from every interaction... unlike most humans");
  })
})

/*
controller.hears('.*', 'direct_message,direct_mention', function(bot,message) {
  witbot.process(message.text, bot, message)
  //bot.reply(message,message.text)
  console.log('heard something: ', message.text)
})

//when witbot hears a hello above .5

*/
<commit_msg>amazon error handling<commit_after>var Botkit = require('botkit')
var Witbot = require('witbot')
var dateFormat = require('dateformat');

var slackToken = process.env.SLACK_TOKEN
var witToken = process.env.WIT_TOKEN
var openWeatherApiKey = process.env.OPENWEATHER_KEY
var qpxApiKey = process.env.QPXKEY
var amazonApiId = process.env.AMAZONAPIID
var amazonSecret = process.env.AMAZONSECRET
var amazonTag = process.env.AMAZONTAG

var controller = Botkit.slackbot({
  debug: false
})

controller.spawn({
  token: slackToken
}).startRTM(function (err, bot, payload) {
  if (err) {
    throw new Error('Error connecting to slack: ', err)
  }
  console.log('Connected to slack')
})

var witbot = Witbot(witToken)
var wit;
var weather = require('./weather')(openWeatherApiKey)
var jokes = require('./jokes')()
var flights = require('./flights')(qpxApiKey)
var amazon = require('./amazon')(amazonApiId, amazonSecret, amazonTag)

controller.hears('.*', 'direct_message,direct_mention', function (bot, message) {
  var wit = witbot.process(message.text, bot, message)

  wit.hears('hello',0.5, function(bot, message, outcome) {
    bot.reply(message, '> Greetings human! \n> :robot_face: :wave:')
  })

  wit.hears('purpose',0.5, function(bot, message, outcome) {
    bot.reply(message, '> 42')
  })

  wit.hears('how_are_you',0.5, function(bot, message, outcome) {
    bot.reply(message, "> I\'m a bot. I\'m doing as well as could be expected. \n> ¯\\_(ツ)_/¯")
  })

  wit.hears('help',0.5, function(bot, message, outcome) {
    bot.reply(message, "> :partly_sunny_rain: I can give you the weather\n> :money_with_wings: I can help you buy things\n> :airplane: I can search for one-way flights\n> :face_with_rolling_eyes: Oh, and I can tell pretty terrible jokes")
  })

  wit.hears('thanks',0.5, function(bot, message, outcome) {
    bot.reply(message, "> Where's the blushing bot emoji when you need it...")
  })

  wit.hears('love',0.5, function(bot, message, outcome) {
    bot.reply(message, "> Right, right now... up the butt :point_right::ok_hand:")
  })

  wit.hears('humanity',0.5, function(bot, message, outcome) {
    bot.reply(message, "> What does it really mean to be human?")
  })

  wit.hears('name',0.5, function(bot, message, outcome) {
    bot.reply(message, "> My name is Reverend Dr. Raymond Arther James III, Esquire")
  })

  wit.hears('joke',0.5, function(bot, message, outcome) {
    jokes.get(function(error, msg) {
      bot.reply(message, msg)
    })
  })

  wit.hears('amazon',0.5, function(bot, message, outcome) {
    if (outcome.entities.object[0].value === undefined) {
      bot.reply(message, "> :money_with_wings:Whachu tryna buy?")
      return
    }
    console.log(outcome.entities.object[0].value)
    var item = outcome.entities.object[0].value;

    bot.reply(message, '> :mag:*' + item + '* coming right up...')
    amazon.get(item, function(error, msg) {
      bot.reply(message, msg)
    })

  })

  wit.hears('flight',0.5, function(bot, message, outcome) {
    if (!outcome.entities.origin || !outcome.entities.destination || !outcome.entities.datetime) {
      bot.reply(message,"> I can't read your mind! I need an origin, a destination and a date!");
      return
    }
    console.log('getting flight info: ' + outcome.entities.origin[0].value + ' - ' + outcome.entities.destination[0].value + ' - ' + outcome.entities.datetime[0].value)
    var origin = outcome.entities.origin[0].value.toUpperCase()
    var destination = outcome.entities.destination[0].value.toUpperCase()
    var dateObj = new Date(outcome.entities.datetime[0].value)
    date = dateFormat(dateObj, "isoDate");

    if (origin.length !== 3 || destination.length !== 3) {
      bot.reply(message,"> I only work with 3 letter airport codes for now");
      return
    }

    flights.get(origin, destination, date, function(error, msg) {
      bot.reply(message, msg)
    })
  })

  wit.hears('weather',0.5, function(bot, message, outcome) {
    console.log('asking for weather from: ' + outcome.entities.location)
    if(!outcome.entities.location || outcome.entities.location.length == 0) {
      bot.reply(message,"> I'm a bot, not a psychic. I need your location first...");
      return
    }
    var location = outcome.entities.location[0].value
    weather.get(location, function(error, msg) {
      if (error) {
        console.log(error)
        bot.reply(message, "> Beep boop pssskt  :boom:")
        return
      }
      bot.reply(message, msg)
    })
  })

  wit.otherwise(function (outcome) {
    bot.reply(message, "> Beep boop pssskt  :boom: I am a weather, one-way flight and joke bot \n> But I learn from every interaction... unlike most humans");
  })
})

/*
controller.hears('.*', 'direct_message,direct_mention', function(bot,message) {
  witbot.process(message.text, bot, message)
  //bot.reply(message,message.text)
  console.log('heard something: ', message.text)
})

//when witbot hears a hello above .5

*/
<|endoftext|>


<commit_before>!function(obj) {
  if (typeof module !== 'undefined')
    module.exports = obj;
  else
    window.vixen = obj;
}(function() {
  var pattern = /\{\{.+?\}\}/g,
      expr = /'.*?'\s*|[^ ]+\s*/g,
      forExpr = /^\s*(?:([^\s]+?)\s*:\s*)?([^\s]+?)\s+in\s+([^\s]+?)(?:\s+do\s+([^\s]+))?\s*$/,
      builtins = {
        '|': function(a, b) { return b(a); },
        '+': function(a, b) { return a + b; },
        '-': function(a, b) { return a - b; },
        '*': function(a, b) { return a * b; },
        '/': function(a, b) { return a / b; },
        '%': function(a, b) { return a % b; },
        'is': function(a, b) { return a == b; },
        'isnt': function(a, b) { return a != b; },
        'then': function(a, b) { return a ? b : a; },
        'else': function(a, b) { return a ? a : b; }
      },
      keys = Object.keys;

  function trim(str) {return String.prototype.trim.call(str);};

  function resolveProp(obj, name) {
    var name = name.trim(), n;
    if (name[0] === "'") return name.slice(1,-1);
    if (!isNaN(n = parseFloat(name))) return n;
    return name.split('.').reduce(function(p, prop) {
      return p ? p[prop] : undefined;
    }, obj);
  }

  function bucket(b, k, v) {
    if (!(k in b)) b[k] = [];
    if (b[k].indexOf(v) === -1) b[k].push(v);
  }

  function extend(orig, obj) {
    Object.keys(obj).forEach(function(prop) {
      orig[prop] = obj[prop];
    });
    return orig;
  }

  function traverseElements(el, callback) {
    var i;
    if (callback(el) !== false) for(i = el.children.length; i--;)
      traverseElements(el.children[i], callback);
  }

  function createProxy(maps, proxy) {
    proxy = proxy || {};
    proxy.extend = proxy.$extend = function(obj) {
      var toRender = {}, rid;
      Object.keys(obj).forEach(function(prop) {
        maps.orig[prop] = obj[prop];
        if (maps.binds[prop]) maps.binds[prop].forEach(function(rid) {
          if (rid >= 0) toRender[rid] = null;
        });
      });
      for (renderId in toRender) maps.renders[renderId](maps.orig);
      return proxy;
    };
    proxy.$splice = function(prop, start, end) {
      if (arguments.length < 2) return [];
      var list = resolveProp(maps.orig, prop),
          middle, args, res;
      if (!list) return;
      args = [].slice.call(arguments, 1);
      middle = Math.max(0, args.length-2);
      res = list.splice.apply(list, args);
      maps.binds[prop].forEach(function(rId) {
        if (rId < 0) return;
        var render = maps.renders[rId];
        if (render.splice) render.splice(start, end, middle);
      });
      return res;
    };
    proxy.$push = function(prop) {
      var list = resolveProp(maps.orig, prop),
          items = [].slice.call(arguments, 1);
      proxy.$splice.apply(proxy, [prop, list.length, 0].concat(items));
      return list.length;
    };
    proxy.$unshift = function(prop, item) {
      var list = resolveProp(maps.orig, prop);
      proxy.$splice(prop, 0, 0, item);
      return list.length;
    };
    proxy.$replace = function(prop, a, b) {
      var list = resolveProp(maps.orig, prop);
      proxy.$splice(prop, list.indexOf(a), 1, b || a);
      return a;
    };

    Object.keys(maps.binds).forEach(function(prop) {
      var ids = maps.binds[prop];
      Object.defineProperty(proxy, prop, {
        set: function(value) {
          maps.orig[prop] = value;
          ids.forEach(function(renderId) {
            if (renderId >= 0) maps.renders[renderId](maps.orig);
          });
        },
        get: function() {
          if (maps.rebinds[prop])
            return maps.rebinds[prop]();
          return maps.orig[prop];
        }
      });
    });
    return proxy;
  }

  function vixen(builtins, el, model) {
    function resolveInFix(obj, props) {
      var p = resolveProp(obj, props[0]), i, len, prop, infix;
      for (i=1, len=props.length; i<len; i+=2) {
        prop = props[i].trim();
        infix = builtins[prop] || resolveProp(obj, prop);
        p = infix(p, resolveProp(obj, props[i+1]));
      }
      return p;
    }

    function resolve(orig, prop) {
      if (!orig) return '';
      var val = resolveInFix(orig, prop.slice(2,-2).match(expr));
      return val === undefined ? '' : val;
    }

    function strTmpl(str, orig) {
      return str.replace(pattern, resolve.bind(undefined, orig));
    }

    function match(str) {
      var m = str.match(pattern);
      if (m) return m.map(function(chain) {
        return chain.slice(2, -2).match(expr).map(trim);
      });
    }

    function traverse(el, orig) {
      var binds = {},
          rebinds = {},
          renders = {},
          count = 0;

      function bindRenders(chains, renderId) {
        // Create property to render mapping
        chains.forEach(function(chain) {
          // Register all chaining functions as binds.
          chain.forEach(function(prop) {
            if (builtins[prop] || prop[0] === "'" || !isNaN(prop)) return;
            bucket(binds, prop.split('.')[0], renderId);
          });
        });
      }

      function parseIterator(el) {
        var nodes = [], marker, key, forStr;
        if (parent_ = (el.parentElement || el.parentNode)) {
          forStr = el.getAttribute('vx-for');
          if (el.tagName === 'VX') {
            marker = el.ownerDocument.createTextNode('');
            parent_.replaceChild(marker, el);
          } else if (forStr) {
            parent_ = el;
            nodes = Array.prototype.slice.call(el.childNodes);
            marker = el.ownerDocument.createTextNode('');
            parent_.appendChild(marker);
          } else return;
          if (m = forExpr.exec(forStr))
            return {
              key: m[1], alias: m[2], prop: m[3], each: m[4], nodes: nodes,
              parent: parent_, marker: marker
            };
          else throw "\"" + forStr + "\" is not a valid vx-for expression";
        }
      }

      function mapAttribute(owner, attr) {
        var name, eventId, renderId, str, noTmpl;
        if ((str = attr.value) && (chains = match(str))) {
          name = attr.name;
          if (name.indexOf('vx-') === 0) {
            owner.removeAttribute(name);
            name = name.substr(3);
          }
          if (name.indexOf('on') === 0) {
            eventName = name.substr(2);
            // Add event listeners
            chains.forEach(function(chain) {
              var cb;
              (renders[renderId=count++] = function(orig) {
                var args = chain.map(resolveProp.bind(null, orig));
                // Multi parameter space syntax
                cb = function(evt) {
                  return args[0].apply(owner, [evt].concat(args.slice(1)));
                };
              })(orig);
              owner.addEventListener(eventName, function(e) { cb(e); });
              bindRenders([chain], renderId);
            });
            owner.removeAttribute(name);
          } else {
            noTmpl = chains.length === 1 && str.substr(0,1) === '{' &&
              str.substr(-1) === '}';
            // Create rendering function for attribute.
            (renders[renderId=count++] = function(orig, clear) {
              var val = noTmpl ? resolve(orig, str) : strTmpl(str, orig);
              !clear && name in owner ? owner[name] = val :
                owner.setAttribute(name, val);
            })(orig, true);
            // Bi-directional coupling.
            if (noTmpl && chains[0].length === 1)
              rebinds[chains[0][0]] = function() {
                // TODO: Getting f.ex. 'value' attribute from an input
                // doesn't return user input value so accessing element
                // object properties directly, find out how to do this
                // more securely.
                return name in owner ?
                  owner[name] : owner.getAttribute(name);
              };
            bindRenders(chains, renderId);
          }
        }
      }

      function mapTextNodes(el) {
        for (var i = el.childNodes.length; i--;) (function(node) {
          var str, renderId, chains;
          if (node.nodeType === el.TEXT_NODE && (str = node.nodeValue) &&
              (chains = match(str))) {
            // Create rendering function for element text node.
            renderId = count++;
            (renders[renderId] = function(orig) {
              node.nodeValue = strTmpl(str, orig);
            })(orig);
            bindRenders(chains, renderId);
          }
        })(el.childNodes[i]);
      }

      // Remove no-traverse attribute if root node
      el.removeAttribute('vx-subview');

      traverseElements(el, function(el_) {
        var i, iter, template, renderId, insertNodes, subproxies, addkv,
            qmatch, qp, splice, removeNodes;

        // Stop handling and recursion if subview.
        if (el_.getAttribute('vx-subview') !== null) return false;

        if (iter = parseIterator(el_)) {
          subproxies = [];
          template = el_.cloneNode(true);
          renderId = count++;
          qmatch = {};
          match(template.innerHTML).forEach(function(c) {
            c.forEach(function(p) { qmatch[p.split('.')[0]] = true; });
          });
          addkv = function(orig, k, v) {
            if (iter.key) orig[iter.key] = k;
            orig[iter.alias] = v;
            return orig;
          };

          for (i=iter.nodes.length; i--;)
            iter.parent.removeChild(iter.nodes[i]);

          insertNodes = function insertNodes(orig, each, marker) {
            var clone = template.cloneNode(true),
                subproxy = createProxy(traverse(clone, orig)),
                nodes = Array.prototype.slice.call(clone.childNodes);
            for (i=0, len=nodes.length; i<len; i++)
              iter.parent.insertBefore(nodes[i], marker || iter.marker);
            if (each) each(nodes);
            subproxy.__nodes = nodes;
            return subproxy;
          };
          removeNodes = function removeNodes(sp) {
            var nodes = sp.__nodes, i;
            for (i=nodes.length; i--;) iter.parent.removeChild(nodes[i]);
          };

          splice = function splice(orig, ext, start, end, middle) {
            var list = resolveProp(orig, iter.prop),
                each = iter.each && resolveProp(orig, iter.each),
                splen = subproxies.length,
                ks, klen, i, i_, len, item, sp, spn, k, orig_;
            if (start == null) start = 0;
            if (end == null || isNaN(end)) end = splen;
            if (list) klen = (ks=keys(list), ks.length);
            if (middle == null || isNaN(middle)) middle = klen || 0;
            if (klen) {
              for (i=start; i<middle; i++) {
                item = list[k=ks[i]];
                if (i < splen && i < end) {
                  subproxies[i].extend(addkv(ext||{}, k, item));
                } else {
                  subproxies.splice(i, 0, insertNodes(addkv(ext||orig, k, item),
                    each && each.bind(null, item, k),
                    subproxies[i] && subproxies[i].__nodes[0]));
                }
              }
            }
            sps = subproxies.splice(middle, end-middle);
            for (i=0, len=sps.length; i<len; i++) removeNodes(sps[i]);
            if (ks && iter.key) for (i=middle, len=subproxies.length; i<len; i++)
              subproxies[i].extend((orig_={}, orig_[iter.key]=ks[i], orig_));
          };

          (renders[renderId] = splice)(orig);
          splice.splice = function(start, end, middle) {
            splice(orig, undefined, start, end+start, middle+start);
          };
          bucket(binds, iter.prop.split('.')[0], renderId);
          keys(qmatch).forEach(function(qp) {
            if (iter.alias !== qp && iter.key !== qp) {
              renders[renderId = count++] = function(orig) {
                var ext = {};
                ext[qp] = resolveProp(orig, qp);
                splice(orig, ext);
              };
              bucket(binds, qp, renderId);
            }
          });
        } else {
          // Bind node text.
          mapTextNodes(el_);
        }
        // Bind node attributes if not a <vx>.
        if (el_.tagName !== 'VX') for (i = el_.attributes.length; i--;)
          mapAttribute(el_, el_.attributes[i]);
        // Stop recursion if iterator.
        return !iter;
      });
      return {orig:orig, binds:binds, rebinds:rebinds, renders:renders};
    }
    return createProxy(traverse(el, extend({}, model || {})), model);
  }

  function factory() {
    var builtins_ = (arguments.length ? [].slice.call(arguments) : [builtins])
          .reduce(function(p, c) { return extend(p, c); }, {}),
        vixen_ = vixen.bind(null, builtins_);
    vixen_.builtins = builtins_;
    vixen_.factory = factory;
    return vixen_;
  }

  return factory();
}());
<commit_msg>Fixed problem with attributes not beeing updated when a DOM object a property with the same name<commit_after>!function(obj) {
  if (typeof module !== 'undefined')
    module.exports = obj;
  else
    window.vixen = obj;
}(function() {
  var pattern = /\{\{.+?\}\}/g,
      expr = /'.*?'\s*|[^ ]+\s*/g,
      forExpr = /^\s*(?:([^\s]+?)\s*:\s*)?([^\s]+?)\s+in\s+([^\s]+?)(?:\s+do\s+([^\s]+))?\s*$/,
      builtins = {
        '|': function(a, b) { return b(a); },
        '+': function(a, b) { return a + b; },
        '-': function(a, b) { return a - b; },
        '*': function(a, b) { return a * b; },
        '/': function(a, b) { return a / b; },
        '%': function(a, b) { return a % b; },
        'is': function(a, b) { return a == b; },
        'isnt': function(a, b) { return a != b; },
        'then': function(a, b) { return a ? b : a; },
        'else': function(a, b) { return a ? a : b; }
      },
      keys = Object.keys;

  function trim(str) {return String.prototype.trim.call(str);};

  function resolveProp(obj, name) {
    var name = name.trim(), n;
    if (name[0] === "'") return name.slice(1,-1);
    if (!isNaN(n = parseFloat(name))) return n;
    return name.split('.').reduce(function(p, prop) {
      return p ? p[prop] : undefined;
    }, obj);
  }

  function bucket(b, k, v) {
    if (!(k in b)) b[k] = [];
    if (b[k].indexOf(v) === -1) b[k].push(v);
  }

  function extend(orig, obj) {
    Object.keys(obj).forEach(function(prop) {
      orig[prop] = obj[prop];
    });
    return orig;
  }

  function traverseElements(el, callback) {
    var i;
    if (callback(el) !== false) for(i = el.children.length; i--;)
      traverseElements(el.children[i], callback);
  }

  function createProxy(maps, proxy) {
    proxy = proxy || {};
    proxy.extend = proxy.$extend = function(obj) {
      var toRender = {}, rid;
      Object.keys(obj).forEach(function(prop) {
        maps.orig[prop] = obj[prop];
        if (maps.binds[prop]) maps.binds[prop].forEach(function(rid) {
          if (rid >= 0) toRender[rid] = null;
        });
      });
      for (renderId in toRender) maps.renders[renderId](maps.orig);
      return proxy;
    };
    proxy.$splice = function(prop, start, end) {
      if (arguments.length < 2) return [];
      var list = resolveProp(maps.orig, prop),
          middle, args, res;
      if (!list) return;
      args = [].slice.call(arguments, 1);
      middle = Math.max(0, args.length-2);
      res = list.splice.apply(list, args);
      maps.binds[prop].forEach(function(rId) {
        if (rId < 0) return;
        var render = maps.renders[rId];
        if (render.splice) render.splice(start, end, middle);
      });
      return res;
    };
    proxy.$push = function(prop) {
      var list = resolveProp(maps.orig, prop),
          items = [].slice.call(arguments, 1);
      proxy.$splice.apply(proxy, [prop, list.length, 0].concat(items));
      return list.length;
    };
    proxy.$unshift = function(prop, item) {
      var list = resolveProp(maps.orig, prop);
      proxy.$splice(prop, 0, 0, item);
      return list.length;
    };
    proxy.$replace = function(prop, a, b) {
      var list = resolveProp(maps.orig, prop);
      proxy.$splice(prop, list.indexOf(a), 1, b || a);
      return a;
    };

    Object.keys(maps.binds).forEach(function(prop) {
      var ids = maps.binds[prop];
      Object.defineProperty(proxy, prop, {
        set: function(value) {
          maps.orig[prop] = value;
          ids.forEach(function(renderId) {
            if (renderId >= 0) maps.renders[renderId](maps.orig);
          });
        },
        get: function() {
          if (maps.rebinds[prop])
            return maps.rebinds[prop]();
          return maps.orig[prop];
        }
      });
    });
    return proxy;
  }

  function vixen(builtins, el, model) {
    function resolveInFix(obj, props) {
      var p = resolveProp(obj, props[0]), i, len, prop, infix;
      for (i=1, len=props.length; i<len; i+=2) {
        prop = props[i].trim();
        infix = builtins[prop] || resolveProp(obj, prop);
        p = infix(p, resolveProp(obj, props[i+1]));
      }
      return p;
    }

    function resolve(orig, prop) {
      if (!orig) return '';
      var val = resolveInFix(orig, prop.slice(2,-2).match(expr));
      return val === undefined ? '' : val;
    }

    function strTmpl(str, orig) {
      return str.replace(pattern, resolve.bind(undefined, orig));
    }

    function match(str) {
      var m = str.match(pattern);
      if (m) return m.map(function(chain) {
        return chain.slice(2, -2).match(expr).map(trim);
      });
    }

    function traverse(el, orig) {
      var binds = {},
          rebinds = {},
          renders = {},
          count = 0;

      function bindRenders(chains, renderId) {
        // Create property to render mapping
        chains.forEach(function(chain) {
          // Register all chaining functions as binds.
          chain.forEach(function(prop) {
            if (builtins[prop] || prop[0] === "'" || !isNaN(prop)) return;
            bucket(binds, prop.split('.')[0], renderId);
          });
        });
      }

      function parseIterator(el) {
        var nodes = [], marker, key, forStr;
        if (parent_ = (el.parentElement || el.parentNode)) {
          forStr = el.getAttribute('vx-for');
          if (el.tagName === 'VX') {
            marker = el.ownerDocument.createTextNode('');
            parent_.replaceChild(marker, el);
          } else if (forStr) {
            parent_ = el;
            nodes = Array.prototype.slice.call(el.childNodes);
            marker = el.ownerDocument.createTextNode('');
            parent_.appendChild(marker);
          } else return;
          if (m = forExpr.exec(forStr))
            return {
              key: m[1], alias: m[2], prop: m[3], each: m[4], nodes: nodes,
              parent: parent_, marker: marker
            };
          else throw "\"" + forStr + "\" is not a valid vx-for expression";
        }
      }

      function mapAttribute(owner, attr) {
        var name, eventId, renderId, str, noTmpl;
        if ((str = attr.value) && (chains = match(str))) {
          name = attr.name;
          if (name.indexOf('vx-') === 0) {
            owner.removeAttribute(name);
            name = name.substr(3);
          }
          if (name.indexOf('on') === 0) {
            eventName = name.substr(2);
            // Add event listeners
            chains.forEach(function(chain) {
              var cb;
              (renders[renderId=count++] = function(orig) {
                var args = chain.map(resolveProp.bind(null, orig));
                // Multi parameter space syntax
                cb = function(evt) {
                  return args[0].apply(owner, [evt].concat(args.slice(1)));
                };
              })(orig);
              owner.addEventListener(eventName, function(e) { cb(e); });
              bindRenders([chain], renderId);
            });
            owner.removeAttribute(name);
          } else {
            noTmpl = chains.length === 1 && str.substr(0,1) === '{' &&
              str.substr(-1) === '}';
            // Create rendering function for attribute.
            (renders[renderId=count++] = function(orig, clear) {
              var val = noTmpl ? resolve(orig, str) : strTmpl(str, orig);
              if (!clear && (name in owner)) owner[name] = val;
              if (typeof val !== 'boolean') owner.setAttribute(name, val);
            })(orig, true);
            // Bi-directional coupling.
            if (noTmpl && chains[0].length === 1)
              rebinds[chains[0][0]] = function() {
                // TODO: Getting f.ex. 'value' attribute from an input
                // doesn't return user input value so accessing element
                // object properties directly, find out how to do this
                // more securely.
                return name in owner ?
                  owner[name] : owner.getAttribute(name);
              };
            bindRenders(chains, renderId);
          }
        }
      }

      function mapTextNodes(el) {
        for (var i = el.childNodes.length; i--;) (function(node) {
          var str, renderId, chains;
          if (node.nodeType === el.TEXT_NODE && (str = node.nodeValue) &&
              (chains = match(str))) {
            // Create rendering function for element text node.
            renderId = count++;
            (renders[renderId] = function(orig) {
              node.nodeValue = strTmpl(str, orig);
            })(orig);
            bindRenders(chains, renderId);
          }
        })(el.childNodes[i]);
      }

      // Remove no-traverse attribute if root node
      el.removeAttribute('vx-subview');

      traverseElements(el, function(el_) {
        var i, iter, template, renderId, insertNodes, subproxies, addkv,
            qmatch, qp, splice, removeNodes;

        // Stop handling and recursion if subview.
        if (el_.getAttribute('vx-subview') !== null) return false;

        if (iter = parseIterator(el_)) {
          subproxies = [];
          template = el_.cloneNode(true);
          renderId = count++;
          qmatch = {};
          match(template.innerHTML).forEach(function(c) {
            c.forEach(function(p) { qmatch[p.split('.')[0]] = true; });
          });
          addkv = function(orig, k, v) {
            if (iter.key) orig[iter.key] = k;
            orig[iter.alias] = v;
            return orig;
          };

          for (i=iter.nodes.length; i--;)
            iter.parent.removeChild(iter.nodes[i]);

          insertNodes = function insertNodes(orig, each, marker) {
            var clone = template.cloneNode(true),
                subproxy = createProxy(traverse(clone, orig)),
                nodes = Array.prototype.slice.call(clone.childNodes);
            for (i=0, len=nodes.length; i<len; i++)
              iter.parent.insertBefore(nodes[i], marker || iter.marker);
            if (each) each(nodes);
            subproxy.__nodes = nodes;
            return subproxy;
          };
          removeNodes = function removeNodes(sp) {
            var nodes = sp.__nodes, i;
            for (i=nodes.length; i--;) iter.parent.removeChild(nodes[i]);
          };

          splice = function splice(orig, ext, start, end, middle) {
            var list = resolveProp(orig, iter.prop),
                each = iter.each && resolveProp(orig, iter.each),
                splen = subproxies.length,
                ks, klen, i, i_, len, item, sp, spn, k, orig_;
            if (start == null) start = 0;
            if (end == null || isNaN(end)) end = splen;
            if (list) klen = (ks=keys(list), ks.length);
            if (middle == null || isNaN(middle)) middle = klen || 0;
            if (klen) {
              for (i=start; i<middle; i++) {
                item = list[k=ks[i]];
                if (i < splen && i < end) {
                  subproxies[i].extend(addkv(ext||{}, k, item));
                } else {
                  subproxies.splice(i, 0, insertNodes(addkv(ext||orig, k, item),
                    each && each.bind(null, item, k),
                    subproxies[i] && subproxies[i].__nodes[0]));
                }
              }
            }
            sps = subproxies.splice(middle, end-middle);
            for (i=0, len=sps.length; i<len; i++) removeNodes(sps[i]);
            if (ks && iter.key) for (i=middle, len=subproxies.length; i<len; i++)
              subproxies[i].extend((orig_={}, orig_[iter.key]=ks[i], orig_));
          };

          (renders[renderId] = splice)(orig);
          splice.splice = function(start, end, middle) {
            splice(orig, undefined, start, end+start, middle+start);
          };
          bucket(binds, iter.prop.split('.')[0], renderId);
          keys(qmatch).forEach(function(qp) {
            if (iter.alias !== qp && iter.key !== qp) {
              renders[renderId = count++] = function(orig) {
                var ext = {};
                ext[qp] = resolveProp(orig, qp);
                splice(orig, ext);
              };
              bucket(binds, qp, renderId);
            }
          });
        } else {
          // Bind node text.
          mapTextNodes(el_);
        }
        // Bind node attributes if not a <vx>.
        if (el_.tagName !== 'VX') for (i = el_.attributes.length; i--;)
          mapAttribute(el_, el_.attributes[i]);
        // Stop recursion if iterator.
        return !iter;
      });
      return {orig:orig, binds:binds, rebinds:rebinds, renders:renders};
    }
    return createProxy(traverse(el, extend({}, model || {})), model);
  }

  function factory() {
    var builtins_ = (arguments.length ? [].slice.call(arguments) : [builtins])
          .reduce(function(p, c) { return extend(p, c); }, {}),
        vixen_ = vixen.bind(null, builtins_);
    vixen_.builtins = builtins_;
    vixen_.factory = factory;
    return vixen_;
  }

  return factory();
}());
<|endoftext|>


<commit_before>var protocol = require('dat-replication-protocol')
var through = require('through2')
var request = require('request')

var STREAM_OPTS = {highWaterMark:16}

var replication = function(dat) {
  var that = {}

  that.createPullStream = function(remote) {
    var rcvd = that.receive()
    var req = request.post(remote+'/api/replicator/send')
    req.pipe(rcvd).pipe(req)
    return rcvd
  }

  that.createPushStream = function(remote) {
    var send = that.send()
    var req = request.post(remote+'/api/replicator/receive')
    req.pipe(send).pipe(req)
    return send
  }

  that.send = function(opts) {
    if (!opts) opts = {}
    var p = protocol()

    var writeAttachments = function(attachments, cb) {
      if (!attachments) return cb()

      var keys = Object.keys(attachments)
      var loop = function(err) {
        if (err) return cb(err)
        if (!keys.length) return cb()
        var bl = attachments[keys.shift()]
        dat.blobs.createReadStream(bl.hash).pipe(p.blob(bl.size, loop))
      }

      loop()
    }

    var write = function(doc, enc, cb) {
      var data = doc.value || doc.data
      writeAttachments(data.attachments, function(err) {
        if (err) return cb(err)
        p.document(data, cb)
      })
    }

    var flush = function(cb) {
      p.finalize(cb)
    }

    var ready = function(meta) {
      var rs = dat.createChangesStream({
        since: meta.change,
        data: true
      })

      rs.pipe(through.obj(STREAM_OPTS, write, flush))
    }

    if (opts.meta) ready(opts.meta)
    else {
      p.once('meta', function(meta, cb) {
        ready(meta)
        cb()
      })
    }

    if (opts.ping !== false) p.ping() // support more transports by forcing a flush (looking at you http)

    // not sure about this but this is a start...
    p.on('conflict', function(conflict, cb) {
      var err = new Error(conflict.message || 'conflict')
      err.conflict = true
      err.key = conflict.key
      err.version = conflict.version
      p.emit('error', err)
      cb()
    })

    return p
  }

  that.receive = function(opts) {
    if (!opts) opts = {}

    var p = protocol()
    var ws = dat.createWriteStream({objects:true})

    if (opts.meta !== false) {
      p.meta({
        change: dat.storage.change,
        schema: dat.schema.toJSON()
      })
    }

    ws.on('error', function(err) {
      p.emit('error', err)
    })

    ws.on('conflict', function(conflict) {
      p.conflict({message:conflict.message, key:conflict.key, version:conflict.version})
    })

    p.on('blob', function(blob, cb) {
      blob.pipe(dat.blobs.createWriteStream(cb))
    })

    p.on('document', function(doc, cb) {
      ws.write(doc, cb)
    })

    p.on('finalize', function(cb) {
      ws.on('end', cb)
      ws.end()
    })

    return p
  }

  return that
}

module.exports = replication<commit_msg>support for blobs === false<commit_after>var protocol = require('dat-replication-protocol')
var through = require('through2')
var request = require('request')

var STREAM_OPTS = {highWaterMark:16}

var replication = function(dat) {
  var that = {}

  that.createPullStream = function(remote) {
    var rcvd = that.receive()
    var req = request.post(remote+'/api/replicator/send')
    req.pipe(rcvd).pipe(req)
    return rcvd
  }

  that.createPushStream = function(remote) {
    var send = that.send()
    var req = request.post(remote+'/api/replicator/receive')
    req.pipe(send).pipe(req)
    return send
  }

  that.send = function(opts) {
    if (!opts) opts = {}
    var p = protocol()

    var writeAttachments = function(attachments, cb) {
      if (!attachments) return cb()

      var keys = Object.keys(attachments)
      var loop = function(err) {
        if (err) return cb(err)
        if (!keys.length) return cb()
        var bl = attachments[keys.shift()]
        dat.blobs.createReadStream(bl.hash).pipe(p.blob(bl.size, loop))
      }

      loop()
    }

    var writeNoBlobs = function(doc, enc, cb) {
      var data = doc.value || doc.data
      p.document(data, cb)
    }

    var write = function(doc, enc, cb) {
      var data = doc.value || doc.data
      writeAttachments(data.attachments, function(err) {
        if (err) return cb(err)
        p.document(data, cb)
      })
    }

    var flush = function(cb) {
      p.finalize(cb)
    }

    var ready = function(meta) {
      var rs = dat.createChangesStream({
        since: meta.change,
        data: true
      })

      rs.pipe(through.obj(STREAM_OPTS, meta.blobs === false ? writeNoBlobs : write, flush))
    }

    if (opts.meta) ready(opts.meta)
    else {
      p.once('meta', function(meta, cb) {
        ready(meta)
        cb()
      })
    }

    if (opts.ping !== false) p.ping() // support more transports by forcing a flush (looking at you http)

    // not sure about this but this is a start...
    p.on('conflict', function(conflict, cb) {
      var err = new Error(conflict.message || 'conflict')
      err.conflict = true
      err.key = conflict.key
      err.version = conflict.version
      p.emit('error', err)
      cb()
    })

    return p
  }

  that.receive = function(opts) {
    if (!opts) opts = {}

    var p = protocol()
    var ws = dat.createWriteStream({objects:true})

    if (opts.meta !== false) {
      p.meta({
        blobs: opts.blobs,
        change: dat.storage.change,
        schema: dat.schema.toJSON()
      })
    }

    ws.on('error', function(err) {
      p.emit('error', err)
    })

    ws.on('conflict', function(conflict) {
      p.conflict({message:conflict.message, key:conflict.key, version:conflict.version})
    })

    p.on('blob', function(blob, cb) {
      blob.pipe(dat.blobs.createWriteStream(cb))
    })

    p.on('document', function(doc, cb) {
      ws.write(doc, cb)
    })

    p.on('finalize', function(cb) {
      ws.on('end', cb)
      ws.end()
    })

    return p
  }

  return that
}

module.exports = replication<|endoftext|>


<commit_before>'use strict'
function ext (a, b) {
  if (a && b) {
    for (let c in b) {
      if (b.hasOwnProperty(c)) {
        a[c] = b[c]
      }
    }
    return a
  }
  return null
}
const _s = require('./lib/string')
ext(String.prototype, _s)
const _d = require('./lib/date')
ext(Date.prototype, _d)
const _a = require('./lib/array')
ext(Array.prototype, _a)
let option = {
  logTime: true
}

Number.prototype.round = function (p) {  //eslint-disable-line
  p = Math.pow(10, p || 0)
  return Math.round(this * p) / p
}
Number.prototype.fillStr = String.prototype.fillStr  //eslint-disable-line
Date.prototype.fillStr = String.prototype.fillStr  //eslint-disable-line
Buffer.prototype.contact = function (b) {
  /*
  utf8 有bom头
  EF BB BF [239 187 191]
  */
  let buf = Buffer.alloc(this.length + b.length)
  this.copy(buf, 0, 0, this.length)
  b.copy(buf, this.length, 0, b.length)
  return buf
}
const c = {
  /*
  http://stanislavs.org/helppc/ansi_codes.html
  */
  cls: '\x1b[0;0;H\x1b[0J',
  xy (x, y) {
    return `\x1b[${y};${x};H`
  },
  none: '\x1b[m',
  black: '\x1b[30m',
  red: '\x1b[31m\x1b[1m',
  green: '\x1b[32m\x1b[1m',
  yellow: '\x1b[33m\x1b[1m',
  blue: '\x1b[34m\x1b[1m',
  magenta: '\x1b[35m\x1b[1m',
  cyan: '\x1b[36m\x1b[1m',
  white: '\x1b[37m\x1b[1m',
  dimred: '\x1b[31m',
  dimgreen: '\x1b[32m',
  dimyellow: '\x1b[33m',
  dimblue: '\x1b[34m',
  dimmagenta: '\x1b[35m',
  dimcyan: '\x1b[36m',
  dimwhite: '\x1b[37m',
  r (s) { return this.red + s + this.none },
  g (s) { return this.green + s + this.none },
  y (s) { return this.yellow + s + this.none },
  b (s) { return this.blue + s + this.none },
  m (s) { return this.magenta + s + this.none },
  c (s) { return this.cyan + s + this.none },
  w (s) { return this.white + s + this.none },
  dimr (s) { return this.dimred + s + this.none },
  dimg (s) { return this.dimgreen + s + this.none },
  dimy (s) { return this.dimyellow + s + this.none },
  dimb (s) { return this.dimblue + s + this.none },
  dimm (s) { return this.dimmagenta + s + this.none },
  dimc (s) { return this.dimcyan + s + this.none }
}
const getStackTrace = function () {
  let obj = {}
  Error.captureStackTrace(obj, getStackTrace)
  return obj.stack
}

const re = /\\(.+)\.js:(\d+:\d+)/g
const trace = console
const log = function (...args) {
  getStackTrace().split('\n')[2].match(re)
  let s = c.none + ' [' + c.dimgreen + RegExp.$1.split('\\').pop() + ':' + RegExp.$2 + ' ' + new Date().date2Str().replaceAll('-', '') + c.none + ']'
  let str = ''
  for (let i = 0; i < args.length; i++) {
    if (typeof args[i] === 'object') {
      str = str + JSON.stringify(args[i]) + ' '
    } else {
      str = str + args[i] + ' '
    }
  }
  trace.log(str + (option.logTime ? s : ''))
  return 1
}
const err = function (...args) {
  getStackTrace().split('\n')[2].match(re)
  let s = c.none + ' [' + c.dimred + RegExp.$1.split('\\').pop() + ':' + RegExp.$2 + ' ' + new Date().date2Str().replaceAll('-', '') + c.none + ']'
  let str = ''
  for (let i = 0; i < args.length; i++) {
    if (typeof args[i] === 'object') {
      str = str + JSON.stringify(args[i]) + ' '
    } else {
      str = str + args[i] + ' '
    }
  }
  trace.log(str + (option.logTime ? s : ''))
  return 1
}
function compare (k, dir) {
  return function (a, b) {
    return (dir === 'desc') ? ~~(a[k] < b[k]) : ~~(a[k] > b[k])
  }
}
const tools = require('./lib/tools')
const fake = require('./lib/fake')
const tpl = require('./lib/tpl')

module.exports = {
  option,
  c,
  ext,
  log,
  err,
  tools,
  fake,
  tpl,
  compare
}
<commit_msg>区分win和非win下的log输出格式，打印输出点全路径<commit_after>'use strict'
function ext (a, b) {
  if (a && b) {
    for (let c in b) {
      if (b.hasOwnProperty(c)) {
        a[c] = b[c]
      }
    }
    return a
  }
  return null
}
const _s = require('./lib/string')
ext(String.prototype, _s)
const _d = require('./lib/date')
ext(Date.prototype, _d)
const _a = require('./lib/array')
ext(Array.prototype, _a)
let option = {
  logTime: true
}

Number.prototype.round = function (p) {  //eslint-disable-line
  p = Math.pow(10, p || 0)
  return Math.round(this * p) / p
}
Number.prototype.fillStr = String.prototype.fillStr  //eslint-disable-line
Date.prototype.fillStr = String.prototype.fillStr  //eslint-disable-line
Buffer.prototype.contact = function (b) {
  /*
  utf8 有bom头
  EF BB BF [239 187 191]
  */
  let buf = Buffer.alloc(this.length + b.length)
  this.copy(buf, 0, 0, this.length)
  b.copy(buf, this.length, 0, b.length)
  return buf
}
const c = {
  /*
  http://stanislavs.org/helppc/ansi_codes.html
  */
  cls: '\x1b[0;0;H\x1b[0J',
  xy (x, y) {
    return `\x1b[${y};${x};H`
  },
  none: '\x1b[m',
  black: '\x1b[30m',
  red: '\x1b[31m\x1b[1m',
  green: '\x1b[32m\x1b[1m',
  yellow: '\x1b[33m\x1b[1m',
  blue: '\x1b[34m\x1b[1m',
  magenta: '\x1b[35m\x1b[1m',
  cyan: '\x1b[36m\x1b[1m',
  white: '\x1b[37m\x1b[1m',
  dimred: '\x1b[31m',
  dimgreen: '\x1b[32m',
  dimyellow: '\x1b[33m',
  dimblue: '\x1b[34m',
  dimmagenta: '\x1b[35m',
  dimcyan: '\x1b[36m',
  dimwhite: '\x1b[37m',
  r (s) { return this.red + s + this.none },
  g (s) { return this.green + s + this.none },
  y (s) { return this.yellow + s + this.none },
  b (s) { return this.blue + s + this.none },
  m (s) { return this.magenta + s + this.none },
  c (s) { return this.cyan + s + this.none },
  w (s) { return this.white + s + this.none },
  dimr (s) { return this.dimred + s + this.none },
  dimg (s) { return this.dimgreen + s + this.none },
  dimy (s) { return this.dimyellow + s + this.none },
  dimb (s) { return this.dimblue + s + this.none },
  dimm (s) { return this.dimmagenta + s + this.none },
  dimc (s) { return this.dimcyan + s + this.none }
}
const getStackTrace = function () {
  let obj = {}
  Error.captureStackTrace(obj, getStackTrace)
  return obj.stack
}
let os = process.platform
const re = os.includes('win32') ? /\\(.+)\.js:(\d+:\d+)/g : /\/(.+)\.js:(\d+:\d+)/g
const trace = console
const log = function (...args) {
  getStackTrace().split('\n')[2].match(re)
  let s = c.none + ' [' + c.dimgreen + RegExp.$1 + ':' + RegExp.$2 + ' ' + new Date().date2Str().replaceAll('-', '') + c.none + ']'
  let str = ''
  for (let i = 0; i < args.length; i++) {
    if (typeof args[i] === 'object') {
      str = str + JSON.stringify(args[i]) + ' '
    } else {
      str = str + args[i] + ' '
    }
  }
  trace.log(str + (option.logTime ? s : ''))
  return 1
}
const err = function (...args) {
  getStackTrace().split('\n')[2].match(re)
  let s = c.none + ' [' + c.dimred + RegExp.$1 + ':' + RegExp.$2 + ' ' + new Date().date2Str().replaceAll('-', '') + c.none + ']'
  let str = ''
  for (let i = 0; i < args.length; i++) {
    if (typeof args[i] === 'object') {
      str = str + JSON.stringify(args[i]) + ' '
    } else {
      str = str + args[i] + ' '
    }
  }
  trace.log(str + (option.logTime ? s : ''))
  return 1
}
function compare (k, dir) {
  return function (a, b) {
    return (dir === 'desc') ? ~~(a[k] < b[k]) : ~~(a[k] > b[k])
  }
}
const tools = require('./lib/tools')
const fake = require('./lib/fake')
const tpl = require('./lib/tpl')

module.exports = {
  option,
  c,
  ext,
  log,
  err,
  tools,
  fake,
  tpl,
  compare
}
<|endoftext|>