<commit_before>/**
* simplePagination.js v1.4
* A simple jQuery pagination plugin.
* http://flaviusmatis.github.com/simplePagination.js/
*
* Copyright 2012, Flavius Matis
* Released under the MIT license.
* http://flaviusmatis.github.com/license.html
*/

(function($){

	var methods = {
		init: function(options) {
			var o = $.extend({
				items: 1,
				itemsOnPage: 1,
				pages: 0,
				displayedPages: 5,
				edges: 2,
				currentPage: 1,
				hrefTextPrefix: '#page-',
				hrefTextSuffix: '',
				prevText: 'Prev',
				nextText: 'Next',
				ellipseText: '…',
				cssStyle: 'light-theme',
				selectOnClick: true,
				onPageClick: function(pageNumber, event) {
					// Callback triggered when a page is clicked
					// Page number is given as an optional parameter
				},
				onInit: function() {
					// Callback triggered immediately after initialization
				}
			}, options || {});

			var self = this;

			o.pages = o.pages ? o.pages : Math.ceil(o.items / o.itemsOnPage) ? Math.ceil(o.items / o.itemsOnPage) : 1;
			o.currentPage = o.currentPage - 1;
			o.halfDisplayed = o.displayedPages / 2;

			this.each(function() {
				self.addClass(o.cssStyle).data('pagination', o);
				methods._draw.call(self);
			});

			o.onInit();

			return this;
		},

		selectPage: function(page) {
			methods._selectPage.call(this, page - 1);
			return this;
		},

		prevPage: function() {
			var o = this.data('pagination');
			if (o.currentPage > 0) {
				methods._selectPage.call(this, o.currentPage - 1);
			}
			return this;
		},

		nextPage: function() {
			var o = this.data('pagination');
			if (o.currentPage < o.pages - 1) {
				methods._selectPage.call(this, o.currentPage + 1);
			}
			return this;
		},

		destroy: function(){
			this.empty();
			return this;
		},

		redraw: function(){
			methods._draw.call(this);
			return this;
		},

		disable: function(){
			var o = this.data('pagination');
			o.disabled = true;
			this.data('pagination', o);
			methods._draw.call(this);
			return this;
		},

		enable: function(){
			var o = this.data('pagination');
			o.disabled = false;
			this.data('pagination', o);
			methods._draw.call(this);
			return this;
		},

		_draw: function() {
			var $panel = this,
				o = $panel.data('pagination'),
				interval = methods._getInterval(o),
				i;

			methods.destroy.call(this);

			// Generate Prev link
			if (o.prevText) {
				methods._appendItem.call(this, o.currentPage - 1, {text: o.prevText, classes: 'prev'});
			}

			// Generate start edges
			if (interval.start > 0 && o.edges > 0) {
				var end = Math.min(o.edges, interval.start);
				for (i = 0; i < end; i++) {
					methods._appendItem.call(this, i);
				}
				if (o.edges < interval.start && (interval.start - o.edges != 1)) {
					$panel.append('' + o.ellipseText + '');
				} else if (interval.start - o.edges == 1) {
					methods._appendItem.call(this, o.edges);
				}
			}

			// Generate interval links
			for (i = interval.start; i < interval.end; i++) {
				methods._appendItem.call(this, i);
			}

			// Generate end edges
			if (interval.end < o.pages && o.edges > 0) {
				if (o.pages - o.edges > interval.end && (o.pages - o.edges - interval.end != 1)) {
					$panel.append('' + o.ellipseText + '');
				} else if (o.pages - o.edges - interval.end == 1) {
					methods._appendItem.call(this, interval.end++);
				}
				var begin = Math.max(o.pages - o.edges, interval.end);
				for (i = begin; i < o.pages; i++) {
					methods._appendItem.call(this, i);
				}
			}

			// Generate Next link
			if (o.nextText) {
				methods._appendItem.call(this, o.currentPage + 1, {text: o.nextText, classes: 'next'});
			}
		},

		_getInterval: function(o) {
			return {
				start: Math.ceil(o.currentPage > o.halfDisplayed ? Math.max(Math.min(o.currentPage - o.halfDisplayed, (o.pages - o.displayedPages)), 0) : 0),
				end: Math.ceil(o.currentPage > o.halfDisplayed ? Math.min(o.currentPage + o.halfDisplayed, o.pages) : Math.min(o.displayedPages, o.pages))
			};
		},

		_appendItem: function(pageIndex, opts) {
			var self = this, options, $link, o = self.data('pagination');

			pageIndex = pageIndex < 0 ? 0 : (pageIndex < o.pages ? pageIndex : o.pages - 1);

			options = $.extend({
				text: pageIndex + 1,
				classes: ''
			}, opts || {});

			if (pageIndex == o.currentPage || o.disabled) {
				$link = $('' + (options.text) + '');
			} else {
				$link = $('' + (options.text) + '');
				$link.click(function(event){
					return methods._selectPage.call(self, pageIndex, event);
				});
			}

			if (options.classes) {
				$link.addClass(options.classes);
			}

			self.append($link);
		},

		_selectPage: function(pageIndex, event) {
			var o = this.data('pagination');
			o.currentPage = pageIndex;
			if (o.selectOnClick) {
				methods._draw.call(this);
			}
			return o.onPageClick(pageIndex + 1, event);
		}

	};

	$.fn.pagination = function(method) {

		// Method calling logic
		if (methods[method] && method.charAt(0) != '_') {
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		} else if (typeof method === 'object' || !method) {
			return methods.init.apply(this, arguments);
		} else {
			$.error('Method ' +  method + ' does not exist on jQuery.pagination');
		}

	};

})(jQuery);
<commit_msg>Added getPagesCount and getCurrentPage methods.<commit_after>/**
* simplePagination.js v1.4
* A simple jQuery pagination plugin.
* http://flaviusmatis.github.com/simplePagination.js/
*
* Copyright 2012, Flavius Matis
* Released under the MIT license.
* http://flaviusmatis.github.com/license.html
*/

(function($){

	var methods = {
		init: function(options) {
			var o = $.extend({
				items: 1,
				itemsOnPage: 1,
				pages: 0,
				displayedPages: 5,
				edges: 2,
				currentPage: 1,
				hrefTextPrefix: '#page-',
				hrefTextSuffix: '',
				prevText: 'Prev',
				nextText: 'Next',
				ellipseText: '…',
				cssStyle: 'light-theme',
				selectOnClick: true,
				onPageClick: function(pageNumber, event) {
					// Callback triggered when a page is clicked
					// Page number is given as an optional parameter
				},
				onInit: function() {
					// Callback triggered immediately after initialization
				}
			}, options || {});

			var self = this;

			o.pages = o.pages ? o.pages : Math.ceil(o.items / o.itemsOnPage) ? Math.ceil(o.items / o.itemsOnPage) : 1;
			o.currentPage = o.currentPage - 1;
			o.halfDisplayed = o.displayedPages / 2;

			this.each(function() {
				self.addClass(o.cssStyle).data('pagination', o);
				methods._draw.call(self);
			});

			o.onInit();

			return this;
		},

		selectPage: function(page) {
			methods._selectPage.call(this, page - 1);
			return this;
		},

		prevPage: function() {
			var o = this.data('pagination');
			if (o.currentPage > 0) {
				methods._selectPage.call(this, o.currentPage - 1);
			}
			return this;
		},

		nextPage: function() {
			var o = this.data('pagination');
			if (o.currentPage < o.pages - 1) {
				methods._selectPage.call(this, o.currentPage + 1);
			}
			return this;
		},

		getPagesCount: function() {
			return this.data('pagination').pages;
		},

		getCurrentPage: function () {
			return this.data('pagination').currentPage + 1;
		},

		destroy: function(){
			this.empty();
			return this;
		},

		redraw: function(){
			methods._draw.call(this);
			return this;
		},

		disable: function(){
			var o = this.data('pagination');
			o.disabled = true;
			this.data('pagination', o);
			methods._draw.call(this);
			return this;
		},

		enable: function(){
			var o = this.data('pagination');
			o.disabled = false;
			this.data('pagination', o);
			methods._draw.call(this);
			return this;
		},

		_draw: function() {
			var $panel = this,
				o = $panel.data('pagination'),
				interval = methods._getInterval(o),
				i;

			methods.destroy.call(this);

			// Generate Prev link
			if (o.prevText) {
				methods._appendItem.call(this, o.currentPage - 1, {text: o.prevText, classes: 'prev'});
			}

			// Generate start edges
			if (interval.start > 0 && o.edges > 0) {
				var end = Math.min(o.edges, interval.start);
				for (i = 0; i < end; i++) {
					methods._appendItem.call(this, i);
				}
				if (o.edges < interval.start && (interval.start - o.edges != 1)) {
					$panel.append('' + o.ellipseText + '');
				} else if (interval.start - o.edges == 1) {
					methods._appendItem.call(this, o.edges);
				}
			}

			// Generate interval links
			for (i = interval.start; i < interval.end; i++) {
				methods._appendItem.call(this, i);
			}

			// Generate end edges
			if (interval.end < o.pages && o.edges > 0) {
				if (o.pages - o.edges > interval.end && (o.pages - o.edges - interval.end != 1)) {
					$panel.append('' + o.ellipseText + '');
				} else if (o.pages - o.edges - interval.end == 1) {
					methods._appendItem.call(this, interval.end++);
				}
				var begin = Math.max(o.pages - o.edges, interval.end);
				for (i = begin; i < o.pages; i++) {
					methods._appendItem.call(this, i);
				}
			}

			// Generate Next link
			if (o.nextText) {
				methods._appendItem.call(this, o.currentPage + 1, {text: o.nextText, classes: 'next'});
			}
		},

		_getInterval: function(o) {
			return {
				start: Math.ceil(o.currentPage > o.halfDisplayed ? Math.max(Math.min(o.currentPage - o.halfDisplayed, (o.pages - o.displayedPages)), 0) : 0),
				end: Math.ceil(o.currentPage > o.halfDisplayed ? Math.min(o.currentPage + o.halfDisplayed, o.pages) : Math.min(o.displayedPages, o.pages))
			};
		},

		_appendItem: function(pageIndex, opts) {
			var self = this, options, $link, o = self.data('pagination');

			pageIndex = pageIndex < 0 ? 0 : (pageIndex < o.pages ? pageIndex : o.pages - 1);

			options = $.extend({
				text: pageIndex + 1,
				classes: ''
			}, opts || {});

			if (pageIndex == o.currentPage || o.disabled) {
				$link = $('' + (options.text) + '');
			} else {
				$link = $('' + (options.text) + '');
				$link.click(function(event){
					return methods._selectPage.call(self, pageIndex, event);
				});
			}

			if (options.classes) {
				$link.addClass(options.classes);
			}

			self.append($link);
		},

		_selectPage: function(pageIndex, event) {
			var o = this.data('pagination');
			o.currentPage = pageIndex;
			if (o.selectOnClick) {
				methods._draw.call(this);
			}
			return o.onPageClick(pageIndex + 1, event);
		}

	};

	$.fn.pagination = function(method) {

		// Method calling logic
		if (methods[method] && method.charAt(0) != '_') {
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		} else if (typeof method === 'object' || !method) {
			return methods.init.apply(this, arguments);
		} else {
			$.error('Method ' +  method + ' does not exist on jQuery.pagination');
		}

	};

})(jQuery);
<|endoftext|>


