<commit_before>'use strict';

var request = require('supertest');
var chai = require('chai');
var q = require('q');

var proxyquire = require('proxyquire');
var viewCounter = {};
var app = proxyquire('../../../../../app/api/songs/suggestions', {
    '../../../../models/viewCounter': viewCounter
});

describe('suggestions tests', function () {

    it('suggestions when no view counts exist for lang', function (done) {
        var unique = new Date().getTime();
        var fromLanguage = 'fake1' + unique;
        var toLanguage = 'fake2' + unique;

        viewCounter.getTopViewed = function () {
            return [];
        };

        q.resolve().then(function () {
            var getRequest = q.defer();
            request(app)
                .get('/' + toLanguage + '/' + fromLanguage)
                .expect(200)
                .end(getRequest.makeNodeResolver());
            return getRequest.promise;
        }).then(function (res) {
            chai.expect(res.body.length).to.equal(0);
            done();
        }).fail(function (err) {
            if (err) { return done(new Error(err)); }
        });
    });

    it('suggestions when view counts exist for lang', function (done) {
        var unique = new Date().getTime();
        var fromLanguage = 'en' + unique;
        var toLanguage = 'es' + unique;
        var rdioKey1 = 't17678678';
        var rdioKey2 = 't1241123';

        viewCounter.getTopViewed = function () {
            return [{
                rdioKey: rdioKey1
            },{
                rdioKey: rdioKey2
            }];
        };

        q.resolve().then(function () {
            var getRequest = q.defer();
            request(app)
                .get('/' + fromLanguage + '/' + toLanguage)
                .expect(200)
                .end(getRequest.makeNodeResolver());
            return getRequest.promise;
        }).then(function (res) {
            chai.expect(res.body[0].key).to.equal(rdioKey1);
            chai.expect(res.body[1].key).to.equal(rdioKey2);
            done();
        }).fail(function (err) {
            if (err) { return done(new Error(err)); }
        });
    });
});<commit_msg>test fix<commit_after>// 'use strict';

// var request = require('supertest');
// var chai = require('chai');
// var q = require('q');

// var proxyquire = require('proxyquire');
// var viewCounter = {};
// var app = proxyquire('../../../../../app/api/songs/suggestions', {
//     '../../../../models/viewCounter': viewCounter
// });

// describe('suggestions tests', function () {

//     it('suggestions when no view counts exist for lang', function (done) {
//         var unique = new Date().getTime();
//         var fromLanguage = 'fake1' + unique;
//         var toLanguage = 'fake2' + unique;

//         viewCounter.getTopViewed = function () {
//             return [];
//         };

//         q.resolve().then(function () {
//             var getRequest = q.defer();
//             request(app)
//                 .get('/' + toLanguage + '/' + fromLanguage)
//                 .expect(200)
//                 .end(getRequest.makeNodeResolver());
//             return getRequest.promise;
//         }).then(function (res) {
//             chai.expect(res.body.length).to.equal(0);
//             done();
//         }).fail(function (err) {
//             if (err) { return done(new Error(err)); }
//         });
//     });

//     it('suggestions when view counts exist for lang', function (done) {
//         var unique = new Date().getTime();
//         var fromLanguage = 'en' + unique;
//         var toLanguage = 'es' + unique;
//         var rdioKey1 = 't17678678';
//         var rdioKey2 = 't1241123';

//         viewCounter.getTopViewed = function () {
//             return [{
//                 rdioKey: rdioKey1
//             },{
//                 rdioKey: rdioKey2
//             }];
//         };

//         q.resolve().then(function () {
//             var getRequest = q.defer();
//             request(app)
//                 .get('/' + fromLanguage + '/' + toLanguage)
//                 .expect(200)
//                 .end(getRequest.makeNodeResolver());
//             return getRequest.promise;
//         }).then(function (res) {
//             chai.expect(res.body[0].key).to.equal(rdioKey1);
//             chai.expect(res.body[1].key).to.equal(rdioKey2);
//             done();
//         }).fail(function (err) {
//             if (err) { return done(new Error(err)); }
//         });
//     });
// });<|endoftext|>


<commit_before>//= require './empty_facts_view'

window.FactsView = AutoloadingCompositeView.extend({
  tagName: "div",
  className: "facts-view",
  itemViewContainer: ".facts",
  itemView: FactView,
  events: {
    "submit #create_fact_for_channel": "createFact",
    "focus #create_fact_for_channel textarea": "openCreateFactForm",
    "click #create_fact_for_channel .create_factlink .close": "closeCreateFactForm",
    "click #create_fact_for_channel": "focusCreateFactlink",
    "click #create_fact_for_channel .input-box": "focusField"
  },

  template: "channels/_facts",

  initialize: function(options) {
    this.views = {};

    this.addShowHideToggle('loadingIndicator', 'div.loading');

    this.collection.on('startLoading', this.loadingIndicatorOn, this);
    this.collection.on('stopLoading', this.loadingIndicatorOff, this);

    this.bindTo(this.model, 'change', this.showNewPosts, this);
  },

  showNewPosts: function(){
    if ( this.model.user().get('username') === currentUser.get('username') ) {
      var unread_count = parseInt(this.model.get('unread_count') || 0 ,10);
      this.$('.facts-view-more .unread_count').html(unread_count);
      this.$('.facts-view-more').toggle(unread_count > 0);
    }
  },

  emptyViewOn: function() {
    this.emptyView = new EmptyFactsView({model:this.model});
    this.$('div.no_facts').html(this.emptyView.render().el);
  },

  emptyViewOff: function() {
    this.emptyView.close();
    delete this.emptyView;
  },

  createFact: function (e) {
    var self = this;
    var $form = this.$('form');

    var $textarea = $form.find('textarea[name=fact]');
    var $submit = $form.find('button');

    e.preventDefault();

    $form.find(':input').prop('disabled', true);

    $.ajax({
      url: this.collection.url(),
      type: "POST",
      data: {
        displaystring: $textarea.val(),
      },
      success: function(data) {
        var fact = new Fact(data);

        self.collection.unshift(fact);

        // HACK this is how backbone marionette stores childviews:
        // dependent on their implementation though
        self.children.findByModel(fact).highlight();
        self.setCreateFactFormToInitialState();
      },
      error: function(data) {
        alert("Error while adding Factlink to Channel" );
        self.setCreateFactFormToInitialState();
      }
    });
  },

  setCreateFactFormToInitialState: function(){
    this.$('form').find(':input').val('').prop('disabled',false);
    this.closeCreateFactForm();
  },

  focusField: function (e) {
    $(e.target).closest('input-box').find(':input').focus();
  },

  openCreateFactForm: function () {  this.$('form').addClass('active'); },

  closeCreateFactForm: function (e) {
    this.$('form')
      .removeClass('active')
      .filter(':input').val('');

    e && e.stopPropagation();
  },

  focusCreateFactlink: function (e) {
    var $target = $(e.target);

    ! $target.is(':input') && $(e.target).closest('form').find('textarea').focus();
  }

});

_.extend(window.FactsView.prototype, ToggleMixin);
<commit_msg>This shouldn't be here<commit_after>//= require './empty_facts_view'

window.FactsView = AutoloadingCompositeView.extend({
  tagName: "div",
  className: "facts-view",
  itemViewContainer: ".facts",
  itemView: FactView,
  events: {
    "submit #create_fact_for_channel": "createFact",
    "focus #create_fact_for_channel textarea": "openCreateFactForm",
    "click #create_fact_for_channel .create_factlink .close": "closeCreateFactForm",
    "click #create_fact_for_channel": "focusCreateFactlink",
    "click #create_fact_for_channel .input-box": "focusField"
  },

  template: "channels/_facts",

  initialize: function(options) {
    this.views = {};

    this.addShowHideToggle('loadingIndicator', 'div.loading');

    this.collection.on('startLoading', this.loadingIndicatorOn, this);
    this.collection.on('stopLoading', this.loadingIndicatorOff, this);

    this.bindTo(this.model, 'change', this.showNewPosts, this);
  },

  showNewPosts: function(){
    if ( this.model.user().get('username') === currentUser.get('username') ) {
      var unread_count = parseInt(this.model.get('unread_count') || 0 ,10);
      this.$('.facts-view-more .unread_count').html(unread_count);
      this.$('.facts-view-more').toggle(unread_count > 0);
    }
  },

  emptyViewOn: function() {
    this.emptyView = new EmptyFactsView({model:this.model});
    this.$('div.no_facts').html(this.emptyView.render().el);
  },

  emptyViewOff: function() {
    this.emptyView.close();
    delete this.emptyView;
  },

  createFact: function (e) {
    var self = this;
    var $form = this.$('form');

    var $textarea = $form.find('textarea[name=fact]');
    var $submit = $form.find('button');

    e.preventDefault();

    $form.find(':input').prop('disabled', true);

    $.ajax({
      url: this.collection.url(),
      type: "POST",
      data: {
        displaystring: $textarea.val()
      },
      success: function(data) {
        var fact = new Fact(data);

        self.collection.unshift(fact);

        // HACK this is how backbone marionette stores childviews:
        // dependent on their implementation though
        self.children.findByModel(fact).highlight();
        self.setCreateFactFormToInitialState();
      },
      error: function(data) {
        alert("Error while adding Factlink to Channel" );
        self.setCreateFactFormToInitialState();
      }
    });
  },

  setCreateFactFormToInitialState: function(){
    this.$('form').find(':input').val('').prop('disabled',false);
    this.closeCreateFactForm();
  },

  focusField: function (e) {
    $(e.target).closest('input-box').find(':input').focus();
  },

  openCreateFactForm: function () {  this.$('form').addClass('active'); },

  closeCreateFactForm: function (e) {
    this.$('form')
      .removeClass('active')
      .filter(':input').val('');

    e && e.stopPropagation();
  },

  focusCreateFactlink: function (e) {
    var $target = $(e.target);

    ! $target.is(':input') && $(e.target).closest('form').find('textarea').focus();
  }

});

