<commit_before>var _ = require('lodash');
var async = require('async');
var HashIndex = require('./level-hash-index');
var toPaddedBase36 = require('./utils/toPaddedBase36');

var escapeRegExp = function(str){
  return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
};

var bindToTuple = function(tuple, binding){
  return tuple.map(function(e){
    if(binding.hasOwnProperty(e)){
      return binding[e];
    }
    return e;
  });
};

var isVar = function(elm){
  return _.isString(elm) && elm[0] === '?';
};

var parseElement = function(hindex, elm, callback){
  if(isVar(elm)){
    return callback(null, {var_name: elm});
  }else if(_.isString(elm)){
    hindex.getHash(elm, function(err, hash){
      if(err){
        return callback(err);
      }
      callback(null, {value: elm, hash: hash});
    });
  }else{
    callback(null, {is_blank: true});
  }
};

var parseTuple = function(hindex, tuple, callback){
  async.parallel({
    e: async.apply(parseElement, hindex, tuple[0]),
    a: async.apply(parseElement, hindex, tuple[1]),
    v: async.apply(parseElement, hindex, tuple[2]),
    t: function(callback){
      if(isVar(tuple[3])){
        return callback(null, {var_name: tuple[3]});
      }else if(_.isNumber(tuple[3])){
        var txn = toPaddedBase36(tuple[3], 6);
        return callback(null, {value: txn, hash: txn});
      }
      callback(null, {is_blank: true});
    },
    o: function(callback){
      if(isVar(tuple[4])){
        return callback(null, {var_name: tuple[4]});
      }else if(tuple[4] === true || tuple[4] === false){
        return callback(null, {value: tuple[4], hash: tuple[4]});
      }
      callback(null, {is_blank: true});
    }
  }, callback);
};

var selectIndex = (function(){
  var getKnowns = function(q_fact){
    var knowns = [];
    "eav".split("").forEach(function(key){
      if(q_fact[key].hasOwnProperty("hash")){
        knowns.push(key);
      }
    });
    return knowns.sort().join("");
  };
  var mapping = {
    '': 'eavto',
    'e': 'eavto',
    'a': 'aevto',
    'v': 'vaeto',
    'av': 'aveto',
    'ev': 'eavto',
    'ae': 'eavto',
    'aev': 'eavto',
  };
  return function(q_fact){
    return 'eavto';//TODO select the index based on attribute schema
    return mapping[getKnowns(q_fact)];
  };
}());

var toMatcher = function(index_to_use, q_fact){

  var prefix = index_to_use + '!';
  var prefix_parts = [];
  var found_a_gap = false;

  var regex = escapeRegExp(prefix) + index_to_use.split("").map(function(k){
    if(q_fact[k].hasOwnProperty('hash')){
      if(!found_a_gap){
        prefix_parts.push(q_fact[k].hash);
      }
      return escapeRegExp(q_fact[k].hash);
    }else{
      found_a_gap = true;
      return '.*';
    }
  }).join(escapeRegExp('!'));

  return {
    prefix: prefix + prefix_parts.join('!'),
    matchRegExp: new RegExp(regex)
  };
};

var findMatchingKeys = function(db, matcher, callback){
  var results = [];
  db.createReadStream({
    keys: true,
    values: false,
    gte: matcher.prefix + '\x00',
    lte: matcher.prefix + '\xFF',
  }).on('data', function(data){
    if(matcher.matchRegExp.test(data)){
      results.push(data);
    }
  }).on('error', function(err){
    callback(err);
  }).on('end', function(){
    callback(null, results);
  });
};

var keyToFact = function(key){
  var parts = key.split("!");
  var index_name = parts[0];
  var fact = {};
  index_name.split('').forEach(function(k, i){
    var part = parts[i + 1];
    if(k === 't'){
      fact[k] = {value: parseInt(part, 36)};
    }else if(k === 'o'){
      fact[k] = {value: part === '1'};
    }else{
      fact[k] = part;
    }
  });
  return fact;
};

var bindKeys = function(matching_keys, q_fact){
  var binding = {};//to ensure unique-ness

  var only_the_latest = q_fact.t.is_blank;//TODO also based on the cardiality of q_fact.a's schema
  var latest_for = {};//latest for the same e+a

  var var_names = "eavto".split('').filter(function(k){
    return q_fact[k].hasOwnProperty('var_name');
  }).map(function(k){
    return [q_fact[k].var_name, k];
  });

  matching_keys.forEach(function(key){
    var fact = keyToFact(key);

    if(only_the_latest){
      if(latest_for.hasOwnProperty(fact.e + fact.a)){
        if(latest_for[fact.e + fact.a] > fact.t.value){
          return;//not the latest, so skip the rest
        }
      }
      latest_for[fact.e + fact.a] = fact.t.value;
    }

    var vars = {};
    var hash_key = '';
    var_names.forEach(function(p){
      var k = p[1];
      vars[p[0]] = fact[k];
      hash_key += _.isString(fact[k]) ? fact[k] : fact[k].value;
    });
    binding[hash_key] = vars;
  });
  return _.values(binding);
};

var qTuple = function(db, hindex, tuple, orig_binding, callback){
  parseTuple(hindex, bindToTuple(tuple, orig_binding), function(err, q_fact){
    if(err){
      if(err.type === 'NotFoundError'){
        //one of the tuple values were not found in the hash, so there must be no results
        return callback(null, []);
      }
      return callback(err);
    }
    var index_to_use = selectIndex(q_fact);

    findMatchingKeys(db, toMatcher(index_to_use, q_fact), function(err, matching_keys){
      if(err){
        return callback(err);
      }
      var bindings = bindKeys(matching_keys, q_fact);

      //de-hash the bindings
      async.map(bindings, function(binding, callback){
        async.map(_.pairs(binding), function(p, callback){
          if(_.isString(p[1])){
            hindex.get(p[1], function(err, val){
              callback(err, [p[0], val]);
            });
          }else{
            callback(null, [p[0], p[1].value]);
          }
        }, function(err, pairs){
          callback(err, _.assign({}, orig_binding, _.object(pairs)));
        });
      }, callback);
    });
  });
};

module.exports = function(db, options){
  options = options || {};

  var hindex = options.HashIndex || HashIndex(db);
  var qTuple_bound = function(tuple, binding, callback){
    //TODO validate tuple
    qTuple(db, hindex, tuple, binding, callback);
  };
  var q = function(tuples, bindings, callback){
    //TODO validate tuples is an array
    async.reduce(tuples, bindings, function(bindings, tuple, callback){
      async.map(bindings, function(binding, callback){
        qTuple(db, hindex, tuple, binding, callback);
      }, function(err, bindings){
        if(err) callback(err);
        else callback(null, _.flatten(bindings));
      });
    }, callback);
  };
  return {
    qTuple: qTuple_bound,
    q: q,
    getEntity: function(e, callback){
      q([["?e", "?a", "?v"]], [{"?e": e}], function(err, results){
        if(err) return callback(err);
        var o = {};
        results.forEach(function(result){
          o[result["?a"]] = result["?v"];
          //TODO cardinality = multiple
        });
        callback(null, o);
      });
    }
  };
};
<commit_msg>fixing bug where it's not actually selecting the latest value by txn<commit_after>var _ = require('lodash');
var async = require('async');
var HashIndex = require('./level-hash-index');
var toPaddedBase36 = require('./utils/toPaddedBase36');

var escapeRegExp = function(str){
  return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
};

var bindToTuple = function(tuple, binding){
  return tuple.map(function(e){
    if(binding.hasOwnProperty(e)){
      return binding[e];
    }
    return e;
  });
};

var isVar = function(elm){
  return _.isString(elm) && elm[0] === '?';
};

var parseElement = function(hindex, elm, callback){
  if(isVar(elm)){
    return callback(null, {var_name: elm});
  }else if(_.isString(elm)){
    hindex.getHash(elm, function(err, hash){
      if(err){
        return callback(err);
      }
      callback(null, {value: elm, hash: hash});
    });
  }else{
    callback(null, {is_blank: true});
  }
};

var parseTuple = function(hindex, tuple, callback){
  async.parallel({
    e: async.apply(parseElement, hindex, tuple[0]),
    a: async.apply(parseElement, hindex, tuple[1]),
    v: async.apply(parseElement, hindex, tuple[2]),
    t: function(callback){
      if(isVar(tuple[3])){
        return callback(null, {var_name: tuple[3]});
      }else if(_.isNumber(tuple[3])){
        var txn = toPaddedBase36(tuple[3], 6);
        return callback(null, {value: txn, hash: txn});
      }
      callback(null, {is_blank: true});
    },
    o: function(callback){
      if(isVar(tuple[4])){
        return callback(null, {var_name: tuple[4]});
      }else if(tuple[4] === true || tuple[4] === false){
        return callback(null, {value: tuple[4], hash: tuple[4]});
      }
      callback(null, {is_blank: true});
    }
  }, callback);
};

var selectIndex = (function(){
  var getKnowns = function(q_fact){
    var knowns = [];
    "eav".split("").forEach(function(key){
      if(q_fact[key].hasOwnProperty("hash")){
        knowns.push(key);
      }
    });
    return knowns.sort().join("");
  };
  var mapping = {
    '': 'eavto',
    'e': 'eavto',
    'a': 'aevto',
    'v': 'vaeto',
    'av': 'aveto',
    'ev': 'eavto',
    'ae': 'eavto',
    'aev': 'eavto',
  };
  return function(q_fact){
    return 'eavto';//TODO select the index based on attribute schema
    return mapping[getKnowns(q_fact)];
  };
}());

var toMatcher = function(index_to_use, q_fact){

  var prefix = index_to_use + '!';
  var prefix_parts = [];
  var found_a_gap = false;

  var regex = escapeRegExp(prefix) + index_to_use.split("").map(function(k){
    if(q_fact[k].hasOwnProperty('hash')){
      if(!found_a_gap){
        prefix_parts.push(q_fact[k].hash);
      }
      return escapeRegExp(q_fact[k].hash);
    }else{
      found_a_gap = true;
      return '.*';
    }
  }).join(escapeRegExp('!'));

  return {
    prefix: prefix + prefix_parts.join('!'),
    matchRegExp: new RegExp(regex)
  };
};

var findMatchingKeys = function(db, matcher, callback){
  var results = [];
  db.createReadStream({
    keys: true,
    values: false,
    gte: matcher.prefix + '\x00',
    lte: matcher.prefix + '\xFF',
  }).on('data', function(data){
    if(matcher.matchRegExp.test(data)){
      results.push(data);
    }
  }).on('error', function(err){
    callback(err);
  }).on('end', function(){
    callback(null, results);
  });
};

var keyToFact = function(key){
  var parts = key.split("!");
  var index_name = parts[0];
  var fact = {};
  index_name.split('').forEach(function(k, i){
    var part = parts[i + 1];
    if(k === 't'){
      fact[k] = {value: parseInt(part, 36)};
    }else if(k === 'o'){
      fact[k] = {value: part === '1'};
    }else{
      fact[k] = part;
    }
  });
  return fact;
};

