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

  function MinimapController($scope, ol, proj4, sitesservice) {
    var me = this;
    this.sitesservice = sitesservice;

    var mapEnabled = true;

    proj4.defs('EPSG:32633', '+proj=utm +zone=33 +ellps=WGS84 +datum=WGS84 +units=m +no_defs');
    proj4.defs('urn:ogc:def:crs:EPSG::32633', proj4.defs('EPSG:32633'));

    var olProjectionCode = 'EPSG:3857';
    var siteProjectionCode = 'EPSG:32633';
    var siteProjection = ol.proj.get(siteProjectionCode);
    var siteStyle =  new ol.style.Style({
      stroke: new ol.style.Stroke({
        color: 'yellow',
        width: 10
      }),
      fill: new ol.style.Fill({
        color: 'rgba(255, 255, 0, 0.1)'
      })
    });

    function centerMap(center) {
      map.getView().setCenter(ol.proj.transform(center, 'EPSG:4326', 'EPSG:3857'));
    }

    function centerOnVisibleSites() {
      map.getView().fitExtent(vectorSource.getExtent(), map.getSize());
    }

    var vectorSource = new ol.source.GeoJSON({
      projection: olProjectionCode
    });

    this.onSitesChanged = function(filtered) {
      var featuresArray = vectorSource.readFeatures(filtered);
      vectorSource.clear();
      vectorSource.addFeatures(featuresArray);
      centerOnVisibleSites();
    };

    $scope.$watch(function() {
      return me.siteservice.filtered;
    }, this.onSitesChanged);

    var vectorLayer = new ol.layer.Vector({
      source: vectorSource,
      style: siteStyle
    });

    var mapType1 = new ol.source.MapQuest({layer: 'sat'});
    var mapType2 = new ol.source.TileWMS({
      url: 'http://maps.opengeo.org/geowebcache/service/wms',
      params: {LAYERS: 'openstreetmap', VERSION: '1.1.1'}
    });
    var mapType3 = new ol.source.TileWMS({
      url: 'http://maps.opengeo.org/geowebcache/service/wms',
      params: {LAYERS: 'bluemarble', VERSION: '1.1.1'}
    });
    var mapType4 = new ol.source.MapQuest({layer: 'osm'});

    var rasterLayer = new ol.layer.Tile({
      source: mapType4
    });

    var map = new ol.Map({
      layers: [rasterLayer, vectorLayer],
      view: new ol.View({
        center: ol.proj.transform([12.5469185, 41.8286509], 'EPSG:4326', 'EPSG:3857'),
        zoom: 17
      })
    });
    this.map = map;
    map.on('rightclick', function(event) {
      event.preventDefault();

      return false;
    });

    // listen on map click
    map.on('click', function(event) {

      // EPSG:3857 (strange internal OpenLayers lat/lon units)
      var lat = event.coordinate[0];
      var lon = event.coordinate[1];
      // EPSG:4326 'normal' lat/long:
      var coord4326 = ol.proj.transform([lat, lon], 'EPSG:3857', 'EPSG:4326');
      var lat4326 = coord4326[0];
      var lon4326 = coord4326[1];
      // EPSG:32633 laz coordinate system:
      var coord32633 = proj4('EPSG:3857', siteProjectionCode, [lat, lon]);
      var lat32633 = coord32633[0];
      var lon32633 = coord32633[1];

      setCameraLocation(coord4326);

      console.log('EPSG:3857 (openlayers)\nx: '+ lat + '\ny: ' + lon +
      '\nESPG:4326 (google)\nx: ' + lat4326 +
      '\ny: ' + lon4326 + '\nEPSG:32633 (drivemap)\nx: ' + lat32633 +
      '\ny: ' + lon32633);
    });

    function toggleMap() {
      mapEnabled = !mapEnabled;
      console.log('toggleMap: '+mapEnabled);
      if (mapEnabled) {
        document.getElementById('overhead-map').style.visibility = 'visible';
      } else {
        document.getElementById('overhead-map').style.visibility = 'hidden';
      }
    }

  }

  angular.module('pattyApp.minimap')
  .controller('MinimapController', MinimapController);
})();
<commit_msg>Cleanup minimap contorller<commit_after>(function() {
  'use strict';

  function MinimapController($scope, ol, proj4, sitesservice) {
    var me = this;
    this.sitesservice = sitesservice;

    proj4.defs('EPSG:32633', '+proj=utm +zone=33 +ellps=WGS84 +datum=WGS84 +units=m +no_defs');
    proj4.defs('urn:ogc:def:crs:EPSG::32633', proj4.defs('EPSG:32633'));

    var olProjectionCode = 'EPSG:3857';
    var siteProjectionCode = 'EPSG:32633';
    var siteStyle =  new ol.style.Style({
      stroke: new ol.style.Stroke({
        color: 'yellow',
        width: 10
      }),
      fill: new ol.style.Fill({
        color: 'rgba(255, 255, 0, 0.1)'
      })
    });

    function centerOnVisibleSites() {
      map.getView().fitExtent(vectorSource.getExtent(), map.getSize());
    }

    var vectorSource = new ol.source.GeoJSON({
      projection: olProjectionCode
    });

    this.onSitesChanged = function(filtered) {
      var featuresArray = vectorSource.readFeatures(filtered);
      vectorSource.clear();
      vectorSource.addFeatures(featuresArray);
      centerOnVisibleSites();
    };

    $scope.$watch(function() {
      return me.siteservice.filtered;
    }, this.onSitesChanged);

    var vectorLayer = new ol.layer.Vector({
      source: vectorSource,
      style: siteStyle
    });

    var mapType = new ol.source.MapQuest({layer: 'osm'});

    var rasterLayer = new ol.layer.Tile({
      source: mapType
    });

    var map = new ol.Map({
      layers: [rasterLayer, vectorLayer],
      view: new ol.View({
        center: ol.proj.transform([12.5469185, 41.8286509], 'EPSG:4326', 'EPSG:3857'),
        zoom: 17
      })
    });
    this.map = map;
    map.on('rightclick', function(event) {
      event.preventDefault();

      return false;
    });

    // listen on map click
    map.on('click', function(event) {

      // EPSG:3857 (strange internal OpenLayers lat/lon units)
      var lat = event.coordinate[0];
      var lon = event.coordinate[1];
      // EPSG:4326 'normal' lat/long:
      var coord4326 = ol.proj.transform([lat, lon], 'EPSG:3857', 'EPSG:4326');
      var lat4326 = coord4326[0];
      var lon4326 = coord4326[1];
      // EPSG:32633 laz coordinate system:
      var coord32633 = proj4('EPSG:3857', siteProjectionCode, [lat, lon]);
      var lat32633 = coord32633[0];
      var lon32633 = coord32633[1];

      console.log('EPSG:3857 (openlayers)\nx: '+ lat + '\ny: ' + lon +
      '\nESPG:4326 (google)\nx: ' + lat4326 +
      '\ny: ' + lon4326 + '\nEPSG:32633 (drivemap)\nx: ' + lat32633 +
      '\ny: ' + lon32633);
    });
  }

  angular.module('pattyApp.minimap')
  .controller('MinimapController', MinimapController);
})();
<|endoftext|>


<commit_before>var TransactionService = require('../../src/performance/transactionService')
var Transaction = require('../../src/performance/transaction')
var Trace = require('../../src/performance/trace')

var ZoneServiceMock = require('./zoneServiceMock.js')
var logger = Object.create(require('loglevel'))

var Config = require('../../src/lib/config')

