<commit_before>// Get Canvas
var canvas = document.getElementById("canvas"),
  ctx = canvas.getContext("2d"),
  width = 512,
  height = 480;

canvas.width = width;
canvas.height = height;

// Background Image
var bgReady = false;
var bgImage = new Image();
bgImage.onload = function () {
  bgReady = true;
};
bgImage.src = "http://placekitten.com//512/480";
// Hero Image
var heroReady = false;
var heroImage = new Image();
heroImage.onload = function () {
  heroReady = true;
};
heroImage.src = "http://placekitten.com/32/32";

// Monster Image
var monsterReady = false;
var monsterImage = new Image();
monsterImage.onload = function () {
  monsterReady = true;
};
monsterImage.src = "http://placekitten.com/30/32";

// Game objects
var hero = {
  speed: 256,
  x: 0,
  y: 0
};

var monster = {
  x: 0,
  y: 0
};
var monstersCaught = 0;

// Handle keyboard controls
var keysDown = {};

addEventListener("keydown", function (e) {
  keysDown[e.keyCode] = true;
}, false);

addEventListener("keyup", function (e) {
  delete keysDown[e.keyCode];
}, false);

var reset = function () {
  hero.x = (canvas.width / 2) - 16;
  hero.y = (canvas.height / 2) - 16;

  monster.x = 32 + (Math.random() * (canvas.width - 64));
  monster.y = 32 + (Math.random() * (canvas.height - 64));
};

// Update game objects
var update = function (modifier) {
  if (38 in keysDown) {
    hero.y -= hero.speed * modifier;
  }
  if (40 in keysDown) {
    hero.y += hero.speed * modifier;
  }
  if (37 in keysDown) {
    hero.x -= hero.speed * modifier;
  }
  if (39 in keysDown) {
    hero.x += hero.speed * modifier;
  }

  // Stop from going off the page
  if (hero.x >= canvas.width - 32) {
    hero.x = canvas.width - 32;
  } else if (hero.x <= 0) {
    hero.x = 0;
  }

  if (hero.y >= canvas.height - 32) {
    hero.y = canvas.height - 32;
  } else if (hero.y <= 0) {
    hero.y = 0;
  }

  // Collision
  if (hero.x <= (monster.x + 32) && monster.x <= (hero.x + 32) && hero.y <= (monster.y + 32) && monster.y <= (hero.y + 32)) {
    ++monstersCaught;
    reset();
  }
};

// Render
var render = function () {
  if (bgReady) {
    ctx.drawImage(bgImage, 0, 0);
  }

  if (heroReady) {
    ctx.drawImage(heroImage, hero.x, hero.y);
  }

  if (monsterReady) {
    ctx.drawImage(monsterImage, monster.x, monster.y);
  }

  ctx.fillStyle = "rgb(250, 250, 250)";
  ctx.font = "24px Helvetica";
  ctx.textAlign = "left";
  ctx.textBaseline = "top";
  ctx.fillText("Monsters caught : " + monstersCaught + ". " + countDown, 32, 32);
  //ctx.fillText("Seconds Up : " + countDown, 32, 32);
};

var main = function () {
  var now = Date.now();
  var delta = now - then;

  var nowSwitch = Date.now();
  var countDown = nowSwitch - thenSwitch;

  update(delta / 1000);
  render();

  then = now;

  requestAnimationFrame(main);
};

var w = window;
requestAnimationFrame = w.requestAnimationFrame || w.webkitRequestAnimationFrame || w.msRequestAnimationFrame || w.mozRequestAnimationFrame;

var then = Date.now();
var thenSwitch = Date.now();
reset();
main();
<commit_msg>Update canvas2.js<commit_after>// Get Canvas
var canvas = document.getElementById("canvas"),
  ctx = canvas.getContext("2d"),
  width = 512,
  height = 480;

canvas.width = width;
canvas.height = height;

// Background Image
var bgReady = false;
var bgImage = new Image();
bgImage.onload = function () {
  bgReady = true;
};
bgImage.src = "http://placekitten.com//512/480";
// Hero Image
var heroReady = false;
var heroImage = new Image();
heroImage.onload = function () {
  heroReady = true;
};
heroImage.src = "http://placekitten.com/32/32";

// Monster Image
var monsterReady = false;
var monsterImage = new Image();
monsterImage.onload = function () {
  monsterReady = true;
};
monsterImage.src = "http://placekitten.com/30/32";

// Game objects
var hero = {
  speed: 256,
  x: 0,
  y: 0
};

var monster = {
  x: 0,
  y: 0
};
var monstersCaught = 0;

// Handle keyboard controls
var keysDown = {};

addEventListener("keydown", function (e) {
  keysDown[e.keyCode] = true;
}, false);

addEventListener("keyup", function (e) {
  delete keysDown[e.keyCode];
}, false);

var reset = function () {
  hero.x = (canvas.width / 2) - 16;
  hero.y = (canvas.height / 2) - 16;

  monster.x = 32 + (Math.random() * (canvas.width - 64));
  monster.y = 32 + (Math.random() * (canvas.height - 64));
};

// Update game objects
var update = function (modifier) {
  if (38 in keysDown) {
    hero.y -= hero.speed * modifier;
  }
  if (40 in keysDown) {
    hero.y += hero.speed * modifier;
  }
  if (37 in keysDown) {
    hero.x -= hero.speed * modifier;
  }
  if (39 in keysDown) {
    hero.x += hero.speed * modifier;
  }

  // Stop from going off the page
  if (hero.x >= canvas.width - 32) {
    hero.x = canvas.width - 32;
  } else if (hero.x <= 0) {
    hero.x = 0;
  }

  if (hero.y >= canvas.height - 32) {
    hero.y = canvas.height - 32;
  } else if (hero.y <= 0) {
    hero.y = 0;
  }

  // Collision
  if (hero.x <= (monster.x + 32) && monster.x <= (hero.x + 32) && hero.y <= (monster.y + 32) && monster.y <= (hero.y + 32)) {
    ++monstersCaught;
    reset();
  }
};

// Render
var render = function () {
  if (bgReady) {
    ctx.drawImage(bgImage, 0, 0);
  }

  if (heroReady) {
    ctx.drawImage(heroImage, hero.x, hero.y);
  }

  if (monsterReady) {
    ctx.drawImage(monsterImage, monster.x, monster.y);
  }

  ctx.fillStyle = "rgb(250, 250, 250)";
  ctx.font = "24px Helvetica";
  ctx.textAlign = "left";
  ctx.textBaseline = "top";
  ctx.fillText("Monsters caught : " + monstersCaught + ". " + countDown, 32, 32);
  //ctx.fillText("Seconds Up : " + countDown, 32, 32);
};

var main = function () {
  var now = Date.now();
  var delta = now - then;

  var nowSwitch = Date.now();
  countDown = nowSwitch - thenSwitch;

  update(delta / 1000);
  render();

  then = now;

  requestAnimationFrame(main);
};

var w = window;
requestAnimationFrame = w.requestAnimationFrame || w.webkitRequestAnimationFrame || w.msRequestAnimationFrame || w.mozRequestAnimationFrame;

var then = Date.now();
var thenSwitch = Date.now();
var countDown = 0;
reset();
main();
<|endoftext|>