var bindKeys = function(matching_keys, q_fact){
  var binding = {};//to ensure unique-ness

  var only_the_latest = q_fact.t.is_blank;//TODO also based on the cardiality of q_fact.a's schema
  var latest_for = {};//latest for the same e+a

  var var_names = "eavto".split('').filter(function(k){
    return q_fact[k].hasOwnProperty('var_name');
  }).map(function(k){
    return [q_fact[k].var_name, k];
  });

  matching_keys.forEach(function(key, i){
    var fact = keyToFact(key);

    var key_for_latest_for = only_the_latest ? fact.e + fact.a : i;

    if(latest_for.hasOwnProperty(key_for_latest_for)){
      if(latest_for[key_for_latest_for].txn > fact.t.value){
        return;//not the latest, so skip the rest
      }
    }

    var vars = {};
    var hash_key = '';
    var_names.forEach(function(p){
      var k = p[1];
      vars[p[0]] = fact[k];
      hash_key += _.isString(fact[k]) ? fact[k] : fact[k].value;
    });
    binding[hash_key] = vars;
    latest_for[key_for_latest_for] = {txn: fact.t.value, hash_key: hash_key};
  });
  return _.values(latest_for).map(function(l){
    return binding[l.hash_key];
  });
};

var qTuple = function(db, hindex, tuple, orig_binding, callback){
  parseTuple(hindex, bindToTuple(tuple, orig_binding), function(err, q_fact){
    if(err){
      if(err.type === 'NotFoundError'){
        //one of the tuple values were not found in the hash, so there must be no results
        return callback(null, []);
      }
      return callback(err);
    }
    var index_to_use = selectIndex(q_fact);

    findMatchingKeys(db, toMatcher(index_to_use, q_fact), function(err, matching_keys){
      if(err){
        return callback(err);
      }
      var bindings = bindKeys(matching_keys, q_fact);

      //de-hash the bindings
      async.map(bindings, function(binding, callback){
        async.map(_.pairs(binding), function(p, callback){
          if(_.isString(p[1])){
            hindex.get(p[1], function(err, val){
              callback(err, [p[0], val]);
            });
          }else{
            callback(null, [p[0], p[1].value]);
          }
        }, function(err, pairs){
          callback(err, _.assign({}, orig_binding, _.object(pairs)));
        });
      }, callback);
    });
  });
};

module.exports = function(db, options){
  options = options || {};

  var hindex = options.HashIndex || HashIndex(db);
  var qTuple_bound = function(tuple, binding, callback){
    //TODO validate tuple
    qTuple(db, hindex, tuple, binding, callback);
  };
  var q = function(tuples, bindings, callback){
    //TODO validate tuples is an array
    async.reduce(tuples, bindings, function(bindings, tuple, callback){
      async.map(bindings, function(binding, callback){
        qTuple(db, hindex, tuple, binding, callback);
      }, function(err, bindings){
        if(err) callback(err);
        else callback(null, _.flatten(bindings));
      });
    }, callback);
  };
  return {
    qTuple: qTuple_bound,
    q: q,
    getEntity: function(e, callback){
      q([["?e", "?a", "?v"]], [{"?e": e}], function(err, results){
        if(err) return callback(err);
        var o = {};
        results.forEach(function(result){
          o[result["?a"]] = result["?v"];
          //TODO cardinality = multiple
        });
        callback(null, o);
      });
    }
  };
};
<|endoftext|>


<commit_before>
function zen(){
    //var debug = console.log;
    var debug = function(){};
    var z = {};
    z._arrayOfFunc = [];
    z._isStarted = false;
    z._exceptionHandler = null;

    z._arrayOfWarnings = [];
    z._eachWarningHandler = null;
    z._allWarningsHandler = null;

    z._isFunction = function(functionToCheck) {
        var getType = {};
        return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
    };
    z._isString = function(p) {
        return typeof p === "string" || p instanceof String;
    };

    z.return = function(result){
        debug('==> returning from function, got result: ', result);
        //console.log('count of functions left: ', zen._arrayOfFunc.length);
        if (z._arrayOfFunc.length > 0) {
            //we have some more functions to execute
            z._executeNextFunction(result);//execute next function
        } else {
            z._stopExecution();
        }
    };
    z.result = z.return;
    z.ok = z.return;

    z.catch = function(exceptionHandler){
        debug('==> adding exception handler');
        if(z._isFunction(exceptionHandler)){
            z._exceptionHandler = exceptionHandler;
        }
    };

    z._executeExceptionHandlerIfExists = function(exception){
        debug('==> executing exception handler or throw');
        if(z._isFunction(z._exceptionHandler)){
            z._exceptionHandler(exception);

        } else {
            console.log('unhandled exception: ', exception);
            throw exception;

        }
    };

    z.then = function(nextFunction) {
        debug('==> adding next function');
        z._arrayOfFunc.push(nextFunction);
        if (z._isStarted == false) {
            debug('==> executing first function');
            z._isStarted = true;
            z._executeNextFunction();
        }
        return this;
    };

    z._executeNextFunction = function(p){
        debug('==> execute next function');
        var nextFunction = z._arrayOfFunc.shift();
        if (z._isFunction(nextFunction)) {
            try {
                nextFunction(p);
            } catch(e) {
                z._stopExecution();
                z._executeExceptionHandlerIfExists(e);
            }
        } else {
            z._stopExecution();
        }
    };

    z._stopExecution = function() {
        debug('==> stop execution');
        // handle warnings
        if (z._eachWarningHandler) {
            for (var warningIndex in z._arrayOfWarnings) {
                z._eachWarningHandler(z._arrayOfWarnings[warningIndex]);
            }
        }

        if (z._allWarningsHandler) {
            z._allWarningsHandler(z._arrayOfWarnings);
        }

        z._isStarted = false;
        z._arrayOfFunc = [];
        z._arrayOfWarnings = [];

    };

    z.addWarning = function(warningMessage) {
        debug('==> adding warning ', warningMessage);
        z._arrayOfWarnings.push(warningMessage);
    };
    z.warning = z.addWarning;

    z.eachWarning = function(warningHandler) {
        debug('==> assign eachWarningHandler');
        if (z._isFunction(warningHandler)) {
            z._eachWarningHandler = warningHandler;
        }
        return this;
    };

    z.getAllWarnings = function(warningsHandler) {
        debug('==> assign allWarningsHandler');
        if (z._isFunction(warningsHandler)) {
            z._allWarningsHandler = warningsHandler;
        }
        return this;
    };

    return z;
}

module.exports = zen;<commit_msg>isFunction, isString are now public<commit_after>function zen(){
    //var debug = console.log;
    var debug = function(){};
    var z = {};
    z._arrayOfFunc = [];
    z._isStarted = false;
    z._exceptionHandler = null;

    z._arrayOfWarnings = [];
    z._eachWarningHandler = null;
    z._allWarningsHandler = null;

    z.isFunction = function(functionToCheck) {
        var getType = {};
        return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
    };
    z.isString = function(p) {
        return typeof p === "string" || p instanceof String;
    };

    z.return = function(result){
        debug('==> returning from function, got result: ', result);
        if (z._arrayOfFunc.length > 0) {
            //we have some more functions to execute
            z._executeNextFunction(result);//execute next function
        } else {
            z._stopExecution();
        }
    };
    z.result = z.return;
    z.ok = z.return;

    z.catch = function(exceptionHandler){
        debug('==> adding exception handler');
        if(z.isFunction(exceptionHandler)){
            z._exceptionHandler = exceptionHandler;
        }
    };

    z._executeExceptionHandlerIfExists = function(exception){
        debug('==> executing exception handler or throw');
        if(z.isFunction(z._exceptionHandler)){
            z._exceptionHandler(exception);

        } else {
            console.log('unhandled exception: ', exception);
            throw exception;

        }
    };

    z.then = function(nextFunction) {
        debug('==> adding next function');
        z._arrayOfFunc.push(nextFunction);
        if (z._isStarted == false) {
            debug('==> executing first function');
            z._isStarted = true;
            z._executeNextFunction();
        }
        return this;
    };

    z._executeNextFunction = function(p){
        debug('==> execute next function');
        var nextFunction = z._arrayOfFunc.shift();
        if (z.isFunction(nextFunction)) {
            try {
                nextFunction(p);
            } catch(e) {
                z._stopExecution();
                z._executeExceptionHandlerIfExists(e);
            }
        } else {
            z._stopExecution();
        }
    };

    z._stopExecution = function() {
        debug('==> stop execution');
        // handle warnings
        if (z._eachWarningHandler) {
            for (var warningIndex in z._arrayOfWarnings) {
                z._eachWarningHandler(z._arrayOfWarnings[warningIndex]);
            }
        }

        if (z._allWarningsHandler) {
            z._allWarningsHandler(z._arrayOfWarnings);
        }

        z._isStarted = false;
        z._arrayOfFunc = [];
        z._arrayOfWarnings = [];

    };

    z.addWarning = function(warningMessage) {
        debug('==> adding warning ', warningMessage);
        z._arrayOfWarnings.push(warningMessage);
    };
    z.warning = z.addWarning;

    z.eachWarning = function(warningHandler) {
        debug('==> assign eachWarningHandler');
        if (z.isFunction(warningHandler)) {
            z._eachWarningHandler = warningHandler;
        }
        return this;
    };

    z.getAllWarnings = function(warningsHandler) {
        debug('==> assign allWarningsHandler');
        if (z.isFunction(warningsHandler)) {
            z._allWarningsHandler = warningsHandler;
        }
        return this;
    };

    return z;
}

module.exports = zen;<|endoftext|>


<commit_before>define([
	'backbone',

	'appconfig',
	'chartsV'
], function (Backbone, appconfig, chartsV) {

	var router = null;

	var enableLocatingChart = !! appconfig.enabledModules.locatingChart;

	function init () {
		if (router === null) {
			router = new Router();
		}
		return router;
	}

	var routes = {
		'': 'defaultChart',
		'cascade': 'waterfallChart',
		'répartition': 'distributionChart',
		'*fragment': 'default'
	};
	if (enableLocatingChart) {
		routes['se-situer'] = 'locatingChart';
	}

	var Router = Backbone.Router.extend({
		routes: routes,
		initialize: function () {
			Backbone.history.start();
		},
		default: function() {
			this.navigate('', {trigger: true});
		},
		defaultChart: function () {
			chartsV.render();
		},
		distributionChart: function () {
			chartsV.render('distribution');
		},
		locatingChart: function () {
			chartsV.render('locating');
		},
		waterfallChart: function () {
			chartsV.render('waterfall');
		}
	});

	return {init: init};

});
<commit_msg>Fix router.<commit_after>define([
	'backbone',

	'appconfig',
	'chartsV'
], function (Backbone, appconfig, chartsV) {

	var router = null;

	var enableLocatingChart = !! appconfig.enabledModules.locatingChart;

	function init () {
		if (router === null) {
			router = new Router();
		}
		return router;
	}

	var routes = {
		'': 'defaultChart',
		'cascade': 'waterfallChart',
		'répartition': 'distributionChart',
		'se-situer': enableLocatingChart ? 'locatingChart' : 'default',
		'*fragment': 'default'
	};

	var Router = Backbone.Router.extend({
		routes: routes,
		initialize: function () {
			Backbone.history.start();
		},
		default: function() {
			this.navigate('', {replace: true, trigger: true});
		},
		defaultChart: function () {
			chartsV.render();
		},
		distributionChart: function () {
			chartsV.render('distribution');
		},
		locatingChart: function () {
			chartsV.render('locating');
		},
		waterfallChart: function () {
			chartsV.render('waterfall');
		}
	});

	return {init: init};

});
<|endoftext|>