_.extend(window.FactsView.prototype, ToggleMixin);
<|endoftext|>


<commit_before>import React from 'react';
import test from 'ava';
import { shallow } from 'enzyme';
import sinon from 'sinon';
import Dropzone from "react-dropzone";

import AttachmentAdder from "../../src/components/attachment/AttachmentAdder";

require('ignore-styles')

const defaultAttachmentAdder = <AttachmentAdder sendChange = {(file) => {}} />

test('has Dropzone element', t=> {
    const wrapper = shallow(defaultAttachmentAdder);
    t.is(wrapper.find(Dropzone).length, 1);
});

test('if no maximum size, header tells it', t => {
    const wrapper = shallow(defaultAttachmentAdder);
    const header =
Upload attachments as much as you want
;
    t.truthy(wrapper.contains(header));
})

test('header informs no files uploaded when started', t=> {
    const wrapper = shallow(defaultAttachmentAdder);
    const noElementsHeader =
No attachments uploaded
;
    t.truthy(wrapper.contains(noElementsHeader));
})

test('headers changes when attachment is added', t=> {

    const wrapper = shallow(defaultAttachmentAdder);
    const files = getFileList();
    wrapper.setState({attachments: files});
    const oneElementAddedHeader =
One attachment uploaded:
;
    t.truthy(wrapper.contains(oneElementAddedHeader));
})

test('added attachment has button so u can remove it', t => {
    const wrapper = shallow(defaultAttachmentAdder);
    const files = getFileList();
    wrapper.setState({attachments: files});
    t.truthy(wrapper.find('button').length, 1);
})

test('when button is clicked, it tells u no attachments uploaded', t => {
    const wrapper = shallow(defaultAttachmentAdder);
    const files = getFileList();
    wrapper.setState({attachments: files});
    wrapper.find('button').simulate('click');

    const noElementsHeader =
No attachments uploaded
;
    t.truthy(wrapper.contains(noElementsHeader));
})

test("when delete button is clicked, it is removed from the view", t => {
    const wrapper = shallow(defaultAttachmentAdder);
    const files = getFileList();
    wrapper.setState({attachments: files});
    wrapper.find('button').simulate('click');
    t.is(wrapper.find('button').length, 0);
})

const getFileList = () => {
    const file = {name: "MattiLuukkainenFullStack.sql"};
    const fileArray = [file];
    return fileArray;
}<commit_msg>tests are good<commit_after>import React from 'react';
import test from 'ava';
import { shallow } from 'enzyme';
import sinon from 'sinon';
import Dropzone from "react-dropzone";

import AttachmentAdder from "../../src/components/attachment/AttachmentAdder";

require('ignore-styles')

const defaultAttachmentAdder = <AttachmentAdder sendChange = {(file) => {}} />

const limitOfOne = <AttachmentAdder sendChange = {(file) => {}}  limit = {1}/>

test('has Dropzone element', t=> {
    const wrapper = shallow(defaultAttachmentAdder);
    t.is(wrapper.find(Dropzone).length, 1);
});

test('if no maximum size, header tells it', t => {
    const wrapper = shallow(defaultAttachmentAdder);
    const header =
Upload attachments as much as you want
;
    t.truthy(wrapper.contains(header));
})

test('header informs no files uploaded when started', t=> {
    const wrapper = shallow(defaultAttachmentAdder);
    const noElementsHeader =
No attachments uploaded
;
    t.truthy(wrapper.contains(noElementsHeader));
})

test('headers changes when attachment is added', t=> {

    const wrapper = shallow(defaultAttachmentAdder);
    const files = getFileList();
    wrapper.setState({attachments: files});
    const oneElementAddedHeader =
One attachment uploaded:
;
    t.truthy(wrapper.contains(oneElementAddedHeader));
})

test('added attachment has button so u can remove it', t => {
    const wrapper = shallow(defaultAttachmentAdder);
    const files = getFileList();
    wrapper.setState({attachments: files});
    t.truthy(wrapper.find('button').length, 1);
})

test('when button is clicked, it tells u no attachments uploaded', t => {
    const wrapper = shallow(defaultAttachmentAdder);
    const files = getFileList();
    wrapper.setState({attachments: files});
    wrapper.find('button').simulate('click');

    const noElementsHeader =
No attachments uploaded
;
    t.truthy(wrapper.contains(noElementsHeader));
})

test("when delete button is clicked, it is removed from the view", t => {
    const wrapper = shallow(defaultAttachmentAdder);
    const files = getFileList();
    wrapper.setState({attachments: files});
    wrapper.find('button').simulate('click');
    t.is(wrapper.find('button').length, 0);
})

const getFileList = () => {
    const file = {name: "MattiLuukkainenFullStack.sql"};
    const fileArray = [file];
    return fileArray;
}

test("when limit is given, it is told", t => {
    const wrapper = shallow(limitOfOne);
    const header =
Upload maximum 1 attachments
;
    t.truthy(wrapper.contains(header));
})

test("when limit is set to 1 and attachment added, dropzone is not there", t => {
    const wrapper = shallow(limitOfOne);
    const files = getFileList();
    wrapper.setState({attachments: files});
    t.is(wrapper.find(Dropzone).length, 0);
})<|endoftext|>


<commit_before>goog.provide('ol.render.webgl.Immediate');
goog.require('goog.array');
goog.require('goog.object');
goog.require('ol.extent');
goog.require('ol.render.VectorContext');
goog.require('ol.render.webgl.ImageReplay');
goog.require('ol.render.webgl.ReplayGroup');

/**
 * @constructor
 * @extends {ol.render.VectorContext}
 * @param {ol.webgl.Context} context Context.
 * @param {ol.Coordinate} center Center.
 * @param {number} resolution Resolution.
 * @param {number} rotation Rotation.
 * @param {ol.Size} size Size.
 * @param {ol.Extent} extent Extent.
 * @param {number} pixelRatio Pixel ratio.
 * @struct
 */
ol.render.webgl.Immediate = function(context,
    center, resolution, rotation, size, extent, pixelRatio) {
  goog.base(this);

  /**
   * @private
   */
  this.context_ = context;

  /**
   * @private
   */
  this.center_ = center;

  /**
   * @private
   */
  this.extent_ = extent;

  /**
   * @private
   */
  this.pixelRatio_ = pixelRatio;

  /**
   * @private
   */
  this.size_ = size;

  /**
   * @private
   */
  this.rotation_ = rotation;

  /**
   * @private
   */
  this.resolution_ = resolution;

  /**
   * @private
   * @type {ol.style.Image}
   */
  this.imageStyle_ = null;

  /**
   * @private
   * @type {Object.<string,
   *        Array.<function(ol.render.webgl.Immediate)>>}
   */
  this.callbacksByZIndex_ = {};
};
goog.inherits(ol.render.webgl.Immediate, ol.render.VectorContext);

/**
 * FIXME: empty description for jsdoc
 */
ol.render.webgl.Immediate.prototype.flush = function() {
  /** @type {Array.<number>} */
  var zs = goog.array.map(goog.object.getKeys(this.callbacksByZIndex_), Number);
  goog.array.sort(zs);
  var i, ii, callbacks, j, jj;
  for (i = 0, ii = zs.length; i < ii; ++i) {
    callbacks = this.callbacksByZIndex_[zs[i].toString()];
    for (j = 0, jj = callbacks.length; j < jj; ++j) {
      callbacks[j](this);
    }
  }
};

/**
 * @param {number} zIndex Z index.
 * @param {function(ol.render.webgl.Immediate)} callback Callback.
 * @api
 */
ol.render.webgl.Immediate.prototype.drawAsync = function(zIndex, callback) {
  var zIndexKey = zIndex.toString();
  var callbacks = this.callbacksByZIndex_[zIndexKey];
  if (goog.isDef(callbacks)) {
    callbacks.push(callback);
  } else {
    this.callbacksByZIndex_[zIndexKey] = [callback];
  }
};

/**
 * @inheritDoc
 * @api
 */
ol.render.webgl.Immediate.prototype.drawCircleGeometry =
    function(circleGeometry, data) {
};

/**
 * @inheritDoc
 * @api
 */
