<commit_before> 'use strict';
var http = require('http'),
fs = require('fs'),
cfg = require('./config').server.game,
server = http.createServer(function (req, res) {
	if (req.url === '/' || req.url === '/index.html' || req.url === '/design.html') {
		if (req.url === '/') {
			req.url = '/index.html';
		}

		fs.readFile('./public' + req.url, function (err, data) {
			if (err) {
				throw err;
			}

			res.writeHead(200, {'Content-Type': 'text/html'});
			res.write(data);
			res.end();
		});
	} else if (req.url === '/styles.css') {
		fs.readFile('./public/css/styles.css', function (err, data) {
			if (err) {
				throw err;
			}

			res.writeHead(200, {'Content-Type': 'text/css'});
			res.write(data);
			res.end();
		});
	} else if (req.url === '/rockmud-client.js') {
		fs.readFile('./public/js/rockmud-client.js', function (err, data) {
			if (err) {
				throw err;
			}

			res.writeHead(200, {'Content-Type': 'text/javascript'});
			res.write(data);
			res.end();
		});
	}
}),
World = require('./src/world').world,
io = require('socket.io')(server);

World.setup(io, cfg, function(Character, Cmds, Skills) {
	server.listen(process.env.PORT || cfg.port);

	io.on('connection', function (s) {
		s.emit('msg', {msg : 'Enter your name:', res: 'login', styleClass: 'enter-name'});

		s.on('login', function (r) {
			var parseCmd = function(r, s) {
				var cmdArr = r.msg.split(' '),
				cmdObj ={};

				if (cmdArr.length === 1) {
					cmdArr[1] = '';
				}

				if (/[`~@#$%^&*()-+={}[]|<>]+$/g.test(r.msg) === false) {
					cmdObj = {
						cmd: cmdArr[0].toLowerCase(), // {cast} spark boar
						msg: cmdArr.slice(1).join(' '), // cast {spark boar}
						arg: cmdArr[1].toLowerCase(), // cast {spark} boar
						input: cmdArr.slice(2).join(' '), // cast spark {boar ...}
						number: 1 // argument target -- cast spark 2.boar
					};

					if (cmdObj.input && 	!isNaN(parseInt(cmdObj.input[0])) || (!cmdObj.input && !isNaN(parseInt(cmdObj.msg[0]))) ) {

						if (!cmdObj.input) {
							cmdObj.number = parseInt(cmdObj.msg[0]);
							cmdObj.msg = cmdObj.msg.replace(/^[0-9][.]/, '');
						} else {
							cmdObj.number = parseInt(cmdObj.input[0]);
							cmdObj.input = cmdObj.input.replace(/^[0-9][.]/, '');
						}
					}

					if (cmdObj.msg === '' || cmdObj.msg.length >= 3 && s.player.wait === 0) {
						if (cmdObj.cmd) {
							if (cmdObj.cmd in Cmds) {
								return Cmds[cmdObj.cmd](s.player, cmdObj);
							} else if (cmdObj.cmd in Skills) {
								return Skills[r.cmd](s.player, cmdObj);
							} else {
								World.msgPlayer(s, {msg: cmdObj.cmd + ' is not a valid command.', styleClass: 'error'});
							}
						} else {
							return World.prompt(s);
						}
					} else {
						if (s.player.wait > 0) {
							World.msgPlayer(s, {msg: 'You cant do that just yet!', styleClass: 'error'});
						} else {
							World.msgPlayer(s, {msg: 'You have to be more specific with your command.', styleClass: 'error'});
						}
					}
				} else {
					World.msgPlayer(s, {msg: 'Invalid characters in command!', styleClass: 'error'});
				}
			};

			if (r.msg !== '') {
				return Character.login(r, s, function (name, s, fnd) {
					if (fnd) {
						s.join('mud'); // mud is one of two rooms, 'creation' being the other
						Character.load(name, s, function (s) {
							Character.getPassword(s, function(s) {
								s.on('cmd', function (r) {
									parseCmd(r, s);
								});
							});
						});
					} else {
						s.join('creation'); // creation is one of two rooms, 'mud' being the other

						s.player = World.mobTemplate;
						s.player.name = name;
						s.player.sid = s.id;
						s.player.socket = s;

						Character.newCharacter(r, s, function(s) {
							s.on('cmd', function (r) {
								parseCmd(r, s);
							});
						});
					}
				});
			} else {
				return s.emit('msg', {msg : 'Enter your name:', res: 'login', styleClass: 'enter-name'});
			}
		});

		s.on('quit', function () {
			if (s.player.position !== 'fighting') {
				Character.save(s.player, function() {
					World.msgPlayer(s, {
						msg: 'Add a little to a little and there will be a big pile.',
						emit: 'disconnect',
						styleClass: 'logout-msg',
						noPrompt: true
					});

					s.leave('mud');
					s.disconnect();
				});
			} else {
				World.msgPlayer(s, {
					msg: 'You are fighting! Finish up before quitting',
					emit: 'disconnect',
					styleClass: 'logout-msg'
				});
			}
		});

		s.on('disconnect', function () {
			var i = 0;
			if (s.player !== undefined) {
				for (i; i < World.players.length; i += 1) {
					if (World.players[i].name === s.player.name) {
						World.players.splice(i, 1);
					}
				}

				World.getRoomObject(s.player.area, s.player.roomid, function(roomObj) {
					var j = 0;

					for (j; j < roomObj.playersInRoom.length; j += 1) {
						if (roomObj.playersInRoom[j].name === s.player.name) {
							roomObj.playersInRoom.splice(j, 1);
						}
					}
				});
			}
		});
	});
});

<commit_msg>removing long polling support<commit_after> 'use strict';
var http = require('http'),
fs = require('fs'),
cfg = require('./config').server.game,
server = http.createServer(function (req, res) {
	if (req.url === '/' || req.url === '/index.html' || req.url === '/design.html') {
		if (req.url === '/') {
			req.url = '/index.html';
		}

		fs.readFile('./public' + req.url, function (err, data) {
			if (err) {
				throw err;
			}

			res.writeHead(200, {'Content-Type': 'text/html'});
			res.write(data);
			res.end();
		});
	} else if (req.url === '/styles.css') {
		fs.readFile('./public/css/styles.css', function (err, data) {
			if (err) {
				throw err;
			}

			res.writeHead(200, {'Content-Type': 'text/css'});
			res.write(data);
			res.end();
		});
	} else if (req.url === '/rockmud-client.js') {
		fs.readFile('./public/js/rockmud-client.js', function (err, data) {
			if (err) {
				throw err;
			}

			res.writeHead(200, {'Content-Type': 'text/javascript'});
			res.write(data);
			res.end();
		});
	}
}),
World = require('./src/world').world,
io = require('socket.io')(server, {
	transports: ['websocket']
});

World.setup(io, cfg, function(Character, Cmds, Skills) {
	server.listen(process.env.PORT || cfg.port);

	io.on('connection', function (s) {
		s.emit('msg', {msg : 'Enter your name:', res: 'login', styleClass: 'enter-name'});

		s.on('login', function (r) {
			var parseCmd = function(r, s) {
				var cmdArr = r.msg.split(' '),
				cmdObj ={};

				if (cmdArr.length === 1) {
					cmdArr[1] = '';
				}

				if (/[`~@#$%^&*()-+={}[]|<>]+$/g.test(r.msg) === false) {
					cmdObj = {
						cmd: cmdArr[0].toLowerCase(), // {cast} spark boar
						msg: cmdArr.slice(1).join(' '), // cast {spark boar}
						arg: cmdArr[1].toLowerCase(), // cast {spark} boar
						input: cmdArr.slice(2).join(' '), // cast spark {boar ...}
						number: 1 // argument target -- cast spark 2.boar
					};

					if (cmdObj.input && 	!isNaN(parseInt(cmdObj.input[0])) || (!cmdObj.input && !isNaN(parseInt(cmdObj.msg[0]))) ) {

						if (!cmdObj.input) {
							cmdObj.number = parseInt(cmdObj.msg[0]);
							cmdObj.msg = cmdObj.msg.replace(/^[0-9][.]/, '');
						} else {
							cmdObj.number = parseInt(cmdObj.input[0]);
							cmdObj.input = cmdObj.input.replace(/^[0-9][.]/, '');
						}
					}

					if (cmdObj.msg === '' || cmdObj.msg.length >= 3 && s.player.wait === 0) {
						if (cmdObj.cmd) {
							if (cmdObj.cmd in Cmds) {
								return Cmds[cmdObj.cmd](s.player, cmdObj);
							} else if (cmdObj.cmd in Skills) {
								return Skills[r.cmd](s.player, cmdObj);
							} else {
								World.msgPlayer(s, {msg: cmdObj.cmd + ' is not a valid command.', styleClass: 'error'});
							}
						} else {
							return World.prompt(s);
						}
					} else {
						if (s.player.wait > 0) {
							World.msgPlayer(s, {msg: 'You cant do that just yet!', styleClass: 'error'});
						} else {
							World.msgPlayer(s, {msg: 'You have to be more specific with your command.', styleClass: 'error'});
						}
					}
				} else {
					World.msgPlayer(s, {msg: 'Invalid characters in command!', styleClass: 'error'});
				}
			};

			if (r.msg !== '') {
				return Character.login(r, s, function (name, s, fnd) {
					if (fnd) {
						s.join('mud'); // mud is one of two rooms, 'creation' being the other
						Character.load(name, s, function (s) {
							Character.getPassword(s, function(s) {
								s.on('cmd', function (r) {
									parseCmd(r, s);
								});
							});
						});
					} else {
						s.join('creation'); // creation is one of two rooms, 'mud' being the other

						s.player = World.mobTemplate;
						s.player.name = name;
						s.player.sid = s.id;
						s.player.socket = s;

						Character.newCharacter(r, s, function(s) {
							s.on('cmd', function (r) {
								parseCmd(r, s);
							});
						});
					}
				});
			} else {
				return s.emit('msg', {msg : 'Enter your name:', res: 'login', styleClass: 'enter-name'});
			}
		});

		s.on('quit', function () {
			if (s.player.position !== 'fighting') {
				Character.save(s.player, function() {
					World.msgPlayer(s, {
						msg: 'Add a little to a little and there will be a big pile.',
						emit: 'disconnect',
						styleClass: 'logout-msg',
						noPrompt: true
					});

					s.leave('mud');
					s.disconnect();
				});
			} else {
				World.msgPlayer(s, {
					msg: 'You are fighting! Finish up before quitting',
					emit: 'disconnect',
					styleClass: 'logout-msg'
				});
			}
		});

		s.on('disconnect', function () {
			var i = 0;
			if (s.player !== undefined) {
				for (i; i < World.players.length; i += 1) {
					if (World.players[i].name === s.player.name) {
						World.players.splice(i, 1);
					}
				}

				World.getRoomObject(s.player.area, s.player.roomid, function(roomObj) {
					var j = 0;

					for (j; j < roomObj.playersInRoom.length; j += 1) {
						if (roomObj.playersInRoom[j].name === s.player.name) {
							roomObj.playersInRoom.splice(j, 1);
						}
					}
				});
			}
		});
	});
});

<|endoftext|>


<commit_before>define(function (require) {

  var a = require('./a.js?v=1.0');
  var a2 = require('./a.js?v=2.0');

  var test = require('../../test');
  test.assert(a.foo === 1, 'module version.');
  test.assert(a.foo === a2.foo, 'module version.');

  test.done();

});
<commit_msg>Update the version test case<commit_after>define(function (require) {

  var a = require('./a.js?v=1.0');
  var a2 = require('./a.js?v=2.0');

  var test = require('../../test');
  test.assert(a.foo === 1, a.foo);
  test.assert(a.foo === a2.foo, a2.foo);

  test.done();

});
<|endoftext|>


<commit_before>(function() {
  /*
   * Generate a random with custom alphabet.
   */

  function create(stringLength) {
    var result = '';

    alphabet = 'CDEHKMPRTUWXY012458';
    var alphabetLength = alphabet.length;

    if ((stringLength === undefined) || isNaN(stringLength)) stringLength = 12;
    for (var i = 0; i < stringLength; i++) {
      var rnd = Math.floor(Math.random() * alphabetLength);
      result += alphabet[rnd];
    }

    return result;
  }

  function parse(string, targetLength) {
      if(!targetLength)
      targetLength = -1;

    replacements = [
      {
        replace: ["v", "V"].join("|"),
        replaceWith: "U"
      },
      {
        replace: ["o", "O", "ö", "Ö"].join("|"),
        replaceWith: "0"
      },
      {
        replace: ["i", "I", "l", "L", "j", "J", "ı"].join("|"),
        replaceWith: "1"
      },
      {
        replace: ["z", "Z"].join("|"),
        replaceWith: "2"
      },
      {
        replace: ["a", "A", "ä", "Ä"].join("|"),
        replaceWith: "4"
      },
      {
        replace: ["s", "S"].join("|"),
        replaceWith: "5"
      },
      {
        replace: ["n", "N"].join("|"),
        replaceWith: "M"
      },
      {
        replace: ["ü", "Ü"].join("|"),
        replaceWith: "U"
      },

    ];

    for (replacement in replacements) {
      var re = new RegExp(replacements[replacement].replace, "g");
      string = string.replace(re, replacements[replacement].replaceWith);
    }

    return string.toUpperCase();
  }

  var distinguishable    = {};
  distinguishable.create = create;
  distinguishable.parse  = parse;

  module.exports = distinguishable;
})();
<commit_msg>The character 'B' is now replaced by '8'<commit_after>(function() {
  /*
   * Generate a random with custom alphabet.
   */

  function create(stringLength) {
    var result = '';

    alphabet = 'CDEHKMPRTUWXY012458';
    var alphabetLength = alphabet.length;

    if ((stringLength === undefined) || isNaN(stringLength)) stringLength = 12;
    for (var i = 0; i < stringLength; i++) {
      var rnd = Math.floor(Math.random() * alphabetLength);
      result += alphabet[rnd];
    }

    return result;
  }

  function parse(string, targetLength) {
      if(!targetLength)
      targetLength = -1;

    replacements = [
      {
        replace: ["v", "V"].join("|"),
        replaceWith: "U"
      },
      {
        replace: ["o", "O", "ö", "Ö"].join("|"),
        replaceWith: "0"
      },
      {
        replace: ["i", "I", "l", "L", "j", "J", "ı"].join("|"),
        replaceWith: "1"
      },
      {
        replace: ["z", "Z"].join("|"),
        replaceWith: "2"
      },
      {
        replace: ["a", "A", "ä", "Ä"].join("|"),
        replaceWith: "4"
      },
      {
        replace: ["s", "S"].join("|"),
        replaceWith: "5"
      },
      {
        replace: ["n", "N"].join("|"),
        replaceWith: "M"
      },
      {
        replace: ["ü", "Ü"].join("|"),
        replaceWith: "U"
      },
      {
        replace: ["B"].join("|"),
        replaceWith: "8"
      },

    ];

    for (replacement in replacements) {
      var re = new RegExp(replacements[replacement].replace, "g");
      string = string.replace(re, replacements[replacement].replaceWith);
    }

    return string.toUpperCase();
  }

  var distinguishable    = {};
  distinguishable.create = create;
  distinguishable.parse  = parse;

  module.exports = distinguishable;
})();
<|endoftext|>


<commit_before>var scaleControl = require('map-scale-control');
var zoomControl = require('map-zoom-control');

var images = require('./images');
var object = require('./object');
var updater = require('./updater');
var util = require('./util');
var makeFeatureEventHandler = require('./feature-event-handler');

module.exports = map;

/* global mapboxgl */

function customControl(options) {
  return {
    onAdd: function (map) {
      var ctrl = this;
      ctrl._map = map;
      ctrl._container = document.createElement('div');
      ctrl._container.className = 'mapboxgl-ctrl';
      if (options.el) {
        ctrl._container.appendChild(options.el);
      }
      if (options.onAdd) {
        options.onAdd.call(ctrl, map);
      }
      return ctrl._container;
    },
    onRemove: function () {
      var ctrl = this;
      if (options.el) {
        ctrl._container.removeChild(options.el);
      }
      if (options.onRemove) {
        options.onRemove.call(ctrl);
      }
      ctrl._container.parentNode.removeChild(ctrl._container);
      delete ctrl._container;
      delete ctrl._map;
    }
  };
}

function mapTypeControl(mapTypeControlOptions, customMapTypes, fn) {
  return customControl({
    onAdd: function () {
      var ctrl = this;
      ctrl._events = [];
      mapTypeControlOptions.mapTypeIds.forEach(function (id) {
        var type = ctrl._container.appendChild(document.createElement('div')),
          ev = {
            el: type,
            event: 'click',
            fn: fn.bind(undefined, id)
          };
        type.className = 'map-type';
        type.innerHTML = '<div>' + customMapTypes[id].name + '</div>';
        type.addEventListener(ev.event, ev.fn);
        ctrl._events.push(ev);
      });
    },
    onRemove: function () {
      var ctrl = this;
      ctrl._events.forEach(function (ev) {
        ev.type.removeEventListener(ev.event, ev.fn);
      });
      delete ctrl._events;
    }
  });
}

function getAttribution(style) {
  var sourceCaches, attributions;
  if (!style) {
    return [];
  }
  sourceCaches = style.sourceCaches;
  attributions = Object.keys(sourceCaches).reduce(function (attributions, id) {
    var source = sourceCaches[id].getSource();
    if (source.attribution && attributions.indexOf(source.attribution) < 0) {
      attributions.push(source.attribution);
    }
    return attributions;
  }, []);

  // remove any entries that are substrings of another entry.
  // first sort by length so that substrings come first
  attributions.sort(function (a, b) {
    return a.length - b.length;
  });
  attributions = attributions.filter(function(attrib, i) {
    var j;
    for (j = i + 1; j < attributions.length; j += 1) {
      if (attributions[j].indexOf(attrib) >= 0) {
        return false;
      }
    }
    return true;
  });
  return attributions.join(' ');
}

function transition(prop) {
  var _m = this;
  _m[prop] = Object.assign(function (options) {
    if (options.zoom) {
      options.zoom = Math.floor(options.zoom);
    }
    _m[prop].superior.apply(this, arguments);
  }, {
    superior: _m[prop]
  });
}

function mapUnits(units) {
  return units === 'km' ? 'metric' : 'imperial';
}

function map(node, options) {
  var controlPosition = {
      BL: 'bottom-left',
      LB: 'bottom-left',
      BR: 'bottom-right',
      RB: 'bottom-right',
      TL: 'top-left',
      LT: 'top-left',
      TR: 'top-right',
      RT: 'top-right'
    }, self, mapTypeId, styles;

  function element() {
    return node;
  }

  function center(c) {
    if (!c) {
      return util.mll2ll(self._m.getCenter());
    }
    self._m.setCenter(c);
  }

  function zoom(z) {
    if (z === undefined) {
      return Math.round(self._m.getZoom() + 1);
    }
    self._m[self._m.isStyleLoaded() ? 'zoomTo' : 'setZoom'](z - 1);
  }

  function bounds(b) {
    var opt;
    if (b === undefined) {
      return util.mbounds2bounds(self._m.getBounds());
    }
    opt = {
      padding: 100
    };
    if (!self._m.isStyleLoaded()) {
      opt.animate = false;
    }
    self._m.fitBounds(b, opt);
  }

  function panToBounds(bounds) {
    // display north-west corner
    self._m.panTo([bounds[1][0], bounds[0][1]]);
    return self;
  }

  function panBy(x, y) {
    self._m.panBy([x, y]);
    return self;
  }

  function mapType() {
    return mapTypeId;
  }

  function refresh() {
    self._m.resize();
  }

  function addStyle(style) {
    if (!self._m.getLayer(style.id)) {
      self._m.addLayer(style, style.metadata && style.metadata.replace);
    }
  }

  function removeStyle(style) {
    if (self._m.getLayer(style.id)) {
      self._m.removeLayer(style.id);
    }
  }

  function applyUnits(units) {
    styles[units].forEach(addStyle);
    styles[units === 'metric' ? 'imperial' : 'metric'].forEach(removeStyle);
  }

  function initStyles() {
    if (!styles) {
      var style = self._m.getStyle();
      if (style.layers) {
        styles = style.layers.reduce((result, layer) => {
          if (layer.metadata) {
            if (layer.metadata.units === 'metric') {
              result.metric.push(layer);
            }
            else if (layer.metadata.units === 'imperial') {
              result.imperial.push(layer);
            }
          }
          return result;
        }, {
          metric: [],
          imperial: []
        });
        if (options.units) {
          applyUnits(mapUnits(options.units));
        }
      }
    }
  }

  function callback(e) {
    if (e.dataType === 'style') {
      initStyles();
      options.onReady(self);
    }
  }

  function addControl(el, position) {
    self._m.addControl(customControl({
      el: el
    }), controlPosition[position]);
    return self;
  }

  function ll(e) {
    if (e && e.lngLat) {
      e.ll = util.mll2ll(e.lngLat);
    }
  }

  function units(u) {
    if (u === undefined) {
      return options.units;
    }
    options.units = u;
    var units = mapUnits(options.units);
    applyUnits(units);
    if (options.scaleControl) {
      options.scaleControl.setUnit(units);
    }
  }

  function destroy() {
    if (self._updater) {
      self._updater.destroy();
      delete self._updater;
    }
    if (self._m) {
      self.off();
      self._m.remove();
      self._images.destroy();
      delete self._m;
      delete self._images;
      delete self._layers;
    }
    styles = undefined;
  }

  options = Object.assign({
    mapboxgl: mapboxgl,
    container: node,
    scaleControl: true,
    mapTypeControl: false,
    style: {
      version: 8,
      sources: {},
      layers: []
    }
  }, options);

  self = object({
    addControl: addControl,
    bounds: bounds,
    center: center,
    destroy: destroy,
    element: element,
    fitBounds: bounds, // obsolete; use bounds(b)
    ll: ll,
    mapType: mapType,
    panBy: panBy,
    panToBounds: panToBounds,
    refresh: refresh,
    units: units,
    zoom: zoom
  });

  if (options.zoom) {
    options.zoom -= 1;
  }
  if (options.minZoom) {
    options.minZoom -= 1;
  }
  if (options.maxZoom) {
    options.maxZoom -= 1;
  }
  if (options.scaleControl === true) {
    options.scaleControl = {};
  }
  if (options.units && options.scaleControl) {
    options.scaleControl.unit = mapUnits(options.units);
  }

  [
    'mapTypeControlOptions',
    'scaleControlOptions',
    'zoomControlOptions',
    'fullscreenControlOptions'
  ].forEach(function (ctrlOptions) {
    ctrlOptions = options[ctrlOptions];
    if (ctrlOptions && ctrlOptions.position) {
      ctrlOptions.position = controlPosition[ctrlOptions.position] || ctrlOptions.position;
    }
  });

  self._m = new options.mapboxgl.Map(options);
  self._featureEventHandler = makeFeatureEventHandler(self._m);
  self._images = images();
  self._layers = {};
  self._updater = updater();

  // ensure integral zoom
  ['flyTo', 'easeTo'].forEach(transition, self._m);

  if (options.onReady) {
    self._m.once('styledata', callback);
  }

  if (options.mapTypeControl) {
    self._m.addControl(mapTypeControl(options.mapTypeControlOptions, options.customMapTypes, function (id) {
      mapTypeId = id;
      self._m.fire('maptypeid_changed');
    }), (options.mapTypeControlOptions && options.mapTypeControlOptions.position) || 'bottom-left');
  }
  if (options.scaleControl) {
    options.scaleControl = scaleControl(options.scaleControl);
    options.scaleControlOptions = options.scaleControlOptions || {};
    options.scaleControlOptions.position = options.scaleControlOptions.position || 'bottom-right';
    self._m.addControl(options.scaleControl, options.scaleControlOptions.position);
  }
  if (options.zoomControl) {
    self._m.addControl(zoomControl(),
        (options.zoomControlOptions && options.zoomControlOptions.position) || 'bottom-right');
  }
  if (options.attribution) {
    self._m.on('data', function (event) {
      if (event.dataType !== 'source') {
        return;
      }
      var attribution = getAttribution(event.style);
      if (typeof options.attribution === 'function') {
        return options.attribution((attribution.match(/href="[^"]+/g) || []).map(function (attr) {
          attr = attr.slice(6);
          attr = attr.match(/(?:http:|https:)?\/\/([^\/?]+)/);
          if (attr) {
            attr = attr[1].split('.');
            if (attr.length > 1) {
              attr = attr[attr.length - 2];
            }
          }
          return attr;
        }));
      }
      options.attribution.innerHTML = attribution;
    });
  }
  return self;
}
<commit_msg>switch mapbox/map.js to ES6<commit_after>const scaleControl = require('map-scale-control');
const zoomControl = require('map-zoom-control');