<commit_before>/**
 * Created by Dominik Serve on 15.06.2016.
 */

var simpleOpcua = require('mi5-simple-opcua');
var mqtt = require('mqtt');
var EventEmitter = require('events').EventEmitter;
var util = require('util');
util.inherits(Mi5Module, EventEmitter);

var debug = require('debug');

var OpcuaServer = simpleOpcua.OpcuaServer;
var OpcuaClient = simpleOpcua.OpcuaClient;
var OpcuaHelper = simpleOpcua.helper;
var OpcuaVariable = simpleOpcua.OpcuaVariable;

var mi5Skill = require('./mi5-skill');

/**Mi5 Module inherits EventEmitter
 *
 * @param moduleName
 * @param {object} settings {opcua: {hostAddress: ..., baseNodeId: ...}, mqtt: ..., indPhysx: ...}
 * @constructor
 */

function Mi5Module(trivialName, settings){
  //console.log(trivialName, 'ceating new module');
  EventEmitter.call(this);
  var self = this;
  var item = this;

  this.debug = debug(trivialName);

  if(settings.storage){
    settings.storage = settings.storage.replace('.', process.cwd());
    this.storage = require('node-persist');
    this.storage.initSync({
      dir: settings.storage,
      stringify: JSON.stringify,
      parse: JSON.parse,
      encoding: 'utf8',
      logging: false,  // can also be custom logging function
      continuous: true,
      interval: false,
      ttl: false // ttl* [NEW], can be true for 24h default or a number in MILLISECONDS
    })/*.then(function(){self.emit()}, function(){console.log('no success')})*/;
  }

  item.numberOfConnections = 0;
  this.trivialName = trivialName;
  this.moduleId = settings.moduleId;
  this.position = -1;
  if(typeof settings.position != 'undefined')
    this.position = settings.position;
  if(self.storage && self.storage.getItem(self.moduleName + 'position'))
    this.position = self.storage.getItem(self.moduleName + 'position');

  // opcua
  if(settings.opcua){
    //baseNodeId handling
    if(settings.opcua.baseNodeId)
      createNodeIds(settings.opcua.baseNodeId);
  }

  function createNodeIds(baseNodeId){
    self.baseNodeId = baseNodeId;
    // baseNodeId handling
    var endOfBaseNodeId = self.baseNodeId.split('').pop();
    var dot = '.';
    if(endOfBaseNodeId === '.'){
      dot = '';
    }
    self.baseNodeIdModule = self.baseNodeId + dot + self.moduleName + '.';
    self.baseNodeIdInput = self.baseNodeIdModule + 'Input.';
    self.baseNodeIdOutput = self.baseNodeIdModule + 'Output.';
  }

  this.opcuaSettings = settings.opcua;
  this.opcuaServer = createOpcuaServer();
  this.opcuaClient = connectToOpcuaServer();
  // mqtt
  this.mqttSettings = settings.mqtt;
  this.mqttClient = connectToMQTTClient();
  // indPhysx
  this.indPhysxSettings = settings.indPhysx;
  // else
  this.simulateBehaviour = settings.simulateBehaviour;
  this.behaviour = settings.behaviour;
  this.initialized = false;
  this.numberOfSkills = 0;

  // functions

  function createOpcuaServer(){
    var opcuaSettings = item.opcuaSettings;
    if(!opcuaSettings){
      return null;
    }
    if(!opcuaSettings.server){
      return null;
    }
    var serverStructure = opcuaSettings.server;

    // add default server structure
    if(serverStructure.content === "default"){
      serverStructure.content = {};
      serverStructure.content[serverStructure.moduleName] = {
        type: 'Folder',
        content: require("./../structure/folderStructure.json")
      };

      // add default init values
      if(!opcuaSettings.setInitValues){
        opcuaSettings.setInitValues = [];
      }
      if(opcuaSettings.server.outputName){
        opcuaSettings.setInitValues.push({
          path: serverStructure.moduleName+'.Output.Name',
          initValue: serverStructure.outputName
        });
      }
      if(opcuaSettings.server.outputId){
        opcuaSettings.setInitValues.push({
          path: serverStructure.moduleName+'.Output.ID',
          initValue: serverStructure.outputId
        });
      }
    }

    // make host address available for client
    opcuaSettings.hostAddress = "opc.tcp://" + require("os").hostname() + ":" + opcuaSettings.server.serverInfo.port;

    // adobt baseNodeId and moduleName for skills etc.
    self.moduleName = opcuaSettings.server.moduleName;
    createNodeIds(opcuaSettings.server.baseNodeId);

    // finish opcua server structure
    if(typeof opcuaSettings.expandRepeatUnits == 'undefined' || opcuaSettings.expandRepeatUnits == true){
      var expandFolderStructure = OpcuaHelper.expandFolderStructure;
      serverStructure.content = expandFolderStructure(serverStructure.content);
    }
    if(opcuaSettings.setInitValues){
      var setInitValues = OpcuaHelper.setInitValues;
      var initValueStatements = opcuaSettings.setInitValues;
      opcuaSettings.server.content = setInitValues(serverStructure.content, initValueStatements);
    }

    // starting server
    return OpcuaServer.newOpcuaServer(opcuaSettings.server);
  }

  function connectToOpcuaServer(){
    var opcuaSettings = self.opcuaSettings;
    if(!opcuaSettings){
      return null;
    }
    //self.log('connecting to opcua server '+JSON.stringify(opcuaSettings.hostAddress));
    item.numberOfConnections++;
    return new OpcuaClient(opcuaSettings.hostAddress, function(err){
      self.log('connected to opcua server');
      if(!err){
        newConnectionEstablished();
      }
      // create variables
      self.reset = new OpcuaVariable(self.opcuaClient, self.baseNodeIdModule + 'reset');
      self.ConnectionTestInput = new OpcuaVariable(self.opcuaClient, self.baseNodeIdInput + 'ConnectionTestInput');
      self.ConnectionTestOutput = new OpcuaVariable(self.opcuaClient, self.baseNodeIdOutput + 'ConnectionTestOutput', false);
      self.PositionInput = new OpcuaVariable(self.opcuaClient, self.baseNodeIdInput + 'PositionInput');
      self.PositionOutput = new OpcuaVariable(self.opcuaClient, self.baseNodeIdOutput + 'PositionOutput', false, self.position);
      // backend logic
      self.reset.onChange(function(value){
        if(value){
          self.emit('reset');
        }
      });
      self.ConnectionTestInput.onChange(function(value){
        self.ConnectionTestOutput.write(value);
      });
      self.PositionInput.onChange(function(value){
        var position = value;
        if(settings.positionOffset)
          position += settings.positionOffset;
        self.PositionOutput.write(position);
        self.storage.setItem(self.moduleName+'position', position);
      });

    });
  }

  function connectToMQTTClient(){
    var mqttSettings = self.mqttSettings;

    if(!mqttSettings){
      return null;
    }
    self.log('connecting to mqtt broker '+mqttSettings.hostAddress);
    item.numberOfConnections++;
    var mqttClient = mqtt.connect(mqttSettings.hostAddress);
    mqttClient.on('connect', function(){
      self.log('connected to mqtt broker at '+mqttSettings.hostAddress);
      newConnectionEstablished();
    });
    mqttClient.on('error', console.log);
    return mqttClient;
  }

  function newConnectionEstablished(){
    item.numberOfConnections--;
    if(item.numberOfConnections == 0){
      self.log('All connections established successfully.');
      self.emit('connect');
      self.initialized = true;
    }
  }
}