<commit_before>$(function() {
    StateManager.init([{
        type: 'smartphone',
        enter: '0em',
        exit: '47.7495em'
    }, {
        type: 'tablet',
        enter: '47.75em',
        exit: '64em'
    }, {
        type: 'desktop',
        enter: '64em',
        exit: '320em'
    }]);

    StateManager.registerListener([{
        type: 'smartphone',
        enter: function() {
            $('.sidebar-main').insertBefore($('.page-wrap'));
            $('*[data-offcanvas="true"]').offcanvasMenu();
            $('*[data-search-dropdown="true"]').searchFieldDropDown();
            $('*[data-slide-panel="true"]').slidePanel();
        },
        exit: function() {
            $('.sidebar-main').insertAfter($('.content--breadcrumb'));
            $('*[data-offcanvas="true"]').data('plugin_offcanvasMenu').destroy();
            $('*[data-search-dropdown="true"]').data('plugin_searchFieldDropDown').destroy();
            $('*[data-slide-panel="true"]').data('plugin_slidePanel').destroy();
        }
    }, {
        type:'tablet',
        enter: function() {
            $('*[data-scrollable-list="true"]').scrollableList();
        },
        exit: function() {
            $('*[data-scrollable-list="true"]').data('plugin_scrollableList').destroy();
        }
    }]);

    $('*[data-emotions="true"]').emotions();
});<commit_msg>SW-7854 Refactored: Disabled the scrollable list due to the incorrect behavior when resizing<commit_after>$(function() {
    StateManager.init([{
        type: 'smartphone',
        enter: '0em',
        exit: '47.7495em'
    }, {
        type: 'tablet',
        enter: '47.75em',
        exit: '64em'
    }, {
        type: 'desktop',
        enter: '64em',
        exit: '320em'
    }]);

    StateManager.registerListener([{
        type: 'smartphone',
        enter: function() {
            ('.sidebar-main').insertBefore($('.page-wrap'));
            $('*[data-offcanvas="true"]').offcanvasMenu();
            $('*[data-search-dropdown="true"]').searchFieldDropDown();
            $('*[data-slide-panel="true"]').slidePanel();
        },
        exit: function() {
            $('.sidebar-main').insertAfter($('.content--breadcrumb'));
            $('*[data-offcanvas="true"]').data('plugin_offcanvasMenu').destroy();
            $('*[data-search-dropdown="true"]').data('plugin_searchFieldDropDown').destroy();
            $('*[data-slide-panel="true"]').data('plugin_slidePanel').destroy();
        }
    }, {
        type:'tablet',
        enter: function() {
            /* $('*[data-scrollable-list="true"]').scrollableList(); */
        },
        exit: function() {
            /* $('*[data-scrollable-list="true"]').data('plugin_scrollableList').destroy(); */
        }
    }]);

    $('*[data-emotions="true"]').emotions();
});<|endoftext|>


<commit_before>import _ from 'lodash';
import curlify from 'request-as-curl';
import errors from '../lib/errors';
import emailLib from '../lib/email';

const sendErrorByEmail = (req, err) => {
  let errorHTML = 'To reproduce this error, run this CURL command:
\n
\n';

  if (req.body.password)
    req.body.password = '***********';

  if (req.body.passwordConfirmation)
    req.body.passwordConfirmation = '***********';

  errorHTML += curlify(req, req.body);
  errorHTML += "
\n
\n";
  errorHTML += "Error:
\n";
  errorHTML += JSON.stringify(err);

  emailLib.sendMessage(
    'server-errors@opencollective.com',
    `[${req.app.set('env')}] Error ${err.code}: ${req.method} ${req.url}`,
    errorHTML,
    {bcc: ' '})
  .catch(console.error);
};

/**
 * error handler of the api
 */
export default (err, req, res, next) => {
  if (res.headersSent) {
    return next(err);
  }

  const { name } = err;

  if (name === 'UnauthorizedError') {// because of jwt-express
    err.code = err.status;
  }

  res.header('Cache-Control', 'no-cache');

  // Validation error.
  const e = name && name.toLowerCase ? name.toLowerCase() : '';

  if (e.indexOf('validation') !== -1) {
    err = new errors.ValidationFailed(null, _.map(err.errors, (e) => e.path), err.message);
  } else if (e.indexOf('uniqueconstraint') !== -1) {
    err = new errors.ValidationFailed(null, _.map(err.errors, (e) => e.path), 'Unique Constraint Error.');
  }

  if (!err.code || !Number.isInteger(err.code)) {
    const code = (err.type && err.type.indexOf('Stripe') > -1) ? 400 : 500;
    err.code = err.status || code;
  }

  if (req.app.set('env') === 'production') {
    sendErrorByEmail(req, err);
  }

  console.error('Error Express : ', err);
  if (err.stack) console.log(err.stack);

  res.status(err.code).send({error: err});
};
<commit_msg>don't send emails for common errors (#853)<commit_after>import _ from 'lodash';
import curlify from 'request-as-curl';
import errors from '../lib/errors';
import emailLib from '../lib/email';

const sendErrorByEmail = (req, err) => {
  let errorHTML = 'To reproduce this error, run this CURL command:
\n
\n';

  if (req.body.password)
    req.body.password = '***********';

  if (req.body.passwordConfirmation)
    req.body.passwordConfirmation = '***********';

  errorHTML += curlify(req, req.body);
  errorHTML += "
\n
\n";
  errorHTML += "Error:
\n";
  errorHTML += JSON.stringify(err);

  emailLib.sendMessage(
    'server-errors@opencollective.com',
    `[${req.app.set('env')}] Error ${err.code}: ${req.method} ${req.url}`,
    errorHTML,
    {bcc: ' '})
  .catch(console.error);
};

/**
 * error handler of the api
 */
export default (err, req, res, next) => {
  if (res.headersSent) {
    return next(err);
  }

  const { name } = err;

  if (name === 'UnauthorizedError') {// because of jwt-express
    err.code = err.status;
  }

  res.header('Cache-Control', 'no-cache');

  // Validation error.
  const e = name && name.toLowerCase ? name.toLowerCase() : '';

  if (e.indexOf('validation') !== -1) {
    err = new errors.ValidationFailed(null, _.map(err.errors, (e) => e.path), err.message);
  } else if (e.indexOf('uniqueconstraint') !== -1) {
    err = new errors.ValidationFailed(null, _.map(err.errors, (e) => e.path), 'Unique Constraint Error.');
  }

  if (!err.code || !Number.isInteger(err.code)) {
    const code = (err.type && err.type.indexOf('Stripe') > -1) ? 400 : 500;
    err.code = err.status || code;
  }

  // only send email for important errors. When someone gets wrong jwt token or api key, it shouldn't spam us.
  if (req.app.set('env') === 'production' &&
    !(err.code === 400 && req.method === 'GET') &&
    !(err.code === 404 && req.method === 'GET')) {
    sendErrorByEmail(req, err);
  }

  console.error('Error Express : ', err);
  if (err.stack) console.log(err.stack);

  res.status(err.code).send({error: err});
};
<|endoftext|>


<commit_before>var socket;
var chat_colors = {
    self: 'lime',
    public: 'white',
    party_from: 'pink',
    party_to: 'orange',
    guild: 'lightgreen',
    private_from: 'yellow',
    private_to: 'yellow'
};

$(document).ready(function()
{
    socket = io.connect(window.location.host);

    socket.on('refresh', function()
    {
        // Reload character data when refresh event is recieved
        ragnarok.ui.load('/character');
    });

    socket.on('chat', function(chat)
    {
        chat.color = chat_colors[chat.type];

        if(chat.type == "private_from")     chat.user = "( From: " + chat.user + " )";
        else if(chat.type == "private_to")  chat.user = "( To: " + chat.user + " )";

        var date = new Date(chat.timestamp);
        var dateString = date.getUTCFullYear() +"/"+
                          ("0" + (date.getUTCMonth()+1)).slice(-2) +"/"+
                          ("0" + date.getUTCDate()).slice(-2) + " " +
                          ("0" + date.getUTCHours()).slice(-2) + ":" +
                          ("0" + date.getUTCMinutes()).slice(-2) + ":" +
                          ("0" + date.getUTCSeconds()).slice(-2);

        chat.timestamp = date;
        ragnarok.data.chat.messsages.push(chat);

        if(ragnarok.data.chat.messages.length > 100) ragnarok.data.chat.messages.shift();
        ragnarok.ui.populate.chat();
    });

    socket.on('move', function(move)
    {
        ragnarok.character.pos = move.to;
        ragnarok.ui.populate.map();
    });

    socket.on('item', function(item)
    {
        if(item.action == 'add')
        {
            ragnarok.inventory.add(item.item_id, item.quantity);
            ragnarok.ui.event.item_obtained(item.item_id, item.quantity);
        }
        else if(item.action == 'remove')
        {
            ragnarok.inventory.remove(item.item_id, item.quantity);
        }

        ragnarok.ui.clear.inventory('.inventory .ro-items');
        ragnarok.ui.populate.inventory('.inventory .ro-items', $('.ragnarok-tab-inventory.active, .ro-tab-inv.active').attr('tab'));
    });

    socket.on('map', function(map)
    {
        ragnarok.character.map = map.map;
        ragnarok.character.pos = map.pos;
        ragnarok.ui.populate.map();
    });

    socket.on('info', function(info)
    {
        // Ensure the server didn't send us something we can't handle
        if(typeof ragnarok.lookup.info_types[info.type] != "undefined" &&
            typeof ragnarok.lookup.info_types[info.type].process == "function")
        {
            ragnarok.lookup.info_types[info.type].process(info.value);
            ragnarok.ui.populate.character();
        }
    });

    socket.on('storage', function(storage)
    {
        if(storage.status == "open")
        {
            ragnarok.window.open('storage');

            ragnarok.ui.clear.storage('.storage .ro-items');
            ragnarok.ui.populate.storage('.storage .ro-items', $('.ragnarok-tab-storage.active, .ro-tab-stor.active').attr('tab'));
        }
        else
        {
            ragnarok.window.close('storage');
        }

        if(storage.action == 'add')
        {
            ragnarok.storage.add(storage.item_id, storage.quantity);
        }
        else if(storage.action == 'remove')
        {
            ragnarok.storage.remove(storage.item_id, storage.quantity);
        }

        ragnarok.ui.clear.storage('.storage .ro-items');
        ragnarok.ui.populate.storage('.storage .ro-items', $('.ragnarok-tab-storage.active, .ro-tab-stor.active').attr('tab'));
    });

    socket.on('equip', function(equip)
    {
        if(equip.equipped)
        {
            var slot = ragnarok.lookup.equipment_slots[equip.type.equip],
                item_id = equip.item;

            // Start by clearing out the slot
            ragnarok.ui.unequip(slot);

            // Now equip our new item!
            ragnarok.ui.equip(item_id, slot);
        }
        else
        {
            var slot = ragnarok.lookup.equipment_slots[equip.type.equip];
            ragnarok.ui.unequip(slot);
        }

        ragnarok.inventory.equip(equip.item, equip.equipped);
        ragnarok.ui.clear.inventory('.inventory .ro-items');
        ragnarok.ui.populate.inventory('.inventory .ro-items', $('.ragnarok-tab-inventory.active, .ro-tab-inv.active').attr('tab'));
    });
});
<commit_msg>Derpy typo xD<commit_after>var socket;
var chat_colors = {
    self: 'lime',
    public: 'white',
    party_from: 'pink',
    party_to: 'orange',
    guild: 'lightgreen',
    private_from: 'yellow',
    private_to: 'yellow'
};