const images = require('./images');
const object = require('./object');
const updater = require('./updater');
const util = require('./util');
const makeFeatureEventHandler = require('./feature-event-handler');

module.exports = map;

/* global mapboxgl */

function customControl(options) {
  return {
    onAdd(map) {
      const ctrl = this;
      ctrl._map = map;
      ctrl._container = document.createElement('div');
      ctrl._container.className = 'mapboxgl-ctrl';
      if (options.el) {
        ctrl._container.appendChild(options.el);
      }
      if (options.onAdd) {
        options.onAdd.call(ctrl, map);
      }
      return ctrl._container;
    },
    onRemove() {
      const ctrl = this;
      if (options.el) {
        ctrl._container.removeChild(options.el);
      }
      if (options.onRemove) {
        options.onRemove.call(ctrl);
      }
      ctrl._container.parentNode.removeChild(ctrl._container);
      delete ctrl._container;
      delete ctrl._map;
    }
  };
}

function mapTypeControl(mapTypeControlOptions, customMapTypes, fn) {
  return customControl({
    onAdd() {
      const ctrl = this;
      ctrl._events = [];
      mapTypeControlOptions.mapTypeIds.forEach(function (id) {
        const type = ctrl._container.appendChild(document.createElement('div'));
        const ev = {
          el: type,
          event: 'click',
          fn: fn.bind(undefined, id)
        };
        type.className = 'map-type';
        type.innerHTML = `<div>${customMapTypes[id].name}</div>`;
        type.addEventListener(ev.event, ev.fn);
        ctrl._events.push(ev);
      });
    },
    onRemove() {
      const ctrl = this;
      ctrl._events.forEach(ev => ev.type.removeEventListener(ev.event, ev.fn));
      delete ctrl._events;
    }
  });
}