Mi5Module.prototype.createSkill = function(SkillNumber, SkillName, SkillId, settings){
  var self = this;
  var skill = new mi5Skill(SkillNumber, SkillName, SkillId, self, settings);
  this[SkillName] = skill;
  return skill;
};

Mi5Module.prototype.log = function(message){
  this.debug(message);
};

module.exports = Mi5Module;<commit_msg>changed storage namespace<commit_after>/**
 * Created by Dominik Serve on 15.06.2016.
 */

var simpleOpcua = require('mi5-simple-opcua');
var mqtt = require('mqtt');
var EventEmitter = require('events').EventEmitter;
var util = require('util');
util.inherits(Mi5Module, EventEmitter);

var debug = require('debug');

var OpcuaServer = simpleOpcua.OpcuaServer;
var OpcuaClient = simpleOpcua.OpcuaClient;
var OpcuaHelper = simpleOpcua.helper;
var OpcuaVariable = simpleOpcua.OpcuaVariable;

var mi5Skill = require('./mi5-skill');

/**Mi5 Module inherits EventEmitter
 *
 * @param moduleName
 * @param {object} settings {opcua: {hostAddress: ..., baseNodeId: ...}, mqtt: ..., indPhysx: ...}
 * @constructor
 */

function Mi5Module(trivialName, settings){
  //console.log(trivialName, 'ceating new module');
  EventEmitter.call(this);
  var self = this;
  var item = this;

  this.debug = debug(trivialName);

  if(settings.storage){
    settings.storage = settings.storage.replace('.', process.cwd());
    this.storage = require('node-persist');
    this.storage.initSync({
      dir: settings.storage,
      stringify: JSON.stringify,
      parse: JSON.parse,
      encoding: 'utf8',
      logging: false,  // can also be custom logging function
      continuous: true,
      interval: false,
      ttl: false // ttl* [NEW], can be true for 24h default or a number in MILLISECONDS
    })/*.then(function(){self.emit()}, function(){console.log('no success')})*/;
  }

  item.numberOfConnections = 0;
  this.trivialName = trivialName;
  this.moduleId = settings.moduleId;
  this.position = -1;
  if(typeof settings.position != 'undefined')
    this.position = settings.position;
  if(self.storage)
    this.position = self.storage.getItem(self.trivialName + ' position');

  // opcua
  if(settings.opcua){
    //baseNodeId handling
    if(settings.opcua.baseNodeId)
      createNodeIds(settings.opcua.baseNodeId);
  }

  function createNodeIds(baseNodeId){
    self.baseNodeId = baseNodeId;
    // baseNodeId handling
    var endOfBaseNodeId = self.baseNodeId.split('').pop();
    var dot = '.';
    if(endOfBaseNodeId === '.'){
      dot = '';
    }
    self.baseNodeIdModule = self.baseNodeId + dot + self.moduleName + '.';
    self.baseNodeIdInput = self.baseNodeIdModule + 'Input.';
    self.baseNodeIdOutput = self.baseNodeIdModule + 'Output.';
  }

  this.opcuaSettings = settings.opcua;
  this.opcuaServer = createOpcuaServer();
  this.opcuaClient = connectToOpcuaServer();
  // mqtt
  this.mqttSettings = settings.mqtt;
  this.mqttClient = connectToMQTTClient();
  // indPhysx
  this.indPhysxSettings = settings.indPhysx;
  // else
  this.simulateBehaviour = settings.simulateBehaviour;
  this.behaviour = settings.behaviour;
  this.initialized = false;
  this.numberOfSkills = 0;

  // functions

  function createOpcuaServer(){
    var opcuaSettings = item.opcuaSettings;
    if(!opcuaSettings){
      return null;
    }
    if(!opcuaSettings.server){
      return null;
    }
    var serverStructure = opcuaSettings.server;

    // add default server structure
    if(serverStructure.content === "default"){
      serverStructure.content = {};
      serverStructure.content[serverStructure.moduleName] = {
        type: 'Folder',
        content: require("./../structure/folderStructure.json")
      };

      // add default init values
      if(!opcuaSettings.setInitValues){
        opcuaSettings.setInitValues = [];
      }
      if(opcuaSettings.server.outputName){
        opcuaSettings.setInitValues.push({
          path: serverStructure.moduleName+'.Output.Name',
          initValue: serverStructure.outputName
        });
      }
      if(opcuaSettings.server.outputId){
        opcuaSettings.setInitValues.push({
          path: serverStructure.moduleName+'.Output.ID',
          initValue: serverStructure.outputId
        });
      }
    }

    // make host address available for client
    opcuaSettings.hostAddress = "opc.tcp://" + require("os").hostname() + ":" + opcuaSettings.server.serverInfo.port;

    // adobt baseNodeId and moduleName for skills etc.
    self.moduleName = opcuaSettings.server.moduleName;
    createNodeIds(opcuaSettings.server.baseNodeId);

    // finish opcua server structure
    if(typeof opcuaSettings.expandRepeatUnits == 'undefined' || opcuaSettings.expandRepeatUnits == true){
      var expandFolderStructure = OpcuaHelper.expandFolderStructure;
      serverStructure.content = expandFolderStructure(serverStructure.content);
    }
    if(opcuaSettings.setInitValues){
      var setInitValues = OpcuaHelper.setInitValues;
      var initValueStatements = opcuaSettings.setInitValues;
      opcuaSettings.server.content = setInitValues(serverStructure.content, initValueStatements);
    }

    // starting server
    return OpcuaServer.newOpcuaServer(opcuaSettings.server);
  }

  function connectToOpcuaServer(){
    var opcuaSettings = self.opcuaSettings;
    if(!opcuaSettings){
      return null;
    }
    //self.log('connecting to opcua server '+JSON.stringify(opcuaSettings.hostAddress));
    item.numberOfConnections++;
    return new OpcuaClient(opcuaSettings.hostAddress, function(err){
      self.log('connected to opcua server');
      if(!err){
        newConnectionEstablished();
      }
      // create variables
      self.reset = new OpcuaVariable(self.opcuaClient, self.baseNodeIdModule + 'reset');
      self.ConnectionTestInput = new OpcuaVariable(self.opcuaClient, self.baseNodeIdInput + 'ConnectionTestInput');
      self.ConnectionTestOutput = new OpcuaVariable(self.opcuaClient, self.baseNodeIdOutput + 'ConnectionTestOutput', false);
      self.PositionInput = new OpcuaVariable(self.opcuaClient, self.baseNodeIdInput + 'PositionInput');
      self.PositionOutput = new OpcuaVariable(self.opcuaClient, self.baseNodeIdOutput + 'PositionOutput', false, self.position);
      // backend logic
      self.reset.onChange(function(value){
        if(value){
          self.emit('reset');
        }
      });
      self.ConnectionTestInput.onChange(function(value){
        self.ConnectionTestOutput.write(value);
      });
      self.PositionInput.onChange(function(value){
        var position = value;
        if(settings.positionOffset)
          position += settings.positionOffset;
        self.PositionOutput.write(position);
        self.storage.setItem(self.trivialName+' position', position);
      });

    });
  }

  function connectToMQTTClient(){
    var mqttSettings = self.mqttSettings;

    if(!mqttSettings){
      return null;
    }
    self.log('connecting to mqtt broker '+mqttSettings.hostAddress);
    item.numberOfConnections++;
    var mqttClient = mqtt.connect(mqttSettings.hostAddress);
    mqttClient.on('connect', function(){
      self.log('connected to mqtt broker at '+mqttSettings.hostAddress);
      newConnectionEstablished();
    });
    mqttClient.on('error', console.log);
    return mqttClient;
  }

  function newConnectionEstablished(){
    item.numberOfConnections--;
    if(item.numberOfConnections == 0){
      self.log('All connections established successfully.');
      self.emit('connect');
      self.initialized = true;
    }
  }
}