$(document).ready(function()
{
    socket = io.connect(window.location.host);

    socket.on('refresh', function()
    {
        // Reload character data when refresh event is recieved
        ragnarok.ui.load('/character');
    });

    socket.on('chat', function(chat)
    {
        chat.color = chat_colors[chat.type];

        if(chat.type == "private_from")     chat.user = "( From: " + chat.user + " )";
        else if(chat.type == "private_to")  chat.user = "( To: " + chat.user + " )";

        var date = new Date(chat.timestamp);
        var dateString = date.getUTCFullYear() +"/"+
                          ("0" + (date.getUTCMonth()+1)).slice(-2) +"/"+
                          ("0" + date.getUTCDate()).slice(-2) + " " +
                          ("0" + date.getUTCHours()).slice(-2) + ":" +
                          ("0" + date.getUTCMinutes()).slice(-2) + ":" +
                          ("0" + date.getUTCSeconds()).slice(-2);

        chat.timestamp = date;
        ragnarok.data.chat.messages.push(chat);

        if(ragnarok.data.chat.messages.length > 100) ragnarok.data.chat.messages.shift();
        ragnarok.ui.populate.chat();
    });

    socket.on('move', function(move)
    {
        ragnarok.character.pos = move.to;
        ragnarok.ui.populate.map();
    });

    socket.on('item', function(item)
    {
        if(item.action == 'add')
        {
            ragnarok.inventory.add(item.item_id, item.quantity);
            ragnarok.ui.event.item_obtained(item.item_id, item.quantity);
        }
        else if(item.action == 'remove')
        {
            ragnarok.inventory.remove(item.item_id, item.quantity);
        }

        ragnarok.ui.clear.inventory('.inventory .ro-items');
        ragnarok.ui.populate.inventory('.inventory .ro-items', $('.ragnarok-tab-inventory.active, .ro-tab-inv.active').attr('tab'));
    });

    socket.on('map', function(map)
    {
        ragnarok.character.map = map.map;
        ragnarok.character.pos = map.pos;
        ragnarok.ui.populate.map();
    });

    socket.on('info', function(info)
    {
        // Ensure the server didn't send us something we can't handle
        if(typeof ragnarok.lookup.info_types[info.type] != "undefined" &&
            typeof ragnarok.lookup.info_types[info.type].process == "function")
        {
            ragnarok.lookup.info_types[info.type].process(info.value);
            ragnarok.ui.populate.character();
        }
    });

    socket.on('storage', function(storage)
    {
        if(storage.status == "open")
        {
            ragnarok.window.open('storage');

            ragnarok.ui.clear.storage('.storage .ro-items');
            ragnarok.ui.populate.storage('.storage .ro-items', $('.ragnarok-tab-storage.active, .ro-tab-stor.active').attr('tab'));
        }
        else
        {
            ragnarok.window.close('storage');
        }

        if(storage.action == 'add')
        {
            ragnarok.storage.add(storage.item_id, storage.quantity);
        }
        else if(storage.action == 'remove')
        {
            ragnarok.storage.remove(storage.item_id, storage.quantity);
        }

        ragnarok.ui.clear.storage('.storage .ro-items');
        ragnarok.ui.populate.storage('.storage .ro-items', $('.ragnarok-tab-storage.active, .ro-tab-stor.active').attr('tab'));
    });

    socket.on('equip', function(equip)
    {
        if(equip.equipped)
        {
            var slot = ragnarok.lookup.equipment_slots[equip.type.equip],
                item_id = equip.item;

            // Start by clearing out the slot
            ragnarok.ui.unequip(slot);

            // Now equip our new item!
            ragnarok.ui.equip(item_id, slot);
        }
        else
        {
            var slot = ragnarok.lookup.equipment_slots[equip.type.equip];
            ragnarok.ui.unequip(slot);
        }

        ragnarok.inventory.equip(equip.item, equip.equipped);
        ragnarok.ui.clear.inventory('.inventory .ro-items');
        ragnarok.ui.populate.inventory('.inventory .ro-items', $('.ragnarok-tab-inventory.active, .ro-tab-inv.active').attr('tab'));
    });
});
<|endoftext|>


<commit_before>// Math Library for ISAAC Physics.

function sqr (number) {
	return number * number;
}

//PS (Thu 19 Jan 2012 08:34:21 PM SGT) - I'm not sure, but I think this MIGHT be a faster alternative to vectorLength
//Also, I'm not sure if using sqrt is a good idea. Comparison between floats is inaccurate.
function sqrNormVector (vector) { //ONLY for 3-dimensional vectors
	return sqr(vector[0]) + sqr(vector[1]) + sqr(vector[2]);
}

// addVector function.
// Takes in two vectors, returns a new vector made by adding
// the inputs together. If the two input vectors don't have the same
// length, the first input vector will be returned.
function addVector (vectorA, vectorB) {
	if(vectorA.length === vectorB.length) {
		var newVector = new Array();
		for(var i = 0; i < vectorA.length; i++) {
			newVector[i] = vectorA[i] + vectorB[i];
		}
		return newVector;
	} else {
		return vectorA;
	}
}

// scaleVector function.
// Takes in a vector and a scalar, returns a new vector made by
// multiplying the scalar through the vector.
function scaleVector (vector, scalar) {
	var newVector = new Array();
	for(var i = 0; i < vector.length; i++) {
		newVector[i] = vector[i] * scalar;
	}
	return newVector;
}

// subtractVector function.
// Takes in two vectors, returns a new vector made by subtracting the
// second vector from the first. If the two input vectors don't have the same
// length, the first input vector will be returned.
function subtractVector (vectorA, vectorB) {
	return addVector(vectorA, scaleVector(vectorB, -1));
}

// dotProduct function.
// Takes in two vectors, returns the dot product of the two. If the two input vectors
// don't have the same length, -1 will be returned.
function dotProduct (vectorA, vectorB) {
	if(vectorA.length === vectorB.length) {
		var sum = 0;
		for (var i = 0; i < vectorA.length; i++) {
			sum += vectorA[i] * vectorB[i];
		}
		return sum;
	} else {
		return -1;
	}
}

// vectorLength function.
// Given a 3D vector, returns the length of it based on the Euclidean norm.
function vectorLength (vector) {
	var squares = 0;

	for (var i = 0; i < vector.length; i++) {
		squares += Math.pow(vector[i], 2);
	}
	return Math.sqrt(squares);
}

// vectorNormalise function.
// Given a 3D vector, returns a unit vector in the same direction.
function vectorNormalise (vector) {
	var length = vectorLength(vector);
	var normal = [];

	for (var i = 0; i < vector.length; i++) {
		normal[i] = vector[i] / length;
	}
	return normal;
}

// vectorFitToLength function.
// Given a 3D vector and a scalar, returns a vector in the same direction whose
// length is the scalar.
function vectorFitToLength (vector, scalar) {
	var scaled = vectorNormalise(vector);

	for (var i = 0; i < scaled.length; i++) {
		scaled[i] *= scalar;
	}
	return scaled;
}<commit_msg>Optimisation: change from using Math.pow to sqr().<commit_after>// Math Library for ISAAC Physics.

function sqr (number) {
	return number * number;
}

//PS (Thu 19 Jan 2012 08:34:21 PM SGT) - I'm not sure, but I think this MIGHT be a faster alternative to vectorLength
//Also, I'm not sure if using sqrt is a good idea. Comparison between floats is inaccurate.
function sqrNormVector (vector) { //ONLY for 3-dimensional vectors
	return sqr(vector[0]) + sqr(vector[1]) + sqr(vector[2]);
}

// addVector function.
// Takes in two vectors, returns a new vector made by adding
// the inputs together. If the two input vectors don't have the same
// length, the first input vector will be returned.
function addVector (vectorA, vectorB) {
	if(vectorA.length === vectorB.length) {
		var newVector = new Array();
		for(var i = 0; i < vectorA.length; i++) {
			newVector[i] = vectorA[i] + vectorB[i];
		}
		return newVector;
	} else {
		return vectorA;
	}
}

// scaleVector function.
// Takes in a vector and a scalar, returns a new vector made by
// multiplying the scalar through the vector.
function scaleVector (vector, scalar) {
	var newVector = new Array();
	for(var i = 0; i < vector.length; i++) {
		newVector[i] = vector[i] * scalar;
	}
	return newVector;
}

// subtractVector function.
// Takes in two vectors, returns a new vector made by subtracting the
// second vector from the first. If the two input vectors don't have the same
// length, the first input vector will be returned.
function subtractVector (vectorA, vectorB) {
	return addVector(vectorA, scaleVector(vectorB, -1));
}

// dotProduct function.
// Takes in two vectors, returns the dot product of the two. If the two input vectors
// don't have the same length, -1 will be returned.
function dotProduct (vectorA, vectorB) {
	if(vectorA.length === vectorB.length) {
		var sum = 0;
		for (var i = 0; i < vectorA.length; i++) {
			sum += vectorA[i] * vectorB[i];
		}
		return sum;
	} else {
		return -1;
	}
}

// vectorLength function.
// Given a 3D vector, returns the length of it based on the Euclidean norm.
function vectorLength (vector) {
	var squares = 0;

	for (var i = 0; i < vector.length; i++) {
		squares += sqr(vector[i]);
	}
	return Math.sqrt(squares);
}

// vectorNormalise function.
// Given a 3D vector, returns a unit vector in the same direction.
function vectorNormalise (vector) {
	var length = vectorLength(vector);
	var normal = [];

	for (var i = 0; i < vector.length; i++) {
		normal[i] = vector[i] / length;
	}
	return normal;
}

// vectorFitToLength function.
// Given a 3D vector and a scalar, returns a vector in the same direction whose
// length is the scalar.
function vectorFitToLength (vector, scalar) {
	var scaled = vectorNormalise(vector);

	for (var i = 0; i < scaled.length; i++) {
		scaled[i] *= scalar;
	}
	return scaled;
}<|endoftext|>


<commit_before>const TipoEnte = require("../src/TipoEnte");
const CatalogoOuvidorias = artifacts.require("./CatalogoOuvidorias.sol");

/**
 * @function contract
 */

/**
 * @namespace artifacts
 */

/**
 * @typedef {Object} uint
 * @property {Array} c
 */

/**
 * @typedef {Object} Transacao
 * @property {Array} logs
 */

/**
 * @typedef {Object} CatalogoOuvidorias
 * @property {Function} deployed
 * @property {Function} new
 * @property {Function} autorizar
 * @property {Function} cadastrar
 * @property {Function} getNumeroDeOuvidorias
 * @property {Function} getOuvidoriaNome
 * @property {Function} getOuvidoriaEnteTipo
 * @property {Function} getOuvidoriaEnteNome
 * @property {Function} getOuvidoriaEndpoint
 */