function getAttribution(style) {
  if (!style) {
    return [];
  }
  let sourceCaches = style.sourceCaches;
  let attributions = Object.values(sourceCaches).reduce(function (attributions, sourceCache) {
    const source = sourceCache.getSource();
    if (source.attribution && attributions.indexOf(source.attribution) < 0) {
      attributions.push(source.attribution);
    }
    return attributions;
  }, []);

  // remove any entries that are substrings of another entry.
  // first sort by length so that substrings come first
  attributions.sort((a, b) => a.length - b.length);
  attributions = attributions.filter(function (attrib, i) {
    for (let j = i + 1; j < attributions.length; j += 1) {
      if (attributions[j].indexOf(attrib) >= 0) {
        return false;
      }
    }
    return true;
  });
  return attributions.join(' ');
}

function transition(prop) {
  const _m = this;
  _m[prop] = Object.assign(function (options) {
    if (options.zoom) {
      options.zoom = Math.floor(options.zoom);
    }
    _m[prop].superior.apply(this, arguments);
  }, {
    superior: _m[prop]
  });
}

function mapUnits(units) {
  return units === 'km' ? 'metric' : 'imperial';
}

function map(node, options) {
  const controlPosition = {
    BL: 'bottom-left',
    LB: 'bottom-left',
    BR: 'bottom-right',
    RB: 'bottom-right',
    TL: 'top-left',
    LT: 'top-left',
    TR: 'top-right',
    RT: 'top-right'
  };

  let self;
  let mapTypeId;
  let styles;

  function element() {
    return node;
  }

  function center(c) {
    if (!c) {
      return util.mll2ll(self._m.getCenter());
    }
    self._m.setCenter(c);
  }

  function zoom(z) {
    if (z === undefined) {
      return Math.round(self._m.getZoom() + 1);
    }
    self._m[self._m.isStyleLoaded() ? 'zoomTo' : 'setZoom'](z - 1);
  }

  function bounds(b) {
    if (b === undefined) {
      return util.mbounds2bounds(self._m.getBounds());
    }
    let opt = {
      padding: 100
    };
    if (!self._m.isStyleLoaded()) {
      opt.animate = false;
    }
    self._m.fitBounds(b, opt);
  }

  function panToBounds(bounds) {
    // display north-west corner
    self._m.panTo([bounds[1][0], bounds[0][1]]);
    return self;
  }

  function panBy(x, y) {
    self._m.panBy([x, y]);
    return self;
  }

  function mapType() {
    return mapTypeId;
  }

  function refresh() {
    self._m.resize();
  }

  function addStyle(style) {
    if (!self._m.getLayer(style.id)) {
      self._m.addLayer(style, style.metadata && style.metadata.replace);
    }
  }

  function removeStyle(style) {
    if (self._m.getLayer(style.id)) {
      self._m.removeLayer(style.id);
    }
  }

  function applyUnits(units) {
    styles[units].forEach(addStyle);
    styles[units === 'metric' ? 'imperial' : 'metric'].forEach(removeStyle);
  }

  function initStyles() {
    if (!styles) {
      let style = self._m.getStyle();
      if (style.layers) {
        styles = style.layers.reduce((result, layer) => {
          if (layer.metadata) {
            if (layer.metadata.units === 'metric') {
              result.metric.push(layer);
            }
            else if (layer.metadata.units === 'imperial') {
              result.imperial.push(layer);
            }
          }
          return result;
        }, {
          metric: [],
          imperial: []
        });
        if (options.units) {
          applyUnits(mapUnits(options.units));
        }
      }
    }
  }

  function callback(e) {
    if (e.dataType === 'style') {
      initStyles();
      options.onReady(self);
    }
  }

  function addControl(el, position) {
    self._m.addControl(customControl({
      el
    }), controlPosition[position]);
    return self;
  }

  function ll(e) {
    if (e && e.lngLat) {
      e.ll = util.mll2ll(e.lngLat);
    }
  }

  function units(u) {
    if (u === undefined) {
      return options.units;
    }
    options.units = u;
    let units = mapUnits(options.units);
    applyUnits(units);
    if (options.scaleControl) {
      options.scaleControl.setUnit(units);
    }
  }

  function destroy() {
    if (self._updater) {
      self._updater.destroy();
      delete self._updater;
    }
    if (self._m) {
      self.off();
      self._m.remove();
      self._images.destroy();
      delete self._m;
      delete self._images;
      delete self._layers;
    }
    styles = undefined;
  }

  options = Object.assign({
    mapboxgl,
    container: node,
    scaleControl: true,
    mapTypeControl: false,
    style: {
      version: 8,
      sources: {},
      layers: []
    }
  }, options);

  self = object({
    addControl,
    bounds,
    center,
    destroy,
    element,
    fitBounds: bounds, // obsolete; use bounds(b)
    ll,
    mapType,
    panBy,
    panToBounds,
    refresh,
    units,
    zoom
  });

  if (options.zoom) {
    options.zoom -= 1;
  }
  if (options.minZoom) {
    options.minZoom -= 1;
  }
  if (options.maxZoom) {
    options.maxZoom -= 1;
  }
  if (options.scaleControl === true) {
    options.scaleControl = {};
  }
  if (options.units && options.scaleControl) {
    options.scaleControl.unit = mapUnits(options.units);
  }

  [
    'mapTypeControlOptions',
    'scaleControlOptions',
    'zoomControlOptions',
    'fullscreenControlOptions'
  ].forEach(function(ctrlOptions) {
    ctrlOptions = options[ctrlOptions];
    if (ctrlOptions && ctrlOptions.position) {
      ctrlOptions.position = controlPosition[ctrlOptions.position] || ctrlOptions.position;
    }
  });

  self._m = new options.mapboxgl.Map(options);
  self._featureEventHandler = makeFeatureEventHandler(self._m);
  self._images = images();
  self._layers = {};
  self._updater = updater();

  // ensure integral zoom
  ['flyTo', 'easeTo'].forEach(transition, self._m);

  if (options.onReady) {
    self._m.once('styledata', callback);
  }

  if (options.mapTypeControl) {
    self._m.addControl(mapTypeControl(options.mapTypeControlOptions, options.customMapTypes, function(id) {
      mapTypeId = id;
      self._m.fire('maptypeid_changed');
    }), (options.mapTypeControlOptions && options.mapTypeControlOptions.position) || 'bottom-left');
  }
  if (options.scaleControl) {
    options.scaleControl = scaleControl(options.scaleControl);
    options.scaleControlOptions = options.scaleControlOptions || {};
    options.scaleControlOptions.position = options.scaleControlOptions.position || 'bottom-right';
    self._m.addControl(options.scaleControl, options.scaleControlOptions.position);
  }
  if (options.zoomControl) {
    self._m.addControl(zoomControl(),
        (options.zoomControlOptions && options.zoomControlOptions.position) || 'bottom-right');
  }
  if (options.attribution) {
    self._m.on('data', function (event) {
      if (event.dataType !== 'source') {
        return;
      }
      const attribution = getAttribution(event.style);
      if (typeof options.attribution === 'function') {
        return options.attribution((attribution.match(/href="[^"]+/g) || []).map(function (attr) {
          attr = attr.slice(6);
          attr = attr.match(/(?:http:|https:)?\/\/([^\/?]+)/);
          if (attr) {
            attr = attr[1].split('.');
            if (attr.length > 1) {
              attr = attr[attr.length - 2];
            }
          }
          return attr;
        }));
      }
      options.attribution.innerHTML = attribution;
    });
  }
  return self;
}
<|endoftext|>


<commit_before>import _ from 'lodash';
import parse from './parse';
import context from './context';

let operators = {
  'continuous.equal'              : (context, value) => context  * 1 === value,
  'enum.equal'                    : (context, value) => context === value,
  'continuous.greaterthan'        : (context, value) => context * 1 > value,
  'continuous.greaterthanorequal' : (context, value) => context * 1 >= value,
  'continuous.lessthan'           : (context, value) => context * 1 < value,
  'continuous.lessthanorequal'    : (context, value) => context * 1 <= value,
  'interval.in'                   : (context, value) => {
    let context_val = context * 1;
    let from = value.interval.from_included;
    let to = value.interval.to_excluded;
    //the interval is not looping
    if (from < to) {
      return (context_val>=from && context_val<to);
    }
    //the interval IS looping
    else {
      return (context_val>=from || context_val<to);
    }
  }
};