describe('TransactionService', function () {
  var transactionService
  var zoneServiceMock
  var config
  beforeEach(function () {
    zoneServiceMock = new ZoneServiceMock()

    spyOn(zoneServiceMock, 'get').and.callThrough()
    spyOn(logger, 'debug')

    config = Object.create(Config)
    config.init()
    transactionService = new TransactionService(zoneServiceMock, logger, config)
  })

  it('should not start trace when there is no current transaction', function () {
    transactionService.startTrace('test-trace', 'test-trace')
    expect(logger.debug).toHaveBeenCalled()
  })

  it('should call startTrace on current Transaction', function () {
    var tr = new Transaction('transaction', 'transaction')
    spyOn(tr, 'startTrace').and.callThrough()
    zoneServiceMock.zone.transaction = tr
    transactionService.startTrace('test-trace', 'test-trace')
    expect(zoneServiceMock.zone.transaction.startTrace).toHaveBeenCalledWith('test-trace', 'test-trace', undefined)
  })

  it('should not start trace when performance monitoring is disabled', function () {
    config.set('performance.enable', false)
    transactionService = new TransactionService(zoneServiceMock, logger, config)
    var tr = new Transaction('transaction', 'transaction')
    spyOn(tr, 'startTrace').and.callThrough()
    zoneServiceMock.zone.transaction = tr
    transactionService.startTrace('test-trace', 'test-trace')
    expect(zoneServiceMock.zone.transaction.startTrace).not.toHaveBeenCalled()
  })

  it('should not start transaction when performance monitoring is disabled', function () {
    config.set('performance.enable', false)
    transactionService = new TransactionService(zoneServiceMock, logger, config)

    var result = transactionService.startTransaction('transaction', 'transaction')

    expect(result).toBeUndefined()
  })

  it('should not start transaction when not in opbeat zone', function () {
    zoneServiceMock.isOpbeatZone = function () {
      return false
    }
    transactionService = new TransactionService(zoneServiceMock, logger, config)

    var result = transactionService.startTransaction('transaction', 'transaction')

    expect(result).toBeUndefined()
  })

  it('should start transaction', function () {
    config.set('performance.enable', true)
    config.set('performance.browserResponsivenessInterval', true)
    transactionService = new TransactionService(zoneServiceMock, logger, config)

    var result = transactionService.startTransaction('transaction1', 'transaction')
    expect(result).toBeDefined()
    result = transactionService.startTransaction('transaction2', 'transaction')
    expect(result.name).toBe('transaction2')
  })

  it('should create a zone transaction on the first trace', function () {
    config.set('performance.enable', true)
    transactionService = new TransactionService(zoneServiceMock, logger, config)

    var trace = transactionService.startTrace('testTrace', 'testtype')
    var trans = zoneServiceMock.get('transaction')
    expect(trans.name).toBe('ZoneTransaction')
    transactionService.startTransaction('transaction', 'transaction')
    expect(trans.name).toBe('transaction')
  })

  it('should not create transaction if performance is not enabled', function () {
    config.set('performance.enable', false)
    transactionService = new TransactionService(zoneServiceMock, logger, config)
    var result = transactionService.createTransaction('test', 'test', config.get('performance'))
    expect(result).toBeUndefined()
  })

  it('should not start interactions by default', function () {
    config.set('performance.enable', true)
    transactionService = new TransactionService(zoneServiceMock, logger, config)

    var trans = transactionService.startTransaction('interaction', 'interaction')
    expect(trans).toBeUndefined()
  })

  it('should call startTrace on current Transaction', function () {
    var tr = new Transaction('transaction', 'transaction')
    zoneServiceMock.zone.transaction = tr
    expect(tr._scheduledTasks).toEqual({})
    zoneServiceMock.spec.onScheduleTask({source: 'setTimeout',taskId: 'setTimeout1'})
    zoneServiceMock.spec.onScheduleTask({source: 'XMLHttpRequest.send',taskId: 'XMLHttpRequest.send1',XHR: {method: 'GET',url: 'url'}})
    expect(tr._scheduledTasks).toEqual({setTimeout1: 'setTimeout1','XMLHttpRequest.send1': 'XMLHttpRequest.send1'})
    zoneServiceMock.spec.onBeforeInvokeTask({source: 'XMLHttpRequest.send',taskId: 'XMLHttpRequest.send1',trace: new Trace(tr, 'trace', 'trace')})
    expect(tr._scheduledTasks).toEqual({setTimeout1: 'setTimeout1','XMLHttpRequest.send1': 'XMLHttpRequest.send1'})
    zoneServiceMock.spec.onInvokeTask({source: 'setTimeout',taskId: 'setTimeout1'})
    expect(tr._scheduledTasks).toEqual({'XMLHttpRequest.send1': 'XMLHttpRequest.send1'})
    zoneServiceMock.spec.onCancelTask({source: 'XMLHttpRequest.send',taskId: 'XMLHttpRequest.send1'})
    expect(tr._scheduledTasks).toEqual({})
  })

  it('should remove XHR query string by default', function () {
    expect(config.get('performance.includeXHRQueryString')).toBe(false)
    var tr = new Transaction('transaction', 'transaction')
    zoneServiceMock.zone.transaction = tr
    spyOn(transactionService, 'startTrace').and.callThrough()

    zoneServiceMock.spec.onScheduleTask({source: 'XMLHttpRequest.send',taskId: 'XMLHttpRequest.send1',XHR: {method: 'GET',url: 'http://test.com/path?key=value'}})
    expect(transactionService.startTrace).toHaveBeenCalledWith('GET http://test.com/path', 'ext.HttpRequest', { enableStackFrames: false })
  })

  it('should check performance.includeXHRQueryString config', function () {
    config.set('performance.includeXHRQueryString', true)
    expect(config.get('performance.includeXHRQueryString')).toBe(true)
    var tr = new Transaction('transaction', 'transaction')
    zoneServiceMock.zone.transaction = tr
    spyOn(transactionService, 'startTrace').and.callThrough()

    zoneServiceMock.spec.onScheduleTask({source: 'XMLHttpRequest.send',taskId: 'XMLHttpRequest.send1',XHR: {method: 'GET',url: 'http://test.com/path?key=value'}})
    expect(transactionService.startTrace).toHaveBeenCalledWith('GET http://test.com/path?key=value', 'ext.HttpRequest', { enableStackFrames: false })
  })

  it('should call detectFinish onInvokeEnd', function () {
    config.set('performance.enable', true)
    transactionService = new TransactionService(zoneServiceMock, logger, config)

    var trans = transactionService.startTransaction('transaction', 'transaction')
    spyOn(trans, 'detectFinish')
    zoneServiceMock.spec.onInvokeStart({source: 'source',type: 'type'})
    zoneServiceMock.spec.onInvokeEnd({source: 'source',type: 'type'})
    expect(trans.detectFinish).toHaveBeenCalled()
  })

  it('should end the trace if onInvokeTask is called first', function () {
    var tr = new Transaction('transaction', 'transaction')
    zoneServiceMock.zone.transaction = tr
    var task = {source: 'XMLHttpRequest.send',taskId: 'XMLHttpRequest.send1',XHR: {method: 'GET',url: 'http://test.com/path?key=value'}}
    zoneServiceMock.spec.onScheduleTask(task)
    expect(task.trace).toBeDefined()
    expect(task.trace.ended).toBe(false)
    zoneServiceMock.spec.onInvokeTask(task)
    expect(task.trace.ended).toBe(true)
  })

  it('should capture page load on first transaction', function (done) {
    config.set('performance.enable', true)
    config.set('performance.capturePageLoad', true)
    transactionService = new TransactionService(zoneServiceMock, logger, config)

    var tr1 = transactionService.startTransaction('transaction1', 'transaction')
    expect(tr1.isHardNavigation).toBe(false)
    tr1.detectFinish()
    tr1.donePromise.then(function () {
      expect(tr1.isHardNavigation).toBe(true)
    })

    var tr2 = transactionService.startTransaction('transaction2', 'transaction')
    expect(tr2.isHardNavigation).toBe(false)
    tr2.detectFinish()
    tr2.donePromise.then(function () {
      expect(tr2.isHardNavigation).toBe(false)
      done()
    })
  })
})
<commit_msg>checking hard navigation duration threshold<commit_after>var TransactionService = require('../../src/performance/transactionService')
var Transaction = require('../../src/performance/transaction')
var Trace = require('../../src/performance/trace')

var ZoneServiceMock = require('./zoneServiceMock.js')
var logger = Object.create(require('loglevel'))

var Config = require('../../src/lib/config')

describe('TransactionService', function () {
  var transactionService
  var zoneServiceMock
  var config
  beforeEach(function () {
    zoneServiceMock = new ZoneServiceMock()

    spyOn(zoneServiceMock, 'get').and.callThrough()
    spyOn(logger, 'debug')

    config = Object.create(Config)
    config.init()
    transactionService = new TransactionService(zoneServiceMock, logger, config)
  })

  it('should not start trace when there is no current transaction', function () {
    transactionService.startTrace('test-trace', 'test-trace')
    expect(logger.debug).toHaveBeenCalled()
  })

  it('should call startTrace on current Transaction', function () {
    var tr = new Transaction('transaction', 'transaction')
    spyOn(tr, 'startTrace').and.callThrough()
    zoneServiceMock.zone.transaction = tr
    transactionService.startTrace('test-trace', 'test-trace')
    expect(zoneServiceMock.zone.transaction.startTrace).toHaveBeenCalledWith('test-trace', 'test-trace', undefined)
  })

  it('should not start trace when performance monitoring is disabled', function () {
    config.set('performance.enable', false)
    transactionService = new TransactionService(zoneServiceMock, logger, config)
    var tr = new Transaction('transaction', 'transaction')
    spyOn(tr, 'startTrace').and.callThrough()
    zoneServiceMock.zone.transaction = tr
    transactionService.startTrace('test-trace', 'test-trace')
    expect(zoneServiceMock.zone.transaction.startTrace).not.toHaveBeenCalled()
  })

  it('should not start transaction when performance monitoring is disabled', function () {
    config.set('performance.enable', false)
    transactionService = new TransactionService(zoneServiceMock, logger, config)

    var result = transactionService.startTransaction('transaction', 'transaction')

    expect(result).toBeUndefined()
  })

  it('should not start transaction when not in opbeat zone', function () {
    zoneServiceMock.isOpbeatZone = function () {
      return false
    }
    transactionService = new TransactionService(zoneServiceMock, logger, config)

    var result = transactionService.startTransaction('transaction', 'transaction')

    expect(result).toBeUndefined()
  })

  it('should start transaction', function () {
    config.set('performance.enable', true)
    config.set('performance.browserResponsivenessInterval', true)
    transactionService = new TransactionService(zoneServiceMock, logger, config)

    var result = transactionService.startTransaction('transaction1', 'transaction')
    expect(result).toBeDefined()
    result = transactionService.startTransaction('transaction2', 'transaction')
    expect(result.name).toBe('transaction2')
  })

  it('should create a zone transaction on the first trace', function () {
    config.set('performance.enable', true)
    transactionService = new TransactionService(zoneServiceMock, logger, config)

    var trace = transactionService.startTrace('testTrace', 'testtype')
    var trans = zoneServiceMock.get('transaction')
    expect(trans.name).toBe('ZoneTransaction')
    transactionService.startTransaction('transaction', 'transaction')
    expect(trans.name).toBe('transaction')
  })

  it('should not create transaction if performance is not enabled', function () {
    config.set('performance.enable', false)
    transactionService = new TransactionService(zoneServiceMock, logger, config)
    var result = transactionService.createTransaction('test', 'test', config.get('performance'))
    expect(result).toBeUndefined()
  })

  it('should not start interactions by default', function () {
    config.set('performance.enable', true)
    transactionService = new TransactionService(zoneServiceMock, logger, config)

    var trans = transactionService.startTransaction('interaction', 'interaction')
    expect(trans).toBeUndefined()
  })

  it('should call startTrace on current Transaction', function () {
    var tr = new Transaction('transaction', 'transaction')
    zoneServiceMock.zone.transaction = tr
    expect(tr._scheduledTasks).toEqual({})
    zoneServiceMock.spec.onScheduleTask({source: 'setTimeout',taskId: 'setTimeout1'})
    zoneServiceMock.spec.onScheduleTask({source: 'XMLHttpRequest.send',taskId: 'XMLHttpRequest.send1',XHR: {method: 'GET',url: 'url'}})
    expect(tr._scheduledTasks).toEqual({setTimeout1: 'setTimeout1','XMLHttpRequest.send1': 'XMLHttpRequest.send1'})
    zoneServiceMock.spec.onBeforeInvokeTask({source: 'XMLHttpRequest.send',taskId: 'XMLHttpRequest.send1',trace: new Trace(tr, 'trace', 'trace')})
    expect(tr._scheduledTasks).toEqual({setTimeout1: 'setTimeout1','XMLHttpRequest.send1': 'XMLHttpRequest.send1'})
    zoneServiceMock.spec.onInvokeTask({source: 'setTimeout',taskId: 'setTimeout1'})
    expect(tr._scheduledTasks).toEqual({'XMLHttpRequest.send1': 'XMLHttpRequest.send1'})
    zoneServiceMock.spec.onCancelTask({source: 'XMLHttpRequest.send',taskId: 'XMLHttpRequest.send1'})
    expect(tr._scheduledTasks).toEqual({})
  })

  it('should remove XHR query string by default', function () {
    expect(config.get('performance.includeXHRQueryString')).toBe(false)
    var tr = new Transaction('transaction', 'transaction')
    zoneServiceMock.zone.transaction = tr
    spyOn(transactionService, 'startTrace').and.callThrough()

    zoneServiceMock.spec.onScheduleTask({source: 'XMLHttpRequest.send',taskId: 'XMLHttpRequest.send1',XHR: {method: 'GET',url: 'http://test.com/path?key=value'}})
    expect(transactionService.startTrace).toHaveBeenCalledWith('GET http://test.com/path', 'ext.HttpRequest', { enableStackFrames: false })
  })

  it('should check performance.includeXHRQueryString config', function () {
    config.set('performance.includeXHRQueryString', true)
    expect(config.get('performance.includeXHRQueryString')).toBe(true)
    var tr = new Transaction('transaction', 'transaction')
    zoneServiceMock.zone.transaction = tr
    spyOn(transactionService, 'startTrace').and.callThrough()

    zoneServiceMock.spec.onScheduleTask({source: 'XMLHttpRequest.send',taskId: 'XMLHttpRequest.send1',XHR: {method: 'GET',url: 'http://test.com/path?key=value'}})
    expect(transactionService.startTrace).toHaveBeenCalledWith('GET http://test.com/path?key=value', 'ext.HttpRequest', { enableStackFrames: false })
  })

  it('should call detectFinish onInvokeEnd', function () {
    config.set('performance.enable', true)
    transactionService = new TransactionService(zoneServiceMock, logger, config)

    var trans = transactionService.startTransaction('transaction', 'transaction')
    spyOn(trans, 'detectFinish')
    zoneServiceMock.spec.onInvokeStart({source: 'source',type: 'type'})
    zoneServiceMock.spec.onInvokeEnd({source: 'source',type: 'type'})
    expect(trans.detectFinish).toHaveBeenCalled()
  })

  it('should end the trace if onInvokeTask is called first', function () {
    var tr = new Transaction('transaction', 'transaction')
    zoneServiceMock.zone.transaction = tr
    var task = {source: 'XMLHttpRequest.send',taskId: 'XMLHttpRequest.send1',XHR: {method: 'GET',url: 'http://test.com/path?key=value'}}
    zoneServiceMock.spec.onScheduleTask(task)
    expect(task.trace).toBeDefined()
    expect(task.trace.ended).toBe(false)
    zoneServiceMock.spec.onInvokeTask(task)
    expect(task.trace.ended).toBe(true)
  })

  it('should capture page load on first transaction', function (done) {
    config.set('performance.enable', true)
    config.set('performance.capturePageLoad', true)
    transactionService = new TransactionService(zoneServiceMock, logger, config)

    var tr1 = transactionService.startTransaction('transaction1', 'transaction')
    expect(tr1.isHardNavigation).toBe(false)
    tr1.detectFinish()
    tr1.donePromise.then(function () {
      expect(tr1.isHardNavigation).toBe(true)
    })
    tr1.traces.forEach(function (t) {
      expect(t.duration()).toBeLessThan(5 * 60 * 1000)
    })

    var tr2 = transactionService.startTransaction('transaction2', 'transaction')
    expect(tr2.isHardNavigation).toBe(false)
    tr2.detectFinish()
    tr2.donePromise.then(function () {
      expect(tr2.isHardNavigation).toBe(false)
      done()
    })
  })
})
<|endoftext|>