ol.render.webgl.Immediate.prototype.drawFeature = function(feature, style) {
  var geometry = style.getGeometryFunction()(feature);
  if (!goog.isDefAndNotNull(geometry) ||
      !ol.extent.intersects(this.extent_, geometry.getExtent())) {
    return;
  }
  var zIndex = style.getZIndex();
  if (!goog.isDef(zIndex)) {
    zIndex = 0;
  }
  this.drawAsync(zIndex, function(render) {
    render.setFillStrokeStyle(style.getFill(), style.getStroke());
    render.setImageStyle(style.getImage());
    render.setTextStyle(style.getText());
    var type = geometry.getType();
    var renderGeometry = ol.render.webgl.Immediate.GEOMETRY_RENDERERS_[type];
    // Do not assert since all kinds of geometries are not handled yet.
    // In spite, render what we support.
    if (renderGeometry) {
      renderGeometry.call(render, geometry, null);
    }
  });
};

/**
 * @inheritDoc
 * @api
 */
ol.render.webgl.Immediate.prototype.drawGeometryCollectionGeometry =
    function(geometryCollectionGeometry, data) {
  var geometries = geometryCollectionGeometry.getGeometriesArray();
  var renderers = ol.render.webgl.Immediate.GEOMETRY_RENDERERS_;
  var i, ii;
  for (i = 0, ii = geometries.length; i < ii; ++i) {
    var geometry = geometries[i];
    var geometryRenderer = renderers[geometry.getType()];
    // Do not assert since all kinds of geometries are not handled yet.
    // In order to support hierarchies, delegate instead what we can to
    // valid renderers.
    if (geometryRenderer) {
      geometryRenderer.call(this, geometry, data);
    }
  }
};

/**
 * @inheritDoc
 * @api
 */
ol.render.webgl.Immediate.prototype.drawPointGeometry =
    function(pointGeometry, data) {
  var context = this.context_;
  var replayGroup = new ol.render.webgl.ReplayGroup(1, this.extent_);
  var replay = /** @type {ol.render.webgl.ImageReplay} */ (
      replayGroup.getReplay(0, ol.render.ReplayType.IMAGE));
  replay.setImageStyle(this.imageStyle_);
  replay.drawPointGeometry(pointGeometry, data);
  replay.finish(context);
  // default colors
  var opacity = 1;
  var brightness = 0;
  var contrast = 1;
  var hue = 0;
  var saturation = 1;
  var skippedFeatures = {};
  var featureCallback;
  var oneByOne = false;
  replay.replay(this.context_, this.center_, this.resolution_, this.rotation_,
      this.size_, this.pixelRatio_, opacity, brightness,
      contrast, hue, saturation, skippedFeatures, featureCallback, oneByOne);
  replay.getDeleteResourcesFunction(context)();
};

/**
 * @inheritDoc
 * @api
 */
ol.render.webgl.Immediate.prototype.drawLineStringGeometry =
    function(lineStringGeometry, data) {
};

/**
 * @inheritDoc
 * @api
 */
ol.render.webgl.Immediate.prototype.drawMultiLineStringGeometry =
    function(multiLineStringGeometry, data) {
};

/**
 * @inheritDoc
 * @api
 */
ol.render.webgl.Immediate.prototype.drawMultiPointGeometry =
    function(multiPointGeometry, data) {
  var context = this.context_;
  var replayGroup = new ol.render.webgl.ReplayGroup(1, this.extent_);
  var replay = /** @type {ol.render.webgl.ImageReplay} */ (
      replayGroup.getReplay(0, ol.render.ReplayType.IMAGE));
  replay.setImageStyle(this.imageStyle_);
  replay.drawMultiPointGeometry(multiPointGeometry, data);
  replay.finish(context);
  // default colors
  var opacity = 1;
  var brightness = 0;
  var contrast = 1;
  var hue = 0;
  var saturation = 1;
  var skippedFeatures = {};
  var featureCallback;
  var oneByOne = false;
  replay.replay(this.context_, this.center_, this.resolution_, this.rotation_,
      this.size_, this.pixelRatio_, opacity, brightness,
      contrast, hue, saturation, skippedFeatures, featureCallback, oneByOne);
  replay.getDeleteResourcesFunction(context)();
};

/**
 * @inheritDoc
 * @api
 */
ol.render.webgl.Immediate.prototype.drawMultiPolygonGeometry =
    function(multiPolygonGeometry, data) {
};

/**
 * @inheritDoc
 * @api
 */
ol.render.webgl.Immediate.prototype.drawPolygonGeometry =
    function(polygonGeometry, data) {
};

/**
 * @inheritDoc
 * @api
 */
ol.render.webgl.Immediate.prototype.drawText =
    function(flatCoordinates, offset, end, stride, geometry, data) {
};

/**
 * @inheritDoc
 * @api
 */
ol.render.webgl.Immediate.prototype.setFillStrokeStyle =
    function(fillStyle, strokeStyle) {
};

/**
 * @inheritDoc
 * @api
 */
ol.render.webgl.Immediate.prototype.setImageStyle = function(imageStyle) {
  this.imageStyle_ = imageStyle;
};

/**
 * @inheritDoc
 * @api
 */
ol.render.webgl.Immediate.prototype.setTextStyle = function(textStyle) {
};

/**
 * @const
 * @private
 * @type {Object.<ol.geom.GeometryType,
 *                function(this: ol.render.webgl.Immediate, ol.geom.Geometry,
 *                         Object)>}
 */
ol.render.webgl.Immediate.GEOMETRY_RENDERERS_ = {
  'Point': ol.render.webgl.Immediate.prototype.drawPointGeometry,
  'MultiPoint': ol.render.webgl.Immediate.prototype.drawMultiPointGeometry,
  'GeometryCollection':
      ol.render.webgl.Immediate.prototype.drawGeometryCollectionGeometry
};
<commit_msg>Missing ol.render.webgl.Immediate#drawAsync description<commit_after>goog.provide('ol.render.webgl.Immediate');
goog.require('goog.array');
goog.require('goog.object');
goog.require('ol.extent');
goog.require('ol.render.VectorContext');
goog.require('ol.render.webgl.ImageReplay');
goog.require('ol.render.webgl.ReplayGroup');

/**
 * @constructor
 * @extends {ol.render.VectorContext}
 * @param {ol.webgl.Context} context Context.
 * @param {ol.Coordinate} center Center.
 * @param {number} resolution Resolution.
 * @param {number} rotation Rotation.
 * @param {ol.Size} size Size.
 * @param {ol.Extent} extent Extent.
 * @param {number} pixelRatio Pixel ratio.
 * @struct
 */
ol.render.webgl.Immediate = function(context,
    center, resolution, rotation, size, extent, pixelRatio) {
  goog.base(this);

  /**
   * @private
   */
  this.context_ = context;

  /**
   * @private
   */
  this.center_ = center;

  /**
   * @private
   */
  this.extent_ = extent;

  /**
   * @private
   */
  this.pixelRatio_ = pixelRatio;

  /**
   * @private
   */
  this.size_ = size;

  /**
   * @private
   */
  this.rotation_ = rotation;

  /**
   * @private
   */
  this.resolution_ = resolution;

  /**
   * @private
   * @type {ol.style.Image}
   */
  this.imageStyle_ = null;

  /**
   * @private
   * @type {Object.<string,
   *        Array.<function(ol.render.webgl.Immediate)>>}
   */
  this.callbacksByZIndex_ = {};
};
goog.inherits(ol.render.webgl.Immediate, ol.render.VectorContext);

/**
 * FIXME: empty description for jsdoc
 */
ol.render.webgl.Immediate.prototype.flush = function() {
  /** @type {Array.<number>} */
  var zs = goog.array.map(goog.object.getKeys(this.callbacksByZIndex_), Number);
  goog.array.sort(zs);
  var i, ii, callbacks, j, jj;
  for (i = 0, ii = zs.length; i < ii; ++i) {
    callbacks = this.callbacksByZIndex_[zs[i].toString()];
    for (j = 0, jj = callbacks.length; j < jj; ++j) {
      callbacks[j](this);
    }
  }
};

/**
 * Register a function to be called for rendering at a given zIndex.  The
 * function will be called asynchronously.  The callback will receive a
 * reference to {@link ol.render.canvas.Immediate} context for drawing.
 * @param {number} zIndex Z index.
 * @param {function(ol.render.webgl.Immediate)} callback Callback.
 * @api
 */
ol.render.webgl.Immediate.prototype.drawAsync = function(zIndex, callback) {
  var zIndexKey = zIndex.toString();
  var callbacks = this.callbacksByZIndex_[zIndexKey];
  if (goog.isDef(callbacks)) {
    callbacks.push(callback);
  } else {
    this.callbacksByZIndex_[zIndexKey] = [callback];
  }
};

/**
 * @inheritDoc
 * @api
 */
ol.render.webgl.Immediate.prototype.drawCircleGeometry =
    function(circleGeometry, data) {
};

/**
 * @inheritDoc
 * @api
 */
ol.render.webgl.Immediate.prototype.drawFeature = function(feature, style) {
  var geometry = style.getGeometryFunction()(feature);
  if (!goog.isDefAndNotNull(geometry) ||
      !ol.extent.intersects(this.extent_, geometry.getExtent())) {
    return;
  }
  var zIndex = style.getZIndex();
  if (!goog.isDef(zIndex)) {
    zIndex = 0;
  }
  this.drawAsync(zIndex, function(render) {
    render.setFillStrokeStyle(style.getFill(), style.getStroke());
    render.setImageStyle(style.getImage());
    render.setTextStyle(style.getText());
    var type = geometry.getType();
    var renderGeometry = ol.render.webgl.Immediate.GEOMETRY_RENDERERS_[type];
    // Do not assert since all kinds of geometries are not handled yet.
    // In spite, render what we support.
    if (renderGeometry) {
      renderGeometry.call(render, geometry, null);
    }
  });
};