function decideRecursion( node, context ) {
  // Leaf
  if ( _.isUndefined( node.predicate_property )) {
    return {
      value: node.value,
      confidence: node.confidence || 0,
      standard_deviation: node.standard_deviation, // may be undefined
      predicates: []
    };
  }

  // Regular node
  const property = node.predicate_property;
  if ( _.isUndefined(context[property]) ) {
    throw new Error( `Unable to take decision, property "${property}" is not defined in the given context.` );
  }

  const propertyValue = context[property];

  const matchingChild = _.find(
    node.children,
    child => operators[child.predicate.op](propertyValue, child.predicate.value));

  if (_.isUndefined(matchingChild)) {
    throw new Error( 'Unable to take decision, no matching child found.' );
  }

  // matching child found: recurse !
  const result = decideRecursion( matchingChild, context );
  return {
    value: result.value,
    confidence: result.confidence,
    standard_deviation: result.standard_deviation,
    predicates: [{
      property: property,
      op: matchingChild.predicate.op,
      value: matchingChild.predicate.value
    }].concat(result.predicates)
  };
}

export default function decide( json, ...args ) {
  const { tree, configuration } = parse(json);
  const ctx = configuration ? context(configuration, ...args) : _.extend({}, ...args);
  const rawDecision = decideRecursion(tree, ctx);
  const outputName = (configuration && configuration.output) ? configuration.output[0] : 'value';
  let decision = {};
  decision.decision = {};
  decision.decision[outputName] = rawDecision.value;
  if (!_.isUndefined(rawDecision.standard_deviation)) {
    decision.decision.standard_deviation = rawDecision.standard_deviation;
  }
  decision.confidence = rawDecision.confidence;
  decision.predicates = rawDecision.predicates;
  decision.context = ctx;
  return decision;
}
<commit_msg>Change the decide function to works with the new format<commit_after>import _ from 'lodash';
import parse from './parse';
import context from './context';

let operators = {
  'is'    : (context, value) => context === value,
  '='     : (context, value) => context  * 1 === value,
  '>'     : (context, value) => context * 1 > value,
  '>='    : (context, value) => context * 1 >= value,
  '<'     : (context, value) => context * 1 < value,
  '<='    : (context, value) => context * 1 <= value,
  '[in['  : (context, value) => {
    let context_val = context * 1;
    let from = value[0];
    let to = value[1];
    //the interval is not looping
    if (from < to) {
      return (context_val >= from && context_val < to);
    }
    //the interval IS looping
    else {
      return (context_val >= from || context_val < to);
    }
  }
};

function decideRecursion(node, context) {
  // Leaf
  if (node.predicted_value) {
    return {
      predicted_value: node.predicted_value,
      confidence: node.confidence || 0,
      standard_deviation: node.standard_deviation, // may be undefined
      decision_rules: node.decision_rule ? [node.decision_rule] : []
    };
  }

  // Regular node
  const matchingChild = _.find(
    node.children,
    (child) => {
      const decision_rule = child.decision_rule;
      const property = decision_rule.property;
      if ( _.isUndefined(context[property]) ) {
        throw new Error( `Unable to take decision, property "${property}" is not defined in the given context.` );
      }

      operators[decision_rule.operator](context[property], decision_rule.operand);
    }
  );

  if (_.isUndefined(matchingChild)) {
    throw new Error( 'Unable to take decision, no matching child found.' );
  }

  // matching child found: recurse !
  const result = decideRecursion( matchingChild, context );
  return {
    predicted_value: result.predicted_value,
    confidence: result.confidence,
    standard_deviation: result.standard_deviation,
    decision_rules: [matchingChild.decision_rule].concat(result.decision_rule)
  };
}

export default function decide( json, ...args ) {
  const { tree, configuration } = parse(json);
  const ctx = configuration ? context(configuration, ...args) : _.extend({}, ...args);
  return {
    _version: tree._version,
    context: ctx,
    output: _.assign(..._.map(configuration.output, (output) => ({
      [output]: decideRecursion(tree, ctx)
    })))
  };
}
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 Realm 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.
//
////////////////////////////////////////////////////////////////////////////

'use strict';

var Realm = require('realm');
var BaseTest = require('./base-test');
var TestCase = require('./asserts');
var schemas = require('./schemas');

module.exports = BaseTest.extend({
    testResultsConstructor: function() {
        var realm = new Realm({schema: [schemas.TestObject]});
        var objects = realm.objects('TestObject');

        TestCase.assertTrue(objects instanceof Realm.Results);
        TestCase.assertTrue(objects instanceof Realm.Collection);

        TestCase.assertThrows(function() {
            new Realm.Results();
        });

        TestCase.assertEqual(typeof Realm.Results, 'function');
        TestCase.assertTrue(Realm.Results instanceof Function);
    },

    testResultsLength: function() {
        var realm = new Realm({schema: [schemas.TestObject]});
        var objects = realm.objects('TestObject');
        TestCase.assertEqual(objects.length, 0);

        realm.write(function() {
            realm.create('TestObject', {doubleCol: 1});
            TestCase.assertEqual(objects.length, 1);
        });
        TestCase.assertEqual(objects.length, 1);
    },

    testResultsSubscript: function() {
        var realm = new Realm({schema: [schemas.PersonObject]});
        TestCase.assertEqual(realm.objects('PersonObject')[0], undefined);

        realm.write(function() {
            realm.create('PersonObject', {name: 'name1', age: 1});
            realm.create('PersonObject', {name: 'name2', age: 2});
        });

        var people = realm.objects('PersonObject');
        TestCase.assertEqual(people[0].age, 1);
        TestCase.assertEqual(people[1].age, 2);
        TestCase.assertEqual(people[2], undefined);
        TestCase.assertEqual(people[-1], undefined);
        TestCase.assertTrue(Object.getPrototypeOf(people[0]) === schemas.PersonObject.prototype);
        TestCase.assertTrue(people[0] instanceof schemas.PersonObject);
    },

    testResultsReadonly: function() {
        var realm = new Realm({schema: [schemas.TestObject]});
        var objects = realm.objects('TestObject');

        realm.write(function() {
            realm.create('TestObject', {doubleCol: 1});
        });

        TestCase.assertThrows(function() {
            objects[-1] = {doubleCol: 0};
        });
        TestCase.assertThrows(function() {
            objects[0] = {doubleCol: 0};
        });
        TestCase.assertThrows(function() {
            objects[1] = {doubleCol: 0};
        });
        TestCase.assertThrows(function() {
            objects.length = 0;
        });
    },

    testResultsInvalidProperty: function() {
        var realm = new Realm({schema: [schemas.TestObject]});
        var objects = realm.objects('TestObject');
        TestCase.assertEqual(undefined, objects.ablasdf);
    },

    testResultsInvalidObjectType: function() {
        var realm = new Realm({schema: [schemas.TestObject]});
        TestCase.assertThrows(function() {
            var objects = realm.objects('NotTestObject');
        });
    },

    testResultsEnumerate: function() {
        var realm = new Realm({schema: [schemas.TestObject]});
        var objects = realm.objects('TestObject');

        for (var index in objects) {
            TestCase.assertTrue(false, "No objects should have been enumerated");
        }

        realm.write(function() {
            realm.create('TestObject', {doubleCol: 1});
            TestCase.assertEqual(objects.length, 1);
        });

        var count = 0;
        var keys = Object.keys(objects);
        for (var index in objects) {
            TestCase.assertEqual(count++, +index);
            TestCase.assertEqual(keys[index], index);
        }

        TestCase.assertEqual(count, 1);
        TestCase.assertEqual(keys.length, 1);
    },

    testResultsFiltered: function() {
        var realm = new Realm({schema: [schemas.PersonObject, schemas.DefaultValues, schemas.TestObject]});
        realm.write(function() {
            realm.create('PersonObject', {name: 'Ari', age: 10});
            realm.create('PersonObject', {name: 'Tim', age: 11});
            realm.create('PersonObject', {name: 'Bjarne', age: 12});
            realm.create('PersonObject', {name: 'Alex', age: 12, married: true});
        });

        TestCase.assertEqual(realm.objects('PersonObject').filtered("truepredicate").length, 4);
        TestCase.assertEqual(realm.objects('PersonObject').length, 4);
        TestCase.assertEqual(realm.objects('PersonObject').filtered('age = 11').length, 1);
        TestCase.assertEqual(realm.objects('PersonObject').filtered('age = 11')[0].name, 'Tim');
        TestCase.assertEqual(realm.objects('PersonObject').filtered('age = 12').length, 2);
        TestCase.assertEqual(realm.objects('PersonObject').filtered('age = 13').length, 0);
        TestCase.assertEqual(realm.objects('PersonObject').filtered('age < 12').length, 2);
        TestCase.assertEqual(realm.objects('PersonObject').filtered('age > 10 && age < 13').length, 3);
        TestCase.assertEqual(realm.objects('PersonObject').filtered('age > 10').filtered('age < 13').length, 3);

        TestCase.assertEqual(realm.objects('PersonObject').filtered('age >= 11 && age < 13').length, 3);
        TestCase.assertEqual(realm.objects('PersonObject').filtered('name = "Tim"').length, 1);
        TestCase.assertEqual(realm.objects('PersonObject').filtered('name = \'Tim\'').length, 1);
        TestCase.assertEqual(realm.objects('PersonObject').filtered('married == TRUE').length, 1);
        TestCase.assertEqual(realm.objects('PersonObject').filtered('married == false').length, 3);

        TestCase.assertEqual(realm.objects('PersonObject').filtered('name = $0', 'Tim').length, 1);
        TestCase.assertEqual(realm.objects('PersonObject').filtered('age > $1 && age < $0', 13, 10).length, 3);
        TestCase.assertThrows(function() {
            realm.objects('PersonObject').filtered('age > $2 && age < $0', 13, 10)
        });

        realm.write(function() {
            realm.create('DefaultValuesObject', {'dateCol': new Date(3)});
            realm.create('DefaultValuesObject', {'dateCol': new Date(4)});
            realm.create('DefaultValuesObject', {'dateCol': new Date(5)});
        });

        TestCase.assertEqual(realm.objects('DefaultValuesObject').filtered('dateCol > $0', new Date(4)).length, 1);
        TestCase.assertEqual(realm.objects('DefaultValuesObject').filtered('dateCol <= $0', new Date(4)).length, 2);

        TestCase.assertThrows(function() {
            realm.objects('PersonObject').filtered("invalidQuery");
        });
    },

    testResultsSorted: function() {
        var realm = new Realm({schema: [schemas.IntPrimary]});
        var objects = realm.objects('IntPrimaryObject');

        realm.write(function() {
            realm.create('IntPrimaryObject', {primaryCol: 2, valueCol: 'a'});
            realm.create('IntPrimaryObject', {primaryCol: 3, valueCol: 'a'});
            realm.create('IntPrimaryObject', {primaryCol: 1, valueCol: 'b'});
            realm.create('IntPrimaryObject', {primaryCol: 4, valueCol: 'c'});
            realm.create('IntPrimaryObject', {primaryCol: 0, valueCol: 'c'});
        });

        var primaries = function(results, prop) {
            return results.map(function(object) {
                return object.primaryCol;
            });
        };

        objects = objects.sorted('primaryCol');
        TestCase.assertArraysEqual(primaries(objects), [0, 1, 2, 3, 4]);

        objects = objects.sorted('primaryCol', true);
        TestCase.assertArraysEqual(primaries(objects), [4, 3, 2, 1, 0]);

        objects = objects.sorted(['primaryCol', 'valueCol']);
        TestCase.assertArraysEqual(primaries(objects), [0, 1, 2, 3, 4]);

        objects = objects.sorted([['primaryCol', true], ['valueCol', true]]);
        TestCase.assertArraysEqual(primaries(objects), [4, 3, 2, 1, 0]);

        objects = objects.sorted([['primaryCol', false], 'valueCol']);
        TestCase.assertArraysEqual(primaries(objects), [0, 1, 2, 3, 4]);

        objects = objects.sorted(['valueCol', 'primaryCol']);
        TestCase.assertArraysEqual(primaries(objects), [2, 3, 1, 0, 4]);

        objects = objects.sorted([['valueCol', false], ['primaryCol', true]]);
        TestCase.assertArraysEqual(primaries(objects), [3, 2, 1, 4, 0]);

        objects = objects.sorted([['valueCol', true], ['primaryCol', false]]);
        TestCase.assertArraysEqual(primaries(objects), [0, 4, 1, 2, 3]);

        objects = objects.sorted([['valueCol', true], ['primaryCol', true]]);
        TestCase.assertArraysEqual(primaries(objects), [4, 0, 1, 3, 2]);

        TestCase.assertThrows(function() {
            objects.sorted();
        });
        TestCase.assertThrows(function() {
            objects.sorted(1);
        });
        TestCase.assertThrows(function() {
            objects.sorted([1]);
        });
        TestCase.assertThrows(function() {
            objects.sorted([]);
        });
        TestCase.assertThrows(function() {
            objects.sorted('fish');
        });
        TestCase.assertThrows(function() {
            objects.sorted(['valueCol', 'fish']);
        });
        TestCase.assertThrows(function() {
            objects.sorted(['valueCol', 'primaryCol'], true);
        });
    },

    testResultsSortedAllTypes: function() {
        var realm = new Realm({schema: [schemas.BasicTypes]});
        var objects = realm.objects('BasicTypesObject');

        realm.write(function() {
            realm.create('BasicTypesObject', [false, 0, 0, 0, '0', new Date(0), new ArrayBuffer()]);
            realm.create('BasicTypesObject', [true, 2, 2, 2, '2', new Date(2), new ArrayBuffer()]);
            realm.create('BasicTypesObject', [false, 1, 1, 1, '1', new Date(1), new ArrayBuffer()]);
        });

        var numberProps = ['intCol', 'floatCol', 'doubleCol', 'stringCol'];
        for (var i = 0; i < numberProps.length; i++) {
            var prop = numberProps[i];

            objects = objects.sorted(prop, false);
            TestCase.assertEqual('' + objects[0][prop], '0', 'first element ascending for ' + prop);
            TestCase.assertEqual('' + objects[2][prop], '2', 'second element ascending for ' + prop);

            objects = objects.sorted(prop, true);
            TestCase.assertEqual('' + objects[0][prop], '2', 'first element descending for ' + prop);
            TestCase.assertEqual('' + objects[2][prop], '0', 'second element descending for ' + prop);
        }

        objects = objects.sorted('dateCol', false);
        TestCase.assertEqual(objects[0].dateCol.getTime(), 0);
        TestCase.assertEqual(objects[2].dateCol.getTime(), 2);

        objects = objects.sorted('dateCol', true);
        TestCase.assertEqual(objects[0].dateCol.getTime(), 2);
        TestCase.assertEqual(objects[2].dateCol.getTime(), 0);

        objects = objects.sorted('boolCol', false);
        TestCase.assertEqual(objects[0].boolCol, false, 'first element ascending for boolCol');
        TestCase.assertEqual(objects[0].boolCol, false, 'second element ascending for boolCol');
        TestCase.assertEqual(objects[2].boolCol, true, 'third element ascending for boolCol');

        objects = objects.sorted('boolCol', true);
        TestCase.assertEqual(objects[0].boolCol, true, 'first element descending for boolCol');
        TestCase.assertEqual(objects[1].boolCol, false, 'second element descending for boolCol');
        TestCase.assertEqual(objects[2].boolCol, false, 'third element descending for boolCol');
    },

    testResultsInvalidation: function() {
        var realm = new Realm({schema: [schemas.TestObject]});
        realm.write(function() {
            for (var i = 10; i > 0; i--) {
                realm.create('TestObject', [i]);
            }
        });

        var resultsVariants = [
            realm.objects('TestObject'),
            realm.objects('TestObject').filtered('doubleCol > 1'),
            realm.objects('TestObject').filtered('doubleCol > 1').sorted('doubleCol'),
            realm.objects('TestObject').filtered('doubleCol > 1').snapshot()
        ];

        // test isValid
        resultsVariants.forEach(function(objects) {
            TestCase.assertEqual(objects.isValid(), true);
        });

        // close and test invalidated accessors
        realm.close();
        realm = new Realm({
            schemaVersion: 1,
            schema: [schemas.TestObject, schemas.BasicTypes]
        });

        resultsVariants.forEach(function(objects) {
            TestCase.assertEqual(objects.isValid(), false);
            TestCase.assertThrows(function() { objects[0]; });
            TestCase.assertThrows(function() { objects.filtered('doubleCol < 42'); });
            TestCase.assertThrows(function() { objects.sorted('doubleCol', true); });
            TestCase.assertThrows(function() { objects.snapshot(); });
        });
    },

    testResultsDeletedObjects: function() {
        var realm = new Realm({schema: [schemas.TestObject]});

        var createTestObjects = function(n) {
            for (var i = 0; i < n; i++) {
                realm.create('TestObject', {doubleCol: i});
            }

            return realm.objects('TestObject');
        }

        realm.write(function() {
            var objects = createTestObjects(10);
            var snapshot = objects.snapshot();

            realm.deleteAll();
            TestCase.assertEqual(objects.length, 0);
            TestCase.assertEqual(snapshot.length, 10);
            TestCase.assertEqual(snapshot[0], null);
        });

        realm.write(function() {
            var objects = createTestObjects(10);
            var snapshot = objects.snapshot();

            realm.delete(snapshot);
            TestCase.assertEqual(objects.length, 0);
            TestCase.assertEqual(snapshot.length, 10);
            TestCase.assertEqual(snapshot[0], null);
        });
    }
});
<commit_msg>Add tests where deletion happens before snapshot()<commit_after>////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 Realm 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.
//
////////////////////////////////////////////////////////////////////////////