<commit_before>/* globals __DEV__ */
import Phaser from 'phaser';
import Player from '../sprites/Player';

export default class extends Phaser.State {
  init() {}

  preload() {}

  create() {
    this.physics.startSystem(Phaser.Physics.ARCADE);

    this.map = this.game.add.tilemap('map1');
    this.map.addTilesetImage('meta_tiles');
    this.map.addTilesetImage('tileset01');

    this.collisionLayer = this.map.createLayer('Collisions');
    this.collisionLayer.debug = true;
    this.map.createLayer('Background');
    this.map.createLayer('Partials');

    this.collisionLayer.resizeWorld();
    this.map.setCollisionBetween(0, 10000, true, this.collisionLayer);

    this.player = new Player({
      game: this.game,
      x: 450,
      y: 150,
      asset: 'player'
    });

    this.camera.follow(this.player);
    this.player.debug = true;
  }

  render() {
    if (__DEV__) {
      this.game.debug.spriteInfo(this.player, 32, 32)
      this.game.debug.body(this.player);
    }
  }

  update() {
    this.physics.arcade.collide(this.player, this.collisionLayer);
  }
}<commit_msg>eslint<commit_after>/* globals __DEV__ */
import Phaser from 'phaser';
import Player from '../sprites/Player';

export default class extends Phaser.State {
  init() {}

  preload() {}

  create() {
    this.physics.startSystem(Phaser.Physics.ARCADE);

    this.map = this.game.add.tilemap('map1');
    this.map.addTilesetImage('meta_tiles');
    this.map.addTilesetImage('tileset01');

    this.collisionLayer = this.map.createLayer('Collisions');
    this.collisionLayer.debug = true;
    this.map.createLayer('Background');
    this.map.createLayer('Partials');

    this.collisionLayer.resizeWorld();
    this.map.setCollisionBetween(0, 10000, true, this.collisionLayer);

    this.player = new Player({
      game: this.game,
      x: 450,
      y: 150,
      asset: 'player'
    });

    this.camera.follow(this.player);
    this.player.debug = true;
  }

  render() {
    if (__DEV__) {
      this.game.debug.spriteInfo(this.player, 32, 32);
      this.game.debug.body(this.player);
    }
  }

  update() {
    this.physics.arcade.collide(this.player, this.collisionLayer);
  }
}<|endoftext|>


<commit_before>var should = require('should');
var sandboxPath = 'test/sandbox';
var fs = require('fs');

describe('Indexing numeric fields, Reuters: ', function(){
  it('should index one file of test data', function(done) {
    this.timeout(5000);
    var data = JSON.parse(fs.readFileSync('node_modules/reuters-21578-json/data/justTen/justTen.json'));
    var si = require('../../')({indexPath: sandboxPath + '/si-reuters-10',
                                logLevel: 'warn'});
    var opt = {};
    opt.batchName = 'reuters';
    opt.filters = ['places', 'topics'];
    si.add(opt, data, function(err) {
      (err === null).should.be.exactly(true);
      si.close(function(err){done();})
    });
  }),
  it('verifies calibration of number after batch is indexed', function(done) {
    var si = require('../../')({indexPath: sandboxPath + '/si-reuters-10',
                                logLevel: 'error'});
    si.indexValue({key:'TF~randomNumber~2749~~'}, function(err, value) {
      (err === null).should.be.exactly(true);
      value.length.should.be.exactly(1);
      si.close(function(err){done();})
    });
  }),
  it('should verify indexing', function(done) {
    var si = require('../../')({indexPath: sandboxPath + '/si-reuters-10',
                                logLevel: 'error'});
    si.tellMeAboutMySearchIndex(function(info) {
      should.exist(info);
      (info.totalDocs).should.be.exactly(10);
      si.close(function(err){
        done();
      })
    });
  }),
  it('should be able to search number fields in indexed datas', function(done) {
    var si = require('../../')({indexPath: sandboxPath + '/si-reuters-10',
                                logLevel: 'warn'});
    var q = {};
    q.query = {randomNumber: [2749]};
    si.search(q, function(err, results) {
      should.exist(results);
      (err === null).should.be.exactly(true);
      results.hits.length.should.be.exactly(1);
      results.hits[0].id.should.be.exactly('9');
      si.close(function(err){done();})
    });
  })
})
<commit_msg>fixed tests<commit_after>var should = require('should');
var sandboxPath = 'test/sandbox';
var fs = require('fs');

describe('Indexing numeric fields, Reuters: ', function(){
  it('should index one file of test data', function(done) {
    this.timeout(5000);
    var data = JSON.parse(fs.readFileSync('node_modules/reuters-21578-json/data/justTen/justTen.json'));
    var si = require('../../')({indexPath: sandboxPath + '/si-reuters-10-2',
                                logLevel: 'warn'});
    var opt = {};
    opt.batchName = 'reuters';
    opt.filters = ['places', 'topics'];
    si.add(opt, data, function(err) {
      (err === null).should.be.exactly(true);
      si.close(function(err){done();})
    });
  }),
  it('verifies calibration of number after batch is indexed', function(done) {
    var si = require('../../')({indexPath: sandboxPath + '/si-reuters-10-2',
                                logLevel: 'error'});
    si.indexValue({key:'TF~randomNumber~2749~~'}, function(err, value) {
      (err === null).should.be.exactly(true);
      value.length.should.be.exactly(1);
      si.close(function(err){done();})
    });
  }),
  it('should verify indexing', function(done) {
    var si = require('../../')({indexPath: sandboxPath + '/si-reuters-10-2',
                                logLevel: 'error'});
    si.tellMeAboutMySearchIndex(function(info) {
      should.exist(info);
      (info.totalDocs).should.be.exactly(10);
      si.close(function(err){
        done();
      })
    });
  }),
  it('should be able to search number fields in indexed datas', function(done) {
    var si = require('../../')({indexPath: sandboxPath + '/si-reuters-10-2',
                                logLevel: 'warn'});
    var q = {};
    q.query = {randomNumber: [2749]};
    si.search(q, function(err, results) {
      should.exist(results);
      (err === null).should.be.exactly(true);
      results.hits.length.should.be.exactly(1);
      results.hits[0].id.should.be.exactly('9');
      si.close(function(err){done();})
    });
  })
})
<|endoftext|>


<commit_before>(function(){
    'use strict';
    angular.module('reservacionesMulti')
            .service('Profesores', Profesores);

    Profesores.$inject = ['$q', '$firebaseObject', '$firebaseArray', 'FURL'];
    function Profesores ($q, $firebaseObject, $firebaseArray, FURL) {
        var ref = new Firebase(FURL),
            profesores = $firebaseArray(ref.child('profesores'));

        var ProfesoresService = {
          all: profesores,
          create: create,
          getSecciones: getProfesorSections
        };

        return ProfesoresService;

        function create (ProfesorData) {
          return profesores.$add(ProfesorData);
        }

        function getProfesorSections (ProfesorID) {
          return $firebaseObject(ref.child('profesores').child(ProfesorID).child('secciones'));
        }
    }
})();
<commit_msg>Complete Profesors.Service<commit_after>'use strict';

import { autobind } from 'core-decorators';

const REF = new WeakMap(),
  firebaseObject = new WeakMap(),
  firebaseArray = new WeakMap();

@autobind
class Profesores {
  constructor($firebaseObject, $firebaseArray, FURL) {
    REF.set(this, new Firebase(FURL));
    firebaseObject.set(this, $firebaseObject);
    firebaseArray.set(this, $firebaseArray);
    this.profesores = $firebaseArray(REF.get(this).child('profesores'));
  }
  @autobind
  all() {
    return this.profesores;
  }
  @autobind
  create(profesorData) {
    this.profesores.$add(profesorData);
  }
  @autobind
  getSections(pofesorID) {
    return firebaseObject.get(this)(REF.get(this).child('profesores').child(pofesorID).child('secciones'));
  }
}

Profesores.$inject = ['$firebaseObject', '$firebaseArray', 'FURL'];
angular.module('reservacionesMulti')
        .service('Profesores', Profesores);
<|endoftext|>


<commit_before>import assignIn from 'lodash/assignIn';

import {
  DISPATCH_TYPE,
  STATE_TYPE
} from '../constants';

class Store {
  /**
   * Creates a new Proxy store
   * @param  {object} options An object of form {portName, state}, where `portName` is a required string and defines the name of the port for state transition changes and `state` is the initial state of this store (default `{}`)
   */
  constructor({portName, state = {}}) {
    if (!portName) {
      throw new Error('portName is required in options');
    }

    this.port = chrome.runtime.connect({name: portName});
    this.listeners = [];
    this.state = state;

    this.port.onMessage.addListener((message) => {
      if (message.type === STATE_TYPE) {
        this.replaceState(message.payload);
      }
    });
  }

  /**
   * Subscribes a listener function for all state changes
   * @param  {function} listener A listener function to be called when store state changes
   * @return {function}          An unsubscribe function which can be called to remove the listener from state updates
   */
  subscribe(listener) {
    this.listeners.push(listener);

    return () => {
      this.listeners = this.listeners.filter((l) => l !== listener);
    };
  }

  /**
   * Replace the current state with a new state. Notifies all listeners of state change.
   * @param  {object} state The new state for the store
   */
  replaceState(state) {
    this.state = state;

    this.listeners.forEach((l) => l());
  }

  /**
   * Get the current state of the store
   * @return {object} the current store state
   */
  getState() {
    return this.state;
  }

  /**
   * Dispatch an action to the background using messaging passing
   * @param  {object} data The action data to dispatch
   * @return {Promise}     Promise that will resolve/reject based on the action response from the background
   */
  dispatch(data) {
    return new Promise((resolve, reject) => {
      chrome.runtime.sendMessage({
        type: DISPATCH_TYPE,
        payload: data
      }, ({error, value}) => {
        if (error) {
          reject(assignIn((new Error()), error));
        } else {
          resolve(value && value.payload);
        }
      });
    });
  }
}

export default Store;
<commit_msg>better error msg<commit_after>import assignIn from 'lodash/assignIn';

import {
  DISPATCH_TYPE,
  STATE_TYPE
} from '../constants';