<commit_before>EsriLeaflet.Layers.FeatureLayer = EsriLeaflet.Layers.FeatureManager.extend({

  statics: {
    EVENTS: 'click dblclick mouseover mouseout mousemove contextmenu popupopen popupclose'
  },

  /**
   * Constructor
   */

  initialize: function (url, options) {
    EsriLeaflet.Layers.FeatureManager.prototype.initialize.call(this, url, options);

    options = L.setOptions(this, options);

    this._layers = {};
    this._leafletIds = {};
    this._key = 'c'+(Math.random() * 1e9).toString(36).replace('.', '_');
  },

  /**
   * Layer Interface
   */

  onAdd: function(map){
    return EsriLeaflet.Layers.FeatureManager.prototype.onAdd.call(this, map);
  },

  onRemove: function(map){

    for (var i in this._layers) {
      map.removeLayer(this._layers[i]);
    }

    return EsriLeaflet.Layers.FeatureManager.prototype.onRemove.call(this, map);
  },

  createNewLayer: function(geojson){
    // @TODO Leaflet 0.8
    //newLayer = L.GeoJSON.geometryToLayer(geojson, this.options);
    return L.GeoJSON.geometryToLayer(geojson, this.options.pointToLayer, L.GeoJSON.coordsToLatLng, this.options);
  },

  /**
   * Feature Managment Methods
   */

  createLayers: function(features){
    for (var i = features.length - 1; i >= 0; i--) {

      var geojson = features[i];

      var layer = this._layers[geojson.id];
      var newLayer;

      if(layer && !this._map.hasLayer(layer)){
        this._map.addLayer(layer);
      }

      if (layer && layer.setLatLngs) {
        // @TODO Leaflet 0.8
        //newLayer = L.GeoJSON.geometryToLayer(geojson, this.options);

        var updateGeo = this.createNewLayer(geojson);
        layer.setLatLngs(updateGeo.getLatLngs());
      }

      if(!layer){
        // @TODO Leaflet 0.8
        //newLayer = L.GeoJSON.geometryToLayer(geojson, this.options);

        newLayer =  this.createNewLayer(geojson);
        newLayer.feature = geojson;
        newLayer.defaultOptions = newLayer.options;
        newLayer._leaflet_id = this._key + '_' + geojson.id;

        this._leafletIds[newLayer._leaflet_id] = geojson.id;

        // bubble events from layers to this
        // @TODO Leaflet 0.8
        // newLayer.addEventParent(this);

        newLayer.on(EsriLeaflet.Layers.FeatureLayer.EVENTS, this._propagateEvent, this);

        // bind a popup if we have one
        if(this._popup && newLayer.bindPopup){
          newLayer.bindPopup(this._popup(newLayer.feature, newLayer), this._popupOptions);
        }

        if(this.options.onEachFeature){
          this.options.onEachFeature(newLayer.feature, newLayer);
        }

        // cache the layer
        this._layers[newLayer.feature.id] = newLayer;

        // style the layer
        this.resetStyle(newLayer.feature.id);

        this.fire('createfeature', {
          feature: newLayer.feature
        });

        // add the layer if it is within the time bounds or our layer is not time enabled
        if(!this.options.timeField || (this.options.timeField && this._featureWithinTimeRange(geojson)) ){
          this._map.addLayer(newLayer);
        }
      }
    }
  },

  addLayers: function(ids){
    for (var i = ids.length - 1; i >= 0; i--) {
      var layer = this._layers[ids[i]];
      if(layer){
        this.fire('addfeature', {
          feature: layer.feature
        });
        this._map.addLayer(layer);
      }
    }
  },

  removeLayers: function(ids, permanent){
    for (var i = ids.length - 1; i >= 0; i--) {
      var id = ids[i];
      var layer = this._layers[id];
      if(layer){
        this.fire('removefeature', {
          feature: layer.feature,
          permanent: permanent
        });
        this._map.removeLayer(layer);
      }
      if(layer && permanent){
        delete this._layers[id];
      }
    }
  },

  /**
   * Styling Methods
   */

  resetStyle: function (id) {
    var layer = this._layers[id];

    if(layer){
      layer.options = layer.defaultOptions;
      this.setFeatureStyle(layer.feature.id, this.options.style);
    }

    return this;
  },

  setStyle: function (style) {
    this.options.style = style;
    this.eachFeature(function (layer) {
      this.setFeatureStyle(layer.feature.id, style);
    }, this);
    return this;
  },

  setFeatureStyle: function (id, style) {
    var layer = this._layers[id];

    if (typeof style === 'function') {
      style = style(layer.feature);
    }

    /*trap inability to access default style options from MultiLine/MultiPolygon
    please revisit at Leaflet 1.0*/
    else if (!style && !layer.defaultOptions) {
      var dummyPath = new L.Path();
      style = L.Path.prototype.options;
    }

    if (layer.setStyle) {
      layer.setStyle(style);
    }
  },

  /**
   * Popup Methods
   */

  bindPopup: function (fn, options) {
    this._popup = fn;
    this._popupOptions = options;
    for (var i in this._layers) {
      var layer = this._layers[i];
      var popupContent = this._popup(layer.feature, layer);
      layer.bindPopup(popupContent, options);
    }
    return this;
  },

  unbindPopup: function () {
    this._popup =  false;
    for (var i in this._layers) {
      var layer = this._layers[i];
      if (layer.unbindPopup) {
        layer.unbindPopup();
      } else if (layer.getLayers) {
        var groupLayers = layer.getLayers();
        for (var j in groupLayers) {
          var gLayer = groupLayers[j];
          gLayer.unbindPopup();
        }
      }
    }
    return this;
  },

  /**
   * Utility Methods
   */

  eachFeature: function (fn, context) {
    for (var i in this._layers) {
      fn.call(context, this._layers[i]);
    }
    return this;
  },

  getFeature: function (id) {
    return this._layers[id];
  },

  // from https://github.com/Leaflet/Leaflet/blob/v0.7.2/src/layer/FeatureGroup.js
  // @TODO remove at Leaflet 0.8
  _propagateEvent: function (e) {
    e.layer = this._layers[this._leafletIds[e.target._leaflet_id]];
    e.target = this;
    this.fire(e.type, e);
  }
});

EsriLeaflet.FeatureLayer = EsriLeaflet.Layers.FeatureLayer;

EsriLeaflet.Layers.featureLayer = function(url, options){
  return new EsriLeaflet.Layers.FeatureLayer(url, options);
};

EsriLeaflet.featureLayer = function(url, options){
  return new EsriLeaflet.Layers.FeatureLayer(url, options);
};
<commit_msg>actually request geojson<commit_after>EsriLeaflet.Layers.FeatureLayer = EsriLeaflet.Layers.FeatureManager.extend({

  statics: {
    EVENTS: 'click dblclick mouseover mouseout mousemove contextmenu popupopen popupclose'
  },

  /**
   * Constructor
   */

  initialize: function (url, options) {
    EsriLeaflet.Layers.FeatureManager.prototype.initialize.call(this, url, options);

    options = L.setOptions(this, options);

    this._layers = {};
    this._leafletIds = {};
    this._key = 'c'+(Math.random() * 1e9).toString(36).replace('.', '_');
  },

  /**
   * Layer Interface
   */

  onAdd: function(map){
    return EsriLeaflet.Layers.FeatureManager.prototype.onAdd.call(this, map);
  },

  onRemove: function(map){

    for (var i in this._layers) {
      map.removeLayer(this._layers[i]);
    }

    return EsriLeaflet.Layers.FeatureManager.prototype.onRemove.call(this, map);
  },

  createNewLayer: function(geojson){
    // @TODO Leaflet 0.8
    //newLayer = L.GeoJSON.geometryToLayer(geojson, this.options);
    return L.GeoJSON.geometryToLayer(geojson, this.options.pointToLayer, L.GeoJSON.coordsToLatLng, this.options);
  },

  /**
   * Feature Managment Methods
   */

  createLayers: function(features){
    for (var i = features.length - 1; i >= 0; i--) {

      var geojson = features[i];
      var layer = this._layers[geojson.id];
      var newLayer;

      if(layer && !this._map.hasLayer(layer)){
        this._map.addLayer(layer);
      }

      if (layer && layer.setLatLngs) {
        // @TODO Leaflet 0.8
        //newLayer = L.GeoJSON.geometryToLayer(geojson, this.options);

        var updateGeo = this.createNewLayer(geojson);
        layer.setLatLngs(updateGeo.getLatLngs());
      }

      if(!layer){
        // @TODO Leaflet 0.8
        //newLayer = L.GeoJSON.geometryToLayer(geojson, this.options);

        newLayer =  this.createNewLayer(geojson);
        newLayer.feature = geojson;
        newLayer.defaultOptions = newLayer.options;
        newLayer._leaflet_id = this._key + '_' + geojson.id;

        this._leafletIds[newLayer._leaflet_id] = geojson.id;

        // bubble events from layers to this
        // @TODO Leaflet 0.8
        // newLayer.addEventParent(this);

        newLayer.on(EsriLeaflet.Layers.FeatureLayer.EVENTS, this._propagateEvent, this);

        // bind a popup if we have one
        if(this._popup && newLayer.bindPopup){
          newLayer.bindPopup(this._popup(newLayer.feature, newLayer), this._popupOptions);
        }

        if(this.options.onEachFeature){
          this.options.onEachFeature(newLayer.feature, newLayer);
        }

        // cache the layer
        this._layers[newLayer.feature.id] = newLayer;

        // style the layer
        this.resetStyle(newLayer.feature.id);

        this.fire('createfeature', {
          feature: newLayer.feature
        });

        // add the layer if it is within the time bounds or our layer is not time enabled
        if(!this.options.timeField || (this.options.timeField && this._featureWithinTimeRange(geojson)) ){
          this._map.addLayer(newLayer);
        }
      }
    }
  },

  addLayers: function(ids){
    for (var i = ids.length - 1; i >= 0; i--) {
      var layer = this._layers[ids[i]];
      if(layer){
        this.fire('addfeature', {
          feature: layer.feature
        });
        this._map.addLayer(layer);
      }
    }
  },

  removeLayers: function(ids, permanent){
    for (var i = ids.length - 1; i >= 0; i--) {
      var id = ids[i];
      var layer = this._layers[id];
      if(layer){
        this.fire('removefeature', {
          feature: layer.feature,
          permanent: permanent
        });
        this._map.removeLayer(layer);
      }
      if(layer && permanent){
        delete this._layers[id];
      }
    }
  },

  /**
   * Styling Methods
   */

  resetStyle: function (id) {
    var layer = this._layers[id];

    if(layer){
      layer.options = layer.defaultOptions;
      this.setFeatureStyle(layer.feature.id, this.options.style);
    }

    return this;
  },

  setStyle: function (style) {
    this.options.style = style;
    this.eachFeature(function (layer) {
      this.setFeatureStyle(layer.feature.id, style);
    }, this);
    return this;
  },

  setFeatureStyle: function (id, style) {
    var layer = this._layers[id];

    if (typeof style === 'function') {
      style = style(layer.feature);
    }

    /*trap inability to access default style options from MultiLine/MultiPolygon
    please revisit at Leaflet 1.0*/
    else if (!style && !layer.defaultOptions) {
      var dummyPath = new L.Path();
      style = L.Path.prototype.options;
    }

    if (layer.setStyle) {
      layer.setStyle(style);
    }
  },

  /**
   * Popup Methods
   */

  bindPopup: function (fn, options) {
    this._popup = fn;
    this._popupOptions = options;
    for (var i in this._layers) {
      var layer = this._layers[i];
      var popupContent = this._popup(layer.feature, layer);
      layer.bindPopup(popupContent, options);
    }
    return this;
  },

  unbindPopup: function () {
    this._popup =  false;
    for (var i in this._layers) {
      var layer = this._layers[i];
      if (layer.unbindPopup) {
        layer.unbindPopup();
      } else if (layer.getLayers) {
        var groupLayers = layer.getLayers();
        for (var j in groupLayers) {
          var gLayer = groupLayers[j];
          gLayer.unbindPopup();
        }
      }
    }
    return this;
  },

  /**
   * Utility Methods
   */

  eachFeature: function (fn, context) {
    for (var i in this._layers) {
      fn.call(context, this._layers[i]);
    }
    return this;
  },

  getFeature: function (id) {
    return this._layers[id];
  },

  // from https://github.com/Leaflet/Leaflet/blob/v0.7.2/src/layer/FeatureGroup.js
  // @TODO remove at Leaflet 0.8
  _propagateEvent: function (e) {
    e.layer = this._layers[this._leafletIds[e.target._leaflet_id]];
    e.target = this;
    this.fire(e.type, e);
  }
});