'use strict';

var Realm = require('realm');
var BaseTest = require('./base-test');
var TestCase = require('./asserts');
var schemas = require('./schemas');

module.exports = BaseTest.extend({
    testResultsConstructor: function() {
        var realm = new Realm({schema: [schemas.TestObject]});
        var objects = realm.objects('TestObject');

        TestCase.assertTrue(objects instanceof Realm.Results);
        TestCase.assertTrue(objects instanceof Realm.Collection);

        TestCase.assertThrows(function() {
            new Realm.Results();
        });

        TestCase.assertEqual(typeof Realm.Results, 'function');
        TestCase.assertTrue(Realm.Results instanceof Function);
    },

    testResultsLength: function() {
        var realm = new Realm({schema: [schemas.TestObject]});
        var objects = realm.objects('TestObject');
        TestCase.assertEqual(objects.length, 0);

        realm.write(function() {
            realm.create('TestObject', {doubleCol: 1});
            TestCase.assertEqual(objects.length, 1);
        });
        TestCase.assertEqual(objects.length, 1);
    },

    testResultsSubscript: function() {
        var realm = new Realm({schema: [schemas.PersonObject]});
        TestCase.assertEqual(realm.objects('PersonObject')[0], undefined);

        realm.write(function() {
            realm.create('PersonObject', {name: 'name1', age: 1});
            realm.create('PersonObject', {name: 'name2', age: 2});
        });

        var people = realm.objects('PersonObject');
        TestCase.assertEqual(people[0].age, 1);
        TestCase.assertEqual(people[1].age, 2);
        TestCase.assertEqual(people[2], undefined);
        TestCase.assertEqual(people[-1], undefined);
        TestCase.assertTrue(Object.getPrototypeOf(people[0]) === schemas.PersonObject.prototype);
        TestCase.assertTrue(people[0] instanceof schemas.PersonObject);
    },

    testResultsReadonly: function() {
        var realm = new Realm({schema: [schemas.TestObject]});
        var objects = realm.objects('TestObject');

        realm.write(function() {
            realm.create('TestObject', {doubleCol: 1});
        });

        TestCase.assertThrows(function() {
            objects[-1] = {doubleCol: 0};
        });
        TestCase.assertThrows(function() {
            objects[0] = {doubleCol: 0};
        });
        TestCase.assertThrows(function() {
            objects[1] = {doubleCol: 0};
        });
        TestCase.assertThrows(function() {
            objects.length = 0;
        });
    },

    testResultsInvalidProperty: function() {
        var realm = new Realm({schema: [schemas.TestObject]});
        var objects = realm.objects('TestObject');
        TestCase.assertEqual(undefined, objects.ablasdf);
    },

    testResultsInvalidObjectType: function() {
        var realm = new Realm({schema: [schemas.TestObject]});
        TestCase.assertThrows(function() {
            var objects = realm.objects('NotTestObject');
        });
    },

    testResultsEnumerate: function() {
        var realm = new Realm({schema: [schemas.TestObject]});
        var objects = realm.objects('TestObject');

        for (var index in objects) {
            TestCase.assertTrue(false, "No objects should have been enumerated");
        }

        realm.write(function() {
            realm.create('TestObject', {doubleCol: 1});
            TestCase.assertEqual(objects.length, 1);
        });

        var count = 0;
        var keys = Object.keys(objects);
        for (var index in objects) {
            TestCase.assertEqual(count++, +index);
            TestCase.assertEqual(keys[index], index);
        }

        TestCase.assertEqual(count, 1);
        TestCase.assertEqual(keys.length, 1);
    },

    testResultsFiltered: function() {
        var realm = new Realm({schema: [schemas.PersonObject, schemas.DefaultValues, schemas.TestObject]});
        realm.write(function() {
            realm.create('PersonObject', {name: 'Ari', age: 10});
            realm.create('PersonObject', {name: 'Tim', age: 11});
            realm.create('PersonObject', {name: 'Bjarne', age: 12});
            realm.create('PersonObject', {name: 'Alex', age: 12, married: true});
        });

        TestCase.assertEqual(realm.objects('PersonObject').filtered("truepredicate").length, 4);
        TestCase.assertEqual(realm.objects('PersonObject').length, 4);
        TestCase.assertEqual(realm.objects('PersonObject').filtered('age = 11').length, 1);
        TestCase.assertEqual(realm.objects('PersonObject').filtered('age = 11')[0].name, 'Tim');
        TestCase.assertEqual(realm.objects('PersonObject').filtered('age = 12').length, 2);
        TestCase.assertEqual(realm.objects('PersonObject').filtered('age = 13').length, 0);
        TestCase.assertEqual(realm.objects('PersonObject').filtered('age < 12').length, 2);
        TestCase.assertEqual(realm.objects('PersonObject').filtered('age > 10 && age < 13').length, 3);
        TestCase.assertEqual(realm.objects('PersonObject').filtered('age > 10').filtered('age < 13').length, 3);

        TestCase.assertEqual(realm.objects('PersonObject').filtered('age >= 11 && age < 13').length, 3);
        TestCase.assertEqual(realm.objects('PersonObject').filtered('name = "Tim"').length, 1);
        TestCase.assertEqual(realm.objects('PersonObject').filtered('name = \'Tim\'').length, 1);
        TestCase.assertEqual(realm.objects('PersonObject').filtered('married == TRUE').length, 1);
        TestCase.assertEqual(realm.objects('PersonObject').filtered('married == false').length, 3);

        TestCase.assertEqual(realm.objects('PersonObject').filtered('name = $0', 'Tim').length, 1);
        TestCase.assertEqual(realm.objects('PersonObject').filtered('age > $1 && age < $0', 13, 10).length, 3);
        TestCase.assertThrows(function() {
            realm.objects('PersonObject').filtered('age > $2 && age < $0', 13, 10)
        });

        realm.write(function() {
            realm.create('DefaultValuesObject', {'dateCol': new Date(3)});
            realm.create('DefaultValuesObject', {'dateCol': new Date(4)});
            realm.create('DefaultValuesObject', {'dateCol': new Date(5)});
        });

        TestCase.assertEqual(realm.objects('DefaultValuesObject').filtered('dateCol > $0', new Date(4)).length, 1);
        TestCase.assertEqual(realm.objects('DefaultValuesObject').filtered('dateCol <= $0', new Date(4)).length, 2);

        TestCase.assertThrows(function() {
            realm.objects('PersonObject').filtered("invalidQuery");
        });
    },

    testResultsSorted: function() {
        var realm = new Realm({schema: [schemas.IntPrimary]});
        var objects = realm.objects('IntPrimaryObject');

        realm.write(function() {
            realm.create('IntPrimaryObject', {primaryCol: 2, valueCol: 'a'});
            realm.create('IntPrimaryObject', {primaryCol: 3, valueCol: 'a'});
            realm.create('IntPrimaryObject', {primaryCol: 1, valueCol: 'b'});
            realm.create('IntPrimaryObject', {primaryCol: 4, valueCol: 'c'});
            realm.create('IntPrimaryObject', {primaryCol: 0, valueCol: 'c'});
        });

        var primaries = function(results, prop) {
            return results.map(function(object) {
                return object.primaryCol;
            });
        };

        objects = objects.sorted('primaryCol');
        TestCase.assertArraysEqual(primaries(objects), [0, 1, 2, 3, 4]);

        objects = objects.sorted('primaryCol', true);
        TestCase.assertArraysEqual(primaries(objects), [4, 3, 2, 1, 0]);

        objects = objects.sorted(['primaryCol', 'valueCol']);
        TestCase.assertArraysEqual(primaries(objects), [0, 1, 2, 3, 4]);

        objects = objects.sorted([['primaryCol', true], ['valueCol', true]]);
        TestCase.assertArraysEqual(primaries(objects), [4, 3, 2, 1, 0]);

        objects = objects.sorted([['primaryCol', false], 'valueCol']);
        TestCase.assertArraysEqual(primaries(objects), [0, 1, 2, 3, 4]);

        objects = objects.sorted(['valueCol', 'primaryCol']);
        TestCase.assertArraysEqual(primaries(objects), [2, 3, 1, 0, 4]);

        objects = objects.sorted([['valueCol', false], ['primaryCol', true]]);
        TestCase.assertArraysEqual(primaries(objects), [3, 2, 1, 4, 0]);

        objects = objects.sorted([['valueCol', true], ['primaryCol', false]]);
        TestCase.assertArraysEqual(primaries(objects), [0, 4, 1, 2, 3]);

        objects = objects.sorted([['valueCol', true], ['primaryCol', true]]);
        TestCase.assertArraysEqual(primaries(objects), [4, 0, 1, 3, 2]);

        TestCase.assertThrows(function() {
            objects.sorted();
        });
        TestCase.assertThrows(function() {
            objects.sorted(1);
        });
        TestCase.assertThrows(function() {
            objects.sorted([1]);
        });
        TestCase.assertThrows(function() {
            objects.sorted([]);
        });
        TestCase.assertThrows(function() {
            objects.sorted('fish');
        });
        TestCase.assertThrows(function() {
            objects.sorted(['valueCol', 'fish']);
        });
        TestCase.assertThrows(function() {
            objects.sorted(['valueCol', 'primaryCol'], true);
        });
    },

    testResultsSortedAllTypes: function() {
        var realm = new Realm({schema: [schemas.BasicTypes]});
        var objects = realm.objects('BasicTypesObject');

        realm.write(function() {
            realm.create('BasicTypesObject', [false, 0, 0, 0, '0', new Date(0), new ArrayBuffer()]);
            realm.create('BasicTypesObject', [true, 2, 2, 2, '2', new Date(2), new ArrayBuffer()]);
            realm.create('BasicTypesObject', [false, 1, 1, 1, '1', new Date(1), new ArrayBuffer()]);
        });

        var numberProps = ['intCol', 'floatCol', 'doubleCol', 'stringCol'];
        for (var i = 0; i < numberProps.length; i++) {
            var prop = numberProps[i];

            objects = objects.sorted(prop, false);
            TestCase.assertEqual('' + objects[0][prop], '0', 'first element ascending for ' + prop);
            TestCase.assertEqual('' + objects[2][prop], '2', 'second element ascending for ' + prop);

            objects = objects.sorted(prop, true);
            TestCase.assertEqual('' + objects[0][prop], '2', 'first element descending for ' + prop);
            TestCase.assertEqual('' + objects[2][prop], '0', 'second element descending for ' + prop);
        }

        objects = objects.sorted('dateCol', false);
        TestCase.assertEqual(objects[0].dateCol.getTime(), 0);
        TestCase.assertEqual(objects[2].dateCol.getTime(), 2);

        objects = objects.sorted('dateCol', true);
        TestCase.assertEqual(objects[0].dateCol.getTime(), 2);
        TestCase.assertEqual(objects[2].dateCol.getTime(), 0);

        objects = objects.sorted('boolCol', false);
        TestCase.assertEqual(objects[0].boolCol, false, 'first element ascending for boolCol');
        TestCase.assertEqual(objects[0].boolCol, false, 'second element ascending for boolCol');
        TestCase.assertEqual(objects[2].boolCol, true, 'third element ascending for boolCol');

        objects = objects.sorted('boolCol', true);
        TestCase.assertEqual(objects[0].boolCol, true, 'first element descending for boolCol');
        TestCase.assertEqual(objects[1].boolCol, false, 'second element descending for boolCol');
        TestCase.assertEqual(objects[2].boolCol, false, 'third element descending for boolCol');
    },

    testResultsInvalidation: function() {
        var realm = new Realm({schema: [schemas.TestObject]});
        realm.write(function() {
            for (var i = 10; i > 0; i--) {
                realm.create('TestObject', [i]);
            }
        });

        var resultsVariants = [
            realm.objects('TestObject'),
            realm.objects('TestObject').filtered('doubleCol > 1'),
            realm.objects('TestObject').filtered('doubleCol > 1').sorted('doubleCol'),
            realm.objects('TestObject').filtered('doubleCol > 1').snapshot()
        ];

        // test isValid
        resultsVariants.forEach(function(objects) {
            TestCase.assertEqual(objects.isValid(), true);
        });

        // close and test invalidated accessors
        realm.close();
        realm = new Realm({
            schemaVersion: 1,
            schema: [schemas.TestObject, schemas.BasicTypes]
        });

        resultsVariants.forEach(function(objects) {
            TestCase.assertEqual(objects.isValid(), false);
            TestCase.assertThrows(function() { objects[0]; });
            TestCase.assertThrows(function() { objects.filtered('doubleCol < 42'); });
            TestCase.assertThrows(function() { objects.sorted('doubleCol', true); });
            TestCase.assertThrows(function() { objects.snapshot(); });
        });
    },

    testResultsDeletedObjects: function() {
        var realm = new Realm({schema: [schemas.TestObject]});

        var createTestObjects = function(n) {
            for (var i = 0; i < n; i++) {
                realm.create('TestObject', {doubleCol: i});
            }

            return realm.objects('TestObject');
        }

        realm.write(function() {
            var objects = createTestObjects(10);
            var snapshot = objects.snapshot();

            realm.deleteAll();
            TestCase.assertEqual(objects.length, 0);
            TestCase.assertEqual(snapshot.length, 10);
            TestCase.assertEqual(snapshot[0], null);
        });

        realm.write(function() {
            var objects = createTestObjects(10);
            realm.deleteAll();

            var snapshot = objects.snapshot();
            TestCase.assertEqual(objects.length, 0);
            TestCase.assertEqual(snapshot.length, 0);
        });

        realm.write(function() {
            var objects = createTestObjects(10);
            var snapshot = objects.snapshot();

            realm.delete(snapshot);
            TestCase.assertEqual(objects.length, 0);
            TestCase.assertEqual(snapshot.length, 10);
            TestCase.assertEqual(snapshot[0], null);
        });

        realm.write(function() {
            var objects = createTestObjects(10);
            realm.delete(objects);

            var snapshot = objects.snapshot();
            TestCase.assertEqual(objects.length, 0);
            TestCase.assertEqual(snapshot.length, 0);
        });
    }
});
<|endoftext|>