Mi5Module.prototype.createSkill = function(SkillNumber, SkillName, SkillId, settings){
  var self = this;
  var skill = new mi5Skill(SkillNumber, SkillName, SkillId, self, settings);
  this[SkillName] = skill;
  return skill;
};

Mi5Module.prototype.log = function(message){
  this.debug(message);
};

module.exports = Mi5Module;<|endoftext|>


<commit_before>/**
 * @license
 * Copyright (C) 2013 Google Inc.
 *
 * 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.
 */

/**
 * @fileoverview
 *

 * Looks at query parameters to decide which language handlers and style-sheets
 * to load.
 *
 * Query Parameter     Format           Effect                        Default
 * +------------------+---------------+------------------------------+--------+
 * | autorun=         | true | false  | If true then prettyPrint()   | "true" |
 * |                  |               | is called on page load.      |        |
 * +------------------+---------------+------------------------------+--------+
 * | lang=            | language name | Loads the language handler   | Can    |
 * |                  |               | named "lang-<NAME>.js".      | appear |
 * |                  |               | See available handlers at    | many   |
 * |                  |               | https://github.com/google/   | times. |
 * |                  |               | code-prettify/tree/master/   |        |
 * |                  |               | src                          |        |
 * +------------------+---------------+------------------------------+--------+
 * | skin=            | skin name     | Loads the skin stylesheet    | none.  |
 * |                  |               | named "<NAME>.css".          |        |
 * |                  |               | https://cdn.rawgit.com/      |        |
 * |                  |               | google/code-prettify/master/ |        |
 * |                  |               | styles/index.html            |        |
 * +------------------+---------------+------------------------------+--------+
 * | callback=        | JS identifier | When "prettyPrint" finishes  | none   |
 * |                  |               | window.exports[js_ident] is  |        |
 * |                  |               | called.                      |        |
 * |                  |               | The callback must be under   |        |
 * |                  |               | exports to reduce the risk   |        |
 * |                  |               | of XSS via query parameter   |        |
 * |                  |               | injection.                   |        |
 * +------------------+---------------+------------------------------+--------+
 *
 * Exmaples
 * .../run_prettify.js?lang=css&skin=sunburst
 *   1. Loads the CSS language handler which can be used to prettify CSS
 *      stylesheets, HTML


<commit_before>var Q = require('q'),
    models,
    datastore = require('../lib/datastore');

module.exports = RecordList;

function RecordList() {
    var me = this;

    this.search = function(query) {
        var deferred = Q.defer();

        datastore.query('SELECT records.*, recordtypes.name AS recordtype FROM records LEFT JOIN recordtypes ON (records.recordtype_id = recordtypes.id) WHERE deleted = 0 AND data LIKE ?', ['%' + query + '%'], function(err, results, fields) {
            if (err) {
                deferred.reject(err);
            } else {
                me.mainfacet = {};
                me.records = [];
                me.total = results.length;
                me.count = results.length;
                var promises = [];
                for (var idx in results) {
                    promises.push(new models.Record(results[idx]));
                }
                Q.all(promises).then(function(records) {
                    for (var idx in records) {
                        records[idx].rendered = records[idx].render();
                        records[idx].number = parseInt(idx, 10) + 1;
                        me.records.push(records[idx]);
                        me.mainfacet[records[idx].recordtype] = (parseInt(me.mainfacet[records[idx].recordtype], 10) || 0) + 1;
                    }
                    deferred.resolve(me);
                });
            }
        });
        return deferred.promise;
    };

    this.fromlinks = function(links) {
        var deferred = Q.defer();
        me.mainfacet = {};
        me.records = [];
        me.total = links.length;
        me.count = links.length;
        var promises = [];
        for (var idx in links) {
            if (links[idx].type === 'In') {
                promises.push(links[idx].source());
            } else {
                promises.push(links[idx].target());
            }
        }
        Q.all(promises).then(function(records) {
            for (var idx in records) {
                records[idx].rendered = records[idx].render();
                records[idx].number = parseInt(idx, 10) + 1;
                me.records.push(records[idx]);
                me.mainfacet[links[idx].type] = (parseInt(me.mainfacet[links[idx].type], 10) || 0) + 1;
            }
            deferred.resolve(me);
        });
        return deferred.promise;
    };
}

RecordList.init = function(ref) {
    models = ref;
};
<commit_msg>Dedup link lists<commit_after>var Q = require('q'),
    models,
    datastore = require('../lib/datastore');

module.exports = RecordList;

function RecordList() {
    var me = this;

    this.search = function(query) {
        var deferred = Q.defer();

        datastore.query('SELECT records.*, recordtypes.name AS recordtype FROM records LEFT JOIN recordtypes ON (records.recordtype_id = recordtypes.id) WHERE deleted = 0 AND data LIKE ?', ['%' + query + '%'], function(err, results, fields) {
            if (err) {
                deferred.reject(err);
            } else {
                me.mainfacet = {};
                me.records = [];
                me.total = results.length;
                me.count = results.length;
                var promises = [];
                for (var idx in results) {
                    promises.push(new models.Record(results[idx]));
                }
                Q.all(promises).then(function(records) {
                    for (var idx in records) {
                        records[idx].rendered = records[idx].render();
                        records[idx].number = parseInt(idx, 10) + 1;
                        me.records.push(records[idx]);
                        me.mainfacet[records[idx].recordtype] = (parseInt(me.mainfacet[records[idx].recordtype], 10) || 0) + 1;
                    }
                    deferred.resolve(me);
                });
            }
        });
        return deferred.promise;
    };

    this.fromlinks = function(links) {
        var deferred = Q.defer();
        me.mainfacet = {};
        me.records = [];
        var promises = [];
        for (var idx in links) {
            if (links[idx].type === 'In') {
                promises.push(links[idx].source());
            } else {
                promises.push(links[idx].target());
            }
        }
        Q.all(promises).then(function(records) {
            var seen = {};
            for (var idx in records) {
                if (typeof seen[records[idx].id] === 'undefined') {
                    seen[records[idx].id] = 1;
                    records[idx].rendered = records[idx].render();
                    records[idx].number = parseInt(idx, 10) + 1;
                    me.records.push(records[idx]);
                    me.mainfacet[links[idx].type] = (parseInt(me.mainfacet[links[idx].type], 10) || 0) + 1;
                }
            }
            me.total = me.records.length;
            me.count = me.records.length;
            deferred.resolve(me);
        });
        return deferred.promise;
    };
}

RecordList.init = function(ref) {
    models = ref;
};
<|endoftext|>


<commit_before>const mongoose = require("mongoose");

const passwordPlugin = require("./plugins/password-plugin");
const passportLocalPlugin = require("./plugins/passport-local-plugin");
const passportOauthPlugin = require("./plugins/passport-oauth-plugin");

const User = mongoose.Schema({
  local: {
    username: { type: String, unique: true, sparse: true, trim: true },
    email: { type: String, unique: true, sparse: true, trim: true },
    hash: { type: String, select: false },
    salt: { type: String, select: false }
  },
  github: {
    id: { type: String },
    username: { type: String, trim: true },
    image_url: { type: String, default: "/media/dummy_image.png" }
  },
  twitter: {
    id: { type: String },
    username: { type: String, trim: true },
    image_url: { type: String, default: "/media/dummy_image.png" }
  }
});

User.plugin(passwordPlugin, {
  usernameField: "local.username",
  hashField: "local.hash",
  saltField: "local.salt"
});

User.plugin(passportLocalPlugin, {
  usernameField: "local.username",
  hashField: "local.hash",
  saltField: "local.salt"
});

User.plugin(passportOauthPlugin);

module.exports = mongoose.model("user", User);
<commit_msg>add image_url to local user info<commit_after>const mongoose = require("mongoose");

const passwordPlugin = require("./plugins/password-plugin");
const passportLocalPlugin = require("./plugins/passport-local-plugin");
const passportOauthPlugin = require("./plugins/passport-oauth-plugin");

const User = mongoose.Schema({
  local: {
    username: { type: String, unique: true, sparse: true, trim: true },
    email: { type: String, unique: true, sparse: true, trim: true },
    image_url: { type: String, default: "/media/dummy_image.png" },
    hash: { type: String, select: false },
    salt: { type: String, select: false }
  },
  github: {
    id: { type: String },
    username: { type: String, trim: true },
    image_url: { type: String, default: "/media/dummy_image.png" }
  },
  twitter: {
    id: { type: String },
    username: { type: String, trim: true },
    image_url: { type: String, default: "/media/dummy_image.png" }
  }
});

User.plugin(passwordPlugin, {
  usernameField: "local.username",
  hashField: "local.hash",
  saltField: "local.salt"
});

User.plugin(passportLocalPlugin, {
  usernameField: "local.username",
  hashField: "local.hash",
  saltField: "local.salt"
});

User.plugin(passportOauthPlugin);

module.exports = mongoose.model("user", User);
<|endoftext|>


<commit_before>#!/usr/bin/env node
var askPush, command, diversityData, exec, filelist, finish, fs, gitPullBranch, newDiversity, newVersion, position, push, readDiversity, rls, runCommand, runTest, settings, shell, shouldPush, updateString, versionArray, versionNumber, writeDiversity;

fs = require('fs');

exec = require('child_process').exec;

push = require('commander');

rls = require('readline-sync');

shell = require('shelljs');

if (!shell.which('git')) {
  shell.echo('Sorry, this script requires git');
  shell.exit(1);
}

settings = {
  diversityPath: process.cwd() + '/diversity.json',
  encoding: 'utf-8',
  jsonSpaces: 2
};

push.version((function() {
  var packageJson, packagePath;
  packagePath = __dirname + '/../package.json';
  packageJson = JSON.parse(fs.readFileSync(packagePath, {
    encoding: 'utf8'
  }));
  return packageJson.version;
})()).option('-r, --release [type]', 'Start up git flow release. Type can be major, minor or patch. Default is patch. Will not finish or push without asking.').parse(process.argv);

readDiversity = function(path) {
  return fs.readFileSync(path, settings.encoding, function(err, data) {
    if (err) {
      throw err;
    }
    return JSON.parse(data);
  });
};

writeDiversity = function(path, data) {
  return fs.writeFileSync(path, data, settings.encoding, function(err) {
    if (err) {
      throw err;
    }
    return true;
  });
};

runCommand = function(command) {
  if ((shell.exec(command)).code !== 0) {
    shell.echo('Error: ' + command + ' failed. Exiting.');
    return shell.exit(1);
  }
};

runTest = function(command) {
  var question;
  if ((shell.exec(command)).code !== 0) {
    question = "\"" + command + "\" failed, do you want to abort the release and fix this? [Y/n]:";
    if (rls.question(question) !== 'n') {
      return shell.exit(0);
    }
  }
};

gitPullBranch = function(branch) {
  runCommand('git checkout ' + branch);
  if (shell.exec('git pull').code !== 0) {
    runCommand('git reset --hard');
    shell.echo('Error: master could not be automatically merged with origin/master. Please update master and try again');
    return shell.exit(1);
  }
};

if (push.release) {
  console.log('Stashing any non-committed changes:');
  runCommand('git stash');
  gitPullBranch('master');
  gitPullBranch('develop');
  runTest('gulp jscs');
  runTest('gulp jshint');
  runTest('gulp lint-css:style-names');
  runTest('gulp lint-css:doiuse');
  runTest('gulp translations-update-fail-on-incomplete');
  runTest('gulp protractor:single-run');
  runTest('gulp karma:single-run');
  diversityData = JSON.parse(readDiversity(settings.diversityPath));
  versionArray = diversityData.version.split('.');
  command = push.release === true ? 'patch' : push.release;
  position = 2;
  if (command === 'major') {
    position = 0;
    versionArray[1] = '0';
    versionArray[2] = '0';
  }
  if (command === 'minor') {
    position = 1;
    versionArray[2] = '0';
  }
  versionNumber = parseInt(versionArray[position], 10);
  versionNumber += 1;
  versionArray[position] = versionNumber.toString();
  newVersion = versionArray.join('.');
  diversityData.version = newVersion;
  newDiversity = JSON.stringify(diversityData, null, settings.jsonSpaces);
  updateString = 'Bumped ' + command + ' version to ' + newVersion + '.';
  console.log(updateString + ' Proceeding.');
  runCommand('git flow release start ' + newVersion);
  console.log('Started git flow release.');
  writeDiversity(settings.diversityPath, newDiversity);
  console.log('Updated version in diversity.json');
  console.log('Starting to minify, may take a few moments...');
  runCommand('gulp minify');
  console.log('Minified to scripts.min.js.');
  filelist = 'diversity.json';
  if (fs.existsSync(process.cwd() + '/scripts.min.js')) {
    filelist += ' scripts.min.js';
  }
  runCommand('git commit ' + filelist + ' -m "' + updateString + ' and minified scripts."');
  console.log('Commited diversity.json and scripts.min.js');
  askPush = false;
  finish = rls.question('Would you like to finish the release? [Y/n]: ');
  if (finish.toLowerCase() === 'n') {
    console.log("Don't forget to finish the release after you're done.");
  } else {
    askPush = true;
    runCommand('git flow release finish -m "' + newVersion + '" ' + newVersion);
    console.log('Finishing git flow release.');
  }
  if (askPush) {
    shouldPush = rls.question('Would you like to push the release? [Y/n]: ');
    if (shouldPush.toLowerCase() === 'n') {
      console.log("Don't forget to push after you're done.");
    } else {
      runCommand('git push --all && git push --tags');
      console.log('Pushing release and tags.');
    }
  }
  console.log("Done!");
} else {
  push.outputHelp();
}
<commit_msg>gulp coffee<commit_after>#!/usr/bin/env node
var askPush, command, diversityData, exec, filelist, finish, fs, gitPullBranch, newDiversity, newVersion, position, push, readDiversity, rls, runCommand, runTest, settings, shell, shouldPush, updateString, versionArray, versionNumber, writeDiversity;

fs = require('fs');

exec = require('child_process').exec;

push = require('commander');

rls = require('readline-sync');

shell = require('shelljs');

if (!shell.which('git')) {
  shell.echo('Sorry, this script requires git');
  shell.exit(1);
}

settings = {
  diversityPath: process.cwd() + '/diversity.json',
  encoding: 'utf-8',
  jsonSpaces: 2
};

push.version((function() {
  var packageJson, packagePath;
  packagePath = __dirname + '/../package.json';
  packageJson = JSON.parse(fs.readFileSync(packagePath, {
    encoding: 'utf8'
  }));
  return packageJson.version;
})()).option('-r, --release [type]', 'Start up git flow release. Type can be major, minor or patch. Default is patch. Will not finish or push without asking.').parse(process.argv);

readDiversity = function(path) {
  return fs.readFileSync(path, settings.encoding, function(err, data) {
    if (err) {
      throw err;
    }
    return JSON.parse(data);
  });
};

writeDiversity = function(path, data) {
  return fs.writeFileSync(path, data, settings.encoding, function(err) {
    if (err) {
      throw err;
    }
    return true;
  });
};

runCommand = function(command) {
  if ((shell.exec(command)).code !== 0) {
    shell.echo('Error: ' + command + ' failed. Exiting.');
    return shell.exit(1);
  }
};

runTest = function(command) {
  var question;
  if ((shell.exec(command)).code !== 0) {
    question = "\"" + command + "\" failed, do you want to abort the release and fix this? [Y/n]:";
    if (rls.question(question) !== 'n') {
      return shell.exit(0);
    }
  }
};

gitPullBranch = function(branch) {
  runCommand('git checkout ' + branch);
  if (shell.exec('git pull').code !== 0) {
    runCommand('git reset --hard');
    shell.echo('Error: master could not be automatically merged with origin/master. Please update master and try again');
    return shell.exit(1);
  }
};

if (push.release) {
  console.log('Stashing any non-committed changes:');
  runCommand('git stash');
  gitPullBranch('master');
  gitPullBranch('develop');
  runTest('gulp jscs');
  runTest('gulp jshint');
  runTest('gulp lint-css:style-names');
  runTest('gulp lint-css:doiuse');
  runTest('gulp translations-update-fail-on-incomplete');
  runTest('gulp protractor:single-run');
  runTest('gulp karma:single-run');
  diversityData = JSON.parse(readDiversity(settings.diversityPath));
  versionArray = diversityData.version.split('.');
  command = push.release === true ? 'patch' : push.release;
  position = 2;
  if (command === 'major') {
    position = 0;
    versionArray[1] = '0';
    versionArray[2] = '0';
  }
  if (command === 'minor') {
    position = 1;
    versionArray[2] = '0';
  }
  versionNumber = parseInt(versionArray[position], 10);
  versionNumber += 1;
  versionArray[position] = versionNumber.toString();
  newVersion = versionArray.join('.');
  diversityData.version = newVersion;
  newDiversity = JSON.stringify(diversityData, null, settings.jsonSpaces);
  updateString = 'Bumped ' + command + ' version to ' + newVersion + '.';
  console.log(updateString + ' Proceeding.');
  runCommand('git flow release start ' + newVersion);
  console.log('Started git flow release.');
  writeDiversity(settings.diversityPath, newDiversity);
  console.log('Updated version in diversity.json');
  console.log('Starting to minify, may take a few moments...');
  runCommand('gulp minify');
  console.log('Minified to scripts.min.js.');
  filelist = 'diversity.json';
  if (fs.existsSync(process.cwd() + '/scripts.min.js')) {
    filelist += ' scripts.min.js';
  }
  runCommand('git commit ' + filelist + ' -m "' + updateString + ' and minified scripts."');
  console.log('Commited diversity.json and scripts.min.js');
  askPush = false;
  finish = rls.question('Would you like to finish the release? [Y/n]: ');
  if (finish.toLowerCase() === 'n') {
    console.log("Don't forget to finish the release after you're done.");
  } else {
    askPush = true;
    runCommand('git flow release finish -m "' + newVersion + '" ' + newVersion);
    console.log('Finishing git flow release.');
  }
  if (askPush) {
    shouldPush = rls.question('Would you like to push the release? [Y/n]: ');
    if (shouldPush.toLowerCase() === 'n') {
      console.log("Don't forget to push after you're done.");
    } else {
      runCommand('git push --all && git push --tags');
      console.log('Pushing release and tags.');
    }
  }
  console.log("Done!");
} else {
  push.outputHelp();
}
<|endoftext|>


<commit_before>System.register('flagrow/analytics/components/AnalyticsSettingsModal', ['flarum/components/SettingsModal'], function (_export) {
    'use strict';

    var SettingsModal, AnalyticsSettingsModal;
    return {
        setters: [function (_flarumComponentsSettingsModal) {
            SettingsModal = _flarumComponentsSettingsModal['default'];
        }],
        execute: function () {
            AnalyticsSettingsModal = (function (_SettingsModal) {
                babelHelpers.inherits(AnalyticsSettingsModal, _SettingsModal);

                function AnalyticsSettingsModal() {
                    babelHelpers.classCallCheck(this, AnalyticsSettingsModal);
                    babelHelpers.get(Object.getPrototypeOf(AnalyticsSettingsModal.prototype), 'constructor', this).apply(this, arguments);
                }

                babelHelpers.createClass(AnalyticsSettingsModal, [{
                    key: 'className',
                    value: function className() {
                        return 'AnalyticsSettingsModal Modal--small';
                    }
                }, {
                    key: 'title',
                    value: function title() {
                        return app.translator.trans('flagrow-analytics.admin.title');
                    }
                }, {
                    key: 'form',
                    value: function form() {
                        var _this = this;

                        // the fields we need to save
                        this.fields = ['googleTrackingCode', 'piwikUrl', 'piwikSiteId', 'piwikAliasUrl'];

                        // the checkboxes we need to save.
                        this.checkboxes = ['statusGoogle', 'statusPiwik', 'piwikTrackSubdomain', 'piwikPrependDomain', 'piwikHideAliasUrl'];

                        this.inputs = [];
                        this.checkbox = [];

                        // our package prefix (to be added to every field and checkbox in the setting table)
                        this.settingsPrefix = 'flagrow.analytics';

                        // the input fields
                        this.fields.forEach(function (key) {
                            return _this.inputs[key] = m('input', {
                                className: 'FormControl',
                                bidi: _this.setting(_this.settingsPrefix + '.' + key),
                                placeholder: app.translator.trans('flagrow-analytics.admin.field.' + key)
                            });
                        });

                        // the checkboxes
                        this.checkboxes.forEach(function (key) {
                            return _this.checkbox[key] = m('input', {
                                id: key,
                                type: 'checkbox',
                                style: 'float:left; margin-right:3px; margin-top: 2px;',
                                bidi: _this.setting(_this.settingsPrefix + '.' + key)
                            });
                        });

                        // the labels
                        this.checkboxes.forEach(function (key) {
                            return _this.checkbox['label.' + key] = m('div', [app.translator.trans('flagrow-analytics.admin.checkbox.label.' + key)]);
                        });

                        return [m('div', { className: 'Form-group' }, [m('label', ['Google Analytics ', this.checkbox['statusGoogle']]), m('div', { style: { display: $('#statusGoogle').prop('checked') === true ? "block" : "none" } }, [this.inputs['googleTrackingCode']]), m('br'), m('label', ['Piwik ', this.checkbox['statusPiwik']]), m('div', { style: { display: $('#statusPiwik').prop('checked') === true ? "block" : "none" } }, [this.inputs['piwikUrl'], m('br'), this.inputs['piwikSiteId'], m('br'), this.checkbox['piwikTrackSubdomain'], this.checkbox['label.piwikTrackSubdomain'], m('br'), this.checkbox['piwikPrependDomain'], this.checkbox['label.piwikPrependDomain'], m('br'), this.checkbox['piwikHideAliasUrl'], this.checkbox['label.piwikHideAliasUrl'], m('div', { style: { display: $('#piwikHideAliasUrl').prop('checked') === true ? "block" : "none" } }, [this.inputs['piwikAliasUrl']])])])];
                    }
                }]);
                return AnalyticsSettingsModal;
            })(SettingsModal);

            _export('default', AnalyticsSettingsModal);
        }
    };
});;
System.register('flagrow/analytics/main', ['flarum/extend', 'flarum/app', 'flagrow/analytics/components/AnalyticsSettingsModal'], function (_export) {
  'use strict';

  var extend, app, AnalyticsSettingsModal;
  return {
    setters: [function (_flarumExtend) {
      extend = _flarumExtend.extend;
    }, function (_flarumApp) {
      app = _flarumApp['default'];
    }, function (_flagrowAnalyticsComponentsAnalyticsSettingsModal) {
      AnalyticsSettingsModal = _flagrowAnalyticsComponentsAnalyticsSettingsModal['default'];
    }],
    execute: function () {

      app.initializers.add('flagrow-analytics', function (app) {
        app.extensionSettings['flagrow-analytics'] = function () {
          return app.modal.show(new AnalyticsSettingsModal());
        };
      });
    }
  };
});<commit_msg>location changes<commit_after>System.register('flagrow/analytics/components/AnalyticsSettingsModal', ['flarum/components/SettingsModal'], function (_export) {
    'use strict';

    var SettingsModal, AnalyticsSettingsModal;
    return {
        setters: [function (_flarumComponentsSettingsModal) {
            SettingsModal = _flarumComponentsSettingsModal['default'];
        }],
        execute: function () {
            AnalyticsSettingsModal = (function (_SettingsModal) {
                babelHelpers.inherits(AnalyticsSettingsModal, _SettingsModal);

                function AnalyticsSettingsModal() {
                    babelHelpers.classCallCheck(this, AnalyticsSettingsModal);
                    babelHelpers.get(Object.getPrototypeOf(AnalyticsSettingsModal.prototype), 'constructor', this).apply(this, arguments);
                }

                babelHelpers.createClass(AnalyticsSettingsModal, [{
                    key: 'className',
                    value: function className() {
                        return 'AnalyticsSettingsModal Modal--small';
                    }
                }, {
                    key: 'title',
                    value: function title() {
                        return app.translator.trans('flagrow-analytics.admin.popup.title');
                    }
                }, {
                    key: 'form',
                    value: function form() {
                        var _this = this;

                        // the fields we need to save
                        this.fields = ['googleTrackingCode', 'piwikUrl', 'piwikSiteId', 'piwikAliasUrl'];

                        // the checkboxes we need to save.
                        this.checkboxes = ['statusGoogle', 'statusPiwik', 'piwikTrackSubdomain', 'piwikPrependDomain', 'piwikHideAliasUrl'];

                        this.inputs = [];
                        this.checkbox = [];

                        // our package prefix (to be added to every field and checkbox in the setting table)
                        this.settingsPrefix = 'flagrow.analytics';

                        // the input fields
                        this.fields.forEach(function (key) {
                            return _this.inputs[key] = m('input', {
                                className: 'FormControl',
                                bidi: _this.setting(_this.settingsPrefix + '.' + key),
                                placeholder: app.translator.trans('flagrow-analytics.admin.popup.field.' + key)
                            });
                        });

                        // the checkboxes
                        this.checkboxes.forEach(function (key) {
                            return _this.checkbox[key] = m('input', {
                                id: key,
                                type: 'checkbox',
                                style: 'float:left; margin-right:3px; margin-top: 2px;',
                                bidi: _this.setting(_this.settingsPrefix + '.' + key)
                            });
                        });

                        // the labels
                        this.checkboxes.forEach(function (key) {
                            return _this.checkbox['label.' + key] = m('div', [app.translator.trans('flagrow-analytics.admin.popup.checkbox.label.' + key)]);
                        });

                        return [m('div', { className: 'Form-group' }, [m('label', ['Google Analytics ', this.checkbox['statusGoogle']]), m('div', { style: { display: $('#statusGoogle').prop('checked') === true ? "block" : "none" } }, [this.inputs['googleTrackingCode']]), m('br'), m('label', ['Piwik ', this.checkbox['statusPiwik']]), m('div', { style: { display: $('#statusPiwik').prop('checked') === true ? "block" : "none" } }, [this.inputs['piwikUrl'], m('br'), this.inputs['piwikSiteId'], m('br'), this.checkbox['piwikTrackSubdomain'], this.checkbox['label.piwikTrackSubdomain'], m('br'), this.checkbox['piwikPrependDomain'], this.checkbox['label.piwikPrependDomain'], m('br'), this.checkbox['piwikHideAliasUrl'], this.checkbox['label.piwikHideAliasUrl'], m('div', { style: { display: $('#piwikHideAliasUrl').prop('checked') === true ? "block" : "none" } }, [this.inputs['piwikAliasUrl']])])])];
                    }
                }]);
                return AnalyticsSettingsModal;
            })(SettingsModal);

            _export('default', AnalyticsSettingsModal);
        }
    };
});;
System.register('flagrow/analytics/main', ['flarum/extend', 'flarum/app', 'flagrow/analytics/components/AnalyticsSettingsModal'], function (_export) {
  'use strict';

  var extend, app, AnalyticsSettingsModal;
  return {
    setters: [function (_flarumExtend) {
      extend = _flarumExtend.extend;
    }, function (_flarumApp) {
      app = _flarumApp['default'];
    }, function (_flagrowAnalyticsComponentsAnalyticsSettingsModal) {
      AnalyticsSettingsModal = _flagrowAnalyticsComponentsAnalyticsSettingsModal['default'];
    }],
    execute: function () {

      app.initializers.add('flagrow-analytics', function (app) {
        app.extensionSettings['flagrow-analytics'] = function () {
          return app.modal.show(new AnalyticsSettingsModal());
        };
      });
    }
  };
});<|endoftext|>


<commit_before>/**
 * Created with IntelliJ IDEA.
 * User: pat
 * Date: 12-05-10
 * Time: 2:15 PM
 * To change this template use File | Settings | File Templates.
 */