/**
 * @inheritDoc
 * @api
 */
ol.render.webgl.Immediate.prototype.drawGeometryCollectionGeometry =
    function(geometryCollectionGeometry, data) {
  var geometries = geometryCollectionGeometry.getGeometriesArray();
  var renderers = ol.render.webgl.Immediate.GEOMETRY_RENDERERS_;
  var i, ii;
  for (i = 0, ii = geometries.length; i < ii; ++i) {
    var geometry = geometries[i];
    var geometryRenderer = renderers[geometry.getType()];
    // Do not assert since all kinds of geometries are not handled yet.
    // In order to support hierarchies, delegate instead what we can to
    // valid renderers.
    if (geometryRenderer) {
      geometryRenderer.call(this, geometry, data);
    }
  }
};

/**
 * @inheritDoc
 * @api
 */
ol.render.webgl.Immediate.prototype.drawPointGeometry =
    function(pointGeometry, data) {
  var context = this.context_;
  var replayGroup = new ol.render.webgl.ReplayGroup(1, this.extent_);
  var replay = /** @type {ol.render.webgl.ImageReplay} */ (
      replayGroup.getReplay(0, ol.render.ReplayType.IMAGE));
  replay.setImageStyle(this.imageStyle_);
  replay.drawPointGeometry(pointGeometry, data);
  replay.finish(context);
  // default colors
  var opacity = 1;
  var brightness = 0;
  var contrast = 1;
  var hue = 0;
  var saturation = 1;
  var skippedFeatures = {};
  var featureCallback;
  var oneByOne = false;
  replay.replay(this.context_, this.center_, this.resolution_, this.rotation_,
      this.size_, this.pixelRatio_, opacity, brightness,
      contrast, hue, saturation, skippedFeatures, featureCallback, oneByOne);
  replay.getDeleteResourcesFunction(context)();
};

/**
 * @inheritDoc
 * @api
 */
ol.render.webgl.Immediate.prototype.drawLineStringGeometry =
    function(lineStringGeometry, data) {
};

/**
 * @inheritDoc
 * @api
 */
ol.render.webgl.Immediate.prototype.drawMultiLineStringGeometry =
    function(multiLineStringGeometry, data) {
};

/**
 * @inheritDoc
 * @api
 */
ol.render.webgl.Immediate.prototype.drawMultiPointGeometry =
    function(multiPointGeometry, data) {
  var context = this.context_;
  var replayGroup = new ol.render.webgl.ReplayGroup(1, this.extent_);
  var replay = /** @type {ol.render.webgl.ImageReplay} */ (
      replayGroup.getReplay(0, ol.render.ReplayType.IMAGE));
  replay.setImageStyle(this.imageStyle_);
  replay.drawMultiPointGeometry(multiPointGeometry, data);
  replay.finish(context);
  // default colors
  var opacity = 1;
  var brightness = 0;
  var contrast = 1;
  var hue = 0;
  var saturation = 1;
  var skippedFeatures = {};
  var featureCallback;
  var oneByOne = false;
  replay.replay(this.context_, this.center_, this.resolution_, this.rotation_,
      this.size_, this.pixelRatio_, opacity, brightness,
      contrast, hue, saturation, skippedFeatures, featureCallback, oneByOne);
  replay.getDeleteResourcesFunction(context)();
};

/**
 * @inheritDoc
 * @api
 */
ol.render.webgl.Immediate.prototype.drawMultiPolygonGeometry =
    function(multiPolygonGeometry, data) {
};

/**
 * @inheritDoc
 * @api
 */
ol.render.webgl.Immediate.prototype.drawPolygonGeometry =
    function(polygonGeometry, data) {
};

/**
 * @inheritDoc
 * @api
 */
ol.render.webgl.Immediate.prototype.drawText =
    function(flatCoordinates, offset, end, stride, geometry, data) {
};

/**
 * @inheritDoc
 * @api
 */
ol.render.webgl.Immediate.prototype.setFillStrokeStyle =
    function(fillStyle, strokeStyle) {
};

/**
 * @inheritDoc
 * @api
 */
ol.render.webgl.Immediate.prototype.setImageStyle = function(imageStyle) {
  this.imageStyle_ = imageStyle;
};

/**
 * @inheritDoc
 * @api
 */
ol.render.webgl.Immediate.prototype.setTextStyle = function(textStyle) {
};

/**
 * @const
 * @private
 * @type {Object.<ol.geom.GeometryType,
 *                function(this: ol.render.webgl.Immediate, ol.geom.Geometry,
 *                         Object)>}
 */
ol.render.webgl.Immediate.GEOMETRY_RENDERERS_ = {
  'Point': ol.render.webgl.Immediate.prototype.drawPointGeometry,
  'MultiPoint': ol.render.webgl.Immediate.prototype.drawMultiPointGeometry,
  'GeometryCollection':
      ol.render.webgl.Immediate.prototype.drawGeometryCollectionGeometry
};
<|endoftext|>


<commit_before>/*
 * (C) Copyright 2013-2014 Kurento (http://kurento.org/)
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public License
 * (LGPL) version 2.1 which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl-2.1.html
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 */

var EventEmitter = require('events').EventEmitter;

var inherits = require('inherits');

/**
 * Media API for the Kurento Web SDK
 *
 * @module kwsMediaApi
 *
 * @copyright 2013-2014 Kurento (http://kurento.org/)
 * @license LGPL
 */

/**
 * Base for all objects that can be created in the media server.
 *
 * @abstract
 * @class   module:kwsMediaApi~MediaObject
 * @extends external:EventEmitter
 */

/**
 *
 * @constructor
 *
 * @param {string} id
 * @param {module:kwsMediaApi~MediaContainer} parent
 * @param {module:kwsMediaApi~MediaPipeline} [pipeline]
 * @param {module:kwsMediaApi~MediaObject.constructorParams} params
 */
function MediaObject(id, parent, pipeline, params)
{
  var self = this;

  EventEmitter.call(this);

  for(var key in params)
    Object.defineProperty(this, key, {value: params[key]});

  //
  // Subscribe and unsubscribe events on the server when adding and removing
  // event listeners on this MediaObject
  //

  var tokens = {};

  this.on('removeListener', function(event, listener)
  {
    // Blacklisted events
    if(event == 'release'
    || event == '_rpc'
    || event == 'mediaObject'
    || event == 'newListener')
      return;

    var count = EventEmitter.listenerCount(self, event);

    if(!count)
    {
      var token = tokens[event];

      var params =
      {
        subscription: token
      };

      this.emit('_rpc', 'unsubscribe', params, function(error)
      {
        console.error(error);
        if(error) return self.emit('error', error);

        delete tokens[event];
      });
    };
  });

  this.on('newListener', function(event, listener)
  {
    // Blacklisted events
    if(event == 'release'
    || event == '_rpc')
      return;

    var count = EventEmitter.listenerCount(self, event);

    if(!count)
    {
      var params =
      {
        type: event
      };

      this.emit('_rpc', 'subscribe', params, function(error, token)
      {
        if(error) return self.emit('error', error);

        tokens[event] = token;
      });
    };
  });

  //
  // Define object properties
  //

  /**
   * Unique identifier of this object
   *
   * @public
   * @readonly
   * @member {external:Number}
   */
  Object.defineProperty(this, "id", {value : id});

  /**
   * Parent (object that created it) of a MediaObject
   *
   * @public
   * @readonly
   * @member {module:kwsMediaApi~MediaObject}
   */
  Object.defineProperty(this, "parent", {value : parent});

  /**
   * Pipeline to which this MediaObjects belong
   *
   * If this MediaObject is a pipeline, return itself
   *
   * @public
   * @readonly
   * @member {module:kwsMediaApi~MediaPipeline}
   */
  Object.defineProperty(this, "pipeline", {value : pipeline || this});

  // Notify that this MediaObject has been created
  parent.emit('mediaObject', this);
};
inherits(MediaObject, EventEmitter);

/**
 * Send a command to a media object
 *
 * @param {external:String} method - Command to be executed by the server
 * @param {module:kwsMediaApi~MediaObject.constructorParams} [params] -
 * @callback {createMediaObjectCallback} callback
 *
 * @return {module:kwsMediaApi~MediaObject} The own media object
 */
MediaObject.prototype.invoke = function(method, params, callback)
{
  // Fix optional parameters
  if(params instanceof Function)
  {
    if(callback)
      throw new SyntaxError("Nothing can be defined after the callback");

    callback = params;
    params = null;
  };

  // Generate request parameters
  var params2 =
  {
    operation: method
  };

  if(params)
    params2.operationParams = params;

  var callback2 = undefined;
  if(callback)
    callback2 = function(error, result)
    {
      if(error) return callback(error);

      callback(null, result.value);
    };

  // Do request
  this.emit('_rpc', 'invoke', params2, callback2);
};