<commit_before>'use strict';

describe('boolean attr directives', function() {
  var element;

  afterEach(function() {
    dealoc(element);
  });

  it('should properly evaluate 0 as false', inject(function($rootScope, $compile) {
    // jQuery does not treat 0 as false, when setting attr()
    element = $compile('<button ng-disabled="isDisabled">Button</button>')($rootScope)
    $rootScope.isDisabled = 0;
    $rootScope.$digest();
    expect(element.attr('disabled')).toBeFalsy();
    $rootScope.isDisabled = 1;
    $rootScope.$digest();
    expect(element.attr('disabled')).toBeTruthy();
  }));

  it('should bind disabled', inject(function($rootScope, $compile) {
    element = $compile('<button ng-disabled="isDisabled">Button</button>')($rootScope)
    $rootScope.isDisabled = false;
    $rootScope.$digest();
    expect(element.attr('disabled')).toBeFalsy();
    $rootScope.isDisabled = true;
    $rootScope.$digest();
    expect(element.attr('disabled')).toBeTruthy();
  }));

  it('should bind checked', inject(function($rootScope, $compile) {
    element = $compile('<input type="checkbox" ng-checked="isChecked" />')($rootScope)
    $rootScope.isChecked = false;
    $rootScope.$digest();
    expect(element.attr('checked')).toBeFalsy();
    $rootScope.isChecked=true;
    $rootScope.$digest();
    expect(element.attr('checked')).toBeTruthy();
  }));

  it('should bind selected', inject(function($rootScope, $compile) {
    element = $compile('<select><option value=""></option><option ng-selected="isSelected">Greetings!</option></select>')($rootScope)
    jqLite(document.body).append(element)
    $rootScope.isSelected=false;
    $rootScope.$digest();
    expect(element.children()[1].selected).toBeFalsy();
    $rootScope.isSelected=true;
    $rootScope.$digest();
    expect(element.children()[1].selected).toBeTruthy();
  }));

  it('should bind readonly', inject(function($rootScope, $compile) {
    element = $compile('<input type="text" ng-readonly="isReadonly" />')($rootScope)
    $rootScope.isReadonly=false;
    $rootScope.$digest();
    expect(element.attr('readOnly')).toBeFalsy();
    $rootScope.isReadonly=true;
    $rootScope.$digest();
    expect(element.attr('readOnly')).toBeTruthy();
  }));

  it('should bind multiple', inject(function($rootScope, $compile) {
    element = $compile('<select ng-multiple="isMultiple"></select>')($rootScope)
    $rootScope.isMultiple=false;
    $rootScope.$digest();
    expect(element.attr('multiple')).toBeFalsy();
    $rootScope.isMultiple='multiple';
    $rootScope.$digest();
    expect(element.attr('multiple')).toBeTruthy();
  }));

  it('should bind open', inject(function($rootScope, $compile) {
    element = $compile('')($rootScope)
    $rootScope.isOpen=false;
    $rootScope.$digest();
    expect(element.attr('open')).toBeFalsy();
    $rootScope.isOpen=true;
    $rootScope.$digest();
    expect(element.attr('open')).toBeTruthy();
  }));
});