class Store {
  /**
   * Creates a new Proxy store
   * @param  {object} options An object of form {portName, state}, where `portName` is a required string and defines the name of the port for state transition changes and `state` is the initial state of this store (default `{}`)
   */
  constructor({portName, state = {}}) {
    if (!portName) {
      throw new Error('portName is required in options');
    }

    this.port = chrome.runtime.connect({name: portName});
    this.listeners = [];
    this.state = state;

    this.port.onMessage.addListener((message) => {
      if (message.type === STATE_TYPE) {
        this.replaceState(message.payload);
      }
    });
  }

  /**
   * Subscribes a listener function for all state changes
   * @param  {function} listener A listener function to be called when store state changes
   * @return {function}          An unsubscribe function which can be called to remove the listener from state updates
   */
  subscribe(listener) {
    this.listeners.push(listener);

    return () => {
      this.listeners = this.listeners.filter((l) => l !== listener);
    };
  }

  /**
   * Replace the current state with a new state. Notifies all listeners of state change.
   * @param  {object} state The new state for the store
   */
  replaceState(state) {
    this.state = state;

    this.listeners.forEach((l) => l());
  }

  /**
   * Get the current state of the store
   * @return {object} the current store state
   */
  getState() {
    return this.state;
  }

  /**
   * Dispatch an action to the background using messaging passing
   * @param  {object} data The action data to dispatch
   * @return {Promise}     Promise that will resolve/reject based on the action response from the background
   */
  dispatch(data) {
    return new Promise((resolve, reject) => {
      chrome.runtime.sendMessage({
        type: DISPATCH_TYPE,
        payload: data
      }, (resp) => {
        if (resp === undefined) {
          throw(
            "Looks like there is an error in the background page. " +
            "You might want to inspect your background page for more details."
          );
        }

        let error = resp.error;
        let value = resp.value;

        if (error) {
          reject(assignIn((new Error()), error));
        } else {
          resolve(value && value.payload);
        }
      });
    });
  }
}

export default Store;
<|endoftext|>


<commit_before>'use strict';

/**
 * @module publish-controllers
 */

/**
 * Provides route actions for all requests relative to videos.
 *
 * @class videoController
 */

var path = require('path');
var openVeoAPI = require('@openveo/api');
var configDir = openVeoAPI.fileSystem.getConfDir();
var errors = process.requirePublish('app/server/httpErrors.js');
var platforms = require(path.join(configDir, 'publish/videoPlatformConf.json'));

var VideoModel = process.requirePublish('app/server/models/VideoModel.js');
var videoModel = new VideoModel();
var async = require('async');

var PropertyModel = process.requirePublish('app/server/models/PropertyModel.js');
var propertyModel = new PropertyModel();
var applicationStorage = openVeoAPI.applicationStorage;

var env = (process.env.NODE_ENV === 'production') ? 'prod' : 'dev';

/**
 * Displays video player template.
 *
 * Checks first if the video id is valid and if the video is published
 * before returning the template.
 *
 * @method displayVideoAction
 * @static
 */
module.exports.displayVideoAction = function(request, response, next) {
  response.locals.scripts = [];
  response.locals.css = [];

  // Retrieve openveo sub plugins
  var plugins = applicationStorage.getPlugins();

  // Got sub plugins
  if (plugins) {
    plugins.forEach(function(subPlugin) {
      if (subPlugin.name === 'publish') {
        if (subPlugin.custom) {
          var customScripts = subPlugin.custom.scriptFiles;
          var playerScripts = customScripts['publishPlayer'];
          response.locals.scripts = response.locals.scripts.concat(
            (customScripts['base'] || []),
            ((playerScripts && playerScripts[env]) ? playerScripts[env] : [])
          );
          response.locals.css = response.locals.css.concat(subPlugin.custom.cssFiles || []);
        }
      }
    });

    response.render('player', response.locals);
  }

  // No sub plugins
  else
    next();
};

/**
 * Gets all media platforms available.
 *
 * @example
 *     {
 *       "platforms" : ["vimeo", "youtube"]
 *     }
 *
 * @method getPlatformsAction
 * @static
 */
module.exports.getPlatformsAction = function(request, response) {
  response.send({
    platforms: Object.keys(platforms) || []
  });
};

/**
 * Gets information about a video.
 *
 * Expects one GET parameter :
 *  - **id** The id of the video
 *
 * @example
 *     {
 *       video : {
 *         id : 123456789,
 *         ...
 *       }
 *     }
 *
 * @method getVideoAction
 * @static
 */
module.exports.getVideoAction = function(request, response, next) {
  if (request.params.id) {
    videoModel.getOneReady(request.params.id, function(error, video) {
      if (error || (video.state === VideoModel.READY_STATE && !request.isAuthenticated()))
        next(errors.GET_VIDEO_ERROR);
      else
        response.send({
          video: video
        });
    });
  }

  // Missing id of the video
  else
    next(errors.GET_VIDEO_MISSING_PARAMETERS);
};

/**
 * Gets published videos by properties.
 *
 * Optional GET parameters :
 *  - **sortBy** Sort videos by either title, description, date or published
 *  - **sortOrder** Sort order (either asc or desc)
 *  - **limit** Limit number of videos per page
 *  - **page** The expected page
 *  - **properties** A list of properties with the property name as the key and the expected property
 *    value as the value. (e.g. properties[property1Name]=property1Value)
 *
 * @example
 *     {
 *       "videos" : [
 *         ...
 *       ]
 *     }
 *
 * @method getVideoByPropertiesAction
 * @static
 */
module.exports.getVideoByPropertiesAction = function(request, response, next) {
  var query = request.query;
  var sortBy = query.sortBy || 'date';
  var sortOrder = query.sortOrder == 'asc' ? -1 : 1;
  var sort = {};
  sort[sortBy] = sortOrder;

  // authorized unlimited query
  var limit = null;
  if (query.limit) {
    limit = parseInt(query.limit) || 10;
    if (limit < 1) limit = null;
  }

  var page = null;
  if (limit) {
    page = query.page || 1;
    if (page < 1) page = 1;
  }

  var wsSearch = query.properties;
  var searchParam = {state: 12};

  var series = [];

  // Construct MongoDb search query with parameters
  Object.keys(wsSearch).forEach(function(key) {
    series.push(function(callback) {

      // get property which name corresponding to parameter
      propertyModel.getByFilter({name: key}, function(error, prop) {
        if (error) return callback(error);

        // Error if no property corresponding
        if (!prop || prop.length == 0) return callback(errors.UNKNOWN_PROPERTY_ERROR);
        var val = wsSearch[key];

        // Build search for each existing property
        searchParam['properties.' + prop.id] = {$in: [].concat(val)};
        callback();
      });
    });
  });

  // Do series call function and execute final search
  async.series(series, function(err) {
    if (err) next(err);

    // find in mongoDb
    else videoModel.getPaginatedFilteredEntities(searchParam, limit, page, sort, true,
      function(error, entities, pagination) {
        if (error) {
          response.status(500).send(error);
        } else {
          response.send({
            videos: entities,
            pagination: pagination
          });
        }
      }
    );
  });
};

/**
 * Publishes a video.
 *
 * Expects one GET parameter :
 *  - **id** The id of the video
 *
 * Change the state of the video to published
 *
 * @example
 *     {
 *       state : 12
 *     }
 *
 * @method publishVideoAction
 * @static
 */
module.exports.publishVideoAction = function(request, response, next) {
  if (request.params.id) {
    var arrayId = request.params.id.split(',');
    videoModel.publishVideo(arrayId, function(error) {
      if (error)
        next(errors.PUBLISH_VIDEO_ERROR);
      else
        response.send({
          state: VideoModel.PUBLISHED_STATE
        });
    });
  }

  // Missing type and / or id of the video
  else
    next(errors.PUBLISH_VIDEO_MISSING_PARAMETERS);
};

/**
 * Unpublishes a video.
 *
 * Expects one GET parameter :
 *  - **id** The id of the video
 *
 * Change the state of the video to unpublished.
 *
 * @example
 *     {
 *       state : 11
 *     }
 *
 * @method unpublishVideoAction
 * @static
 */
module.exports.unpublishVideoAction = function(request, response, next) {
  if (request.params.id) {
    var arrayId = request.params.id.split(',');
    videoModel.unpublishVideo(arrayId, function(error) {
      if (error)
        next(errors.UNPUBLISH_VIDEO_ERROR);
      else
        response.send({
          state: VideoModel.READY_STATE
        });
    });
  }

  // Missing type and / or id of the video
  else
    next(errors.UNPUBLISH_VIDEO_MISSING_PARAMETERS);
};
<commit_msg>Correct bug on /videos web service endpoint when requesting wihtout property<commit_after>'use strict';

/**
 * @module publish-controllers
 */

/**
 * Provides route actions for all requests relative to videos.
 *
 * @class videoController
 */

var path = require('path');
var openVeoAPI = require('@openveo/api');
var configDir = openVeoAPI.fileSystem.getConfDir();
var errors = process.requirePublish('app/server/httpErrors.js');
var platforms = require(path.join(configDir, 'publish/videoPlatformConf.json'));

var VideoModel = process.requirePublish('app/server/models/VideoModel.js');
var videoModel = new VideoModel();
var async = require('async');

var PropertyModel = process.requirePublish('app/server/models/PropertyModel.js');
var propertyModel = new PropertyModel();
var applicationStorage = openVeoAPI.applicationStorage;

var env = (process.env.NODE_ENV === 'production') ? 'prod' : 'dev';

/**
 * Displays video player template.
 *
 * Checks first if the video id is valid and if the video is published
 * before returning the template.
 *
 * @method displayVideoAction
 * @static
 */
module.exports.displayVideoAction = function(request, response, next) {
  response.locals.scripts = [];
  response.locals.css = [];

  // Retrieve openveo sub plugins
  var plugins = applicationStorage.getPlugins();

  // Got sub plugins
  if (plugins) {
    plugins.forEach(function(subPlugin) {
      if (subPlugin.name === 'publish') {
        if (subPlugin.custom) {
          var customScripts = subPlugin.custom.scriptFiles;
          var playerScripts = customScripts['publishPlayer'];
          response.locals.scripts = response.locals.scripts.concat(
            (customScripts['base'] || []),
            ((playerScripts && playerScripts[env]) ? playerScripts[env] : [])
          );
          response.locals.css = response.locals.css.concat(subPlugin.custom.cssFiles || []);
        }
      }
    });

    response.render('player', response.locals);
  }

  // No sub plugins
  else
    next();
};

/**
 * Gets all media platforms available.
 *
 * @example
 *     {
 *       "platforms" : ["vimeo", "youtube"]
 *     }
 *
 * @method getPlatformsAction
 * @static
 */
module.exports.getPlatformsAction = function(request, response) {
  response.send({
    platforms: Object.keys(platforms) || []
  });
};

/**
 * Gets information about a video.
 *
 * Expects one GET parameter :
 *  - **id** The id of the video
 *
 * @example
 *     {
 *       video : {
 *         id : 123456789,
 *         ...
 *       }
 *     }
 *
 * @method getVideoAction
 * @static
 */
module.exports.getVideoAction = function(request, response, next) {
  if (request.params.id) {
    videoModel.getOneReady(request.params.id, function(error, video) {
      if (error || (video.state === VideoModel.READY_STATE && !request.isAuthenticated()))
        next(errors.GET_VIDEO_ERROR);
      else
        response.send({
          video: video
        });
    });
  }

  // Missing id of the video
  else
    next(errors.GET_VIDEO_MISSING_PARAMETERS);
};