define(['underscore', 'backbone', '../lib/utility', '../lib/backbone-utility', '../lib/backbone-couch-schema-model', '../lib/backbone.couchdb'],
    function (_, Backbone, Utility, BackboneUtility, BackboneCouchSchemaModel, Backbone) {

  var TodoApp = {
    Models:{},
    Collections:{},
    Routers:{},
    App: {
      router: false
    }
  };

  TodoApp.Models.Todo = BackboneCouchSchemaModel.extend({
    // TODO Introduce a app-config dependency that contains all the configuration options of the application, such as the url of the couchdb server
    defaults: {
      type: 'todo',
      name: ''
    },
    schema:{
      description:'Todo item',
      type:'todo',
      properties:{
        name:{
          title:'Name',
          type:'string',
          required:true,
          'default':'What needs to be done?'
        },
        description:{
          title:'Description',
          type:'string'
        },
        createdAt:{
          title:'Creation date',
          type:'string',
          format: 'date-time'
        },
        completedAt:{
          title:'Completion date',
          type:'string',
          format: 'date-time'
        }
      }
    }
  });

  TodoApp.Collections.TodoCollection = Backbone.couch.Collection.extend({
    model:TodoApp.Models.Todo,
    change_feed: true,
    couch: function() {
      return {
        view: Backbone.couch.options.design + '/by_type',
        key: 'todo',
        include_docs: true
      }
    },
    initialize: function(){
      this._db = Backbone.couch.db(Backbone.couch.options.database);
    }
    // _db:Backbone.couch.db(Backbone.couch.options.database) // Set a runtime...
  });

  TodoApp.Routers.TodoRouter = BackboneUtility.Routers.ScaffoldViewBasedRouter.extend({
    modelName:'todo',
    pluralModelName:'todos',
    modelClass:TodoApp.Models.Todo,
    parentContainer: $("#apps-container").append('

'),
    initialize: function(opts){
      BackboneUtility.Routers.ScaffoldViewBasedRouter.prototype.initialize.apply(this, arguments);
      this.collection = new TodoApp.Collections.TodoCollection();
    }
  });

  return TodoApp;
});<commit_msg>Removing defaults 'name' field, it already puts the backbone model in an invalid state.. which is no good<commit_after>/**
 * Created with IntelliJ IDEA.
 * User: pat
 * Date: 12-05-10
 * Time: 2:15 PM
 * To change this template use File | Settings | File Templates.
 */
define(['underscore', 'backbone', '../lib/utility', '../lib/backbone-utility', '../lib/backbone-couch-schema-model', '../lib/backbone.couchdb'],
    function (_, Backbone, Utility, BackboneUtility, BackboneCouchSchemaModel, Backbone) {

  var TodoApp = {
    Models:{},
    Collections:{},
    Routers:{},
    App: {
      router: false
    }
  };

  TodoApp.Models.Todo = BackboneCouchSchemaModel.extend({
    // TODO Introduce a app-config dependency that contains all the configuration options of the application, such as the url of the couchdb server
    defaults: {
      type: 'todo'
    },
    schema:{
      description:'Todo item',
      type:'todo',
      properties:{
        name:{
          title:'Name',
          type:'string',
          required:true,
          'default':'What needs to be done?'
        },
        description:{
          title:'Description',
          required: false,
          type:'string'
        },
        createdAt:{
          title:'Creation date',
          type:'string',
          format: 'date-time'
        },
        completedAt:{
          title:'Completion date',
          type:'string',
          format: 'date-time'
        }
      }
    }
  });

  TodoApp.Collections.TodoCollection = Backbone.couch.Collection.extend({
    model:TodoApp.Models.Todo,
    change_feed: true,
    couch: function() {
      return {
        view: Backbone.couch.options.design + '/by_type',
        key: 'todo',
        include_docs: true
      }
    },
    initialize: function(){
      this._db = Backbone.couch.db(Backbone.couch.options.database);
    }
    // _db:Backbone.couch.db(Backbone.couch.options.database) // Set a runtime...
  });

  TodoApp.Routers.TodoRouter = BackboneUtility.Routers.ScaffoldViewBasedRouter.extend({
    modelName:'todo',
    pluralModelName:'todos',
    modelClass:TodoApp.Models.Todo,
    parentContainer: $("#apps-container").append('

'),
    initialize: function(opts){
      BackboneUtility.Routers.ScaffoldViewBasedRouter.prototype.initialize.apply(this, arguments);
      this.collection = new TodoApp.Collections.TodoCollection();
    }
  });

  return TodoApp;
});<|endoftext|>


<commit_before>function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.projectId = $("#projectHeader").data('value');

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);
    gvm.menuLanguage = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("MenuLanguage");}, gvm);
    gvm.savePage = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SaveBtn");}, gvm);

    gvm.competences = ko.observableArray([]);

    gvm.getProjectInfo = function() {
        $.getJSON('/api/project/' + gvm.projectId, function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
        });
    };

    gvm.getAllData = function() {
         $.getJSON('/api/project/getAllData/' + gvm.projectId, function(data) {
            console.log(data);
         });
    };

    gvm.updateCompetence = function(id, code, description, max, weight) {
        var comp = new Competence(this, id, code, description, weight);
        gvm.competences.push(comp);
        return comp;
    };

    gvm.clearStructure = function() {
        gvm.competences.destroyAll();
    };
}