describe('ngSrc', function() {
  it('should interpolate the expression and bind to src', inject(function($compile, $rootScope) {
    var element = $compile('

')($rootScope);

    $rootScope.$digest();
    expect(element.attr('src')).toBeUndefined();

    $rootScope.$apply(function() {
      $rootScope.id = 1;
    });
    expect(element.attr('src')).toEqual('1');

    dealoc(element);
  }));

  describe('isTrustedContext', function() {
    it('should NOT interpolate a multi-part expression for non-img src attribute', inject(function($compile, $rootScope) {
      expect(function() {
          var element = $compile('

')($rootScope);
          dealoc(element);
        }).toThrow(
            "[$interpolate:noconcat] Error while interpolating: some/{{id}}\nYou may not use " +
            "multiple expressions when interpolating this expression.");
    }));

    it('should interpolate a multi-part expression for regular attributes', inject(function($compile, $rootScope) {
      var element = $compile('

')($rootScope);
      $rootScope.$digest();
      expect(element.attr('foo')).toBe('some/');
      $rootScope.$apply(function() {
        $rootScope.id = 1;
      });
      expect(element.attr('foo')).toEqual('some/1');
    }));

  });

  if (msie) {
    it('should update the element property as well as the attribute', inject(
        function($compile, $rootScope) {
      // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
      // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
      // to set the property as well to achieve the desired effect

      var element = $compile('

')($rootScope);

      $rootScope.$digest();
      expect(element.prop('src')).toEqual('some/');

      $rootScope.$apply(function() {
        $rootScope.id = 1;
      });
      expect(element.prop('src')).toEqual('some/1');

      dealoc(element);
    }));
  }
});

describe('ngSrcset', function() {
  it('should interpolate the expression and bind to srcset', inject(function($compile, $rootScope) {
    var element = $compile('

')($rootScope);

    $rootScope.$digest();
    expect(element.attr('srcset')).toEqual('some/ 2x');

    $rootScope.$apply(function() {
      $rootScope.id = 1;
    });
    expect(element.attr('srcset')).toEqual('some/1 2x');

    dealoc(element);
  }));
});

describe('ngHref', function() {
  var element;

  afterEach(function() {
    dealoc(element);
  });

  it('should interpolate the expression and bind to href', inject(function($compile, $rootScope) {
    element = $compile('

')($rootScope)
    $rootScope.$digest();
    expect(element.attr('href')).toEqual('some/');

    $rootScope.$apply(function() {
      $rootScope.id = 1;
    });
    expect(element.attr('href')).toEqual('some/1');
  }));

  it('should bind href and merge with other attrs', inject(function($rootScope, $compile) {
    element = $compile('')($rootScope);
    $rootScope.url = 'http://server';
    $rootScope.rel = 'REL';
    $rootScope.$digest();
    expect(element.attr('href')).toEqual('http://server');
    expect(element.attr('rel')).toEqual('REL');
  }));

  it('should bind href even if no interpolation', inject(function($rootScope, $compile) {
    element = $compile('')($rootScope)
    $rootScope.$digest();
    expect(element.attr('href')).toEqual('http://server');
  }));
});
<commit_msg>test($compile): fix IE specific test.<commit_after>'use strict';

describe('boolean attr directives', function() {
  var element;

  afterEach(function() {
    dealoc(element);
  });

  it('should properly evaluate 0 as false', inject(function($rootScope, $compile) {
    // jQuery does not treat 0 as false, when setting attr()
    element = $compile('<button ng-disabled="isDisabled">Button</button>')($rootScope)
    $rootScope.isDisabled = 0;
    $rootScope.$digest();
    expect(element.attr('disabled')).toBeFalsy();
    $rootScope.isDisabled = 1;
    $rootScope.$digest();
    expect(element.attr('disabled')).toBeTruthy();
  }));

  it('should bind disabled', inject(function($rootScope, $compile) {
    element = $compile('<button ng-disabled="isDisabled">Button</button>')($rootScope)
    $rootScope.isDisabled = false;
    $rootScope.$digest();
    expect(element.attr('disabled')).toBeFalsy();
    $rootScope.isDisabled = true;
    $rootScope.$digest();
    expect(element.attr('disabled')).toBeTruthy();
  }));

  it('should bind checked', inject(function($rootScope, $compile) {
    element = $compile('<input type="checkbox" ng-checked="isChecked" />')($rootScope)
    $rootScope.isChecked = false;
    $rootScope.$digest();
    expect(element.attr('checked')).toBeFalsy();
    $rootScope.isChecked=true;
    $rootScope.$digest();
    expect(element.attr('checked')).toBeTruthy();
  }));

  it('should bind selected', inject(function($rootScope, $compile) {
    element = $compile('<select><option value=""></option><option ng-selected="isSelected">Greetings!</option></select>')($rootScope)
    jqLite(document.body).append(element)
    $rootScope.isSelected=false;
    $rootScope.$digest();
    expect(element.children()[1].selected).toBeFalsy();
    $rootScope.isSelected=true;
    $rootScope.$digest();
    expect(element.children()[1].selected).toBeTruthy();
  }));

  it('should bind readonly', inject(function($rootScope, $compile) {
    element = $compile('<input type="text" ng-readonly="isReadonly" />')($rootScope)
    $rootScope.isReadonly=false;
    $rootScope.$digest();
    expect(element.attr('readOnly')).toBeFalsy();
    $rootScope.isReadonly=true;
    $rootScope.$digest();
    expect(element.attr('readOnly')).toBeTruthy();
  }));

  it('should bind multiple', inject(function($rootScope, $compile) {
    element = $compile('<select ng-multiple="isMultiple"></select>')($rootScope)
    $rootScope.isMultiple=false;
    $rootScope.$digest();
    expect(element.attr('multiple')).toBeFalsy();
    $rootScope.isMultiple='multiple';
    $rootScope.$digest();
    expect(element.attr('multiple')).toBeTruthy();
  }));

  it('should bind open', inject(function($rootScope, $compile) {
    element = $compile('')($rootScope)
    $rootScope.isOpen=false;
    $rootScope.$digest();
    expect(element.attr('open')).toBeFalsy();
    $rootScope.isOpen=true;
    $rootScope.$digest();
    expect(element.attr('open')).toBeTruthy();
  }));
});

describe('ngSrc', function() {
  it('should interpolate the expression and bind to src', inject(function($compile, $rootScope) {
    var element = $compile('

')($rootScope);

    $rootScope.$digest();
    expect(element.attr('src')).toBeUndefined();

    $rootScope.$apply(function() {
      $rootScope.id = 1;
    });
    expect(element.attr('src')).toEqual('1');

    dealoc(element);
  }));

  describe('isTrustedContext', function() {
    it('should NOT interpolate a multi-part expression for non-img src attribute', inject(function($compile, $rootScope) {
      expect(function() {
          var element = $compile('

')($rootScope);
          dealoc(element);
        }).toThrow(
            "[$interpolate:noconcat] Error while interpolating: some/{{id}}\nYou may not use " +
            "multiple expressions when interpolating this expression.");
    }));

    it('should interpolate a multi-part expression for regular attributes', inject(function($compile, $rootScope) {
      var element = $compile('

')($rootScope);
      $rootScope.$digest();
      expect(element.attr('foo')).toBe('some/');
      $rootScope.$apply(function() {
        $rootScope.id = 1;
      });
      expect(element.attr('foo')).toEqual('some/1');
    }));

  });

  if (msie) {
    it('should update the element property as well as the attribute', inject(
        function($compile, $rootScope) {
      // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
      // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
      // to set the property as well to achieve the desired effect

      var element = $compile('

')($rootScope);

      $rootScope.$digest();
      expect(element.prop('src')).toBeUndefined();

      $rootScope.$apply(function() {
        $rootScope.id = 1;
      });
      expect(element.prop('src')).toEqual('1');

      dealoc(element);
    }));
  }
});

describe('ngSrcset', function() {
  it('should interpolate the expression and bind to srcset', inject(function($compile, $rootScope) {
    var element = $compile('

')($rootScope);

    $rootScope.$digest();
    expect(element.attr('srcset')).toEqual('some/ 2x');

    $rootScope.$apply(function() {
      $rootScope.id = 1;
    });
    expect(element.attr('srcset')).toEqual('some/1 2x');

    dealoc(element);
  }));
});

describe('ngHref', function() {
  var element;

  afterEach(function() {
    dealoc(element);
  });

  it('should interpolate the expression and bind to href', inject(function($compile, $rootScope) {
    element = $compile('

')($rootScope)
    $rootScope.$digest();
    expect(element.attr('href')).toEqual('some/');

    $rootScope.$apply(function() {
      $rootScope.id = 1;
    });
    expect(element.attr('href')).toEqual('some/1');
  }));

  it('should bind href and merge with other attrs', inject(function($rootScope, $compile) {
    element = $compile('')($rootScope);
    $rootScope.url = 'http://server';
    $rootScope.rel = 'REL';
    $rootScope.$digest();
    expect(element.attr('href')).toEqual('http://server');
    expect(element.attr('rel')).toEqual('REL');
  }));

  it('should bind href even if no interpolation', inject(function($rootScope, $compile) {
    element = $compile('')($rootScope)
    $rootScope.$digest();
    expect(element.attr('href')).toEqual('http://server');
  }));
});
<|endoftext|>


<commit_before>/**
 * This component has an authority in managing the steps needed
 * to paint an object on top of the canvas
 */
define(function(require){
  var fabric = require("fabric"),
      defineComponent = require("flight/lib/component"),
      withCanvasEvents = require("painters/withCanvasEvents"),
      withBrushPainter = require("painters/withBrushPainter"),
      withOutlinePainter = require("painters/withOutlinePainter"),
      withFreehandPainter = require("painters/withFreehandPainter"),
      withImagePainter = require("painters/withImagePainter");

  return defineComponent(Lukis, withCanvasEvents, withBrushPainter, withOutlinePainter, withFreehandPainter, withImagePainter);

  function Lukis(){

    this.defaultAttrs({
    /**
       * Canvas instance
       * @type {String}
       */
      canvas: "",
      /**
       * Canvas element
       * @type {String}
       */
      canvasEl: "",
      /**
       * Canvas configuration
       * @type {Object}
       */
      canvasCfg: {

      },

      /**
       * Custom event handlers for events related to this module
       * @type {Array}
       */
      customHandlers: {}
    });

    this.after("initialize", function(){
      this.constructCanvas();
      this.attachEventListeners();
    });

    this.constructCanvas = function(){
      this.attr.canvas = new fabric.Canvas(this.attr.canvasEl.replace(/(#|\.)/,''));

      this.trigger("canvasConstructed", {
        canvasEl: this.attr.canvasEl,
        canvas: this.attr.canvas
      });
    };

    this.attachEventListeners = function(){
      this.on("freehandPaintingReady", this.initFreehandPainting);
      this.on("outlineShapePaintingReady", this.initOutlineShapePainting);

      this.on("outlineShapePaintingFinished", function(e, data){
        if (this.attr.customHandlers.outlineShapePaintingFinished) {
          var handler = this.attr.customHandlers.outlineShapePaintingFinished;

          // custom handler lives once only
          delete this.attr.customHandlers["outlineShapePaintingFinished"];

          handler.call(this, this.attr.canvas, data);
        } else {
          this.initBrushPainting(data);
        }
      }.bind(this));
    };

    this.cancelCurrentPainting = function(){
      this.unregisterExistingListeners(this.attr.canvas);
      this.stopFreehandPainting();
    };

    this.initFreehandPainting = function(e, data){
      this.cancelCurrentPainting();
      this.startFreehandPainting(this.attr.canvas, this.attr.activeBrush.brush);
    };

    this.initOutlineShapePainting = function(e, data){
      this.cancelCurrentPainting();

      // if a customHandler is provided, than we need to call this handler
      // later
      if (data.customHandler){
        var key = Object.keys(data.customHandler)[0];
        this.attr.customHandlers[key] = data.customHandler[key];
      }

      this.prepareOutlineShapePainting(this.attr.canvas, {
        registerEventListeners: this.registerEventListeners,
        unregisterExistingListeners: this.unregisterExistingListeners
      }, data.outlineShape || null);
    };

    // TODO should this provide a way for customHandler to be registered
    this.initBrushPainting = function(data){
      this.prepareBrushPainting(this.attr.canvas, {
          registerEventListeners: this.registerEventListeners,
          unregisterEventListerns: this.unregisterEventListerns
        },
        data.outlineShape.getOutlinePoints(this.attr.activeBrush.brush.get('width'))
      );
    };

  }
});<commit_msg>common signature for event handler<commit_after>/**
 * I have the authority to manage the steps needed
 * to paint an object on top of the canvas
 */
define(function(require){
  var fabric = require("fabric"),
      defineComponent = require("flight/lib/component"),
      withCanvasEvents = require("painters/withCanvasEvents"),
      withBrushPainter = require("painters/withBrushPainter"),
      withOutlinePainter = require("painters/withOutlinePainter"),
      withFreehandPainter = require("painters/withFreehandPainter"),
      withImagePainter = require("painters/withImagePainter");

  return defineComponent(Lukis, withCanvasEvents, withBrushPainter, withOutlinePainter, withFreehandPainter, withImagePainter);

  function Lukis(){

    this.defaultAttrs({
    /**
       * Canvas instance
       * @type {String}
       */
      canvas: "",
      /**
       * Canvas element
       * @type {String}
       */
      canvasEl: "",
      /**
       * Canvas configuration
       * @type {Object}
       */
      canvasCfg: {

      },

      /**
       * Custom event handlers for events related to this module
       * @type {Array}
       */
      customHandlers: {}
    });

    this.after("initialize", function(){
      this.constructCanvas();
      this.attachEventListeners();
    });

    /**
     * Initialize the canvas instance. Once it's done, publish the canvas
     * element and instance on canvasConstructod event
     */
    this.constructCanvas = function(){
      this.attr.canvas = new fabric.Canvas(this.attr.canvasEl.replace(/(#|\.)/,''));

      this.trigger("canvasConstructed", {
        canvasEl: this.attr.canvasEl,
        canvas: this.attr.canvas
      });
    };

    this.attachEventListeners = function(){
      this.on("freehandPaintingReady", function(e, data){
        this.initFreehandPainting(data);
      }.bind(this));

      this.on("outlineShapePaintingReady", function(e, data){
        this.initOutlineShapePainting(data);
      }.bind(this));

      this.on("outlineShapePaintingFinished", function(e, data){
        // allowing a custom handler
        if (this.attr.customHandlers.outlineShapePaintingFinished) {
          var handler = this.attr.customHandlers.outlineShapePaintingFinished;

          // custom handler lives once only
          delete this.attr.customHandlers["outlineShapePaintingFinished"];

          handler.call(this, this.attr.canvas, data);
        } else {
          this.initBrushPainting(data);
        }
      }.bind(this));
    };

    /**
     * Cancel current painting
     */
    this.cancelCurrentPainting = function(){
      this.unregisterExistingListeners(this.attr.canvas);
      this.stopFreehandPainting();
    };

    this.initFreehandPainting = function(data){
      this.cancelCurrentPainting();
      this.startFreehandPainting(this.attr.canvas, this.attr.activeBrush.brush);
    };

    this.initOutlineShapePainting = function(data){
      this.cancelCurrentPainting();

      // if a customHandler is provided, than we need to call this handler
      // later
      if (data.customHandler){
        var key = Object.keys(data.customHandler)[0];
        this.attr.customHandlers[key] = data.customHandler[key];
      }

      this.prepareOutlineShapePainting(this.attr.canvas, {
        registerEventListeners: this.registerEventListeners,
        unregisterExistingListeners: this.unregisterExistingListeners
      }, data.outlineShape || null);
    };

    // TODO should this provide a way for customHandler to be registered
    this.initBrushPainting = function(data){
      this.prepareBrushPainting(this.attr.canvas, {
          registerEventListeners: this.registerEventListeners,
          unregisterEventListerns: this.unregisterEventListerns
        },
        data.outlineShape.getOutlinePoints(this.attr.activeBrush.brush.get('width'))
      );
    };

  }
});<|endoftext|>


<commit_before>'use strict';

var config = require('./server/config');
var express = require('express');
var handlebars = require('express-handlebars');
var app = express();

// Middlewares configuration
var oneWeek = 604800000;
app.use(express.static('build', { maxAge: oneWeek }));
app.use(express.static('data', { maxAge: oneWeek, extensions: ['png'] }));

// Handlebars configuration
app.set('views', 'client/views');
app.engine('.hbs', handlebars({ extname: '.hbs', partialsDir: ['client/views/components/', 'client/views/partials/'] }));
app.set('view engine', '.hbs');

// Starts application listening
app.listen(config.port, (err) => {
    console.log('running on ' + config.port);
});

// Regsiters routes
var indexRoutes = require('./server/routes/indexRoutes');
app.use('/', indexRoutes);<commit_msg>Remove cache  on build folder<commit_after>'use strict';

var config = require('./server/config');
var express = require('express');
var handlebars = require('express-handlebars');
var app = express();

// Middlewares configuration
var oneWeek = 604800000;
app.use(express.static('build'));
app.use(express.static('data', { maxAge: oneWeek, extensions: ['png'] }));

// Handlebars configuration
app.set('views', 'client/views');
app.engine('.hbs', handlebars({ extname: '.hbs', partialsDir: ['client/views/components/', 'client/views/partials/'] }));
app.set('view engine', '.hbs');

// Starts application listening
app.listen(config.port, (err) => {
    console.log('running on ' + config.port);
});

// Regsiters routes
var indexRoutes = require('./server/routes/indexRoutes');
app.use('/', indexRoutes);<|endoftext|>


<commit_before>/* -*- mode: javascript; c-basic-offset: 4; indent-tabs-mode: nil -*- */

//
// Dalliance Genome Explorer
// (c) Thomas Down 2006-2010
//
// version.js
//

var VERSION = {
    CONFIG: 4,
    MAJOR:  0,
    MINOR:  11,
    MICRO:  0,
    PATCH:  'pre1',
    BRANCH: ''
}

VERSION.toString = function() {
    var vs = '' + this.MAJOR + '.' + this.MINOR + '.' + this.MICRO;
    if (this.PATCH) {
        vs = vs + this.PATCH;
    }
    if (this.BRANCH && this.BRANCH != '') {
        vs = vs + '-' + this.BRANCH;
    }
    return vs;
}
<commit_msg>updated.<commit_after>/* -*- mode: javascript; c-basic-offset: 4; indent-tabs-mode: nil -*- */

//
// Dalliance Genome Explorer
// (c) Thomas Down 2006-2010
//
// version.js
//

var VERSION = {
    CONFIG: 4,
    MAJOR:  0,
    MINOR:  11,
    MICRO:  0,
    PATCH:  'pre2',
    BRANCH: ''
}

VERSION.toString = function() {
    var vs = '' + this.MAJOR + '.' + this.MINOR + '.' + this.MICRO;
    if (this.PATCH) {
        vs = vs + this.PATCH;
    }
    if (this.BRANCH && this.BRANCH != '') {
        vs = vs + '-' + this.BRANCH;
    }
    return vs;
}
<|endoftext|>


<commit_before>const deepcopy = require('deepcopy');
const Metric = require('./Metric');
const log = require('../support/log');

function prefix(namespace, codeId) {
  return `namespace:${namespace}, id:${codeId}`;
}

function codeFileName(namespace, codeId) {
  return `${namespace}/${codeId}.js`;
}

class Pipeline {
  constructor(sandbox, req, steps) {
    this.sandbox = sandbox;
    this.req = req;
    this.steps = steps;
    this.previousResult = null;
    this.totalMetric = new Metric('pipeline-run');
  }
  run() {
    return this.runStep();
  }
  runStep() {
    const [step, ...nextSteps] = this.steps;
    this.steps = nextSteps;

    const stepPrefix = prefix(step.namespace, step.id);
    const metric = new Metric('function-run');
    const filename = codeFileName(step.namespace, step.id);

    return this.sandbox.runScript(step.script, this.req, { prefix: stepPrefix })
      .then((result) => {
        const spent = metric.finish({
          filename,
          status: result.status,
        });
        log.info(`[${stepPrefix}] Step finished ${spent} ms`);

        const previousResult = this.previousResult;
        this.previousResult = result;

        if (result.status === 304) {
          if (previousResult) {
            result.status = previousResult.status;
            result.body = deepcopy(previousResult.body);
          }
        } else if (result.status === 200) {
          this.req.body = deepcopy(result.body);
        } else {
          result.body.namespace = step.namespace;
          result.body.functionId = step.id;

          return result;
        }

        if (this.steps.length === 0) {
          return result;
        }

        return this.runStep();
      }, (err) => {
        const status = err.statusCode || 500;

        const spent = metric.finish({
          filename,
          status,
          error: err.message,
        });
        log.error(`[${stepPrefix}] Failed to run function: ${err}, ${spent} ms`);
        log.error(`[${stepPrefix}] ${err.stack}`);
      });
  }
}

module.exports = Pipeline;
<commit_msg>throw err when pipeline fails<commit_after>const deepcopy = require('deepcopy');
const Metric = require('./Metric');
const log = require('../support/log');

function prefix(namespace, codeId) {
  return `namespace:${namespace}, id:${codeId}`;
}

function codeFileName(namespace, codeId) {
  return `${namespace}/${codeId}.js`;
}

class Pipeline {
  constructor(sandbox, req, steps) {
    this.sandbox = sandbox;
    this.req = req;
    this.steps = steps;
    this.previousResult = null;
    this.totalMetric = new Metric('pipeline-run');
  }
  run() {
    return this.runStep();
  }
  runStep() {
    const [step, ...nextSteps] = this.steps;
    this.steps = nextSteps;

    const stepPrefix = prefix(step.namespace, step.id);
    const metric = new Metric('function-run');
    const filename = codeFileName(step.namespace, step.id);

    return this.sandbox.runScript(step.script, this.req, { prefix: stepPrefix })
      .then((result) => {
        const spent = metric.finish({
          filename,
          status: result.status,
        });
        log.info(`[${stepPrefix}] Step finished ${spent} ms`);

        const previousResult = this.previousResult;
        this.previousResult = result;

        if (result.status === 304) {
          if (previousResult) {
            result.status = previousResult.status;
            result.body = deepcopy(previousResult.body);
          }
        } else if (result.status === 200) {
          this.req.body = deepcopy(result.body);
        } else {
          result.body.namespace = step.namespace;
          result.body.functionId = step.id;

          return result;
        }

        if (this.steps.length === 0) {
          return result;
        }

        return this.runStep();
      }, (err) => {
        const status = err.statusCode || 500;

        const spent = metric.finish({
          filename,
          status,
          error: err.message,
        });
        log.error(`[${stepPrefix}] Failed to run function: ${filename} ${err}, ${spent} ms`);
        log.error(`[${stepPrefix}] ${err.stack}`);
        throw err;
      });
  }
}

module.exports = Pipeline;
<|endoftext|>