function fail(mensagem) {
    assert.fail(false, false, mensagem);
}
function assertRequireFalhou(erro) {
    // falha de alguma condicao dentro de um require(...) no solidity
    assert.equal(erro.message, 'VM Exception while processing transaction: invalid opcode');
}
function uint(_uint) {
    return _uint.c[0];
}

function clonarEventoConvertendoPropriedades(log, propriedadesBytes32, propriedadesUint) {
    function bytes32ToString(hexx) {
        const hex = hexx.toString();
        let str = '';
        for (let i = 0; i < hex.length; i += 2)
            str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
        return str.replace(/\u0000/g, '');
    }
    let retorno = Object.assign({}, log.args);
    propriedadesBytes32.forEach((propBytes32) => {
        retorno[propBytes32] = bytes32ToString(retorno[propBytes32]);
    });
    propriedadesUint.forEach((propUint) => {
        retorno[propUint] = uint(retorno[propUint]);
    });
    return retorno;
}

function assertPrimeiroEvento(resultadoTransacao, propriedadesBytes32, propriedadesUint, nomeTipoEvento, eventoEsperado) {
    assert.deepEqual(
        clonarEventoConvertendoPropriedades(resultadoTransacao.logs[0], propriedadesBytes32, propriedadesUint),
        eventoEsperado
    );
    assert.equal(resultadoTransacao.logs[0].event, nomeTipoEvento);
}

function assertEventoOuvidoriaAutorizada(resultadoTransacao, eventoEsperado) {
    assertPrimeiroEvento(
        resultadoTransacao,
        [],
        [],
        "ouvidoriaAutorizada",
        eventoEsperado
    );
}

function assertEventoOuvidoriaCadastrada(resultadoTransacao, eventoEsperado) {
    assertPrimeiroEvento(
        resultadoTransacao,
        ["nome", "nomeEnte", "endpoint"],
        ["tipoEnte"],
        "ouvidoriaCadastrada",
        eventoEsperado
    );
}

function assertOuvidoria(catalogoOuvidoriasPromise, ouvidoriaEsperada) {
    return catalogoOuvidoriasPromise.then((co) => {
        let ouvidoriaObtida = {};
        return co.getOuvidoriaNome(ouvidoriaEsperada.conta).then((nome) => {
            ouvidoriaObtida.nome = nome;
            return co.getOuvidoriaEnteTipo(ouvidoriaEsperada.conta);
        }).then((tipoEnte) => {
            ouvidoriaObtida.tipoEnte = uint(tipoEnte);
            return co.getOuvidoriaEnteNome(ouvidoriaEsperada.conta);
        }).then((nomeEnte) => {
            ouvidoriaObtida.nomeEnte = nomeEnte;
            return co.getOuvidoriaEndpoint(ouvidoriaEsperada.conta);
        }).then((_endpoint) => {
            assert.equal(ouvidoriaObtida.nome, ouvidoriaEsperada.nome);
            assert.equal(ouvidoriaObtida.tipoEnte, ouvidoriaEsperada.tipoEnte);
            assert.equal(ouvidoriaObtida.nomeEnte, ouvidoriaEsperada.nomeEnte);
            assert.equal(_endpoint, ouvidoriaEsperada.endpoint);
        });
    });
}

contract('CatalogoOuvidorias', (accounts) => {

    it("script de deploy padrao constroi corretamente o contrato inicial", () => {
        const ouvGeral = {
            conta: accounts[0],
            nome: "CGU-OGU",
            tipoEnte: 0,
            nomeEnte: "Uniao",
            endpoint: "http://cgu.gov.br/ogu"
        };

        let catalogoOuvidoriasPromise = CatalogoOuvidorias.deployed();

        return assertOuvidoria(
            catalogoOuvidoriasPromise,
            ouvGeral
        );
    });

    describe("criado ambiente de testes", () => {
        const ouvDF = {
            conta: accounts[0],
            nome: "CGU-DF",
            tipoEnte: 1,
            nomeEnte: "DF",
            endpoint: "http://cgu.gov.br/ouv-ba"
        };
        const ouvBA = {
            conta: accounts[1],
            nome: "CGU-BA",
            tipoEnte: 1,
            nomeEnte: "BA",
            endpoint: "http://cgu.gov.br/ouv-ba"
        };
        const ouvAJU = {
            conta: accounts[2],
            nome: "Pref. Aracaju",
            tipoEnte: 2,
            nomeEnte: "Aracaju-SE",
            endpoint: "http://aracaju.se.gov.br/ouv"
        };

        let catalogoOuvidoriasPromise;

        beforeEach(() => {
            catalogoOuvidoriasPromise = CatalogoOuvidorias.new(ouvDF.nome, ouvDF.tipoEnte, ouvDF.nomeEnte, ouvDF.endpoint);
        });

        it("construtor cria catalogo com uma ouvidoria cadastrada inicialmente", () => {
            return assertOuvidoria(catalogoOuvidoriasPromise, ouvDF);
        });

        it("ouvidoria jah cadastrada pode chamar autorizar", () => {
            return catalogoOuvidoriasPromise.then((catalogoOuvidorias) => {
                return catalogoOuvidorias.autorizar(ouvBA.conta, {from: ouvDF.conta});
            }).then((resultadoTransacao) => {
                assertEventoOuvidoriaAutorizada(
                    resultadoTransacao,
                    {
                        ouvidoriaAutorizadora: ouvDF.conta,
                        ouvidoriaCandidata: ouvBA.conta
                    }
                );
            });
        });

        it("ouvidoria nao cadastrada NAO pode chamar autorizar", () => {
            return catalogoOuvidoriasPromise.then((catalogoOuvidorias) => {
                return catalogoOuvidorias.autorizar(ouvDF.conta, {from: ouvBA.conta});
            }).then(() => {
                fail("ouvBA nao estah cadastrada, portanto nao pode autorizar ninguem")
            }, (erro) => {
                assertRequireFalhou(erro);
            });
        });

        it("ouvidoria jah cadastrada nao pode autorizar uma outra ouvidoria mais de uma vez", () => {
            return catalogoOuvidoriasPromise.then((catalogoOuvidorias) => {
                return catalogoOuvidorias.autorizar(ouvBA.conta, {from: ouvDF.conta}).then(() => {
                    return catalogoOuvidorias.autorizar(ouvBA.conta, {from: ouvDF.conta});
                }).then(() => {
                    fail("ouvDF jah autorizou a ouvBA, nao poderia autorizar uma segunda vez")
                }, (erro) => {
                    assertRequireFalhou(erro);
                });
            })
        });

        xit("ouvidoria jah cadastrada nao pode autorizar uma outra ouvidoria jah cadastrada", () => {
            // soh vou conseguir implementar depois que o metodo de efetivacao de cadastro estiver concluido
        });

        it("candidata sem autorizacoes nao consegue cadastrar-se", () => {
            return catalogoOuvidoriasPromise.then((catalogoOuvidorias) => {
                return catalogoOuvidorias.cadastrar(ouvBA.nome, ouvBA.tipoEnte, ouvBA.nomeEnte, ouvBA.endpoint, {from: ouvBA.conta}).then(() => {
                    fail("como a ouvBA nao recebeu uma autorizacao, nao pode se cadastrar")
                }, (erro) => {
                    assertRequireFalhou(erro);
                });
            });
        });

        it("quando ha somente uma ouvidoria cadastrada, uma candidata consegue cadastrar-se tendo apenas uma autorizacao", () => {
            return catalogoOuvidoriasPromise.then((catalogoOuvidorias) => {
                return catalogoOuvidorias.autorizar(ouvBA.conta, {from: ouvDF.conta}).then(() => {
                    return catalogoOuvidorias.cadastrar(ouvBA.nome, ouvBA.tipoEnte, ouvBA.nomeEnte, ouvBA.endpoint, {from: ouvBA.conta}).then((tx) => {
                        assertEventoOuvidoriaCadastrada(tx, ouvBA);

                        return catalogoOuvidorias.getNumeroDeOuvidorias();
                    }).then((numeroDeOuvidorias) => {
                        assert.equal(uint(numeroDeOuvidorias), 2);

                        return assertOuvidoria(Promise.resolve(catalogoOuvidorias), ouvBA)
                    });
                });
            });
        });

        it("quando ha somente duas ouvidorias cadastradas, uma candidata NAO consegue cadastrar-se tendo apenas uma autorizacao", () => {
            return catalogoOuvidoriasPromise.then((catalogoOuvidorias) => {
                return catalogoOuvidorias.autorizar(ouvBA.conta, {from: ouvDF.conta}).then(() => {
                    return catalogoOuvidorias.cadastrar(ouvBA.nome, ouvBA.tipoEnte, ouvBA.nomeEnte, ouvBA.endpoint, {from: ouvBA.conta});
                }).then(() => {
                    return catalogoOuvidorias.autorizar(ouvAJU.conta, {from: ouvDF.conta});
                }).then(() => {
                    return catalogoOuvidorias.cadastrar(ouvAJU.nome, ouvAJU.tipoEnte, ouvAJU.nomeEnte, ouvAJU.endpoint, {from: ouvAJU.conta}).then(() => {
                        fail("como a ouvAJU nao recebeu duas autorizacoes, nao poderia se cadastrar")
                    }, (erro) => {
                        assertRequireFalhou(erro);
                    });
                });
            });
        });

        it("quando ha somente duas ouvidorias cadastradas, uma candidata consegue cadastrar-se tendo apenas duas autorizacoes", () => {
            return catalogoOuvidoriasPromise.then((catalogoOuvidorias) => {
                return catalogoOuvidorias.autorizar(ouvBA.conta, {from: ouvDF.conta}).then(() => {
                    return catalogoOuvidorias.cadastrar(ouvBA.nome, ouvBA.tipoEnte, ouvBA.nomeEnte, ouvBA.endpoint, {from: ouvBA.conta});
                }).then(() => {
                    return catalogoOuvidorias.autorizar(ouvAJU.conta, {from: ouvDF.conta});
                }).then(() => {
                    return catalogoOuvidorias.autorizar(ouvAJU.conta, {from: ouvBA.conta});
                }).then(() => {
                    return catalogoOuvidorias.cadastrar(ouvAJU.nome, ouvAJU.tipoEnte, ouvAJU.nomeEnte, ouvAJU.endpoint, {from: ouvAJU.conta}).then((tx) => {
                        assertEventoOuvidoriaCadastrada(tx, ouvAJU);

                        return catalogoOuvidorias.getNumeroDeOuvidorias();
                    }).then((numeroDeOuvidorias) => {
                        assert.equal(uint(numeroDeOuvidorias), 3);

                        return assertOuvidoria(Promise.resolve(catalogoOuvidorias), ouvAJU)
                    });
                });
            });
        });

        xit("quando ha tres ou mais ouvidorias cadastradas, uma candidata NAO consegue cadastrar-se tendo apenas uma autorizacao", () => { });
        xit("quando ha tres ou mais ouvidorias cadastradas, uma candidata NAO consegue cadastrar-se tendo apenas duas autorizacoes", () => { });
        xit("quando ha tres ou mais ouvidorias cadastradas, uma candidata consegue cadastrar-se tendo apenas tres autorizacoes", () => { });

    });

});
<commit_msg>refactor(catalogo): melhorar mensagem de erro quando teste falhar<commit_after>const TipoEnte = require("../src/TipoEnte");
const CatalogoOuvidorias = artifacts.require("./CatalogoOuvidorias.sol");