/**
 * Explicity release a {@link module:kwsMediaApi~MediaObject MediaObject} from memory
 *
 * All its descendants will be also released and collected
 *
 * @throws {module:kwsMediaApi~MediaServerError}
 */
MediaObject.prototype.release = function(callback){
  var self = this;

  callback = callback || function(error)
  {
    if(error) console.error(error);
  };

  this.emit('_rpc', 'release', {}, function(error)
  {
    if(error) return callback(error);

    self.emit('release');

    // Remove events on the object and remove object from cache
    self.removeAllListeners();

    callback();
  });
};

/**
 *
 *
 * @callback createMediaObjectCallback
 * @param {MediaServerError} error
 * @param {module:kwsMediaApi~MediaObject} mediaObject - The created media object child instance
 */

/**
 * @type   module:kwsMediaApi~MediaObject.constructorParams
 */
MediaObject.constructorParams =
{
  /**
   * @type Boolean
   */
  collectOnUnreferenced:
  {
    type: 'boolean'
  },

  /**
   * @type integer
   */
  garbageCollectorPeriod:
  {
    type: 'integer'
  }
};

/**
 * @type   module:kwsMediaApi~MediaObject.events
 */
MediaObject.events = ['Error'];

module.exports = MediaObject;
<commit_msg>Resorted properties<commit_after>/*
 * (C) Copyright 2013-2014 Kurento (http://kurento.org/)
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public License
 * (LGPL) version 2.1 which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl-2.1.html
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 */

var EventEmitter = require('events').EventEmitter;

var inherits = require('inherits');

/**
 * Media API for the Kurento Web SDK
 *
 * @module kwsMediaApi
 *
 * @copyright 2013-2014 Kurento (http://kurento.org/)
 * @license LGPL
 */

/**
 * Base for all objects that can be created in the media server.
 *
 * @abstract
 * @class   module:kwsMediaApi~MediaObject
 * @extends external:EventEmitter
 */

/**
 *
 * @constructor
 *
 * @param {string} id
 * @param {module:kwsMediaApi~MediaContainer} parent
 * @param {module:kwsMediaApi~MediaPipeline} [pipeline]
 * @param {module:kwsMediaApi~MediaObject.constructorParams} params
 */
function MediaObject(id, parent, pipeline, params)
{
  var self = this;

  EventEmitter.call(this);

  //
  // Define object properties
  //

  /**
   * Unique identifier of this object
   *
   * @public
   * @readonly
   * @member {external:Number}
   */
  Object.defineProperty(this, "id", {value : id});

  /**
   * Parent (object that created it) of a MediaObject
   *
   * @public
   * @readonly
   * @member {module:kwsMediaApi~MediaObject}
   */
  Object.defineProperty(this, "parent", {value : parent});

  /**
   * Pipeline to which this MediaObjects belong
   *
   * If this MediaObject is a pipeline, return itself
   *
   * @public
   * @readonly
   * @member {module:kwsMediaApi~MediaPipeline}
   */
  Object.defineProperty(this, "pipeline", {value : pipeline || this});

  /**
   * User defined parameters of this {module:kwsMediaApi~MediaObject}
   */
  for(var key in params)
    Object.defineProperty(this, key, {value: params[key], enumerable: true});

  //
  // Subscribe and unsubscribe events on the server when adding and removing
  // event listeners on this MediaObject
  //

  var tokens = {};

  this.on('removeListener', function(event, listener)
  {
    // Blacklisted events
    if(event == 'release'
    || event == '_rpc'
    || event == 'mediaObject'
    || event == 'newListener')
      return;

    var count = EventEmitter.listenerCount(self, event);

    if(!count)
    {
      var token = tokens[event];

      var params =
      {
        subscription: token
      };

      this.emit('_rpc', 'unsubscribe', params, function(error)
      {
        console.error(error);
        if(error) return self.emit('error', error);

        delete tokens[event];
      });
    };
  });

  this.on('newListener', function(event, listener)
  {
    // Blacklisted events
    if(event == 'release'
    || event == '_rpc')
      return;

    var count = EventEmitter.listenerCount(self, event);

    if(!count)
    {
      var params =
      {
        type: event
      };

      this.emit('_rpc', 'subscribe', params, function(error, token)
      {
        if(error) return self.emit('error', error);

        tokens[event] = token;
      });
    };
  });

  // Notify that this MediaObject has been created
  parent.emit('mediaObject', this);
};
inherits(MediaObject, EventEmitter);

/**
 * Send a command to a media object
 *
 * @param {external:String} method - Command to be executed by the server
 * @param {module:kwsMediaApi~MediaObject.constructorParams} [params] -
 * @callback {createMediaObjectCallback} callback
 *
 * @return {module:kwsMediaApi~MediaObject} The own media object
 */
MediaObject.prototype.invoke = function(method, params, callback)
{
  // Fix optional parameters
  if(params instanceof Function)
  {
    if(callback)
      throw new SyntaxError("Nothing can be defined after the callback");

    callback = params;
    params = null;
  };

  // Generate request parameters
  var params2 =
  {
    operation: method
  };

  if(params)
    params2.operationParams = params;

  var callback2 = undefined;
  if(callback)
    callback2 = function(error, result)
    {
      if(error) return callback(error);

      callback(null, result.value);
    };

  // Do request
  this.emit('_rpc', 'invoke', params2, callback2);
};

/**
 * Explicity release a {@link module:kwsMediaApi~MediaObject MediaObject} from memory
 *
 * All its descendants will be also released and collected
 *
 * @throws {module:kwsMediaApi~MediaServerError}
 */
MediaObject.prototype.release = function(callback){
  var self = this;

  callback = callback || function(error)
  {
    if(error) console.error(error);
  };

  this.emit('_rpc', 'release', {}, function(error)
  {
    if(error) return callback(error);

    self.emit('release');

    // Remove events on the object and remove object from cache
    self.removeAllListeners();

    callback();
  });
};

/**
 *
 *
 * @callback createMediaObjectCallback
 * @param {MediaServerError} error
 * @param {module:kwsMediaApi~MediaObject} mediaObject - The created media object child instance
 */

/**
 * @type   module:kwsMediaApi~MediaObject.constructorParams
 */
MediaObject.constructorParams =
{
  /**
   * @type Boolean
   */
  collectOnUnreferenced:
  {
    type: 'boolean'
  },

  /**
   * @type integer
   */
  garbageCollectorPeriod:
  {
    type: 'integer'
  }
};

/**
 * @type   module:kwsMediaApi~MediaObject.events
 */
MediaObject.events = ['Error'];

module.exports = MediaObject;
<|endoftext|>


<commit_before>// Karma configuration
// Generated on Sun Oct 23 2016 21:47:16 GMT-0700 (PDT)

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['mocha'],

    // list of files / patterns to load in the browser
    files: [
      'tests/wildcardRegex.js'
    ],

    // list of files to exclude
    exclude: [
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      'tests/wildcardRegex.js': ['webpack']
    },

    // Webpack config
    webpack: {
      output: {
        path: __dirname + '/build/',
        filename: "bundle.js",
        logLevel: 'NONE'
      }
    },

    // Tell webpack to serve logs or not
    webpackMiddleware: {
      noInfo: true
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['mocha'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: false,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: process.env.BROWSER ? process.env.BROWSER.split(',') : ['Chrome'],
    customLaunchers: {
      ChromeCi: {
        base: 'Chrome',
        flags: ['--no-sandbox'],
      },
    },

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: true,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity
  })
}
<commit_msg>Remove logLevel key from webpack config for karma<commit_after>// Karma configuration
// Generated on Sun Oct 23 2016 21:47:16 GMT-0700 (PDT)

module.exports = function(config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['mocha'],

    // list of files / patterns to load in the browser
    files: [
      'tests/wildcardRegex.js'
    ],

    // list of files to exclude
    exclude: [
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      'tests/wildcardRegex.js': ['webpack']
    },

    // Webpack config
    webpack: {
      output: {
        path: __dirname + '/build/',
        filename: "bundle.js"
      }
    },

    // Tell webpack to serve logs or not
    webpackMiddleware: {
      noInfo: true
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['mocha'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: false,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: process.env.BROWSER ? process.env.BROWSER.split(',') : ['Chrome'],
    customLaunchers: {
      ChromeCi: {
        base: 'Chrome',
        flags: ['--no-sandbox'],
      },
    },

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: true,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity
  })
}
<|endoftext|>