EsriLeaflet.FeatureLayer = EsriLeaflet.Layers.FeatureLayer;

EsriLeaflet.Layers.featureLayer = function(url, options){
  return new EsriLeaflet.Layers.FeatureLayer(url, options);
};

EsriLeaflet.featureLayer = function(url, options){
  return new EsriLeaflet.Layers.FeatureLayer(url, options);
};
<|endoftext|>


<commit_before>function validateForm() {
    soortTafel = document.forms["myForm"]["fname"].value;
    soortTafelNummer = parseInt(soortTafel);
    switch (soortTafelNummer){
      case 1:
        tafelOefenen = 1;
        document.write("11n");
        break;
      case 2:
        tafelOefenen = 2;
        break;
      case 3:
        tafelOefenen = 3;
        break;
      default:
      document.write("WOLO");
    }
}
<commit_msg>fixed the breaks<commit_after>function validateForm() {
    soortTafel = document.forms["myForm"]["fname"].value;
    soortTafelNummer = parseInt(soortTafel);
    switch (soortTafelNummer){
      case 1:
        tafelOefenen = 1;
        document.write("11n");
        break;
      case 2:
        tafelOefenen = 2;
        break;
      case 3:
        tafelOefenen = 3;
        break;
      case 4:
        tafelOefenen = 4;
        break;
      case 5:
        tafelOefenen = 5;
        break;
      case 6:
        tafelOefenen = 6;
        break;
      case 7:
        tafelOefenen = 7;
        break;
      case 8:
        tafelOefenen = 8;
        break;
      case 9:
        tafelOefenen = 9;
        break;
      case 10:
        tafelOefenen = 10;
        break;
      case 11:
        tafelOefenen = 11;
        break;
      case 12:
        tafelOefenen = 12;
        break;
      case 13:
        tafelOefenen = 13;
        break;
      default:
      document.write("WOLO");
    }
}
<|endoftext|>


<commit_before>import { cssToDom, nProps, isArray } from './util'
import { diff } from './vdom/diff'
import options from './options'
import { proxyUpdate } from './observe'

export default class WeElement extends HTMLElement {
  static is = 'WeElement'

  constructor() {
    super()
    this.props = Object.assign(
      nProps(this.constructor.props),
      this.constructor.defaultProps
    )
    this.data = this.constructor.data || {}
  }

  connectedCallback() {
    if (!this.constructor.pure) {
      let p = this.parentNode
      while (p && !this.store) {
        this.store = p.store
        p = p.parentNode || p.host
      }
      if (this.store) {
        this.store.instances.push(this)
      }
    }

    this.install()
    let shadowRoot
    if (!this.shadowRoot) {
      shadowRoot = this.attachShadow({
        mode: 'open'
      })
    } else {
      shadowRoot = this.shadowRoot
      let fc
      while ((fc = shadowRoot.firstChild)) {
        shadowRoot.removeChild(fc)
      }
    }

    this.css && shadowRoot.appendChild(cssToDom(this.css()))
    this.beforeRender()
    options.afterInstall && options.afterInstall(this)
    if (this.constructor.observe) {
      proxyUpdate(this)
    }
    this.host = diff(
      null,
      this.render(
        this.props,
        !this.constructor.pure && this.store ? this.store.data : this.data
      ),
      {},
      false,
      null,
      false
    )
    if (isArray(this.host)) {
      this.host.forEach(function(item) {
        shadowRoot.appendChild(item)
      })
    } else {
      shadowRoot.appendChild(this.host)
    }
    this.installed()
    this._isInstalled = true
  }

  disconnectedCallback() {
    this.uninstall()
    if (this.store) {
      for (let i = 0, len = this.store.instances.length; i < len; i++) {
        if (this.store.instances[i] === this) {
          this.store.instances.splice(i, 1)
          break
        }
      }
    }
  }

  update() {
    this.beforeUpdate()
    this.beforeRender()
    diff(
      this.host,
      this.render(
        this.props,
        !this.constructor.pure && this.store ? this.store.data : this.data
      )
    )
    this.afterUpdate()
  }

  fire(name, data) {
    this.dispatchEvent(new CustomEvent(name, { detail: data }))
  }

  install() {}

  installed() {}

  uninstall() {}

  beforeUpdate() {}

  afterUpdate() {}

  beforeRender() {}
}
<commit_msg>fix bug<commit_after>import { cssToDom, nProps, isArray } from './util'
import { diff } from './vdom/diff'
import options from './options'
import { proxyUpdate } from './observe'

export default class WeElement extends HTMLElement {
  static is = 'WeElement'

  constructor() {
    super()
    this.props = Object.assign(
      nProps(this.constructor.props),
      this.constructor.defaultProps
    )
    this.data = this.constructor.data || {}
  }

  connectedCallback() {
    if (!this.constructor.pure) {
      let p = this.parentNode
      while (p && !this.store) {
        this.store = p.store
        p = p.parentNode || p.host
      }
      if (this.store) {
        this.store.instances.push(this)
      }
    }

    !this._isInstalled && this.install()
    let shadowRoot
    if (!this.shadowRoot) {
      shadowRoot = this.attachShadow({
        mode: 'open'
      })
    } else {
      shadowRoot = this.shadowRoot
      let fc
      while ((fc = shadowRoot.firstChild)) {
        shadowRoot.removeChild(fc)
      }
    }

    this.css && shadowRoot.appendChild(cssToDom(this.css()))
    !this._isInstalled && this.beforeRender()
    options.afterInstall && options.afterInstall(this)
    if (this.constructor.observe) {
      proxyUpdate(this)
    }
    this.host = diff(
      null,
      this.render(
        this.props,
        !this.constructor.pure && this.store ? this.store.data : this.data
      ),
      {},
      false,
      null,
      false
    )
    if (isArray(this.host)) {
      this.host.forEach(function(item) {
        shadowRoot.appendChild(item)
      })
    } else {
      shadowRoot.appendChild(this.host)
    }
    !this._isInstalled && this.installed()
    this._isInstalled = true
  }