/**
 * @function contract
 */

/**
 * @namespace artifacts
 */

/**
 * @typedef {Object} uint
 * @property {Array} c
 */

/**
 * @typedef {Object} Transacao
 * @property {Array} logs
 */

/**
 * @typedef {Object} CatalogoOuvidorias
 * @property {Function} deployed
 * @property {Function} new
 * @property {Function} autorizar
 * @property {Function} cadastrar
 * @property {Function} getNumeroDeOuvidorias
 * @property {Function} getOuvidoriaNome
 * @property {Function} getOuvidoriaEnteTipo
 * @property {Function} getOuvidoriaEnteNome
 * @property {Function} getOuvidoriaEndpoint
 */

function fail(mensagem) {
    assert.fail(false, false, mensagem);
}
function assertRequireFalhou(erro) {
    // falha de alguma condicao dentro de um require(...) no solidity
    assert.equal(erro.message, 'VM Exception while processing transaction: invalid opcode');
}
function uint(_uint) {
    return _uint.c[0];
}

function clonarEventoConvertendoPropriedades(log, propriedadesBytes32, propriedadesUint) {
    function bytes32ToString(hexx) {
        const hex = hexx.toString();
        let str = '';
        for (let i = 0; i < hex.length; i += 2)
            str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
        return str.replace(/\u0000/g, '');
    }
    let retorno = Object.assign({}, log.args);
    propriedadesBytes32.forEach((propBytes32) => {
        retorno[propBytes32] = bytes32ToString(retorno[propBytes32]);
    });
    propriedadesUint.forEach((propUint) => {
        retorno[propUint] = uint(retorno[propUint]);
    });
    return retorno;
}

function assertPrimeiroEvento(resultadoTransacao, propriedadesBytes32, propriedadesUint, nomeTipoEvento, eventoEsperado) {
    assert.deepEqual(
        clonarEventoConvertendoPropriedades(resultadoTransacao.logs[0], propriedadesBytes32, propriedadesUint),
        eventoEsperado
    );
    assert.equal(resultadoTransacao.logs[0].event, nomeTipoEvento);
}

function assertEventoOuvidoriaAutorizada(resultadoTransacao, eventoEsperado) {
    assertPrimeiroEvento(
        resultadoTransacao,
        [],
        [],
        "ouvidoriaAutorizada",
        eventoEsperado
    );
}

function assertEventoOuvidoriaCadastrada(resultadoTransacao, eventoEsperado) {
    assertPrimeiroEvento(
        resultadoTransacao,
        ["nome", "nomeEnte", "endpoint"],
        ["tipoEnte"],
        "ouvidoriaCadastrada",
        eventoEsperado
    );
}

function assertOuvidoria(catalogoOuvidoriasPromise, ouvidoriaEsperada) {
    return catalogoOuvidoriasPromise.then((co) => {
        let ouvidoriaObtida = {
            conta: ouvidoriaEsperada.conta
        };
        return co.getOuvidoriaNome(ouvidoriaEsperada.conta).then((nome) => {
            ouvidoriaObtida.nome = nome;
            return co.getOuvidoriaEnteTipo(ouvidoriaEsperada.conta);
        }).then((tipoEnte) => {
            ouvidoriaObtida.tipoEnte = uint(tipoEnte);
            return co.getOuvidoriaEnteNome(ouvidoriaEsperada.conta);
        }).then((nomeEnte) => {
            ouvidoriaObtida.nomeEnte = nomeEnte;
            return co.getOuvidoriaEndpoint(ouvidoriaEsperada.conta);
        }).then((_endpoint) => {
            ouvidoriaObtida.endpoint = _endpoint;

            assert.deepEqual(
                ouvidoriaObtida,
                ouvidoriaEsperada
            );
        });
    });
}

contract('CatalogoOuvidorias', (accounts) => {

    it("script de deploy padrao constroi corretamente o contrato inicial", () => {
        const ouvGeral = {
            conta: accounts[0],
            nome: "CGU-OGU",
            tipoEnte: 0,
            nomeEnte: "Uniao",
            endpoint: "http://cgu.gov.br/ogu"
        };

        let catalogoOuvidoriasPromise = CatalogoOuvidorias.deployed();

        return assertOuvidoria(
            catalogoOuvidoriasPromise,
            ouvGeral
        );
    });

    describe("criado ambiente de testes", () => {
        const ouvDF = {
            conta: accounts[0],
            nome: "CGU-DF",
            tipoEnte: 1,
            nomeEnte: "DF",
            endpoint: "http://cgu.gov.br/ouv-ba"
        };
        const ouvBA = {
            conta: accounts[1],
            nome: "CGU-BA",
            tipoEnte: 1,
            nomeEnte: "BA",
            endpoint: "http://cgu.gov.br/ouv-ba"
        };
        const ouvAJU = {
            conta: accounts[2],
            nome: "Pref. Aracaju",
            tipoEnte: 2,
            nomeEnte: "Aracaju-SE",
            endpoint: "http://aracaju.se.gov.br/ouv"
        };

        let catalogoOuvidoriasPromise;

        beforeEach(() => {
            catalogoOuvidoriasPromise = CatalogoOuvidorias.new(ouvDF.nome, ouvDF.tipoEnte, ouvDF.nomeEnte, ouvDF.endpoint);
        });

        it("construtor cria catalogo com uma ouvidoria cadastrada inicialmente", () => {
            return assertOuvidoria(catalogoOuvidoriasPromise, ouvDF);
        });

        it("ouvidoria jah cadastrada pode chamar autorizar", () => {
            return catalogoOuvidoriasPromise.then((catalogoOuvidorias) => {
                return catalogoOuvidorias.autorizar(ouvBA.conta, {from: ouvDF.conta});
            }).then((resultadoTransacao) => {
                assertEventoOuvidoriaAutorizada(
                    resultadoTransacao,
                    {
                        ouvidoriaAutorizadora: ouvDF.conta,
                        ouvidoriaCandidata: ouvBA.conta
                    }
                );
            });
        });

        it("ouvidoria nao cadastrada NAO pode chamar autorizar", () => {
            return catalogoOuvidoriasPromise.then((catalogoOuvidorias) => {
                return catalogoOuvidorias.autorizar(ouvDF.conta, {from: ouvBA.conta});
            }).then(() => {
                fail("ouvBA nao estah cadastrada, portanto nao pode autorizar ninguem")
            }, (erro) => {
                assertRequireFalhou(erro);
            });
        });

        it("ouvidoria jah cadastrada nao pode autorizar uma outra ouvidoria mais de uma vez", () => {
            return catalogoOuvidoriasPromise.then((catalogoOuvidorias) => {
                return catalogoOuvidorias.autorizar(ouvBA.conta, {from: ouvDF.conta}).then(() => {
                    return catalogoOuvidorias.autorizar(ouvBA.conta, {from: ouvDF.conta});
                }).then(() => {
                    fail("ouvDF jah autorizou a ouvBA, nao poderia autorizar uma segunda vez")
                }, (erro) => {
                    assertRequireFalhou(erro);
                });
            })
        });

        xit("ouvidoria jah cadastrada nao pode autorizar uma outra ouvidoria jah cadastrada", () => {
            // soh vou conseguir implementar depois que o metodo de efetivacao de cadastro estiver concluido
        });

        it("candidata sem autorizacoes nao consegue cadastrar-se", () => {
            return catalogoOuvidoriasPromise.then((catalogoOuvidorias) => {
                return catalogoOuvidorias.cadastrar(ouvBA.nome, ouvBA.tipoEnte, ouvBA.nomeEnte, ouvBA.endpoint, {from: ouvBA.conta}).then(() => {
                    fail("como a ouvBA nao recebeu uma autorizacao, nao pode se cadastrar")
                }, (erro) => {
                    assertRequireFalhou(erro);
                });
            });
        });

        it("quando ha somente uma ouvidoria cadastrada, uma candidata consegue cadastrar-se tendo apenas uma autorizacao", () => {
            return catalogoOuvidoriasPromise.then((catalogoOuvidorias) => {
                return catalogoOuvidorias.autorizar(ouvBA.conta, {from: ouvDF.conta}).then(() => {
                    return catalogoOuvidorias.cadastrar(ouvBA.nome, ouvBA.tipoEnte, ouvBA.nomeEnte, ouvBA.endpoint, {from: ouvBA.conta}).then((tx) => {
                        assertEventoOuvidoriaCadastrada(tx, ouvBA);

                        return catalogoOuvidorias.getNumeroDeOuvidorias();
                    }).then((numeroDeOuvidorias) => {
                        assert.equal(uint(numeroDeOuvidorias), 2);

                        return assertOuvidoria(Promise.resolve(catalogoOuvidorias), ouvBA)
                    });
                });
            });
        });

        it("quando ha somente duas ouvidorias cadastradas, uma candidata NAO consegue cadastrar-se tendo apenas uma autorizacao", () => {
            return catalogoOuvidoriasPromise.then((catalogoOuvidorias) => {
                return catalogoOuvidorias.autorizar(ouvBA.conta, {from: ouvDF.conta}).then(() => {
                    return catalogoOuvidorias.cadastrar(ouvBA.nome, ouvBA.tipoEnte, ouvBA.nomeEnte, ouvBA.endpoint, {from: ouvBA.conta});
                }).then(() => {
                    return catalogoOuvidorias.autorizar(ouvAJU.conta, {from: ouvDF.conta});
                }).then(() => {
                    return catalogoOuvidorias.cadastrar(ouvAJU.nome, ouvAJU.tipoEnte, ouvAJU.nomeEnte, ouvAJU.endpoint, {from: ouvAJU.conta}).then(() => {
                        fail("como a ouvAJU nao recebeu duas autorizacoes, nao poderia se cadastrar")
                    }, (erro) => {
                        assertRequireFalhou(erro);
                    });
                });
            });
        });

        it("quando ha somente duas ouvidorias cadastradas, uma candidata consegue cadastrar-se tendo apenas duas autorizacoes", () => {
            return catalogoOuvidoriasPromise.then((catalogoOuvidorias) => {
                return catalogoOuvidorias.autorizar(ouvBA.conta, {from: ouvDF.conta}).then(() => {
                    return catalogoOuvidorias.cadastrar(ouvBA.nome, ouvBA.tipoEnte, ouvBA.nomeEnte, ouvBA.endpoint, {from: ouvBA.conta});
                }).then(() => {
                    return catalogoOuvidorias.autorizar(ouvAJU.conta, {from: ouvDF.conta});
                }).then(() => {
                    return catalogoOuvidorias.autorizar(ouvAJU.conta, {from: ouvBA.conta});
                }).then(() => {
                    return catalogoOuvidorias.cadastrar(ouvAJU.nome, ouvAJU.tipoEnte, ouvAJU.nomeEnte, ouvAJU.endpoint, {from: ouvAJU.conta}).then((tx) => {
                        assertEventoOuvidoriaCadastrada(tx, ouvAJU);

                        return catalogoOuvidorias.getNumeroDeOuvidorias();
                    }).then((numeroDeOuvidorias) => {
                        assert.equal(uint(numeroDeOuvidorias), 3);

                        return assertOuvidoria(Promise.resolve(catalogoOuvidorias), ouvAJU)
                    });
                });
            });
        });

        xit("quando ha tres ou mais ouvidorias cadastradas, uma candidata NAO consegue cadastrar-se tendo apenas uma autorizacao", () => { });
        xit("quando ha tres ou mais ouvidorias cadastradas, uma candidata NAO consegue cadastrar-se tendo apenas duas autorizacoes", () => { });
        xit("quando ha tres ou mais ouvidorias cadastradas, uma candidata consegue cadastrar-se tendo apenas tres autorizacoes", () => { });

    });

});
<|endoftext|>