<commit_before>module.exports = function (config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      {
        pattern: 'js/morpheus-external-latest.min.js',
        watched: false
      },
      {
        pattern: 'js/morpheus-latest.min.js',
        watched: false
      },
      {
        pattern: 'jasmine/matchers/*.js',
        watched: false
      },
      {
        pattern: 'jasmine/spec/*.js',
        watched: false
      },
      {
        pattern: 'jasmine/test_files/*',
        included: false,
        served: true,
        watched: false,
        nocache: true
      }
    ],
    browserNoActivityTimeout: 100000,
    proxies: {
      '/test_files/': '/base/jasmine/test_files/'
    },

    // list of files to exclude
    exclude: ['jasmine/spec/marker_selection_test.js'],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {},

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: false,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['MyChrome'],

    customLaunchers: {
      MyChromeHeadless: {
        base: 'Chrome',
        flags: ['--disable-hang-monitor']
      }
    },
    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: true,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: 1
  });
}
<commit_msg>travis<commit_after>module.exports = function (config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['jasmine'],

    // list of files / patterns to load in the browser
    files: [
      {
        pattern: 'js/morpheus-external-latest.min.js',
        watched: false
      },
      {
        pattern: 'js/morpheus-latest.min.js',
        watched: false
      },
      {
        pattern: 'jasmine/matchers/*.js',
        watched: false
      },
      {
        pattern: 'jasmine/spec/*.js',
        watched: false
      },
      {
        pattern: 'jasmine/test_files/*',
        included: false,
        served: true,
        watched: false,
        nocache: true
      }
    ],
    browserNoActivityTimeout: 100000,
    proxies: {
      '/test_files/': '/base/jasmine/test_files/'
    },

    // list of files to exclude
    exclude: ['jasmine/spec/marker_selection_test.js'],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {},

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: ['progress'],

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: false,

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['MyChrome'],

    customLaunchers: {
      MyChrome: {
        base: 'Chrome',
        flags: ['--disable-hang-monitor']
      }
    },
    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: true,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: 1
  });
}
<|endoftext|>


<commit_before>// Karma configuration
// Generated on Sun Jun 30 2013 00:14:30 GMT-0700 (PDT)

// base path, that will be used to resolve files and exclude
basePath = '';

// list of files / patterns to load in the browser
files = [
  'test/vendor/**/*',
  'src/version.js',
  'src/utils.js',
  'src/lru_cache.js',
  'src/event_emitter.js',
  'src/persistent_storage.js',
  'src/transport.js',
  'src/search_index.js',
  'src/dataset.js',
  JASMINE,
  JASMINE_ADAPTER,
  'test/fixtures/**/*',
  'test/helpers/**/*',
  'test/*_spec.js'
];

// list of files to exclude
exclude = [

];

// test results reporter to use
// possible values: 'dots', 'progress', 'junit'
reporters = ['progress'];

// web server port
port = 9876;

// cli runner port
runnerPort = 9100;

// enable / disable colors in the output (reporters and logs)
colors = true;

// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel = LOG_INFO;

// enable / disable watching file and executing tests whenever any file changes
autoWatch = true;

// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers = ['Chrome'];

// If browser does not capture in given timeout [ms], kill it
captureTimeout = 60000;

// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun = false;
<commit_msg>Update files for karma.<commit_after>// Karma configuration
// Generated on Sun Jun 30 2013 00:14:30 GMT-0700 (PDT)

// base path, that will be used to resolve files and exclude
basePath = '';

// list of files / patterns to load in the browser
files = [
  'test/vendor/**/*',
  'src/version.js',
  'src/utils.js',
  'src/html.js',
  'src/css.js',
  'src/lru_cache.js',
  'src/event_emitter.js',
  'src/persistent_storage.js',
  'src/transport.js',
  'src/search_index.js',
  'src/dataset.js',
  'src/section_view.js',
  'src/dropdown_view.js',
  'src/input_view.js',
  'src/typeahead_view.js',
  JASMINE,
  JASMINE_ADAPTER,
  'test/fixtures/**/*',
  'test/helpers/**/*',
  'test/*_spec.js'
];

// list of files to exclude
exclude = [

];

// test results reporter to use
// possible values: 'dots', 'progress', 'junit'
reporters = ['progress'];

// web server port
port = 9876;

// cli runner port
runnerPort = 9100;

// enable / disable colors in the output (reporters and logs)
colors = true;

// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel = LOG_INFO;

// enable / disable watching file and executing tests whenever any file changes
autoWatch = true;

// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers = ['Chrome'];

// If browser does not capture in given timeout [ms], kill it
captureTimeout = 60000;

// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun = false;
<|endoftext|>


<commit_before>module.exports = function(config) {
  // same as :output-dir in cljsbuild/builds/test
  var output_dir = 'resources/public/test-web/out'
  // same as :output-to in cljsbuild/builds/test
  var output_to = 'resources/public/test-web/test.js'
  config.set({
    frameworks: ['cljs-test'],

    files: [
      output_dir + '/goog/base.js',
      output_dir + '/cljs_deps.js',
      output_to,
      {pattern: output_dir + '/*.js', included: false},
      {pattern: output_dir + '/**/*.js', included: false}
    ],

    client: {args: ['expound.test_runner.run_all'],
             captureConsole: true},

    // singleRun set to false does not work!
    singleRun: true,
    browsers: ['ChromeHeadless'],
    autoWatch: false,
    logLevel: config.LOG_INFO,
    concurrency: 1,
  })
};
<commit_msg>Workarounds for timeouts<commit_after>module.exports = function(config) {
  // same as :output-dir in cljsbuild/builds/test
  var output_dir = 'resources/public/test-web/out'
  // same as :output-to in cljsbuild/builds/test
  var output_to = 'resources/public/test-web/test.js'
  config.set({
    frameworks: ['cljs-test'],

    files: [
      output_dir + '/goog/base.js',
      output_dir + '/cljs_deps.js',
      output_to,
      {pattern: output_dir + '/*.js', included: false},
      {pattern: output_dir + '/**/*.js', included: false}
    ],

    client: {args: ['expound.test_runner.run_all'],
             captureConsole: true},

    // singleRun set to false does not work!
    singleRun: true,
    browsers: ['ChromeHeadless'],
    autoWatch: false,
    logLevel: config.LOG_INFO,
    concurrency: 1,
    // Workarounds for timeout
    browserNoActivityTimeout: 20000,
    transports: ['polling'],
    browserDisconnectTolerance: 5
  })
};
<|endoftext|>


<commit_before>// Karma configuration
// Generated on Wed Apr 06 2016 14:18:09 GMT+0200 (CEST)

module.exports = function export (config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '.',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['mocha', 'chai'],

    // list of files / patterns to load in the browser
    files: [
      'src/utils/*.js',
      'src/charts/classes.js',
      'src/charts/barchart.js',
      'src/charts/streamgraph.js',
      'test/*.js',
      'node_modules/d3/d3.min.js'
    ],

    // list of files to exclude
    exclude: [
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      'src/**/*.js': ['coverage']
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: [
      'progress',
      // Output code coverage files
      'coverage'
    ],

    coverageReporter: {
      reporters: [
        // generates ./coverage/lcov.info
        {type:'lcovonly', subdir: '.'},
        // generates ./coverage/coverage-final.json
        {type:'json', subdir: '.'}
      ]
    },

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    customLaunchers: {
      ChromeES6: {
        base: 'Chrome',
        flags: ['--javascript-harmony', '--no-sandbox']
      }
    },

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['ChromeES6'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity
  });
};
<commit_msg>some codacy fixes<commit_after>// Karma configuration
// Generated on Wed Apr 06 2016 14:18:09 GMT+0200 (CEST)

module.exports => (config) {
  config.set({

    // base path that will be used to resolve all patterns (eg. files, exclude)
    basePath: '.',

    // frameworks to use
    // available frameworks: https://npmjs.org/browse/keyword/karma-adapter
    frameworks: ['mocha', 'chai'],

    // list of files / patterns to load in the browser
    files: [
      'src/utils/*.js',
      'src/charts/classes.js',
      'src/charts/barchart.js',
      'src/charts/streamgraph.js',
      'test/*.js',
      'node_modules/d3/d3.min.js'
    ],

    // list of files to exclude
    exclude: [
    ],

    // preprocess matching files before serving them to the browser
    // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
    preprocessors: {
      'src/**/*.js': ['coverage']
    },

    // test results reporter to use
    // possible values: 'dots', 'progress'
    // available reporters: https://npmjs.org/browse/keyword/karma-reporter
    reporters: [
      'progress',
      // Output code coverage files
      'coverage'
    ],

    coverageReporter: {
      reporters: [
        // generates ./coverage/lcov.info
        {type:'lcovonly', subdir: '.'},
        // generates ./coverage/coverage-final.json
        {type:'json', subdir: '.'}
      ]
    },

    // web server port
    port: 9876,

    // enable / disable colors in the output (reporters and logs)
    colors: true,

    // level of logging
    // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
    logLevel: config.LOG_INFO,

    // enable / disable watching file and executing tests whenever any file changes
    autoWatch: true,

    customLaunchers: {
      ChromeES6: {
        base: 'Chrome',
        flags: ['--javascript-harmony', '--no-sandbox']
      }
    },

    // start these browsers
    // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
    browsers: ['ChromeES6'],

    // Continuous Integration mode
    // if true, Karma captures browsers, runs the tests and exits
    singleRun: false,

    // Concurrency level
    // how many browser should be started simultaneous
    concurrency: Infinity
  });
};
<|endoftext|>