/**
 * Gets published videos by properties.
 *
 * Optional GET parameters :
 *  - **sortBy** Sort videos by either title, description, date or published
 *  - **sortOrder** Sort order (either asc or desc)
 *  - **limit** Limit number of videos per page
 *  - **page** The expected page
 *  - **properties** A list of properties with the property name as the key and the expected property
 *    value as the value. (e.g. properties[property1Name]=property1Value)
 *
 * @example
 *     {
 *       "videos" : [
 *         ...
 *       ]
 *     }
 *
 * @method getVideoByPropertiesAction
 * @static
 */
module.exports.getVideoByPropertiesAction = function(request, response, next) {
  var query = request.query;
  var sortBy = query.sortBy || 'date';
  var sortOrder = query.sortOrder == 'asc' ? -1 : 1;
  var sort = {};
  sort[sortBy] = sortOrder;

  // authorized unlimited query
  var limit = null;
  if (query.limit) {
    limit = parseInt(query.limit) || 10;
    if (limit < 1) limit = null;
  }

  var page = null;
  if (limit) {
    page = query.page || 1;
    if (page < 1) page = 1;
  }

  var wsSearch = query.properties || {};
  var searchParam = {state: 12};

  var series = [];

  // Construct MongoDb search query with parameters
  Object.keys(wsSearch).forEach(function(key) {
    series.push(function(callback) {

      // get property which name corresponding to parameter
      propertyModel.getByFilter({name: key}, function(error, prop) {
        if (error) return callback(error);

        // Error if no property corresponding
        if (!prop || prop.length == 0) return callback(errors.UNKNOWN_PROPERTY_ERROR);
        var val = wsSearch[key];

        // Build search for each existing property
        searchParam['properties.' + prop.id] = {$in: [].concat(val)};
        callback();
      });
    });
  });

  // Do series call function and execute final search
  async.series(series, function(err) {
    if (err) next(err);

    // find in mongoDb
    else videoModel.getPaginatedFilteredEntities(searchParam, limit, page, sort, true,
      function(error, entities, pagination) {
        if (error) {
          response.status(500).send(error);
        } else {
          response.send({
            videos: entities,
            pagination: pagination
          });
        }
      }
    );
  });
};

/**
 * Publishes a video.
 *
 * Expects one GET parameter :
 *  - **id** The id of the video
 *
 * Change the state of the video to published
 *
 * @example
 *     {
 *       state : 12
 *     }
 *
 * @method publishVideoAction
 * @static
 */
module.exports.publishVideoAction = function(request, response, next) {
  if (request.params.id) {
    var arrayId = request.params.id.split(',');
    videoModel.publishVideo(arrayId, function(error) {
      if (error)
        next(errors.PUBLISH_VIDEO_ERROR);
      else
        response.send({
          state: VideoModel.PUBLISHED_STATE
        });
    });
  }

  // Missing type and / or id of the video
  else
    next(errors.PUBLISH_VIDEO_MISSING_PARAMETERS);
};

/**
 * Unpublishes a video.
 *
 * Expects one GET parameter :
 *  - **id** The id of the video
 *
 * Change the state of the video to unpublished.
 *
 * @example
 *     {
 *       state : 11
 *     }
 *
 * @method unpublishVideoAction
 * @static
 */
module.exports.unpublishVideoAction = function(request, response, next) {
  if (request.params.id) {
    var arrayId = request.params.id.split(',');
    videoModel.unpublishVideo(arrayId, function(error) {
      if (error)
        next(errors.UNPUBLISH_VIDEO_ERROR);
      else
        response.send({
          state: VideoModel.READY_STATE
        });
    });
  }

  // Missing type and / or id of the video
  else
    next(errors.UNPUBLISH_VIDEO_MISSING_PARAMETERS);
};
<|endoftext|>


<commit_before>import Vue from 'vue';
import Vuex from 'vuex';
import firebase from 'firebase';
import { emailIsWhitelisted, addIdToItems } from '../utils';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    user: null,
    error: null,
    challenges: {
      areLoading: true,
      items: [],
      ref: null,
    },
    solutions: {
      areLoading: true,
      items: [],
      ref: null,
    },
  },
  getters: {
    challenges: state => [...state.challenges.items].sort((a, b) => b.createdAt - a.createdAt),
    solutions: state => [...state.solutions.items].sort((a, b) => a.createdAt - b.createdAt),
  },
  mutations: {
    setUser(state, payload) {
      state.user = payload;
    },
    setError(state, payload) {
      state.error = payload;
    },
    setChallenges(state, payload) {
      state.challenges = payload;
    },
    setSolutions(state, payload) {
      state.solutions = payload;
    },
    clearSolutions(state) {
      state.solutions.ref.off();
      state.solutions = {
        areLoading: true,
        items: [],
        ref: null,
      };
    },
  },
  actions: {
    validateUser({ commit, dispatch }, payload) {
      if (emailIsWhitelisted(payload.email)) {
        const { displayName: name, email, photoURL: photoUrl, uid: id } = payload;
        const user = { name, email, photoUrl };
        firebase.database().ref(`/users/${id}`).set(user);
        commit('setUser', { ...user, id });
        commit('setError', null);
      } else {
        dispatch('signOut', 'You must be part of the "umich.edu" domain to use this app.');
      }
    },
    signIn({ dispatch }) {
      const google = new firebase.auth.GoogleAuthProvider();
      firebase.auth()
        .signInWithPopup(google)
        .then(({ user }) => { dispatch('validateUser', user); })
        .catch(() => {});
    },
    signOut({ commit }, payload) {
      firebase.auth().signOut();
      commit('setUser', null);
      const error = typeof payload === 'string' ? payload : null;
      commit('setError', error);
    },
    loadChallenges({ commit }) {
      const ref = firebase.database().ref('challenges');
      ref.on('value', (snapshot) => {
        commit('setChallenges', {
          items: addIdToItems(snapshot.val() || {}),
          areLoading: false,
          ref,
        });
      });
    },
    loadSolutions({ commit }, challengeId) {
      const ref = firebase.database().ref(`solutions/${challengeId}`);
      ref.on('value', (snapshot) => {
        commit('setSolutions', {
          items: addIdToItems(snapshot.val() || {}),
          areLoading: false,
          ref,
        });
      });
    },
  },
});
<commit_msg>Don't save email as part of user data<commit_after>import Vue from 'vue';
import Vuex from 'vuex';
import firebase from 'firebase';
import { emailIsWhitelisted, addIdToItems } from '../utils';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    user: null,
    error: null,
    challenges: {
      areLoading: true,
      items: [],
      ref: null,
    },
    solutions: {
      areLoading: true,
      items: [],
      ref: null,
    },
  },
  getters: {
    challenges: state => [...state.challenges.items].sort((a, b) => b.createdAt - a.createdAt),
    solutions: state => [...state.solutions.items].sort((a, b) => a.createdAt - b.createdAt),
  },
  mutations: {
    setUser(state, payload) {
      state.user = payload;
    },
    setError(state, payload) {
      state.error = payload;
    },
    setChallenges(state, payload) {
      state.challenges = payload;
    },
    setSolutions(state, payload) {
      state.solutions = payload;
    },
    clearSolutions(state) {
      state.solutions.ref.off();
      state.solutions = {
        areLoading: true,
        items: [],
        ref: null,
      };
    },
  },
  actions: {
    validateUser({ commit, dispatch }, payload) {
      if (emailIsWhitelisted(payload.email)) {
        const { displayName: name, photoURL: photoUrl, uid: id } = payload;
        const user = { name, photoUrl };
        firebase.database().ref(`/users/${id}`).set(user);
        commit('setUser', { ...user, id });
        commit('setError', null);
      } else {
        dispatch('signOut', 'You must be part of the "umich.edu" domain to use this app.');
      }
    },
    signIn({ dispatch }) {
      const google = new firebase.auth.GoogleAuthProvider();
      firebase.auth()
        .signInWithPopup(google)
        .then(({ user }) => { dispatch('validateUser', user); })
        .catch(() => {});
    },
    signOut({ commit }, payload) {
      firebase.auth().signOut();
      commit('setUser', null);
      const error = typeof payload === 'string' ? payload : null;
      commit('setError', error);
    },
    loadChallenges({ commit }) {
      const ref = firebase.database().ref('challenges');
      ref.on('value', (snapshot) => {
        commit('setChallenges', {
          items: addIdToItems(snapshot.val() || {}),
          areLoading: false,
          ref,
        });
      });
    },
    loadSolutions({ commit }, challengeId) {
      const ref = firebase.database().ref(`solutions/${challengeId}`);
      ref.on('value', (snapshot) => {
        commit('setSolutions', {
          items: addIdToItems(snapshot.val() || {}),
          areLoading: false,
          ref,
        });
      });
    },
  },
});
<|endoftext|>


<commit_before>/*global $: false, kanso: true */

/**
 * Contains functions for querying and storing data in CouchDB.
 *
 * @module
 */

/**
 * Module dependencies
 */

var core = require('./db.core'),
    utils = require('kanso/utils'),
    _ = require('underscore')._;

/**
 * Returns the authentication database for the current user's session.
 *
 * @name authDb(callback)
 * @param {Function} callback
 * @api public
 */

var authDb = function(callback) {
    core.request({
        type: "GET",
        url: "/_session"
    },
    function (err, resp) {
        if(err) {
            callback(err, null);
        } else {
            callback(null, resp.info.authentication_db);
        }
    });
};

/**
 * Deletes an existing user document, given its username. You
 * must be logged in as an administrative user for this function
 * to succeed.
 *
 * @name deleteUser(username, callback)
 * @param {String} username
 * @param {Function} callback
 * @api public
 */

exports.deleteUser = function (username, callback) {
    var id = 'org.couchdb.user:' + username;

    authDb(function (err, authDb) {
        if (err) { callback(err); }

        core.request({
            type: 'GET',
            url: '/' + core.encode(authDb) + '/' + core.encode(id),
            contentType: 'application/json'
        }, function(err, user) {
            if(err) { callback(err); }

            core.request({
                type: 'GET',
                url: '/_config/admins/' + username,
                contentType: 'application/json'
            }, function(err, admin) {
                if(!err) {
                    core.request({
                        type: 'DELETE',
                        url: '/_config/admins/' + username,
                        contentType: 'application/json'
                    }, function() {});
                }
            });

            core.request({
                type: 'DELETE',
                url: '/' + core.encode(authDb) + '/' + core.encode(id) + '?rev=' + core.encode(user._rev),
                contentType: 'application/json'
            }, callback);
        });
    });
};

/**
 * Lists users.
 *
 * @name listUsers(callback)
 * @param {Function} callback
 * @api public
 */

exports.listUsers = function(callback, options) {
    if(options && options.include_docs) {
        var include_docs = 'true';
    } else {
        var include_docs = 'false';
    }

    authDb(function (err, authDb) {
        if (err) {
            callback(err, null);
        }
        var req = {
            type: 'GET',
            url: '/' + core.encode(authDb) + '/_all_docs?include_docs=' + include_docs,
            contentType: 'application/json'
        };
        core.request(req, function(err, result) {
            if(err) {
                callback(err, null);
            } else {
                var users = _(result.rows).select(function(row) {
                    return row.id.match(/org\.couchdb\.user/);
                });
                callback(null, users);
            }
        });
    });
};<commit_msg>minor fixes to increase code quality of deleteUser function<commit_after>/*global $: false, kanso: true */

/**
 * Contains functions for querying and storing data in CouchDB.
 *
 * @module
 */

/**
 * Module dependencies
 */

var core = require('./db.core'),
    utils = require('kanso/utils'),
    _ = require('underscore')._;

/**
 * Returns the authentication database for the current user's session.
 *
 * @name authDb(callback)
 * @param {Function} callback
 * @api public
 */