  disconnectedCallback() {
    this.uninstall()
    if (this.store) {
      for (let i = 0, len = this.store.instances.length; i < len; i++) {
        if (this.store.instances[i] === this) {
          this.store.instances.splice(i, 1)
          break
        }
      }
    }
  }

  update() {
    this.beforeUpdate()
    this.beforeRender()
    diff(
      this.host,
      this.render(
        this.props,
        !this.constructor.pure && this.store ? this.store.data : this.data
      )
    )
    this.afterUpdate()
  }

  fire(name, data) {
    this.dispatchEvent(new CustomEvent(name, { detail: data }))
  }

  install() {}

  installed() {}

  uninstall() {}

  beforeUpdate() {}

  afterUpdate() {}

  beforeRender() {}
}
<|endoftext|>


<commit_before>/**
 * @file TransferList component
 * @author sunday(sunday.wei@derbysoft.com)
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import _ from 'lodash';
import classNames from 'classnames';

import TextField from '../TextField';
import Checkbox from '../Checkbox';

class TransferList extends Component {

    constructor(props, ...restArgs) {

        super(props, ...restArgs);

        this.state = {
            filter: ''
        };

        this.select = ::this.select;
        this.selectAllHandle = ::this.selectAllHandle;
        this.filterChangeHandle = ::this.filterChangeHandle;
        this.getItemValue = ::this.getItemValue;

    }

    select(item) {
        if (!item.disabled) {
            let data = _.cloneDeep(this.props.value);
            let selectAll = this.state.selectAll;
            let flag = false;
            for (let i = 0; i < data.length; i++) {
                if (data[i].id === item.id) {
                    flag = true;
                    break;
                }
            }
            if (flag) {
                let index = data.findIndex(function (value, index, arr) {
                    return value.id == item.id;
                });
                data.splice(index, 1);
                selectAll = false;
            } else {
                data.push(item);
                if (data.length == this.props.data.length) {
                    selectAll = true;
                }
            }
            this.setState({
                selectAll
            }, () => {
                this.props.onChange && this.props.onChange(data);
            });
        }
    }

    selectAllHandle() {
        const {selectAll, filter} = this.state;
        const {data} = this.props;
        const filterList = this.getFilterList(data, filter);
        let newData = [];
        for (let i = 0; i < filterList.length; i++) {
            if (!filterList[i]['disabled']) {
                newData.push(filterList[i]);
            }
        }
        let value = selectAll ? [] : newData;
        this.setState({
            selectAll: !selectAll
        }, () => {
            this.props.onChange && this.props.onChange(value);
        });
    }

    filterChangeHandle(value) {
        this.setState({
            filter: value,
            selectAll: false
        }, () => {
            this.props.onChange && this.props.onChange([]);
        });
    }

    getItemValue(id) {
        let data = this.props.value;
        let flag = false;
        for (let i = 0; i < data.length; i++) {
            if (data[i].id === id) {
                flag = true;
                break;
            } else {
                flag = false;
            }
        }
        return flag;
    }

    getFilterList(list, filter) {
        return list.filter((value) => {
            if (typeof value == 'object') {
                return value.text.toUpperCase().indexOf(filter.toUpperCase()) != -1;
            } else {
                return value.toUpperCase().indexOf(filter.toUpperCase()) != -1;
            }
        });
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.data.length !== this.props.data.length) {
            this.setState({
                selectAll: false
            });
        }
    }

    render() {

        const {className, listStyle, data, value} = this.props,
            {filter, selectAll} = this.state,
            {filterChangeHandle, getItemValue, getFilterList, select, selectAllHandle} = this,

            listClassName = classNames('transfer-list', {
                [className]: className
            }),

            filterList = getFilterList(data, filter),

            headerLabel = value && value.length > 0 ?
                value.length + '/' + filterList.length + ' items'
                :
                filterList.length + ' items';

        this.filterList = filterList;

        return (

                    <Checkbox label={headerLabel}
                              checked={selectAll}
                              onChange={selectAllHandle}/>

                <TextField className="search"
                           rightIconCls={'fas fa-search'}
                           onChange={filterChangeHandle}
                           placeholder={'Search here'}
                           value={filter}/>

                    {

                        this.filterList.map(item => (
                            <div key={item.text}
                                 className={`option ${item.disabled ? 'disabled' : ''}`}>
                                <Checkbox label={item.text}
                                          checked={getItemValue(item.id)}
                                          disabled={item.disabled ? item.disabled : false}
                                          onChange={() => {
                                              select(item);
                                          }}/>

                        ))
                    }

        );
    }

};

TransferList.propTypes = {

    /**
     * The CSS class name of the root element.
     */
    className: PropTypes.string,

    /**
     * Override the styles of the root element.
     */
    listStyle: PropTypes.object,

    /**
     *
     */
    data: PropTypes.array,

    /**
     *
     */
    value: PropTypes.array

};

TransferList.defaultProps = {
    className: '',
    style: null
};

export default TransferList;<commit_msg>update TransferList<commit_after>/**
 * @file TransferList component
 * @author sunday(sunday.wei@derbysoft.com)
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import cloneDeep from 'lodash/cloneDeep';
import classNames from 'classnames';

import TextField from '../TextField';
import Checkbox from '../Checkbox';

class TransferList extends Component {

    constructor(props, ...restArgs) {

        super(props, ...restArgs);

        this.state = {
            filter: ''
        };

        this.select = ::this.select;
        this.selectAllHandle = ::this.selectAllHandle;
        this.filterChangeHandle = ::this.filterChangeHandle;
        this.getItemValue = ::this.getItemValue;

    }

    select(item) {
        if (!item.disabled) {
            let data = cloneDeep(this.props.value);
            let selectAll = this.state.selectAll;
            let flag = false;
            for (let i = 0; i < data.length; i++) {
                if (data[i].id === item.id) {
                    flag = true;
                    break;
                }
            }
            if (flag) {
                let index = data.findIndex(function (value, index, arr) {
                    return value.id == item.id;
                });
                data.splice(index, 1);
                selectAll = false;
            } else {
                data.push(item);
                if (data.length == this.props.data.length) {
                    selectAll = true;
                }
            }
            this.setState({
                selectAll
            }, () => {
                this.props.onChange && this.props.onChange(data);
            });
        }
    }

    selectAllHandle() {
        const {selectAll, filter} = this.state;
        const {data} = this.props;
        const filterList = this.getFilterList(data, filter);
        let newData = [];
        for (let i = 0; i < filterList.length; i++) {
            if (!filterList[i]['disabled']) {
                newData.push(filterList[i]);
            }
        }
        let value = selectAll ? [] : newData;
        this.setState({
            selectAll: !selectAll
        }, () => {
            this.props.onChange && this.props.onChange(value);
        });
    }

    filterChangeHandle(value) {
        this.setState({
            filter: value,
            selectAll: false
        }, () => {
            this.props.onChange && this.props.onChange([]);
        });
    }

    getItemValue(id) {
        let data = this.props.value;
        let flag = false;
        for (let i = 0; i < data.length; i++) {
            if (data[i].id === id) {
                flag = true;
                break;
            } else {
                flag = false;
            }
        }
        return flag;
    }

    getFilterList(list, filter) {
        return list.filter((value) => {
            if (typeof value == 'object') {
                return value.text.toUpperCase().indexOf(filter.toUpperCase()) != -1;
            } else {
                return value.toUpperCase().indexOf(filter.toUpperCase()) != -1;
            }
        });
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.data.length !== this.props.data.length) {
            this.setState({
                selectAll: false
            });
        }
    }

    render() {

        const {className, listStyle, data, value} = this.props,
            {filter, selectAll} = this.state,
            {filterChangeHandle, getItemValue, getFilterList, select, selectAllHandle} = this,

            listClassName = classNames('transfer-list', {
                [className]: className
            }),

            filterList = getFilterList(data, filter),

            headerLabel = value && value.length > 0 ?
                value.length + '/' + filterList.length + ' items'
                :
                filterList.length + ' items';

        this.filterList = filterList;

        return (

                    <Checkbox label={headerLabel}
                              checked={selectAll}
                              onChange={selectAllHandle}/>

                <TextField className="search"
                           rightIconCls={'fas fa-search'}
                           onChange={filterChangeHandle}
                           placeholder={'Search here'}
                           value={filter}/>

                    {

                        this.filterList.map(item => (
                            <div key={item.text}
                                 className={`option ${item.disabled ? 'disabled' : ''}`}>
                                <Checkbox label={item.text}
                                          checked={getItemValue(item.id)}
                                          disabled={item.disabled ? item.disabled : false}
                                          onChange={() => {
                                              select(item);
                                          }}/>

                        ))
                    }

        );
    }

};

TransferList.propTypes = {

    /**
     * The CSS class name of the root element.
     */
    className: PropTypes.string,

    /**
     * Override the styles of the root element.
     */
    listStyle: PropTypes.object,

    /**
     *
     */
    data: PropTypes.array,

    /**
     *
     */
    value: PropTypes.array

};