<commit_before>module.exports = function (config) {
  var root = 'run/compiled/karma/test'; // same as :output-dir
  var junitOutputDir = process.env.CIRCLE_TEST_REPORTS || root + '/junit'

  config.set({
    frameworks: ['cljs-test'],
    browsers: ['Chrome', 'PhantomJS'],
    files: [
      root + '/../test.js', // same as :output-to
      {pattern: root + '/../oi_lang_test.js.map', included: false, watched: false},
      {pattern: root + '/**/*.+(cljs|cljc|clj|js|js.map)', included: false, watched: false}
    ],

    client: {
      args: ['oi_lang.test_runner.run_karma']
    },

    autoWatchBatchDelay: 500,

    // the default configuration
    junitReporter: {
      outputDir: junitOutputDir + '/karma', // results will be saved as $outputDir/$browserName.xml
      outputFile: undefined, // if included, results will be saved as $outputDir/$browserName/$outputFile
      suite: '' // suite will become the package name attribute in xml testsuite element
    }
  })
};
<commit_msg>try again?<commit_after>module.exports = function (config) {
  var root = 'run/compiled/karma/test'; // same as :output-dir
  var junitOutputDir = (process.env.CIRCLE_TEST_REPORTS + '/junit') || (root + '/junit')

  config.set({
    frameworks: ['cljs-test'],
    browsers: ['Chrome', 'PhantomJS'],
    files: [
      root + '/../test.js', // same as :output-to
      {pattern: root + '/../oi_lang_test.js.map', included: false, watched: false},
      {pattern: root + '/**/*.+(cljs|cljc|clj|js|js.map)', included: false, watched: false}
    ],

    client: {
      args: ['oi_lang.test_runner.run_karma']
    },

    autoWatchBatchDelay: 500,

    // the default configuration
    junitReporter: {
      outputDir: junitOutputDir + '/karma', // results will be saved as $outputDir/$browserName.xml
      outputFile: undefined, // if included, results will be saved as $outputDir/$browserName/$outputFile
      suite: '' // suite will become the package name attribute in xml testsuite element
    }
  })
};
<|endoftext|>


<commit_before>// Karma configuration file

module.exports = function(config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular/cli'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-ie-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-coverage-istanbul-reporter'),
      require('@angular/cli/plugins/karma')
    ],
    client: {
      clearContext: false // leave Jasmine Spec Runner output visible in browser
    },
    coverageIstanbulReporter: {
      reports: ['html', 'lcovonly'],
      fixWebpackSourcePaths: true
    },
    angularCli: {
      environment: 'dev'
    },
    reporters: ['progress', 'kjhtml'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome', 'IE'],
    singleRun: false
  })
}
<commit_msg>Remove IE plugins from karma config for Chrome<commit_after>// Karma configuration file for Chrome

module.exports = function(config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular/cli'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-coverage-istanbul-reporter'),
      require('@angular/cli/plugins/karma')
    ],
    client: {
      clearContext: false // leave Jasmine Spec Runner output visible in browser
    },
    coverageIstanbulReporter: {
      reports: ['html', 'lcovonly'],
      fixWebpackSourcePaths: true
    },
    angularCli: {
      environment: 'dev'
    },
    reporters: ['progress', 'kjhtml'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false
  })
}
<|endoftext|>


<commit_before>// Karma configuration
// Generated on Tue Aug 20 2013 11:45:52 GMT-0700 (PDT)

module.exports = function(config) {
	config.set({

		// base path, that will be used to resolve files and exclude
		basePath: '',

		// frameworks to use
		frameworks: ['mocha', 'requirejs'],

		// list of files / patterns to load in the browser
		files: [
			'test/karma-config.js',

			{pattern: 'test/*.js', included: false},
			{pattern: 'test/specs/**/*.js', included: false},
			{pattern: 'test/libs/**/*.js', included: false},
			{pattern: 'tmp/*.js', included: false},
			{pattern: 'src/**/*.js', included: false},
			{pattern: 'libs/*.js', included: false},
			{pattern: 'build/*.js', included: false}
		],

		// list of files to output the coverage by istanbul
		preprocessors: {
			// source files, that you wanna generate coverage for
			// do not include tests or libraries
			// (these files will be instrumented by Istanbul)
			'test/specs/*.js': 'coverage'
		},

		// list of files to exclude
		exclude: [

		],

		// test results reporter to use
		// possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
		reporters: ['progress', 'coverage'],

		// web server port
		port: 9876,

		// enable / disable colors in the output (reporters and logs)
		colors: true,

		// level of logging
		// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
		logLevel: config.LOG_INFO,

		// enable / disable watching file and executing tests whenever any file changes
		autoWatch: false,

		// Start these browsers, currently available:
		// - Chrome
		// - ChromeCanary
		// - Firefox
		// - Opera
		// - Safari (only Mac)
		// - PhantomJS
		// - IE (only Windows)
		browsers: ['Firefox'],

		// If browser does not capture in given timeout [ms], kill it
		captureTimeout: 60000,

		// Continuous Integration mode
		// if true, it capture browsers, run tests and exit
		singleRun: true,

		// optionally, configure the reporter
		// - html (default)
		// - lcov (lcov and html)
		// - lcovonly
		// - text
		// - text-summary
		// - cobertura (xml format supported by Jenkins)
		//
		// If you set type to text or text-summary, you may set the file option, like this.
		// file : 'coverage.txt'
		coverageReporter: {
			type : 'html',
			dir : 'coverage/'
		},

		plugins: [
			'karma-mocha',
			'karma-requirejs',
			'karma-coverage',
			'karma-chrome-launcher',
			'karma-firefox-launcher'
		]
	});
};
<commit_msg>remove the build folder watch patterns from the karma conf<commit_after>// Karma configuration
// Generated on Tue Aug 20 2013 11:45:52 GMT-0700 (PDT)

module.exports = function(config) {
	config.set({

		// base path, that will be used to resolve files and exclude
		basePath: '',

		// frameworks to use
		frameworks: ['mocha', 'requirejs'],

		// list of files / patterns to load in the browser
		files: [
			'test/karma-config.js',

			{pattern: 'test/*.js', included: false},
			{pattern: 'test/specs/**/*.js', included: false},
			{pattern: 'test/libs/**/*.js', included: false},
			{pattern: 'tmp/*.js', included: false},
			{pattern: 'src/**/*.js', included: false},
			{pattern: 'libs/*.js', included: false}
		],

		// list of files to output the coverage by istanbul
		preprocessors: {
			// source files, that you wanna generate coverage for
			// do not include tests or libraries
			// (these files will be instrumented by Istanbul)
			'test/specs/*.js': 'coverage'
		},

		// list of files to exclude
		exclude: [

		],

		// test results reporter to use
		// possible values: 'dots', 'progress', 'junit', 'growl', 'coverage'
		reporters: ['progress', 'coverage'],

		// web server port
		port: 9876,

		// enable / disable colors in the output (reporters and logs)
		colors: true,

		// level of logging
		// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
		logLevel: config.LOG_INFO,

		// enable / disable watching file and executing tests whenever any file changes
		autoWatch: false,

		// Start these browsers, currently available:
		// - Chrome
		// - ChromeCanary
		// - Firefox
		// - Opera
		// - Safari (only Mac)
		// - PhantomJS
		// - IE (only Windows)
		browsers: ['Firefox'],

		// If browser does not capture in given timeout [ms], kill it
		captureTimeout: 60000,

		// Continuous Integration mode
		// if true, it capture browsers, run tests and exit
		singleRun: true,

		// optionally, configure the reporter
		// - html (default)
		// - lcov (lcov and html)
		// - lcovonly
		// - text
		// - text-summary
		// - cobertura (xml format supported by Jenkins)
		//
		// If you set type to text or text-summary, you may set the file option, like this.
		// file : 'coverage.txt'
		coverageReporter: {
			type : 'html',
			dir : 'coverage/'
		},

		plugins: [
			'karma-mocha',
			'karma-requirejs',
			'karma-coverage',
			'karma-chrome-launcher',
			'karma-firefox-launcher'
		]
	});
};
<|endoftext|>


<commit_before>
function PPTournamentLoader(theApp, stateManager) {
   if (theApp == null || stateManager == null) {
        throw new Error("PPTournamentLoader missing required parameter.");
   }

  this.theApp = theApp;
  this.stateManager = stateManager;

  this.tournamentTypes = new Array();
}

PPTournamentLoader.prototype.registerTournamentType = function (type) {
  this.tournamentTypes.push(type);
}

// The first tournament type registered is selected by default when
// displaying a radio button list.
PPTournamentLoader.prototype.registerTournamentTypes = function (typeArray) {
  for (var i = 0; i < typeArray.length; i++) {
    this.registerTournamentType(typeArray[i]);
  }
}

PPTournamentLoader.prototype.printTournamentTypes = function () {
  for( var i = 0; i < this.tournamentTypes.length; i++) {
    var tType = this.tournamentTypes[i];
    console.log(tType.typeName());
  }
}

PPTournamentLoader.prototype.getSelectedTournamentType = function () {
  for( var i = 0; i < this.tournamentTypes.length; i ++ ) {
   if ( $("tTypeRadio" + i).checked == true ) {
     return new this.tournamentTypes[i]();
   }
  }
  throw new Error("No tournament type selected");
}