var authDb = function(callback) {
    core.request({
        type: "GET",
        url: "/_session"
    },
    function (err, resp) {
        if(err) {
            callback(err, null);
        } else {
            callback(null, resp.info.authentication_db);
        }
    });
};

/**
 * Deletes an existing user document, given its username. You
 * must be logged in as an administrative user for this function
 * to succeed.
 *
 * @name deleteUser(username, callback)
 * @param {String} username
 * @param {Function} callback
 * @api public
 */

exports.deleteUser = function (username, callback) {
    var id = 'org.couchdb.user:' + username;

    authDb(function (err, authDb) {
        if (err) { return callback(err); }

        core.request({
            type: 'GET',
            url: '/' + core.encode(authDb) + '/' + core.encode(id),
            contentType: 'application/json'
        }, function(err, user) {
            if(err) { return callback(err); }

            core.request({
                type: 'GET',
                url: '/_config/admins/' + username,
                contentType: 'application/json'
            }, function(err, admin) {
                if(err) {
                    if(err.status !== 404) {
                        return callback(err);
                    }
                } else {
                    core.request({
                        type: 'DELETE',
                        url: '/_config/admins/' + username,
                        contentType: 'application/json'
                    }, function() {});
                }

                core.request({
                    type: 'DELETE',
                    url: '/' + core.encode(authDb) + '/' + core.encode(id) + '?rev=' + core.encode(user._rev),
                    contentType: 'application/json'
                }, callback);
            });
        });
    });
};

/**
 * Lists users.
 *
 * @name listUsers(callback)
 * @param {Function} callback
 * @api public
 */

exports.listUsers = function(callback, options) {
    if(options && options.include_docs) {
        var include_docs = 'true';
    } else {
        var include_docs = 'false';
    }

    authDb(function (err, authDb) {
        if (err) {
            callback(err, null);
        }
        var req = {
            type: 'GET',
            url: '/' + core.encode(authDb) + '/_all_docs?include_docs=' + include_docs,
            contentType: 'application/json'
        };
        core.request(req, function(err, result) {
            if(err) {
                callback(err, null);
            } else {
                var users = _(result.rows).select(function(row) {
                    return row.id.match(/org\.couchdb\.user/);
                });
                callback(null, users);
            }
        });
    });
};<|endoftext|>


<commit_before>/*
 This file is a part of libertysoil.org website
 Copyright (C) 2015  Loki Education (Social Enterprise)

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU Affero General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU Affero General Public License for more details.

 You should have received a copy of the GNU Affero General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
import i from 'immutable';
import _ from 'lodash';

import * as a from '../actions';

const initialState = i.Map({});

const cleanUser = user => {
  let users = {};

  if ('following' in user) {
    for (let followed_user of user.following) {
      users[followed_user.id] = followed_user;
    }

    user = _.cloneDeep(user);
    delete user.following;
  }

  if ('followers' in user) {
    for (let follower of user.followers) {
      users[follower.id] = follower;
    }

    user = _.cloneDeep(user);
    delete user.following;
  }

  users[user.id] = user;

  return users;
};

export default function reducer(state=initialState, action) {
  switch (action.type) {
    case a.ADD_USER:
    case a.SET_CURRENT_USER:
    {
      state = state.merge(i.fromJS(cleanUser(action.user)));
      break;
    }

    case a.ADD_POST:
    case a.ADD_POST_TO_RIVER: {
      const user = action.post.user;
      state = state.set(user.id, i.fromJS(user));

      break;
    }

    case a.SET_POSTS_TO_RIVER:
    case a.SET_POSTS_TO_LIKES_RIVER:
    case a.SET_POSTS_TO_FAVOURITES_RIVER:
    case a.SET_TAG_POSTS: {
      let users = _.indexBy(_.unique(action.posts.map(post => post.user), 'id'), 'id');
      state = state.merge(i.fromJS(users));
    }
  }

  return state;
}
<commit_msg>Better if condition<commit_after>/*
 This file is a part of libertysoil.org website
 Copyright (C) 2015  Loki Education (Social Enterprise)

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU Affero General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU Affero General Public License for more details.

 You should have received a copy of the GNU Affero General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
import i from 'immutable';
import _ from 'lodash';

import * as a from '../actions';

const initialState = i.Map({});

const cleanUser = user => {
  let users = {};

  if (user.following) {
    for (let followed_user of user.following) {
      users[followed_user.id] = followed_user;
    }

    user = _.cloneDeep(user);
    delete user.following;
  }

  if (user.followers) {
    for (let follower of user.followers) {
      users[follower.id] = follower;
    }

    user = _.cloneDeep(user);
    delete user.following;
  }

  users[user.id] = user;

  return users;
};

export default function reducer(state=initialState, action) {
  switch (action.type) {
    case a.ADD_USER:
    case a.SET_CURRENT_USER:
    {
      state = state.merge(i.fromJS(cleanUser(action.user)));
      break;
    }

    case a.ADD_POST:
    case a.ADD_POST_TO_RIVER: {
      const user = action.post.user;
      state = state.set(user.id, i.fromJS(user));

      break;
    }

    case a.SET_POSTS_TO_RIVER:
    case a.SET_POSTS_TO_LIKES_RIVER:
    case a.SET_POSTS_TO_FAVOURITES_RIVER:
    case a.SET_TAG_POSTS: {
      let users = _.indexBy(_.unique(action.posts.map(post => post.user), 'id'), 'id');
      state = state.merge(i.fromJS(users));
    }
  }

  return state;
}
<|endoftext|>


<commit_before>import _ from 'lodash';
let finiteStateMachine = require('javascript-state-machine');

class memoryCmpCtrl {
  /* @ngInject */
  constructor($log, $element) {
    this._log = $log;
    this.$element = $element;
    this.memoryCards = [
      {
        id: 1,
        background: "red",
        state: 'covered'
      },
      {
        id: 1,
        background: "red",
        state: 'covered'
      },
      {
        id: 2,
        background: "yellow",
        state: 'covered'
      },
      {
        id: 2,
        background: "yellow",
        state: 'covered'
      },
      {
        id: 3,
        background: "blue",
        state: 'covered'
      },
      {
        id: 3,
        background: "blue",
        state: 'covered'
      },
      {
        id: 4,
        background: "green",
        state: 'covered'
      },
      {
        id: 4,
        background: "green",
        state: 'covered'
      },
    ];
    this.memoryCardsRandom = _.shuffle(this.memoryCards);

    this.firstTurn = undefined;
    this.secondTurn = undefined;

    this.fsm = finiteStateMachine.StateMachine.create({
      initial: 'pristine',
      events: [
        {name: 'firstTurn', from: ['pristine'], to: 'firstTurned'},
        {name: 'secondTurn', from: ['firstTurned'], to: 'secondTurned'},
        {name: 'proceede', from: ['secondTurned'], to: 'pristine'},
        {name: 'win', from: ['secondTurned'], to: 'win'},
      ],
      //callbacks: {
        //onmatch: this._onmatch,
      //}
    });
  }

  turnCard(card){
    if (card.state==='covered') {
      switch(this.fsm.current) {
        case 'pristine':
          card.state = 'turned';
          this.firstTurn = card;
          this.fsm.firstTurn();
          break;
        case 'firstTurned':
          card.state = 'turned';
          this.secondTurn = card;
          this.fsm.secondTurn();
          break;
      }
      this.evaluateState();
    }
  }

  //_firstTurn(){
  //}

  evaluateState( ){
    this._log.debug('evaluating state...');
    switch(this.fsm.current) {
      case 'secondTurned':
        if(this.firstTurn.id === this.secondTurn.id){
          this._log.debug('a match!');
          this.firstTurn.state = 'matched';
          this.secondTurn.state = 'matched';
          this._clearSelection();
          this.fsm.proceede();
        }
        else {
          this.firstTurn.state = 'covered';
          this.secondTurn.state = 'covered';
          this._clearSelection();
          this.fsm.proceede();
        }
        break;
    }
  }

  _clearSelection(){
    this.firstTurn = undefined;
    this.secondTurn = undefined;
  }

}

let memoryCmp = {
  controller: 'memoryCmpCtrl',
  template: require('./component.jade')(),
  bindings: {
  },
};

const MODULE_NAME = 'app.views.memoryCmp.component';

angular.module(MODULE_NAME, [
])
  .component('memoryCmp', memoryCmp)
  .controller('memoryCmpCtrl', memoryCmpCtrl);

export default MODULE_NAME;
<commit_msg>timeout after no match<commit_after>import _ from 'lodash';
let finiteStateMachine = require('javascript-state-machine');

class memoryCmpCtrl {
  /* @ngInject */
  constructor($log, $element, $timeout) {
    this._log = $log;
    this.$element = $element;
    this.$timeout = $timeout;
    this.memoryCards = [
      {
        id: 1,
        background: "red",
        state: 'covered'
      },
      {
        id: 1,
        background: "red",
        state: 'covered'
      },
      {
        id: 2,
        background: "yellow",
        state: 'covered'
      },
      {
        id: 2,
        background: "yellow",
        state: 'covered'
      },
      {
        id: 3,
        background: "blue",
        state: 'covered'
      },
      {
        id: 3,
        background: "blue",
        state: 'covered'
      },
      {
        id: 4,
        background: "green",
        state: 'covered'
      },
      {
        id: 4,
        background: "green",
        state: 'covered'
      },
    ];
    this.memoryCardsRandom = _.shuffle(this.memoryCards);

    this.firstTurn = undefined;
    this.secondTurn = undefined;

    this.fsm = finiteStateMachine.StateMachine.create({
      initial: 'pristine',
      events: [
        {name: 'firstTurn', from: ['pristine'], to: 'firstTurned'},
        {name: 'secondTurn', from: ['firstTurned'], to: 'secondTurned'},
        {name: 'proceede', from: ['secondTurned'], to: 'pristine'},
        {name: 'win', from: ['secondTurned'], to: 'win'},
      ],
      //callbacks: {
        //onmatch: this._onmatch,
      //}
    });
  }

  turnCard(card){
    if (card.state==='covered') {
      switch(this.fsm.current) {
        case 'pristine':
          card.state = 'turned';
          this.firstTurn = card;
          this.fsm.firstTurn();
          break;
        case 'firstTurned':
          card.state = 'turned';
          this.secondTurn = card;
          this.fsm.secondTurn();
          break;
      }
      this.evaluateState();
    }
  }

  //_firstTurn(){
  //}

  evaluateState( ){
    this._log.debug('evaluating state...');
    switch(this.fsm.current) {
      case 'secondTurned':
        if(this.firstTurn.id === this.secondTurn.id){
          this._log.debug('a match!');
          this.firstTurn.state = 'matched';
          this.secondTurn.state = 'matched';
          this._clearSelection();
          this.fsm.proceede();
        }
        else {
          let callback = () => {
            this.firstTurn.state = 'covered';
            this.secondTurn.state = 'covered';
            this._clearSelection();
            this.fsm.proceede();
          }
          this.$timeout(callback, 2000);
        }
        break;
    }
  }

  _clearSelection(){
    this.firstTurn = undefined;
    this.secondTurn = undefined;
  }

}

let memoryCmp = {
  controller: 'memoryCmpCtrl',
  template: require('./component.jade')(),
  bindings: {
  },
};

const MODULE_NAME = 'app.views.memoryCmp.component';

angular.module(MODULE_NAME, [
])
  .component('memoryCmp', memoryCmp)
  .controller('memoryCmpCtrl', memoryCmpCtrl);

export default MODULE_NAME;
<|endoftext|>