TransferList.defaultProps = {
    className: '',
    style: null
};

export default TransferList;<|endoftext|>


<commit_before>GotandaDiamondMine.TILE_IMAGE_8x8 = new Image();
GotandaDiamondMine.TILE_IMAGE_8x8.src = "img/8x8.png";
GotandaDiamondMine.TILE_IMAGE_8x8_COLS = 16;
GotandaDiamondMine.prototype.initialCanvas = function (element) {
  this.canvasElement = document.createElement('canvas');
  element.appendChild(this.canvasElement);
  this.resizeCanvas();

  GotandaDiamondMine.ins = this;
  var gdm = this;
  this.canvasElement.addEventListener('touchstart', function (e) {
    e.preventDefault();
    var rect = e.target.getBoundingClientRect();
    var point = gdm.getPointFromHTML(e.changedTouches[0].clientX - rect.left, e.changedTouches[0].clientY - rect.top);
    if (gdm.point(point[0], point[1])) {
      if (gdm.state == GotandaDiamondMine.STATE_ANIMATION && !gdm.animationInterval) {
        gdm.startAnimation();
      }
      gdm.draw();
    }
    gdm.touchNow = point;
  });

  this.canvasElement.addEventListener('touchmove', function (e) {
    e.preventDefault();
    var rect = e.target.getBoundingClientRect();
    var point = gdm.getPointFromHTML(e.changedTouches[0].clientX - rect.left, e.changedTouches[0].clientY - rect.top);
    if (gdm.touchNow[0] !== point[0] && gdm.touchNow[1] !== point[1] && gdm.point(point[0], point[1])) {
      if (gdm.state == GotandaDiamondMine.STATE_ANIMATION && !gdm.animationInterval) {
        gdm.startAnimation();
      }
      gdm.draw();
    }
    gdm.touchNow = point;
  });

  this.canvasElement.addEventListener('mousedown', function (e) {
    e.preventDefault();
    var rect = e.target.getBoundingClientRect();
    var point = gdm.getPointFromHTML(e.clientX - rect.left, e.clientY - rect.top);
    if (gdm.point(point[0], point[1])) {
      if (gdm.state == GotandaDiamondMine.STATE_ANIMATION && !gdm.animationInterval) {
        gdm.startAnimation();
      }
      gdm.draw();
    }
  });

  window.addEventListener('resize', function() {
    if (gdm.resizeTimer) {
      clearTimeout(gdm.resizeTimer);
    }
    gdm.resizeTimer = setTimeout(function () {
      gdm.resizeCanvas();
    }, 100);
  });

};

GotandaDiamondMine.prototype.resizeCanvas = function () {
  if (this.maxWidth  && this.maxWidth  == window.innerWidth &&
      this.maxHeight && this.maxHeight == window.innerHeight) {
    return; // nothing to do
  }

  this.fontX = 8; this.fontY = 8;
  this.canvasElement.setAttribute('width',  this.fontX * 27);
  this.canvasElement.setAttribute('height', this.fontY * 48);
  this.canvasElement.parentElement.style.width  = (this.fontX * 27) + 'px';
  this.canvasElement.parentElement.style.height = (this.fontY * 48) + 'px';
  this.canvasElement.style.width  = (this.fontX * 27) + 'px';
  this.canvasElement.style.height = (this.fontY * 48) + 'px';
  this.canvasContext = this.canvasElement.getContext("2d");
  this.canvasContext.fillStyle = this.fillStyle = 'white';

  var viewport = document.querySelector("meta[name=viewport]");
  var new_width = Math.round(this.fontY * 48 * window.innerWidth / window.innerHeight);
  viewport.setAttribute('content', 'width=' + (new_width - new_width % 10 + 10));
  this.maxWidth  = window.innerWidth;
  this.maxHeight = window.innerHeight;

  // initial drawing
  this.draw(true);
};

GotandaDiamondMine.prototype.pointHTML = function (x, y) {
  var mx = parseInt(x / this.fontX), my = parseInt(y / this.fontY);
  return this.point(mx, my);
};

GotandaDiamondMine.prototype.getPointFromHTML = function (x, y) {
  var mx = parseInt(x / this.fontX), my = parseInt(y / this.fontY);
  return [ mx, my ];
};

GotandaDiamondMine.COLOR_REGEXP = /^\{([^-]+)-fg\}(.*)\{\/\1-fg\}$/;
GotandaDiamondMine.prototype.draw = function (initial) {
  var screen = this.getScreen();
  var context = this.canvasContext;
  var old_screen = initial ? null : this.oldScreen;
  var dw = this.fontX, dh = this.fontY;
  for (var y = 0; y < 48; ++y) {
    for (var x = 0; x < 27; ++x) {
      var str = screen[y][x];
      if (old_screen && str == old_screen[y][x]) {
        continue;
      }

      var colors = GotandaDiamondMine.COLOR_REGEXP.exec(str);
      if (colors) {
        if (this.fillStyle != colors[1]) {
          context.fillStyle = this.fillStyle = colors[1];
        }
        str = colors[2];
      } else {
        if (this.fillStyle != 'white') {
          context.fillStyle = this.fillStyle = 'white';
        }
      }
      var char_code = str.charCodeAt(0);
      var dx = dw * x, dy = dh * y;
      var sx = char_code % GotandaDiamondMine.TILE_IMAGE_8x8_COLS;
      var sy = Math.floor(char_code / GotandaDiamondMine.TILE_IMAGE_8x8_COLS);
      context.fillRect(dx, dy, dw, dh);
      context.drawImage(GotandaDiamondMine.TILE_IMAGE_8x8, sx * dw, sy * dh, dw, dh, dx, dy, dw, dh);
    }
  }
  // for debug
  //context.fillStyle = 'red';
  //context.fillText(this.maxWidth + "," + this.maxHeight + ',' + window.devicePixelRatio, 30, 350);
  //context.fillStyle = 'white';
  this.oldScreen = screen.map(function (row) { return row.concat(); });
};

GotandaDiamondMine.prototype.startAnimation = function () {
  var gdm = this;
  this.animationInterval = setInterval(function () {
    gdm.point(0, 0);
    gdm.draw();
    if (gdm.state != GotandaDiamondMine.STATE_ANIMATION) {
      clearInterval(gdm.animationInterval);
      gdm.animationInterval = null;
    }
  }, 20);
};
<commit_msg>Fixed wrong judge<commit_after>GotandaDiamondMine.TILE_IMAGE_8x8 = new Image();
GotandaDiamondMine.TILE_IMAGE_8x8.src = "img/8x8.png";
GotandaDiamondMine.TILE_IMAGE_8x8_COLS = 16;
GotandaDiamondMine.prototype.initialCanvas = function (element) {
  this.canvasElement = document.createElement('canvas');
  element.appendChild(this.canvasElement);
  this.resizeCanvas();

  GotandaDiamondMine.ins = this;
  var gdm = this;
  this.canvasElement.addEventListener('touchstart', function (e) {
    e.preventDefault();
    var rect = e.target.getBoundingClientRect();
    var point = gdm.getPointFromHTML(e.changedTouches[0].clientX - rect.left, e.changedTouches[0].clientY - rect.top);
    if (gdm.point(point[0], point[1])) {
      if (gdm.state == GotandaDiamondMine.STATE_ANIMATION && !gdm.animationInterval) {
        gdm.startAnimation();
      }
      gdm.draw();
    }
    gdm.touchNow = point;
  });

  this.canvasElement.addEventListener('touchmove', function (e) {
    e.preventDefault();
    var rect = e.target.getBoundingClientRect();
    var point = gdm.getPointFromHTML(e.changedTouches[0].clientX - rect.left, e.changedTouches[0].clientY - rect.top);
    if (gdm.touchNow[0] === point[0] && gdm.touchNow[1] === point[1]) {
      // nothing

    } else if (gdm.point(point[0], point[1])) {
      if (gdm.state == GotandaDiamondMine.STATE_ANIMATION && !gdm.animationInterval) {
        gdm.startAnimation();
      }
      gdm.draw();
    }
    gdm.touchNow = point;
  });

  this.canvasElement.addEventListener('mousedown', function (e) {
    e.preventDefault();
    var rect = e.target.getBoundingClientRect();
    var point = gdm.getPointFromHTML(e.clientX - rect.left, e.clientY - rect.top);
    if (gdm.point(point[0], point[1])) {
      if (gdm.state == GotandaDiamondMine.STATE_ANIMATION && !gdm.animationInterval) {
        gdm.startAnimation();
      }
      gdm.draw();
    }
  });

  window.addEventListener('resize', function() {
    if (gdm.resizeTimer) {
      clearTimeout(gdm.resizeTimer);
    }
    gdm.resizeTimer = setTimeout(function () {
      gdm.resizeCanvas();
    }, 100);
  });

};