function initPage() {
    fetchProjectStructure();
    viewModel.getProjectInfo();
    viewModel.getAllData();

    $(".savePageBtn").click(function(){
        saveProjectScore();
    });
}

function fetchProjectScore()
{
    $.getJSON("/api/projectscore/" + projectid + "/" + studentid, function(data)
    {
        $.each(viewModel.competences(), function(i,item){
                    $.each(item.subcompetences(), function(i, subcomp)
                    {
                        $.each(subcomp.indicators(),function(i,indic)
                        {
                            for(var i = 0; i < data.length; i++) {
                            if (indic.id() == data[i].indicator) {
                                indic.score(data[i].score);
                                indic.scoreid(data[i].id);
                            }
                    }
                });
            });
        });
    });
}

function saveProjectScore()
{
    console.log(viewModel.competences()[1].subcompetences()[0].indicators()[4].scoreid());
    //console.log(viewModel.competences()[0].subcompetences()[0].indicators()[0].score());
    $.ajax({
        type: "POST",
        url: "/api/projectscore/" + projectid + "/" + studentid,
        data: ko.toJSON(viewModel.competences),
        success: function(data){
            // TODO make multilangual and with modals
            alert("Saved projectscore to server");
            console.log(data);
            //window.location = "/assess/project/" + projectid + "/students";
        }
    });
}