<commit_before>define(['./stream', '../functional/isDefined'], function (Stream, isDefined, undefined) {
    'use strict';

    /**
     * @param {Stream} stream
     * @return {Stream}
     */
    return function last(stream) {
        var lastValue;

        stream.on(function(value) {
            lastValue = value;
            return Stream.stop;
        });

        return new stream.constructor(function(sinkValue, sinkError, sinkComplete) {
            if (isDefined(lastValue)) {
                sinkValue(lastValue);
            }

            stream.on(function (value) {
                sinkValue(value);
                lastValue = value;
            }, sinkError, function () {
                lastValue = undefined;
                sinkComplete();
            });
        });
    };
});
<commit_msg>Update last.js stream<commit_after>define(['./stream', '../functional/isDefined'], function (Stream, isDefined) {
    'use strict';

    /**
     * @param {Stream} stream
     * @return {Stream}
     */
    return function last(stream) {
        var lastValue;

        stream.on(function(value) {
            lastValue = value;
            return Stream.stop;
        });

        return new stream.constructor(function(sinkValue, sinkError, sinkComplete) {
            var received;

            if (!isDefined(received) && isDefined(lastValue)) {
                received = true;
                sinkValue(lastValue);
            }

            stream.on(function (value) {
                lastValue = value;
                sinkValue(value);
            }, sinkError, function () {
                sinkComplete();
            });
        });
    };
});
<|endoftext|>


<commit_before>import { registerFragment } from 'meteor/vulcan:core';

registerFragment(`
  fragment UsersAdmin on User {
    _id
    username
    createdAt
    isAdmin
    displayName
    email
    slug
    groups
    services

    karma
  }
`);

registerFragment(`
  fragment conversationsListFragment on Conversation {
    _id
    title
    createdAt
    latestActivity
    participantIds
    participants {
      ...UsersMinimumInfo
    }
    archivedByIds
    messageCount
  }
`);

registerFragment(`
  fragment newConversationFragment on Conversation {
    _id
    title
    participantIds
  }
`);

registerFragment(`
  fragment messageListFragment on Message {
    _id
    user {
      ...UsersMinimumInfo
    }
    contents {
      html
    }
    createdAt
    conversationId
  }
`);

registerFragment(`
  fragment editTitle on Conversation {
    _id
    title
  }
`);

registerFragment(`
  fragment NotificationsList on Notification {
    _id
    userId
    createdAt
    link
    message
    type
    viewed
  }
`);

registerFragment(`
  fragment UsersCurrent on User {
    ...UsersMinimumInfo

    _id
    username
    createdAt
    isAdmin
    displayName
    email
    slug
    groups
    services
    pageUrl
    locale
    defaultToCKEditor
    voteBanned
    banned
    isReviewed
    nullifyVotes
    hideIntercom
    hideNavigationSidebar
    currentFrontpageFilter
    allPostsTimeframe
    allPostsSorting
    allPostsFilter
    allPostsShowLowKarma
    allPostsOpenSettings
    lastNotificationsCheck
    groups
    bannedUserIds
    moderationStyle
    moderationGuidelines {
      ...RevisionEdit
    }
    markDownPostEditor
    commentSorting
    location
    googleLocation
    mongoLocation
    mapLocation
    mapLocationSet
    mapMarkerText
    htmlMapMarkerText
    nearbyEventsNotifications
    nearbyEventsNotificationsLocation
    nearbyEventsNotificationsRadius
    nearbyPeopleNotificationThreshold
    hideFrontpageMap
    emailSubscribedToCurated
    unsubscribeFromAll
    emails
    whenConfirmationEmailSent
    noCollapseCommentsFrontpage
    noCollapseCommentsPosts
    noSingleLineComments
    karmaChangeNotifierSettings
    karmaChangeLastOpened
    shortformFeedId
    viewUnreviewedComments
    sunshineShowNewUserContent
    recommendationSettings

    auto_subscribe_to_my_posts
    auto_subscribe_to_my_comments
    autoSubscribeAsOrganizer
  }
`);

registerFragment(`
  fragment UserKarmaChanges on User {
    _id
    karmaChanges {
      totalChange
      updateFrequency
      startDate
      endDate
      nextBatchDate
      posts {
        _id
        scoreChange
        title
        slug
      }
      comments {
        _id
        scoreChange
        description
        postId
      }
    }
  }
`);

registerFragment(`
  fragment RSSFeedMinimumInfo on RSSFeed {
    _id
    userId
    user {
      ...UsersMinimumInfo
    }
    createdAt
    ownedByUser
    displayFullContent
    nickname
    url
  }
`);

registerFragment(`
  fragment CommentStats on Comment {
    currentUserVotes{
      ...VoteFragment
    }
    baseScore
    score
  }
`);

registerFragment(`
  fragment DeletedCommentsMetaData on Comment {
    _id
    deleted
    deletedDate
    deletedByUser {
      _id
      displayName
    }
    deletedReason
    deletedPublic
  }
`)

registerFragment(`
  fragment DeletedCommentsModerationLog on Comment {
    ...DeletedCommentsMetaData
    user {
      ...UsersMinimumInfo
    }
    post {
      title
      slug
      _id
    }
  }
`)

registerFragment(`
  fragment UsersBannedFromUsersModerationLog on User {
    _id
    slug
    displayName
    bannedUserIds
  }
`)

registerFragment(`
  fragment SelectCommentsList on Comment {
    ...CommentsList
    post {
      title
      _id
      slug
    }
  }
`);

registerFragment(`
  fragment UsersList on User {
    ...UsersMinimumInfo
    karma
  }
`);

registerFragment(`
  fragment SunshineUsersList on User {
    ...UsersMinimumInfo
    karma
    bio
    htmlBio
    createdAt
    email
    commentCount
    postCount
    voteCount
    smallUpvoteCount
    bigUpvoteCount
    smallDownvoteCount
    bigDownvoteCount
    banned
    reviewedByUserId
    signUpReCaptchaRating
  }
`);

registerFragment(`
  fragment newRSSFeedFragment on RSSFeed {
    _id
    userId
    createdAt
    ownedByUser
    displayFullContent
    nickname
    url
    status
  }
`);

registerFragment(`
  fragment RSSFeedMutationFragment on RSSFeed {
    _id
    userId
    ownedByUser
    displayFullContent
    nickname
    url
  }
`);

registerFragment(`
  fragment newEventFragment on LWEvent {
    _id
    createdAt
    userId
    name
    important
    properties
    intercom
  }
`);

registerFragment(`
  fragment lastEventFragment on LWEvent {
    _id
    createdAt
    documentId
    userId
    name
    important
    properties
    intercom
  }
`);

registerFragment(`
  fragment commentWithContextFragment on Comment {
    # example-forum
    _id
    parentCommentId
    topLevelCommentId
    contents {
      ...RevisionDisplay
    }
    postedAt
    # vulcan:users
    userId
    user {
      ...UsersMinimumInfo
    }
    # example-forum
    # vulcan:voting
    currentUserVotes{
      ...VoteFragment
    }
    baseScore
    score
  }
`);

registerFragment(`
  fragment commentInlineFragment on Comment {
    # example-forum
    _id
    contents {
      ...RevisionDisplay
    }
    # vulcan:users
    userId
    user {
      ...UsersMinimumInfo
    }
  }
`);

registerFragment(`
  fragment UsersMinimumInfo on User {
    # vulcan:users
    _id
    slug
    oldSlugs
    createdAt
    username
    displayName
    fullName
    karma
    afKarma
    deleted
    groups
    htmlBio
    postCount
    commentCount
    sequenceCount
    afPostCount
    afCommentCount
    beta
    spamRiskScore
  }
`);

registerFragment(`
  fragment UsersProfile on User {
    # vulcan:users
    ...UsersMinimumInfo
    createdAt
    isAdmin
    bio
    htmlBio
    website
    groups
    # example-forum
    postCount
    afPostCount
    frontpagePostCount
    # example-forum
    commentCount
    sequenceCount
    afCommentCount
    sequenceCount
    afSequenceCount
    afSequenceDraftCount
    sequenceDraftCount
    moderationStyle
    moderationGuidelines {
      ...RevisionDisplay
    }
    bannedUserIds
    location
    googleLocation
    mapLocation
    mapLocationSet
    mapMarkerText
    htmlMapMarkerText
    mongoLocation
    shortformFeedId
    viewUnreviewedComments
    auto_subscribe_to_my_posts
    auto_subscribe_to_my_comments
    autoSubscribeAsOrganizer
    sunshineShowNewUserContent
    defaultToCKEditor
  }
`);

registerFragment(`
  fragment UsersMapEntry on User {
    # vulcan:users
    ...UsersMinimumInfo
    createdAt
    isAdmin
    groups
    # example-forum
    location
    googleLocation
    mapLocation
    mapLocationSet
    mapMarkerText
    htmlMapMarkerText
    mongoLocation
  }
`);

registerFragment(`
  fragment UsersEdit on User {
    ...UsersProfile
    # Moderation Guidelines editor information
    moderationGuidelines {
      ...RevisionEdit
    }

    # UI Settings
    markDownPostEditor
    hideIntercom
    commentSorting
    currentFrontpageFilter
    noCollapseCommentsPosts
    noCollapseCommentsFrontpage
    noSingleLineComments
    sunshineShowNewUserContent

    # Emails
    email
    whenConfirmationEmailSent
    emailSubscribedToCurated
    unsubscribeFromAll

    # Moderation
    moderatorAssistance
    collapseModerationGuidelines
    bannedUserIds
    bannedPersonalUserIds

    # Ban & Purge
    voteBanned
    nullifyVotes
    deleteContent
    banned

    # Name
    username
    displayName
    fullName

    # Location
    mongoLocation
    googleLocation
    location

    # Admin & Review
    reviewedByUserId

    # Alignment Forum
    reviewForAlignmentForumUserId
    groups
    afApplicationText
    afSubmittedApplication

    # Karma Settings
    karmaChangeLastOpened
    karmaChangeNotifierSettings

    recommendationSettings

    notificationCommentsOnSubscribedPost
    notificationRepliesToMyComments
    notificationPostsInGroups

    hideFrontpageMap
  }
`)

registerFragment(`
  fragment unclaimedReportsList on Report {
    _id
    userId
    user {
      _id
      displayName
      username
      slug
    }
    commentId
    comment {
      _id
      userId
      user {
        ...UsersMinimumInfo
      }
      baseScore
      contents {
        ...RevisionDisplay
      }
      postedAt
      deleted
      postId
      post {
        _id
        slug
        title
        isEvent
      }
    }
    postId
    post {
      _id
      slug
      title
      isEvent
      contents {
        ...RevisionDisplay
      }
    }
    closedAt
    createdAt
    claimedUserId
    claimedUser {
      _id
      displayName
      username
      slug
    }
    link
    description
    reportedAsSpam
    markedAsSpam
  }
`);

registerFragment(`
  fragment VoteMinimumInfo on Vote {
    _id
    voteType
  }
`);

registerFragment(`
  fragment VoteFragment on Vote {
    _id
    voteType
    power
  }
`);

registerFragment(`
  fragment WithVotePost on Post {
    __typename
    _id
    currentUserVotes{
      _id
      voteType
      power
    }
    baseScore
    score
    afBaseScore
    voteCount
  }
`);

registerFragment(`
  fragment WithVoteComment on Comment {
    __typename
    _id
    currentUserVotes{
      _id
      voteType
      power
    }
    baseScore
    score
    afBaseScore
    voteCount
  }
`);

//
// example-forum migrated fragments
//