GotandaDiamondMine.prototype.resizeCanvas = function () {
  if (this.maxWidth  && this.maxWidth  == window.innerWidth &&
      this.maxHeight && this.maxHeight == window.innerHeight) {
    return; // nothing to do
  }

  this.fontX = 8; this.fontY = 8;
  this.canvasElement.setAttribute('width',  this.fontX * 27);
  this.canvasElement.setAttribute('height', this.fontY * 48);
  this.canvasElement.parentElement.style.width  = (this.fontX * 27) + 'px';
  this.canvasElement.parentElement.style.height = (this.fontY * 48) + 'px';
  this.canvasElement.style.width  = (this.fontX * 27) + 'px';
  this.canvasElement.style.height = (this.fontY * 48) + 'px';
  this.canvasContext = this.canvasElement.getContext("2d");
  this.canvasContext.fillStyle = this.fillStyle = 'white';

  var viewport = document.querySelector("meta[name=viewport]");
  var new_width = Math.round(this.fontY * 48 * window.innerWidth / window.innerHeight);
  viewport.setAttribute('content', 'width=' + (new_width - new_width % 10 + 10));
  this.maxWidth  = window.innerWidth;
  this.maxHeight = window.innerHeight;

  // initial drawing
  this.draw(true);
};

GotandaDiamondMine.prototype.pointHTML = function (x, y) {
  var mx = parseInt(x / this.fontX), my = parseInt(y / this.fontY);
  return this.point(mx, my);
};

GotandaDiamondMine.prototype.getPointFromHTML = function (x, y) {
  var mx = parseInt(x / this.fontX), my = parseInt(y / this.fontY);
  return [ mx, my ];
};

GotandaDiamondMine.COLOR_REGEXP = /^\{([^-]+)-fg\}(.*)\{\/\1-fg\}$/;
GotandaDiamondMine.prototype.draw = function (initial) {
  var screen = this.getScreen();
  var context = this.canvasContext;
  var old_screen = initial ? null : this.oldScreen;
  var dw = this.fontX, dh = this.fontY;
  for (var y = 0; y < 48; ++y) {
    for (var x = 0; x < 27; ++x) {
      var str = screen[y][x];
      if (old_screen && str == old_screen[y][x]) {
        continue;
      }

      var colors = GotandaDiamondMine.COLOR_REGEXP.exec(str);
      if (colors) {
        if (this.fillStyle != colors[1]) {
          context.fillStyle = this.fillStyle = colors[1];
        }
        str = colors[2];
      } else {
        if (this.fillStyle != 'white') {
          context.fillStyle = this.fillStyle = 'white';
        }
      }
      var char_code = str.charCodeAt(0);
      var dx = dw * x, dy = dh * y;
      var sx = char_code % GotandaDiamondMine.TILE_IMAGE_8x8_COLS;
      var sy = Math.floor(char_code / GotandaDiamondMine.TILE_IMAGE_8x8_COLS);
      context.fillRect(dx, dy, dw, dh);
      context.drawImage(GotandaDiamondMine.TILE_IMAGE_8x8, sx * dw, sy * dh, dw, dh, dx, dy, dw, dh);
    }
  }
  // for debug
  //context.fillStyle = 'red';
  //context.fillText(this.maxWidth + "," + this.maxHeight + ',' + window.devicePixelRatio, 30, 350);
  //context.fillStyle = 'white';
  this.oldScreen = screen.map(function (row) { return row.concat(); });
};

GotandaDiamondMine.prototype.startAnimation = function () {
  var gdm = this;
  this.animationInterval = setInterval(function () {
    gdm.point(0, 0);
    gdm.draw();
    if (gdm.state != GotandaDiamondMine.STATE_ANIMATION) {
      clearInterval(gdm.animationInterval);
      gdm.animationInterval = null;
    }
  }, 20);
};
<|endoftext|>


<commit_before>function planeType = (displayName, healthPoints, maxSpeed, weight, gunTurrets, rpm, functionality, range, bombDamage, gunDamage, bombPayload, ammoAmount){

this.displayName = displayname;
this.healthPoints = healthPoints;
this.maxSpeed = maxSpeed;
this.weight = weight;
this.gunTurrets = gunTurrets;
this.rpm = rpm;
this.functionality = functionality;
this.range = range;
this.bombDamage = bombDamage;
this.gunDamage = gunDamage;
this.bombPayload = bombPayload;
this.ammoAmount = ammoAmount;

}
<commit_msg>Partially done...<commit_after>function planeType = (displayName, healthPoints, maxSpeed, weight, gunTurrets, rpm, functionality, range, bombDamage, gunDamage, bombPayload, ammoAmount){

this.displayName = displayname;
this.healthPoints = healthPoints;
this.maxSpeed = maxSpeed;                  //Required to be in Feet Per Second
this.weight = weight;                      //Required to be in Pounds (American)
this.gunTurrets = gunTurrets;              //Number of Turrets not Guns
this.rpm = rpm;
this.functionality = functionality;
this.range = range;
this.bombDamage = bombDamage;
this.gunDamage = gunDamage;
this.bombPayload = bombPayload;
this.ammoAmount = ammoAmount;

}

//var b17 = new planeType("B-17", 1234, 421, 33279, 8, )
<|endoftext|>


<commit_before>const chai = require('chai');
const chaiAsPromised = require('chai-as-promised');
const { ObjectId } = require('mongoose').Types;
const appPromise = require('../../../app');
const testObjects = require('../../../../test/services/helpers/testObjects')(appPromise);
const { problemRepo } = require('.');
const { GeneralError, ValidationError } = require('../../../errors');

chai.use(chaiAsPromised);
const { expect } = chai;

describe('problem repo', () => {
	let app;
	let server;

	before(async () => {
		app = await appPromise;
		server = await app.listen(0);
	});

	afterEach(async () => {
		await testObjects.cleanup();
	});

	after(async () => {
		await server.close();
	});

	describe('deleteProblems', () => {
		it('when problem is deleted, it should return deleted problem ids', async () => {
			const user = await testObjects.createTestUser();
			await testObjects.createTestProblem(user);
			const result = await problemRepo.deleteProblemsForUser(user._id);
			expect(result.success).to.be.equal(true);
			expect(result.deletedDocuments).to.be.equal(1);
		});

		it('when problem is deleted, it should be gone from db', async () => {
			const user = await testObjects.createTestUser();
			await testObjects.createTestProblem(user);
			await problemRepo.deleteProblemsForUser(user._id);

			const result = await problemRepo.getProblemsForUser(user._id);

			expect(result.length).to.be.equal(0);
		});

		it('when the function is called with invalid id, it throws an error', async () => {
			const notExistedId = new ObjectId();
			expect(problemRepo.deleteProblemsForUser(notExistedId)).to.eventually.throw(GeneralError);
		});
	});

	describe('getProblemsForUser', () => {
		it('when the function is called with user id, it should return list of problems ', async () => {
			const user = await testObjects.createTestUser();
			const testProblem = await testObjects.createTestProblem(user);
			const problems = await problemRepo.getProblemsForUser(user._id);
			expect(problems[0]._id).to.deep.equal(testProblem._id);
			expect(problems[0].userId).to.deep.equal(user._id);
		});

		it('when the function is called with user id, for which problems dont exist, then it should return empty array', async () => {
			const user = await testObjects.createTestUser();
			const problems = await problemRepo.getProblemsForUser(user._id);
			expect(problems.length).to.be.equal(0);
		});

		it('when the function is called with invalid user id, it should return an error', async () => {
			expect(problemRepo.getProblemsForUser('INVALID_USER_ID')).to.eventually.throw(ValidationError);
		});
	});
});
<commit_msg>SC-7835: review fixes<commit_after>const chai = require('chai');
const chaiAsPromised = require('chai-as-promised');
const { ObjectId } = require('mongoose').Types;
const appPromise = require('../../../app');
const testObjects = require('../../../../test/services/helpers/testObjects')(appPromise);
const { problemRepo } = require('.');
const { GeneralError, ValidationError } = require('../../../errors');