PPTournamentLoader.prototype.generateRadioList = function (id) {
  var tList = $(id);

  //typeName + "<input id='tTypeRadio" + i + "' name='tType' type='radio' value='" + typeName + "'>" + "
"
  for( var i = 0; i < this.tournamentTypes.length; i ++ ) {
    var typeName = this.tournamentTypes[i].labelName();

    var label = document.createTextNode(typeName);
    tList.appendChild(label);
    var radio = document.createElement('input');
    // TODO -- setAttributes helper method... two arrays...
    radio.setAttribute('id', "tTypeRadio" + i);
    radio.setAttribute('name', "tType");
    radio.setAttribute('type', "radio");
    radio.setAttribute('value', typeName);
    if ( i == 0) {
       radio.setAttribute('checked');
    }
    tList.appendChild(radio);
    var brk = document.createElement('br');
    tList.appendChild(brk);

  }

}

PPTournamentLoader.prototype.process = function(data) {
  var jsonData = JSON.parse(data);

  // Convert string to new object statement:
  // "PPTennisTournament" ==> new PPTennisTournament();
  var tournament = eval("new " + jsonData.class +"();");
  tournament.name = jsonData.name;
  // TODO -- this could be a bound configuration, push to edit controller?
  console.log("TODO -- remove hardcoded element name.")
  $("tournamentNameTextField").value = tournament.name;
  tournament.loadRoundsFromJSON(jsonData.rounds);

  this.theApp.setTournament(tournament);
  this.stateManager.startTournament();

  this.theApp.redraw();
}<commit_msg>Remove hardcoded field name.  Handled by SinglesEditController now.<commit_after>
function PPTournamentLoader(theApp, stateManager) {
   if (theApp == null || stateManager == null) {
        throw new Error("PPTournamentLoader missing required parameter.");
   }

  this.theApp = theApp;
  this.stateManager = stateManager;

  this.tournamentTypes = new Array();
}

PPTournamentLoader.prototype.registerTournamentType = function (type) {
  this.tournamentTypes.push(type);
}

// The first tournament type registered is selected by default when
// displaying a radio button list.
PPTournamentLoader.prototype.registerTournamentTypes = function (typeArray) {
  for (var i = 0; i < typeArray.length; i++) {
    this.registerTournamentType(typeArray[i]);
  }
}

PPTournamentLoader.prototype.printTournamentTypes = function () {
  for( var i = 0; i < this.tournamentTypes.length; i++) {
    var tType = this.tournamentTypes[i];
    console.log(tType.typeName());
  }
}

PPTournamentLoader.prototype.getSelectedTournamentType = function () {
  for( var i = 0; i < this.tournamentTypes.length; i ++ ) {
   if ( $("tTypeRadio" + i).checked == true ) {
     return new this.tournamentTypes[i]();
   }
  }
  throw new Error("No tournament type selected");
}

PPTournamentLoader.prototype.generateRadioList = function (id) {
  var tList = $(id);

  //typeName + "<input id='tTypeRadio" + i + "' name='tType' type='radio' value='" + typeName + "'>" + "
"
  for( var i = 0; i < this.tournamentTypes.length; i ++ ) {
    var typeName = this.tournamentTypes[i].labelName();

    var label = document.createTextNode(typeName);
    tList.appendChild(label);
    var radio = document.createElement('input');
    // TODO -- setAttributes helper method... two arrays...
    radio.setAttribute('id', "tTypeRadio" + i);
    radio.setAttribute('name', "tType");
    radio.setAttribute('type', "radio");
    radio.setAttribute('value', typeName);
    if ( i == 0) {
       radio.setAttribute('checked');
    }
    tList.appendChild(radio);
    var brk = document.createElement('br');
    tList.appendChild(brk);

  }

}

PPTournamentLoader.prototype.process = function(data) {
  var jsonData = JSON.parse(data);

  // Convert string to new object statement:
  // "PPTennisTournament" ==> new PPTennisTournament();
  var tournament = eval("new " + jsonData.class +"();");
  tournament.name = jsonData.name;
  tournament.loadRoundsFromJSON(jsonData.rounds);

  this.theApp.setTournament(tournament);
  this.stateManager.startTournament();
  this.theApp.redraw();
}<|endoftext|>


<commit_before>const Command = require('../Command')
const DiscordServer = require('../../DiscordServer')

async function recursiveUpdate (memberArray, server, msg) {
  let nextMember = memberArray.pop()
  if (!nextMember) {
    return msg.reply(`:white_check_mark: Finished bulk update! ${server.bulkUpdateCount} members affected.`).then(() => {
      server.bulkUpdateCount = 0
      server.ongoingBulkUpdate = false
    })
  }

  if (!nextMember.user.bot) {
    let member = await server.getMember(nextMember.id)
    if (member) {
      await member.verify({ skipWelcomeMessage: true })
      server.bulkUpdateCount++
    }
  }
  return recursiveUpdate(memberArray, server, msg)
}

module.exports =
class UpdateCommand extends Command {
  constructor (client) {
    super(client, {
      name: 'update',
      properName: 'Update',
      aliases: ['roverupdate'],
      description: '`<Discord User>` Forcibly update verification status of a user, same as them running !verify. Make sure you @mention the user.',

      args: [
        {
          key: 'user',
          prompt: 'User to update',
          type: 'user|role'
        }
      ]
    })
  }

  hasPermission (msg) {
    return this.client.isOwner(msg.author) || msg.member.hasPermission(this.userPermissions) || msg.member.roles.find(role => role.name === 'RoVer Admin') || msg.member.roles.find(role => role.name === 'RoVer Updater')
  }

  async fn (msg, args) {
    let user = args.user
    DiscordServer.clearMemberCache(user.id)

    let server = await this.discordBot.getServer(msg.guild.id)
    if (user.hoist === undefined) { // They want to update a specific user (roles have .hoist, users do not)
      let member = await server.getMember(user.id)
      if (!member) {
        return msg.reply('User not in guild.')
      }

      member.verify({ message: msg, skipWelcomeMessage: true })
    } else { // They want to update a whole role (premium feature)
      let roleMembers = user.members.array()
      let affectedCount = roleMembers.length // # of affected users
      let server = await this.discordBot.getServer(msg.guild.id)

      if (server.ongoingBulkUpdate) {
        return msg.reply('There is already an ongoing bulk update in this server.')
      }

      if (affectedCount > 250) {
        return msg.reply(`Sorry, but RoVer only supports updating up to 250 members at once. Updating this role would affect ${affectedCount} members.`)
      }

      server.ongoingBulkUpdate = true
      msg.channel.send(`:hourglass_flowing_sand: Please wait - bulk update for ${affectedCount} members in progress. We'll let you know when it's done.`)

      recursiveUpdate(roleMembers, server, msg)
    }
  }
}
<commit_msg>Switch to instanceof check<commit_after>const Command = require('../Command')
const DiscordServer = require('../../DiscordServer')
const { Role } = require('discord.js')

async function recursiveUpdate (memberArray, server, msg) {
  let nextMember = memberArray.pop()
  if (!nextMember) {
    return msg.reply(`:white_check_mark: Finished bulk update! ${server.bulkUpdateCount} members affected.`).then(() => {
      server.bulkUpdateCount = 0
      server.ongoingBulkUpdate = false
    })
  }

  if (!nextMember.user.bot) {
    let member = await server.getMember(nextMember.id)
    if (member) {
      await member.verify({ skipWelcomeMessage: true })
      server.bulkUpdateCount++
    }
  }
  return recursiveUpdate(memberArray, server, msg)
}

module.exports =
class UpdateCommand extends Command {
  constructor (client) {
    super(client, {
      name: 'update',
      properName: 'Update',
      aliases: ['roverupdate'],
      description: '`<Discord User>` Forcibly update verification status of a user, same as them running !verify. Make sure you @mention the user.',

      args: [
        {
          key: 'user',
          prompt: 'User to update',
          type: 'user|role'
        }
      ]
    })
  }

  hasPermission (msg) {
    return this.client.isOwner(msg.author) || msg.member.hasPermission(this.userPermissions) || msg.member.roles.find(role => role.name === 'RoVer Admin') || msg.member.roles.find(role => role.name === 'RoVer Updater')
  }

  async fn (msg, args) {
    let target = args.user
    DiscordServer.clearMemberCache(target.id)

    let server = await this.discordBot.getServer(msg.guild.id)
    if (!(target instanceof Role)) { // They want to update a specific user (roles have .hoist, users do not)
      let member = await server.getMember(target.id)
      if (!member) {
        return msg.reply('User not in guild.')
      }

      member.verify({ message: msg, skipWelcomeMessage: true })
    } else { // They want to update a whole role (premium feature)
      let roleMembers = target.members.array()
      let affectedCount = roleMembers.length // # of affected users
      let server = await this.discordBot.getServer(msg.guild.id)

      if (server.ongoingBulkUpdate) {
        return msg.reply('There is already an ongoing bulk update in this server.')
      }

      if (affectedCount > 250) {
        return msg.reply(`Sorry, but RoVer only supports updating up to 250 members at once. Updating this role would affect ${affectedCount} members.`)
      }

      server.ongoingBulkUpdate = true
      msg.channel.send(`:hourglass_flowing_sand: Please wait - bulk update for ${affectedCount} members in progress. We'll let you know when it's done.`)

      recursiveUpdate(roleMembers, server, msg)
    }
  }
}
<|endoftext|>