function fetchProjectStructure() {
    viewModel.clearStructure();

    $.getJSON("/api/projectstructure/" + projectid, function(data){
        $.each(data, function(i, item){
            var competence = viewModel.updateCompetence(item.id, item.code, item.description);

            $.each(item.subcompetences, function(i, subcomp){
                var subcompetence = new SubCompetence(competence, subcomp.id, subcomp.code, subcomp.description);
                competence.subcompetences.push(subcompetence);

                $.each(subcomp.indicators, function(i, indic){
                    subcompetence.indicators.push(new Indicator(subcompetence, indic.id, indic.name, indic.description, 0,indic.id, indic.pointType));
                });
            });
        });
        fetchProjectScore();
    });
}

function Competence(viewmodel, id, code, name, subcompetences) {
    return {
        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        subcompetences: ko.observableArray(subcompetences)
    };
}

function SubCompetence(parent, id, code, name, indicators) {
    return {
        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        indicators: ko.observableArray(indicators)
    };
}

function Indicator(parent, id, name, description, score, scoreid,pointType, checked) {
    return {
        id: ko.observable(id),
        name: ko.observable(name),
        description: ko.observable(description),
        score: ko.observable(score),
        scoreid: ko.observable(scoreid || 0),
        pointType: ko.observable(pointType),
        checked : ko.observable(checked)
    };
}<commit_msg>Fixing save grades<commit_after>function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.projectId = $("#projectHeader").data('value');

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);
    gvm.menuLanguage = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("MenuLanguage");}, gvm);
    gvm.savePage = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SaveBtn");}, gvm);

    gvm.competences = ko.observableArray([]);

    gvm.getProjectInfo = function() {
        $.getJSON('/api/project/' + gvm.projectId, function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
        });
    };

    gvm.getAllData = function() {
         $.getJSON('/api/project/getAllData/' + gvm.projectId, function(data) {
            console.log(data);
         });
    };

    gvm.updateCompetence = function(id, code, description, max, weight) {
        var comp = new Competence(this, id, code, description, weight);
        gvm.competences.push(comp);
        return comp;
    };

    gvm.clearStructure = function() {
        gvm.competences.destroyAll();
    };
}