// note: fragment used by default on the UsersProfile fragment
registerFragment(/* GraphQL */`
  fragment VotedItem on Vote {
    # vulcan:voting
    documentId
    power
    votedAt
  }
`);

registerFragment(`
  fragment RevisionDisplay on Revision {
    version
    updateType
    editedAt
    userId
    html
    wordCount
    htmlHighlight
    plaintextDescription
  }
`)

registerFragment(`
  fragment RevisionEdit on Revision {
    version
    updateType
    editedAt
    userId
    originalContents
    html
    markdown
    draftJS
    ckEditorMarkup
    wordCount
    htmlHighlight
    plaintextDescription
  }
`)
<commit_msg>Add notification types to fragment<commit_after>import { registerFragment } from 'meteor/vulcan:core';

registerFragment(`
  fragment UsersAdmin on User {
    _id
    username
    createdAt
    isAdmin
    displayName
    email
    slug
    groups
    services

    karma
  }
`);

registerFragment(`
  fragment conversationsListFragment on Conversation {
    _id
    title
    createdAt
    latestActivity
    participantIds
    participants {
      ...UsersMinimumInfo
    }
    archivedByIds
    messageCount
  }
`);

registerFragment(`
  fragment newConversationFragment on Conversation {
    _id
    title
    participantIds
  }
`);

registerFragment(`
  fragment messageListFragment on Message {
    _id
    user {
      ...UsersMinimumInfo
    }
    contents {
      html
    }
    createdAt
    conversationId
  }
`);

registerFragment(`
  fragment editTitle on Conversation {
    _id
    title
  }
`);

registerFragment(`
  fragment NotificationsList on Notification {
    _id
    userId
    createdAt
    link
    message
    type
    viewed
  }
`);

registerFragment(`
  fragment UsersCurrent on User {
    ...UsersMinimumInfo

    _id
    username
    createdAt
    isAdmin
    displayName
    email
    slug
    groups
    services
    pageUrl
    locale
    defaultToCKEditor
    voteBanned
    banned
    isReviewed
    nullifyVotes
    hideIntercom
    hideNavigationSidebar
    currentFrontpageFilter
    allPostsTimeframe
    allPostsSorting
    allPostsFilter
    allPostsShowLowKarma
    allPostsOpenSettings
    lastNotificationsCheck
    groups
    bannedUserIds
    moderationStyle
    moderationGuidelines {
      ...RevisionEdit
    }
    markDownPostEditor
    commentSorting
    location
    googleLocation
    mongoLocation
    mapLocation
    mapLocationSet
    mapMarkerText
    htmlMapMarkerText
    nearbyEventsNotifications
    nearbyEventsNotificationsLocation
    nearbyEventsNotificationsRadius
    nearbyPeopleNotificationThreshold
    hideFrontpageMap
    emailSubscribedToCurated
    unsubscribeFromAll
    emails
    whenConfirmationEmailSent
    noCollapseCommentsFrontpage
    noCollapseCommentsPosts
    noSingleLineComments
    karmaChangeNotifierSettings
    karmaChangeLastOpened
    shortformFeedId
    viewUnreviewedComments
    sunshineShowNewUserContent
    recommendationSettings

    auto_subscribe_to_my_posts
    auto_subscribe_to_my_comments
    autoSubscribeAsOrganizer
  }
`);

registerFragment(`
  fragment UserKarmaChanges on User {
    _id
    karmaChanges {
      totalChange
      updateFrequency
      startDate
      endDate
      nextBatchDate
      posts {
        _id
        scoreChange
        title
        slug
      }
      comments {
        _id
        scoreChange
        description
        postId
      }
    }
  }
`);

registerFragment(`
  fragment RSSFeedMinimumInfo on RSSFeed {
    _id
    userId
    user {
      ...UsersMinimumInfo
    }
    createdAt
    ownedByUser
    displayFullContent
    nickname
    url
  }
`);

registerFragment(`
  fragment CommentStats on Comment {
    currentUserVotes{
      ...VoteFragment
    }
    baseScore
    score
  }
`);

registerFragment(`
  fragment DeletedCommentsMetaData on Comment {
    _id
    deleted
    deletedDate
    deletedByUser {
      _id
      displayName
    }
    deletedReason
    deletedPublic
  }
`)

registerFragment(`
  fragment DeletedCommentsModerationLog on Comment {
    ...DeletedCommentsMetaData
    user {
      ...UsersMinimumInfo
    }
    post {
      title
      slug
      _id
    }
  }
`)

registerFragment(`
  fragment UsersBannedFromUsersModerationLog on User {
    _id
    slug
    displayName
    bannedUserIds
  }
`)

registerFragment(`
  fragment SelectCommentsList on Comment {
    ...CommentsList
    post {
      title
      _id
      slug
    }
  }
`);

registerFragment(`
  fragment UsersList on User {
    ...UsersMinimumInfo
    karma
  }
`);

registerFragment(`
  fragment SunshineUsersList on User {
    ...UsersMinimumInfo
    karma
    bio
    htmlBio
    createdAt
    email
    commentCount
    postCount
    voteCount
    smallUpvoteCount
    bigUpvoteCount
    smallDownvoteCount
    bigDownvoteCount
    banned
    reviewedByUserId
    signUpReCaptchaRating
  }
`);

registerFragment(`
  fragment newRSSFeedFragment on RSSFeed {
    _id
    userId
    createdAt
    ownedByUser
    displayFullContent
    nickname
    url
    status
  }
`);

registerFragment(`
  fragment RSSFeedMutationFragment on RSSFeed {
    _id
    userId
    ownedByUser
    displayFullContent
    nickname
    url
  }
`);

registerFragment(`
  fragment newEventFragment on LWEvent {
    _id
    createdAt
    userId
    name
    important
    properties
    intercom
  }
`);

registerFragment(`
  fragment lastEventFragment on LWEvent {
    _id
    createdAt
    documentId
    userId
    name
    important
    properties
    intercom
  }
`);

registerFragment(`
  fragment commentWithContextFragment on Comment {
    # example-forum
    _id
    parentCommentId
    topLevelCommentId
    contents {
      ...RevisionDisplay
    }
    postedAt
    # vulcan:users
    userId
    user {
      ...UsersMinimumInfo
    }
    # example-forum
    # vulcan:voting
    currentUserVotes{
      ...VoteFragment
    }
    baseScore
    score
  }
`);

registerFragment(`
  fragment commentInlineFragment on Comment {
    # example-forum
    _id
    contents {
      ...RevisionDisplay
    }
    # vulcan:users
    userId
    user {
      ...UsersMinimumInfo
    }
  }
`);

registerFragment(`
  fragment UsersMinimumInfo on User {
    # vulcan:users
    _id
    slug
    oldSlugs
    createdAt
    username
    displayName
    fullName
    karma
    afKarma
    deleted
    groups
    htmlBio
    postCount
    commentCount
    sequenceCount
    afPostCount
    afCommentCount
    beta
    spamRiskScore
  }
`);

registerFragment(`
  fragment UsersProfile on User {
    # vulcan:users
    ...UsersMinimumInfo
    createdAt
    isAdmin
    bio
    htmlBio
    website
    groups
    # example-forum
    postCount
    afPostCount
    frontpagePostCount
    # example-forum
    commentCount
    sequenceCount
    afCommentCount
    sequenceCount
    afSequenceCount
    afSequenceDraftCount
    sequenceDraftCount
    moderationStyle
    moderationGuidelines {
      ...RevisionDisplay
    }
    bannedUserIds
    location
    googleLocation
    mapLocation
    mapLocationSet
    mapMarkerText
    htmlMapMarkerText
    mongoLocation
    shortformFeedId
    viewUnreviewedComments
    auto_subscribe_to_my_posts
    auto_subscribe_to_my_comments
    autoSubscribeAsOrganizer
    sunshineShowNewUserContent
    defaultToCKEditor
  }
`);

registerFragment(`
  fragment UsersMapEntry on User {
    # vulcan:users
    ...UsersMinimumInfo
    createdAt
    isAdmin
    groups
    # example-forum
    location
    googleLocation
    mapLocation
    mapLocationSet
    mapMarkerText
    htmlMapMarkerText
    mongoLocation
  }
`);

registerFragment(`
  fragment UsersEdit on User {
    ...UsersProfile
    # Moderation Guidelines editor information
    moderationGuidelines {
      ...RevisionEdit
    }

    # UI Settings
    markDownPostEditor
    hideIntercom
    commentSorting
    currentFrontpageFilter
    noCollapseCommentsPosts
    noCollapseCommentsFrontpage
    noSingleLineComments
    sunshineShowNewUserContent

    # Emails
    email
    whenConfirmationEmailSent
    emailSubscribedToCurated
    unsubscribeFromAll

    # Moderation
    moderatorAssistance
    collapseModerationGuidelines
    bannedUserIds
    bannedPersonalUserIds

    # Ban & Purge
    voteBanned
    nullifyVotes
    deleteContent
    banned

    # Name
    username
    displayName
    fullName

    # Location
    mongoLocation
    googleLocation
    location

    # Admin & Review
    reviewedByUserId

    # Alignment Forum
    reviewForAlignmentForumUserId
    groups
    afApplicationText
    afSubmittedApplication

    # Karma Settings
    karmaChangeLastOpened
    karmaChangeNotifierSettings

    recommendationSettings

    notificationCommentsOnSubscribedPost
    notificationRepliesToMyComments
    notificationRepliesToSubscribedComments
    notificationPostsInGroups
    notificationPrivateMessage
    notificationSharedWithMe

    hideFrontpageMap
  }
`)

registerFragment(`
  fragment unclaimedReportsList on Report {
    _id
    userId
    user {
      _id
      displayName
      username
      slug
    }
    commentId
    comment {
      _id
      userId
      user {
        ...UsersMinimumInfo
      }
      baseScore
      contents {
        ...RevisionDisplay
      }
      postedAt
      deleted
      postId
      post {
        _id
        slug
        title
        isEvent
      }
    }
    postId
    post {
      _id
      slug
      title
      isEvent
      contents {
        ...RevisionDisplay
      }
    }
    closedAt
    createdAt
    claimedUserId
    claimedUser {
      _id
      displayName
      username
      slug
    }
    link
    description
    reportedAsSpam
    markedAsSpam
  }
`);

registerFragment(`
  fragment VoteMinimumInfo on Vote {
    _id
    voteType
  }
`);

registerFragment(`
  fragment VoteFragment on Vote {
    _id
    voteType
    power
  }
`);

registerFragment(`
  fragment WithVotePost on Post {
    __typename
    _id
    currentUserVotes{
      _id
      voteType
      power
    }
    baseScore
    score
    afBaseScore
    voteCount
  }
`);

registerFragment(`
  fragment WithVoteComment on Comment {
    __typename
    _id
    currentUserVotes{
      _id
      voteType
      power
    }
    baseScore
    score
    afBaseScore
    voteCount
  }
`);

//
// example-forum migrated fragments
//

// note: fragment used by default on the UsersProfile fragment
registerFragment(/* GraphQL */`
  fragment VotedItem on Vote {
    # vulcan:voting
    documentId
    power
    votedAt
  }
`);

registerFragment(`
  fragment RevisionDisplay on Revision {
    version
    updateType
    editedAt
    userId
    html
    wordCount
    htmlHighlight
    plaintextDescription
  }
`)

registerFragment(`
  fragment RevisionEdit on Revision {
    version
    updateType
    editedAt
    userId
    originalContents
    html
    markdown
    draftJS
    ckEditorMarkup
    wordCount
    htmlHighlight
    plaintextDescription
  }
`)
<|endoftext|>