chai.use(chaiAsPromised);
const { expect } = chai;

describe('problem repo', () => {
	let app;
	let server;

	before(async () => {
		app = await appPromise;
		server = await app.listen(0);
	});

	afterEach(async () => {
		await testObjects.cleanup();
	});

	after(async () => {
		await server.close();
	});

	describe('deleteProblems', () => {
		it('when problem is deleted, it should return deleted problem ids', async () => {
			const user = await testObjects.createTestUser();
			await testObjects.createTestProblem(user);
			const result = await problemRepo.deleteProblemsForUser(user._id);
			expect(result.success).to.be.equal(true);
			expect(result.deletedDocuments).to.be.equal(1);
		});

		it('when problem is deleted, it should be gone from db', async () => {
			const user = await testObjects.createTestUser();
			await testObjects.createTestProblem(user);
			const userId = user._id;

			let userProblems = await problemRepo.getProblemsForUser(userId);
			expect(userProblems.length).to.be.equal(1);
			await problemRepo.deleteProblemsForUser(userId);

			userProblems = await problemRepo.getProblemsForUser(userId);
			expect(userProblems.length).to.be.equal(0);
		});

		it('when the function is called with invalid id, it throws an error', async () => {
			const notExistedId = new ObjectId();
			expect(problemRepo.deleteProblemsForUser(notExistedId)).to.eventually.throw(GeneralError);
		});
	});

	describe('getProblemsForUser', () => {
		it('when the function is called with user id, it should return list of problems ', async () => {
			const user = await testObjects.createTestUser();
			const testProblem = await testObjects.createTestProblem(user);
			const problems = await problemRepo.getProblemsForUser(user._id);
			expect(problems[0]._id).to.deep.equal(testProblem._id);
			expect(problems[0].userId).to.deep.equal(user._id);
		});

		it('when the function is called with user id, for which problems dont exist, then it should return empty array', async () => {
			const user = await testObjects.createTestUser();
			const problems = await problemRepo.getProblemsForUser(user._id);
			expect(problems.length).to.be.equal(0);
		});

		it('when the function is called with invalid user id, it should return an error', async () => {
			expect(problemRepo.getProblemsForUser('INVALID_USER_ID')).to.eventually.throw(ValidationError);
		});
	});
});
<|endoftext|>


<commit_before>import React from 'react';
import {NavLink, navigateAction} from 'fluxible-router';
import classNames from 'classnames/bind';
import {connectToStores} from 'fluxible-addons-react';
import ContentUtil from '../util/ContentUtil';
import DeckTreeStore from '../../../../stores/DeckTreeStore';
import UserProfileStore from '../../../../stores/UserProfileStore';
import addTreeNodeAndNavigate from '../../../../actions/decktree/addTreeNodeAndNavigate';
import deleteTreeNodeAndNavigate from '../../../../actions/decktree/deleteTreeNodeAndNavigate';
import AttachSubdeck from '../AttachSubdeck/AttachSubdeckModal';
import AttachSlides from '../AttachSubdeck/AttachSlidesModal';
import PermissionsStore from '../../../../stores/PermissionsStore';
import ContentStore from '../../../../stores/ContentStore';
import showNoPermissionsModal from '../../../../actions/permissions/showNoPermissionsModal';

class ContentActionsHeader extends React.Component {

    componentDidUpdate(){

    }
    handleAddNode(selector, nodeSpec) {
        //selector: Object {id: "56", stype: "deck", sid: 67, spath: "67:2"}
        //nodeSec: Object {type: "slide", id: "0"}
        this.context.executeAction(addTreeNodeAndNavigate, {selector: selector, nodeSpec: nodeSpec});
    }

    handleDeleteNode(selector) {
        this.context.executeAction(deleteTreeNodeAndNavigate, selector);
    }

    handleEditNode(selector) {
        const nodeURL = ContentUtil.makeNodeURL(selector, 'edit');
        if (this.props.PermissionsStore.permissions.readOnly || !this.props.PermissionsStore.permissions.edit) {
            this.context.executeAction(showNoPermissionsModal, {selector: selector, user: this.props.UserProfileStore.userid, permissions: this.props.PermissionsStore.permissions});
        } else {
            this.context.executeAction(navigateAction, {
                url: nodeURL
            });
        }
    }
    render() {
        const contentDetails = this.props.ContentStore;
        //config buttons based on the selected item
        const addSlideClass = classNames({
            'item ui small basic left attached button': true,
            'disabled': this.props.PermissionsStore.permissions.readOnly || !this.props.PermissionsStore.permissions.edit || contentDetails.mode ==='edit'
        });
        const addDeckClass = classNames({
            'item ui small basic left attached button': true,
            'disabled': this.props.PermissionsStore.permissions.readOnly || !this.props.PermissionsStore.permissions.edit || contentDetails.mode ==='edit'
        });
        const duplicateItemClass = classNames({
            'item ui small basic left attached button': true,
            'disabled': contentDetails.selector.id === contentDetails.selector.sid || contentDetails.selector.stype==='deck' || this.props.PermissionsStore.permissions.readOnly || !this.props.PermissionsStore.permissions.edit || contentDetails.mode ==='edit'
        });
        const deleteItemClass = classNames({
            'item ui small basic left attached button': true,
            'disabled': contentDetails.selector.id === contentDetails.selector.sid || this.props.PermissionsStore.permissions.readOnly || !this.props.PermissionsStore.permissions.edit || contentDetails.mode ==='edit'
        });
        let selectorImm = this.props.DeckTreeStore.selector;
        let selector = {id: selectorImm.get('id'), stype: selectorImm.get('stype'), sid: selectorImm.get('sid'), spath: selectorImm.get('spath')};

        let buttonStyle = {
            classNames : classNames({
                'item small attached left':true,
                'disabled': this.props.PermissionsStore.permissions.readOnly || !this.props.PermissionsStore.permissions.edit || contentDetails.mode ==='edit'
            }),
            iconSize : 'large',
            attached : 'left',
            noTabIndex : this.props.PermissionsStore.permissions.readOnly || !this.props.PermissionsStore.permissions.edit || contentDetails.mode ==='edit'
        } ;

        return (

                <NavLink activeClass=" " className={'item link' + (contentDetails.mode === 'view' ? ' active' : '')} href={ContentUtil.makeNodeURL(selector, 'view')} role={'tab'}>
                    View
                </NavLink>
                {this.props.UserProfileStore.username === '' ? '' :

                         Edit

                }
                {this.props.UserProfileStore.username === '' ? '' :

                    <button className={duplicateItemClass} onClick={this.handleAddNode.bind(this, selector, {type: selector.stype, id: selector.sid})}
                           type="button"
                           aria-label="Duplicate"
                           data-tooltip="Duplicate"
                           tabIndex={contentDetails.selector.id === contentDetails.selector.sid || contentDetails.selector.stype==='deck' || this.props.PermissionsStore.permissions.readOnly || !this.props.PermissionsStore.permissions.edit || contentDetails.mode ==='edit'?-1:0}>

                          </button>
                <button className={deleteItemClass} onClick={this.handleDeleteNode.bind(this, selector)}
                            type="button"
                            aria-label="Delete"
                            data-tooltip="Delete"
                            tabIndex={this.props.PermissionsStore.permissions.readOnly || !this.props.PermissionsStore.permissions.edit || contentDetails.mode ==='edit'?-1:0}>

                          </button>

                        <button className={addSlideClass} onClick={this.handleAddNode.bind(this, selector, {type: 'slide', id: '0'}) }
                          type="button"
                          aria-label="Add Slide"
                          data-tooltip="Add Slide"
                          tabIndex={this.props.PermissionsStore.permissions.readOnly || !this.props.PermissionsStore.permissions.edit || contentDetails.mode ==='edit'?-1:0}>

                        </button>
                        <AttachSlides buttonStyle={buttonStyle} selector={selector} />
                          <button className={addDeckClass} onClick={this.handleAddNode.bind(this, selector, {type: 'deck', id: '0'})}
                           type="button"
                           aria-label="Add Deck"
                           data-tooltip="Add Deck"
                           tabIndex={this.props.PermissionsStore.permissions.readOnly || !this.props.PermissionsStore.permissions.edit || contentDetails.mode ==='edit'?-1:0}>

                          </button>
                          <AttachSubdeck buttonStyle={buttonStyle} selector={selector} />

                          {/*
                          <button className="item ui small basic right attached disabled button">

                          </button>
                          */}

                  }

        );
    }
  }