function initPage() {
    fetchProjectStructure();
    viewModel.getProjectInfo();
    viewModel.getAllData();

    $(".savePageBtn").click(function(){
        saveProjectScore();
    });
}

function fetchProjectScore()
{
    $.getJSON("/api/projectscore/" + projectid + "/" + studentid, function(data)
    {
        console.log(data);
        $.each(viewModel.competences(), function(i,item){
                    $.each(item.subcompetences(), function(i, subcomp)
                    {
                        $.each(subcomp.indicators(),function(i,indic)
                        {
                            for(var i = 0; i < data.length; i++) {
                            if (indic.id() == data[i].indicator) {
                                indic.score(data[i].score);
                                indic.scoreid(data[i].id);
                            }
                    }
                });
            });
        });
    });
}

function saveProjectScore()
{
    //console.log(viewModel.competences()[1].subcompetences()[0].indicators()[4].scoreid());
    //console.log(viewModel.competences()[0].subcompetences()[0].indicators()[0].score());
    $.ajax({
        type: "POST",
        url: "/api/projectscore/" + projectid + "/" + studentid,
        data: ko.toJSON(viewModel.competences),
        success: function(data){
            // TODO make multilangual and with modals
            alert("Saved projectscore to server");
            console.log(data);
            //window.location = "/assess/project/" + projectid + "/students";
        }
    });
}

function fetchProjectStructure() {
    viewModel.clearStructure();

    $.getJSON("/api/projectstructure/" + projectid, function(data){
        $.each(data, function(i, item){
            var competence = viewModel.updateCompetence(item.id, item.code, item.description);

            $.each(item.subcompetences, function(i, subcomp){
                var subcompetence = new SubCompetence(competence, subcomp.id, subcomp.code, subcomp.description);
                competence.subcompetences.push(subcompetence);

                $.each(subcomp.indicators, function(i, indic){
                    subcompetence.indicators.push(new Indicator(subcompetence, indic.id, indic.name, indic.description, 0,indic.id, indic.pointType));
                });
            });
        });
        fetchProjectScore();
    });
}

function Competence(viewmodel, id, code, name, subcompetences) {
    return {
        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        subcompetences: ko.observableArray(subcompetences)
    };
}

function SubCompetence(parent, id, code, name, indicators) {
    return {
        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        indicators: ko.observableArray(indicators)
    };
}

function Indicator(parent, id, name, description, score, scoreid,pointType, checked) {
    return {
        id: ko.observable(id),
        name: ko.observable(name),
        description: ko.observable(description),
        score: ko.observable(score),
        scoreid: ko.observable(scoreid || 0),
        pointType: ko.observable(pointType),
        checked : ko.observable(checked)
    };
}<|endoftext|>


<commit_before>function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.projectId = $("#projectHeader").data('value');

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);
    gvm.savePage = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SaveBtn");}, gvm);

    gvm.competences = ko.observableArray([]);

    gvm.getProjectInfo = function() {
        $.getJSON('/api/project/' + gvm.projectId, function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
        });
    };

    gvm.getAllData = function() {
         $.getJSON('/api/project/getAllData/' + gvm.projectId, function(data) {
            console.log(data);
         });
    };

    gvm.updateCompetence = function(id, code, description, max, weight) {
        var comp = new Competence(this, id, code, description, weight);
        gvm.competences.push(comp);
        return comp;
    };

    gvm.clearStructure = function() {
        gvm.competences.destroyAll();
    };
}

function initPage() {
    viewModel.getProjectInfo();
    viewModel.getAllData();

    fetchProjectStructure()
    fetchProjectScore();

    $(".savePageBtn").click(function(){

    });
}

function fetchProjectScore()
{
    $.getJSON("/api/projectscore/" + projectid + "/" + studentid, function(data)
    {
        $.each(viewModel.competences, function(i,item){
            console.log(item.id);
        });
    });
}

function fetchProjectStructure() {
    viewModel.clearStructure();

    $.getJSON("/api/projectstructure/" + projectid, function(data){
        $.each(data, function(i, item){
            var competence = viewModel.updateCompetence(item.id, item.code, item.description);

            $.each(item.subcompetences, function(i, subcomp){
                var subcompetence = new SubCompetence(competence, subcomp.id, subcomp.code, subcomp.description);
                competence.subcompetences.push(subcompetence);

                $.each(subcomp.indicators, function(i, indic){
                    subcompetence.indicators.push(new Indicator(subcompetence, indic.id, indic.name, indic.description, 0));
                });
            });
        })
    });
}

function Competence(viewmodel, id, code, name, subcompetences) {
    return {
        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        subcompetences: ko.observableArray(subcompetences)
    };
}

function SubCompetence(parent, id, code, name, indicators) {
    return {
        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        indicators: ko.observableArray(indicators)
    };
}

function Indicator(parent, id, name, description, score) {
    return {
        id: ko.observable(id),
        name: ko.observable(name),
        description: ko.observable(description),
        score: ko.observable(score)
    };
}<commit_msg>save/get project score<commit_after>function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.projectId = $("#projectHeader").data('value');

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);
    gvm.savePage = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SaveBtn");}, gvm);

    gvm.competences = ko.observableArray([]);

    gvm.getProjectInfo = function() {
        $.getJSON('/api/project/' + gvm.projectId, function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
        });
    };

    gvm.getAllData = function() {
         $.getJSON('/api/project/getAllData/' + gvm.projectId, function(data) {
            console.log(data);
         });
    };

    gvm.updateCompetence = function(id, code, description, max, weight) {
        var comp = new Competence(this, id, code, description, weight);
        gvm.competences.push(comp);
        return comp;
    };

    gvm.clearStructure = function() {
        gvm.competences.destroyAll();
    };
}

function initPage() {
    viewModel.getProjectInfo();
    viewModel.getAllData();

    fetchProjectStructure()
    fetchProjectScore();

    $(".savePageBtn").click(function(){

    });
}

function fetchProjectScore()
{
    $.getJSON("/api/projectscore/" + projectid + "/" + studentid, function(data)
    {
        $.each(viewModel.competences(), function(i,item){
            console.log(item.id);
        });
    });
}

function fetchProjectStructure() {
    viewModel.clearStructure();

    $.getJSON("/api/projectstructure/" + projectid, function(data){
        $.each(data, function(i, item){
            var competence = viewModel.updateCompetence(item.id, item.code, item.description);

            $.each(item.subcompetences, function(i, subcomp){
                var subcompetence = new SubCompetence(competence, subcomp.id, subcomp.code, subcomp.description);
                competence.subcompetences.push(subcompetence);

                $.each(subcomp.indicators, function(i, indic){
                    subcompetence.indicators.push(new Indicator(subcompetence, indic.id, indic.name, indic.description, 0));
                });
            });
        })
    });
}

function Competence(viewmodel, id, code, name, subcompetences) {
    return {
        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        subcompetences: ko.observableArray(subcompetences)
    };
}

function SubCompetence(parent, id, code, name, indicators) {
    return {
        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        indicators: ko.observableArray(indicators)
    };
}

function Indicator(parent, id, name, description, score) {
    return {
        id: ko.observable(id),
        name: ko.observable(name),
        description: ko.observable(description),
        score: ko.observable(score)
    };
}<|endoftext|>