<commit_before>/*global jQuery:false */

(function ($) {

  function CentreonForm(settings, $elem) {
    var self = this,
        rules;
    this.settings = settings;
    this.$elem = $elem;
    this.groups = {};
    this.formUrl = this.$elem.data("route");

    this.initClassInput();

    /* Add event for change the float label */
    this.$elem.find("input, textarea").on(
      "focus",
      function () {
        var $parent = $(this).closest(".form-group"),
            $help = $parent.find("cite");
        self.getHelp($(this));
        $help.show();
        self.toggleLabel($(this));
      }
    )
    .on(
      "keyup change",
      function (e) {
        self.toggleLabel($(this));
      }
    )
    .on(
      "blur",
      function () {
        var $parent = $(this).closest(".form-group"),
            $help = $parent.find("cite");
        if (false === $parent.hasClass("has-error")) {
          $help.hide();
        }
        self.toggleLabel($(this));
      }
    );

    /* Add validation for this form */
    if (this.settings.rules === undefined) {
      rules = (formValidRule[this.$elem.id] === undefined ? {} : formValidRule[this.$elem.id]);
    } else {
      rules = this.settings.rules;
    }
    this.$elem.validate({
      rules: rules,
      invalidHandler: function (event, validator) {
        self.invalidHandler(event, validator);
      }
    });
  }

  /**
   * Initialize label classes
   */
  CentreonForm.prototype.initClassInput = function () {
    var self = this;
    this.$elem.find(".form-group").each(function () {
      var name = $(this).find("input[name]").attr("name");
      /* Add group in cache */
      self.groups[name] = {
        help: undefined
      };

      /* Set css if input is empty */
      $(this).find("input[name]").each(function () {
        self.toggleLabel($(this));
      });
    });
  };

  /**
   * Get the help from ajax or cache
   *
   * @param {Object} $el: The input element
   */
  CentreonForm.prototype.getHelp = function ($el) {
    var self = this,
        $parent = $el.closest(".form-group"),
        $help = $parent.find("cite"),
        name = $el.attr("name");

    /* Test if name is set, else it's not the primary element input */
    if (name === undefined) {
      name = $parent.find("input[name]").attr("name");
    }

    /* Test if the help is in cache */
    if (this.groups[name]["help"] !== undefined) {
      if (false === $parent.hasClass("has-error")) {
        $help.html(this.groups[name]["help"]);
      }
      return;
    }

    /* Get the help with ajax */
    $.ajax({
      url: this.settings.helpUrl,
      type: "get",
      dataType: "json",
      data: {
        form: this.formUrl,
        field: name
      },
      success: function (data) {
        if (false === $parent.hasClass("has-error")) {
          /* Add cache */
          self.groups[name]["help"] = data.text;
          $help.html(data.text);
        }
      }
    });
  };

  /**
   * Display the label for an element
   *
   * @param {Object} $el: The input element
   */
  CentreonForm.prototype.showLabel = function ($el) {
    $el.closest(".form-group").removeClass("js-hide-label").addClass("js-unhighlight-label");
    $el.css("padding", "16px 12px 6px");
  };

  /**
   * Hide the label for an element
   *
   * @param {Object} $el: The input element
   */
  CentreonForm.prototype.hideLabel = function ($el) {
    $el.closest(".form-group").addClass("js-hide-label").removeClass("js-unhighlight-label");
    $el.css("padding", "10px 12px 12px");
  };

  /**
   * Toggle the label by the value of the element
   *
   * @param {Object} $el: The input element
   */
  CentreonForm.prototype.toggleLabel = function ($el) {
    var $parent;
    if ($el.attr("name") === undefined) {
      $parent = $el.closest(".form-group");
      $el = $parent.find("input[name]");
    }
    if ($.trim($el.val()) !== "") {
      this.showLabel($el);
    } else {
      this.hideLabel($el);
    }
  };

  /**
   * Event for invalid hanlder, emit by jQuery validator
   *
   * @param {Event} event: The jQuery validator event
   * @param {Object} validator: The validator object
   */
  CentreonForm.prototype.invalidHandler = function (event, validator) {
    var formId = this.$elem.id,
        $list = $("#" + formId + "_errors"),
        $firstInput = $(validator.errorList[0].element);
    $list.children().remove();
    $("

").text("There are " + validator.errorList.length + " errors").appendTo($list);
    $list.closest(".flash").addClass("alert-danger").show();
    /* Focus the first element in error */
    $firstInput.focus();
    $("body").scrollTop($firstInput);
  };

  $.fn.centreonForm = function (options) {
    var args = Array.prototype.slice.call(arguments, 1);
    var settings = $.extend({}, $.fn.centreonForm.defaults, options);
    var methodReturn = undefined;
    var $set = this.each(function () {
      var $this = $(this);
      var data = $this.data("centreonForm");

      if (!data) {
        $this.data("centreonForm", ( data = new CentreonForm(settings, $this)));
      }

      if (typeof options === "string") {
        methodReturn = data[options].apply(data, args);
      }

      return (methodReturn === undefined) ? $set : methodReturn;
    });
  };

  $.fn.centreonForm.defaults = {
    helpUrl: "/form/help",
    rules: undefined
  };
})(jQuery);
<commit_msg>Fix when field has no help<commit_after>/*global jQuery:false */

(function ($) {

  function CentreonForm(settings, $elem) {
    var self = this,
        rules;
    this.settings = settings;
    this.$elem = $elem;
    this.groups = {};
    this.formUrl = this.$elem.data("route");

    this.initClassInput();

    /* Add event for change the float label */
    this.$elem.find("input, textarea").on(
      "focus",
      function () {
        var $parent = $(this).closest(".form-group"),
            $help = $parent.find("cite");
        self.getHelp($(this));
        $help.show();
        self.toggleLabel($(this));
      }
    )
    .on(
      "keyup change",
      function (e) {
        self.toggleLabel($(this));
      }
    )
    .on(
      "blur",
      function () {
        var $parent = $(this).closest(".form-group"),
            $help = $parent.find("cite");
        if (false === $parent.hasClass("has-error")) {
          $help.hide();
        }
        self.toggleLabel($(this));
      }
    );

    /* Add validation for this form */
    if (this.settings.rules === undefined) {
      rules = (formValidRule[this.$elem.id] === undefined ? {} : formValidRule[this.$elem.id]);
    } else {
      rules = this.settings.rules;
    }
    this.$elem.validate({
      rules: rules,
      invalidHandler: function (event, validator) {
        self.invalidHandler(event, validator);
      }
    });
  }

  /**
   * Initialize label classes
   */
  CentreonForm.prototype.initClassInput = function () {
    var self = this;
    this.$elem.find(".form-group").each(function () {
      var name = $(this).find("input[name]").attr("name");
      /* Add group in cache */
      self.groups[name] = {
        help: undefined
      };

      /* Set css if input is empty */
      $(this).find("input[name]").each(function () {
        self.toggleLabel($(this));
      });
    });
  };

  /**
   * Get the help from ajax or cache
   *
   * @param {Object} $el: The input element
   */
  CentreonForm.prototype.getHelp = function ($el) {
    var self = this,
        $parent = $el.closest(".form-group"),
        $help = $parent.find("cite"),
        name = $el.attr("name");

    /* Test if name is set, else it's not the primary element input */
    if (name === undefined) {
      name = $parent.find("input[name]").attr("name");
    }

    /* Test if the help is in cache */
    if ((name !== undefined) && (this.groups[name]["help"] !== undefined)) {
      if (false === $parent.hasClass("has-error")) {
        $help.html(this.groups[name]["help"]);
      }
      return;
    }

    /* Get the help with ajax */
    $.ajax({
      url: this.settings.helpUrl,
      type: "get",
      dataType: "json",
      data: {
        form: this.formUrl,
        field: name
      },
      success: function (data) {
        if (false === $parent.hasClass("has-error")) {
          /* Add cache */
          self.groups[name]["help"] = data.text;
          $help.html(data.text);
        }
      }
    });
  };

  /**
   * Display the label for an element
   *
   * @param {Object} $el: The input element
   */
  CentreonForm.prototype.showLabel = function ($el) {
    $el.closest(".form-group").removeClass("js-hide-label").addClass("js-unhighlight-label");
    $el.css("padding", "16px 12px 6px");
  };

  /**
   * Hide the label for an element
   *
   * @param {Object} $el: The input element
   */
  CentreonForm.prototype.hideLabel = function ($el) {
    $el.closest(".form-group").addClass("js-hide-label").removeClass("js-unhighlight-label");
    $el.css("padding", "10px 12px 12px");
  };

  /**
   * Toggle the label by the value of the element
   *
   * @param {Object} $el: The input element
   */
  CentreonForm.prototype.toggleLabel = function ($el) {
    var $parent;
    if ($el.attr("name") === undefined) {
      $parent = $el.closest(".form-group");
      $el = $parent.find("input[name]");
    }
    if ($.trim($el.val()) !== "") {
      this.showLabel($el);
    } else {
      this.hideLabel($el);
    }
  };

  /**
   * Event for invalid hanlder, emit by jQuery validator
   *
   * @param {Event} event: The jQuery validator event
   * @param {Object} validator: The validator object
   */
  CentreonForm.prototype.invalidHandler = function (event, validator) {
    var formId = this.$elem.id,
        $list = $("#" + formId + "_errors"),
        $firstInput = $(validator.errorList[0].element);
    $list.children().remove();
    $("

").text("There are " + validator.errorList.length + " errors").appendTo($list);
    $list.closest(".flash").addClass("alert-danger").show();
    /* Focus the first element in error */
    $firstInput.focus();
    $("body").scrollTop($firstInput);
  };

  $.fn.centreonForm = function (options) {
    var args = Array.prototype.slice.call(arguments, 1);
    var settings = $.extend({}, $.fn.centreonForm.defaults, options);
    var methodReturn = undefined;
    var $set = this.each(function () {
      var $this = $(this);
      var data = $this.data("centreonForm");

      if (!data) {
        $this.data("centreonForm", ( data = new CentreonForm(settings, $this)));
      }

      if (typeof options === "string") {
        methodReturn = data[options].apply(data, args);
      }

      return (methodReturn === undefined) ? $set : methodReturn;
    });
  };

  $.fn.centreonForm.defaults = {
    helpUrl: "/form/help",
    rules: undefined
  };
})(jQuery);
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import Counter from './Counter.js';
import Summary from './Summary.js';

const style = {
  margin: '20px'
};

class ControlPanel extends Component {
  render() {
    const store = this.context.store;
    const state = store.getState();

    return (

        {
          Object.keys(state).map(key => <Counter caption={key} key={key} />)
        }

    );
  }
}

ControlPanel.contextTypes = {
  store: PropTypes.object
}

export default ControlPanel;

<commit_msg>make ControlPanel independent of store<commit_after>import React, { Component } from 'react';
import Counter from './Counter.js';
import Summary from './Summary.js';

const style = {
  margin: '20px'
};

class ControlPanel extends Component {
  render() {
    return (

        <Counter caption="First" />
        <Counter caption="Second" />
        <Counter caption="Third" />

    );
  }
}

export default ControlPanel;

<|endoftext|>


<commit_before><commit_msg>Tests added for contains validation API<commit_after>var contains = require('../validate.js').contains,
    expect   = require('chai').expect;

describe('contains API Tests', function () {
    describe('Valid tests for contains API', function () {
        var baseStr = 'This is this and that is that';
        var searchStr = 'this';

        it('contains value test 1', function () {
            expect(contains(baseStr, searchStr)).to.be.true;
        });

        baseStr = 'GAURAV IS AWESOME';
        searchStr = 'awesome';

        it('contains value test 2', function () {
            expect(contains(baseStr, searchStr)).to.be.true;
        });

        baseStr = 'awesome';
        searchStr = 'awe';

        it('contains value test 3', function () {
            expect(contains(baseStr, searchStr)).to.be.true;
        });

        baseStr = 'This is an epic line';
        searchStr = 'epic';

        it('contains value test 4', function () {
            expect(contains(baseStr, searchStr)).to.be.true;
        });

        baseStr = 'null';
        searchStr = 'null';

        it('contains value test 5', function () {
            expect(contains(baseStr, searchStr)).to.be.true;
        });

        baseStr = 'undefined is not null';
        searchStr = 'null';

        it('contains value test 6', function () {
            expect(contains(baseStr, searchStr)).to.be.true;
        });

        baseStr = 'GAURAV IS AWESOME';
        searchStr = 'AWESOME';

        it('contains value test 7', function () {
            expect(contains(baseStr, searchStr)).to.be.true;
        });
    });

    describe('Invalid tests for contains API', function () {
        it('contains value - invalid test 1', function () {
            expect(contains('hellow', null)).to.be.false;
        });

        it('contains value - invalid test 2', function () {
            expect(contains('hellow', undefined)).to.be.false;
        });

        it('contains value - invalid test 3', function () {
            expect(contains(undefined, null)).to.be.false;
        });

        it('contains value - invalid test 4', function () {
            expect(contains(undefined, 'null')).to.be.false;
        });

        it('contains value - invalid test 5', function () {
            expect(contains(null, null)).to.be.false;
        });

        it('contains value - invalid test 5', function () {
            expect(contains(undefined, undefined)).to.be.false;
        });

        it('contains value - invalid test 6', function () {
            expect(contains(new Date(), 'undefined')).to.be.false;
        });

        it('contains value - invalid test 7', function () {
            expect(contains(new Date(), new Date())).to.be.false;
        });
    });
});<|endoftext|>


<commit_before>var crc32 = require('../lib/util.js').crc32;
var test = require('tap').test;

test('simple crc32 is no problem', function (t) {
  var input = Buffer('hey sup bros');
  var expected = Buffer([0x47, 0xfa, 0x55, 0x70]);
  t.same(crc32(input), expected);
  t.end();
});

test('another simple one', function (t) {
  var input = Buffer('IEND');
  var expected = Buffer([0xae, 0x42, 0x60, 0x82]);
  t.same(crc32(input), expected);
  t.end();
});

test('slightly more complex', function (t) {
  var input = Buffer([0x00, 0x00, 0x00]);
  var expected = Buffer([0xff, 0x41, 0xd9, 0x12]);
  t.same(crc32(input), expected);
  t.end();
});

test('complex crc32 gets calculated like a champ', function (t) {
  var input = Buffer('शीर्षक');
  var expected = Buffer([0x17, 0xb8, 0xaf, 0xf1]);
  t.same(crc32(input), expected);
  t.end();
});
<commit_msg>Use buffer-crc32<commit_after><|endoftext|>


<commit_before>// 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.

(function($) {

  suggest = function(elem, options) {
    var timer = null;
    var prevVal = null;

    var input = $(elem).attr("autocomplete", "off");
    var offset = input.offset();
    var dropdown = $('

')
      .addClass(options.dropdownClass).appendTo("body").css({
        top: (offset.top + elem.offsetHeight) + "px",
        left: offset.left + "px",
        minWidth: input.css("width")
      });

    input
      .blur(function() {
        if (timer) clearTimeout(timer);
        setTimeout(function() { dropdown.hide() }, 200);
      })
      .keydown(function(e) {
        if ($.inArray(e.keyCode, [16, 17, 18, 20, 144, 91, 93, 224]) != -1) {
          return; // ignore modifier keys
        }
        if (timer) clearTimeout(timer);
        if ($.inArray(e.keyCode, [38, 40]) != -1 ||
            (dropdown.is(":visible") && (e.keyCode == 27 ||
             ($.inArray(e.keyCode, [9, 13]) != -1 && getSelection())))) {
          switch(e.keyCode) {
            case 38: // up
              moveUp();
              break;
            case 40: // down
              moveDown();
              break;
            case 9:  // tab
            case 13: // return
              commit();
              if (e.keyCode == 9) return true;
              break;
            case 27: // escape
              dropdown.hide();
              break;
          }
          e.preventDefault(); e.stopPropagation();
          return false;
        } else {
          timer = setTimeout(function() { suggest() }, options.delay);
        }
      });

    function suggest(force) {
      var newVal = $.trim(input.val());
      if (force || newVal != prevVal) {
        if (force || newVal.length >= options.minChars) {
          options.callback.apply(elem, [$.trim(input.val()), function(items, render) {
            show(items, render);
          }]);
        } else {
          dropdown.hide();
        }
        prevVal = newVal;
      }
    }

    function show(items, render) {
      if (!items) return;
      if (!items.length) { dropdown.hide(); return; }
      render = render || function(idx, value) { return value; }
      dropdown.empty();
      for (var i = 0; i < items.length; i++) {
        var item = $("

").data("value", items[i]);
        var rendered = render(i, items[i]);
        if (typeof(rendered) == "string") {
          item.text(rendered);
        } else {
          item.append(rendered);
        }
        item.appendTo(dropdown);
      }
      dropdown.slideDown("fast");
      dropdown.children('li').click(function(e) {
        $(this).addClass("selected");
        commit();
      });
    }

    function commit() {
      var sel = getSelection();
      if (sel) {
        prevVal = sel.data("value");
        input.val(prevVal);
        dropdown.hide();
      }
      if (timer) clearTimeout(timer)
    }

    function getSelection() {
      if (!dropdown.is(":visible")) return null;
      var sel = dropdown.children("li.selected");
      return sel.length ? sel : null;
    }

    function moveDown() {
      if (!dropdown.is(":visible")) suggest(true);
      var sel = getSelection();
      if (sel) sel.removeClass("selected").next().addClass("selected");
      else dropdown.children("li:first-child").addClass("selected");
    }

    function moveUp() {
      if (!dropdown.is(":visible")) suggest(true);
      var sel = getSelection();
      if (sel) sel.removeClass("selected").prev().addClass("selected");
      else dropdown.children("li:last-child").addClass("selected");
    }
  }

  $.fn.suggest = function(callback, options) {
    options = $.extend({
      callback: callback,
      delay: 100,
      dropdownClass: "suggest-dropdown",
      minChars: 1
    }, options || {});
    return this.each(function() {
      suggest(this, options);
    });
  };

})(jQuery);
<commit_msg>Add on-select callback to Futon autocompletion plugin.<commit_after>// 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.

(function($) {

  suggest = function(elem, options) {
    var timer = null;
    var prevVal = null;

    var input = $(elem).attr("autocomplete", "off");
    var offset = input.offset();
    var dropdown = $('

')
      .addClass(options.dropdownClass).appendTo("body").css({
        top: (offset.top + elem.offsetHeight) + "px",
        left: offset.left + "px",
        minWidth: input.css("width")
      });

    input
      .blur(function() {
        if (timer) clearTimeout(timer);
        setTimeout(function() { dropdown.hide() }, 200);
      })
      .keydown(function(e) {
        if ($.inArray(e.keyCode, [16, 17, 18, 20, 144, 91, 93, 224]) != -1) {
          return; // ignore modifier keys
        }
        if (timer) clearTimeout(timer);
        if ($.inArray(e.keyCode, [38, 40]) != -1 ||
            (dropdown.is(":visible") && (e.keyCode == 27 ||
             ($.inArray(e.keyCode, [9, 13]) != -1 && getSelection())))) {
          switch(e.keyCode) {
            case 38: // up
              moveUp();
              break;
            case 40: // down
              moveDown();
              break;
            case 9:  // tab
            case 13: // return
              commit();
              if (e.keyCode == 9) return true;
              break;
            case 27: // escape
              dropdown.hide();
              break;
          }
          e.preventDefault(); e.stopPropagation();
          return false;
        } else {
          timer = setTimeout(function() { suggest() }, options.delay);
        }
      });

    function suggest(force) {
      var newVal = $.trim(input.val());
      if (force || newVal != prevVal) {
        if (force || newVal.length >= options.minChars) {
          options.callback.apply(elem, [$.trim(input.val()), function(items, render) {
            show(items, render);
          }]);
        } else {
          dropdown.hide();
        }
        prevVal = newVal;
      }
    }

    function show(items, render) {
      if (!items) return;
      if (!items.length) { dropdown.hide(); return; }
      render = render || function(idx, value) { return value; }
      dropdown.empty();
      for (var i = 0; i < items.length; i++) {
        var item = $("

").data("value", items[i]);
        var rendered = render(i, items[i]);
        if (typeof(rendered) == "string") {
          item.text(rendered);
        } else {
          item.append(rendered);
        }
        item.appendTo(dropdown);
      }
      dropdown.slideDown("fast");
      dropdown.children('li').click(function(e) {
        $(this).addClass("selected");
        commit();
      });
    }

    function commit() {
      var sel = getSelection();
      if (sel) {
        prevVal = sel.data("value");
        input.val(prevVal);
        if (options.select) {
          options.select.apply(elem, [prevVal]);
        }
        dropdown.hide();
      }
      if (timer) clearTimeout(timer)
    }

    function getSelection() {
      if (!dropdown.is(":visible")) return null;
      var sel = dropdown.children("li.selected");
      return sel.length ? sel : null;
    }

    function moveDown() {
      if (!dropdown.is(":visible")) suggest(true);
      var sel = getSelection();
      if (sel) sel.removeClass("selected").next().addClass("selected");
      else dropdown.children("li:first-child").addClass("selected");
    }

    function moveUp() {
      if (!dropdown.is(":visible")) suggest(true);
      var sel = getSelection();
      if (sel) sel.removeClass("selected").prev().addClass("selected");
      else dropdown.children("li:last-child").addClass("selected");
    }
  }

  $.fn.suggest = function(callback, options) {
    options = $.extend({
      callback: callback,
      delay: 100,
      dropdownClass: "suggest-dropdown",
      minChars: 1,
      select: null
    }, options || {});
    return this.each(function() {
      suggest(this, options);
    });
  };

})(jQuery);
<|endoftext|>