ContentActionsHeader.contextTypes = {
    executeAction: React.PropTypes.func.isRequired
};
//it should listen to decktree store in order to handle adding slides/decks
ContentActionsHeader = connectToStores(ContentActionsHeader, [DeckTreeStore, UserProfileStore, PermissionsStore, ContentStore], (context, props) => {
    return {
        DeckTreeStore: context.getStore(DeckTreeStore).getState(),
        UserProfileStore: context.getStore(UserProfileStore).getState(),
        PermissionsStore: context.getStore(PermissionsStore).getState(),
        ContentStore: context.getStore(ContentStore).getState()
    };
});
export default ContentActionsHeader;
<commit_msg>Fix eslint<commit_after>import React from 'react';
import {NavLink, navigateAction} from 'fluxible-router';
import classNames from 'classnames/bind';
import {connectToStores} from 'fluxible-addons-react';
import ContentUtil from '../util/ContentUtil';
import DeckTreeStore from '../../../../stores/DeckTreeStore';
import UserProfileStore from '../../../../stores/UserProfileStore';
import addTreeNodeAndNavigate from '../../../../actions/decktree/addTreeNodeAndNavigate';
import deleteTreeNodeAndNavigate from '../../../../actions/decktree/deleteTreeNodeAndNavigate';
import AttachSubdeck from '../AttachSubdeck/AttachSubdeckModal';
import AttachSlides from '../AttachSubdeck/AttachSlidesModal';
import PermissionsStore from '../../../../stores/PermissionsStore';
import ContentStore from '../../../../stores/ContentStore';
import showNoPermissionsModal from '../../../../actions/permissions/showNoPermissionsModal';

class ContentActionsHeader extends React.Component {

    componentDidUpdate(){

    }
    handleAddNode(selector, nodeSpec) {
        //selector: Object {id: "56", stype: "deck", sid: 67, spath: "67:2"}
        //nodeSec: Object {type: "slide", id: "0"}
        this.context.executeAction(addTreeNodeAndNavigate, {selector: selector, nodeSpec: nodeSpec});
    }

    handleDeleteNode(selector) {
        this.context.executeAction(deleteTreeNodeAndNavigate, selector);
    }

    handleEditNode(selector) {
        const nodeURL = ContentUtil.makeNodeURL(selector, 'edit');
        if (this.props.PermissionsStore.permissions.readOnly || !this.props.PermissionsStore.permissions.edit) {
            this.context.executeAction(showNoPermissionsModal, {selector: selector, user: this.props.UserProfileStore.userid, permissions: this.props.PermissionsStore.permissions});
        } else {
            this.context.executeAction(navigateAction, {
                url: nodeURL
            });
        }
    }
    render() {
        const contentDetails = this.props.ContentStore;
        //config buttons based on the selected item
        const addSlideClass = classNames({
            'item ui small basic left attached button': true,
            'disabled': this.props.PermissionsStore.permissions.readOnly || !this.props.PermissionsStore.permissions.edit || contentDetails.mode ==='edit'
        });
        const addDeckClass = classNames({
            'item ui small basic left attached button': true,
            'disabled': this.props.PermissionsStore.permissions.readOnly || !this.props.PermissionsStore.permissions.edit || contentDetails.mode ==='edit'
        });
        const duplicateItemClass = classNames({
            'item ui small basic left attached button': true,
            'disabled': contentDetails.selector.id === contentDetails.selector.sid || contentDetails.selector.stype==='deck' || this.props.PermissionsStore.permissions.readOnly || !this.props.PermissionsStore.permissions.edit || contentDetails.mode ==='edit'
        });
        const deleteItemClass = classNames({
            'item ui small basic left attached button': true,
            'disabled': contentDetails.selector.id === contentDetails.selector.sid || this.props.PermissionsStore.permissions.readOnly || !this.props.PermissionsStore.permissions.edit || contentDetails.mode ==='edit'
        });
        let selectorImm = this.props.DeckTreeStore.selector;
        let selector = {id: selectorImm.get('id'), stype: selectorImm.get('stype'), sid: selectorImm.get('sid'), spath: selectorImm.get('spath')};

        let buttonStyle = {
            classNames : classNames({
                'item small attached left':true,
                'disabled': this.props.PermissionsStore.permissions.readOnly || !this.props.PermissionsStore.permissions.edit || contentDetails.mode ==='edit'
            }),
            iconSize : 'large',
            attached : 'left',
            noTabIndex : this.props.PermissionsStore.permissions.readOnly || !this.props.PermissionsStore.permissions.edit || contentDetails.mode ==='edit'
        } ;

        return (

                <NavLink activeClass=" " className={'item link' + (contentDetails.mode === 'view' ? ' active' : '')} href={ContentUtil.makeNodeURL(selector, 'view')} role={'tab'}>
                    View
                </NavLink>
                {this.props.UserProfileStore.username === '' ? '' :

                         Edit

                }
                {this.props.UserProfileStore.username === '' ? '' :

                    <button className={duplicateItemClass} onClick={this.handleAddNode.bind(this, selector, {type: selector.stype, id: selector.sid})}
                           type="button"
                           aria-label="Duplicate"
                           data-tooltip="Duplicate"
                           tabIndex={contentDetails.selector.id === contentDetails.selector.sid || contentDetails.selector.stype==='deck' || this.props.PermissionsStore.permissions.readOnly || !this.props.PermissionsStore.permissions.edit || contentDetails.mode ==='edit'?-1:0}>

                          </button>
                <button className={deleteItemClass} onClick={this.handleDeleteNode.bind(this, selector)}
                            type="button"
                            aria-label="Delete"
                            data-tooltip="Delete"
                            tabIndex={this.props.PermissionsStore.permissions.readOnly || !this.props.PermissionsStore.permissions.edit || contentDetails.mode ==='edit'?-1:0}>

                          </button>

                        <button className={addSlideClass} onClick={this.handleAddNode.bind(this, selector, {type: 'slide', id: '0'}) }
                          type="button"
                          aria-label="Add Slide"
                          data-tooltip="Add Slide"
                          tabIndex={this.props.PermissionsStore.permissions.readOnly || !this.props.PermissionsStore.permissions.edit || contentDetails.mode ==='edit'?-1:0}>

                        </button>
                        <AttachSlides buttonStyle={buttonStyle} selector={selector} />
                          <button className={addDeckClass} onClick={this.handleAddNode.bind(this, selector, {type: 'deck', id: '0'})}
                           type="button"
                           aria-label="Add Deck"
                           data-tooltip="Add Deck"
                           tabIndex={this.props.PermissionsStore.permissions.readOnly || !this.props.PermissionsStore.permissions.edit || contentDetails.mode ==='edit'?-1:0}>

                          </button>
                          <AttachSubdeck buttonStyle={buttonStyle} selector={selector} />

                          {/*
                          <button className="item ui small basic right attached disabled button">

                          </button>
                          */}

                  }

        );
    }
  }
ContentActionsHeader.contextTypes = {
    executeAction: React.PropTypes.func.isRequired
};
//it should listen to decktree store in order to handle adding slides/decks
ContentActionsHeader = connectToStores(ContentActionsHeader, [DeckTreeStore, UserProfileStore, PermissionsStore, ContentStore], (context, props) => {
    return {
        DeckTreeStore: context.getStore(DeckTreeStore).getState(),
        UserProfileStore: context.getStore(UserProfileStore).getState(),
        PermissionsStore: context.getStore(PermissionsStore).getState(),
        ContentStore: context.getStore(ContentStore).getState()
    };
});
export default ContentActionsHeader;
<|endoftext|>